claude-code-session-manager 0.39.0 → 0.39.1
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-CtuLATFR.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var bA=Object.defineProperty;var yA=(i,e,n)=>e in i?bA(i,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):i[e]=n;var Ui=(i,e,n)=>yA(i,typeof e!="symbol"?e+"":e,n);import{_ as Dg}from"./monaco-editor-BW5C4Iv1.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const u of a.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function n(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(s){if(s.ep)return;s.ep=!0;const a=n(s);fetch(s.href,a)}})();function zb(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var py={exports:{}},pm={},fy={exports:{}},vi={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -40,7 +40,7 @@ var bA=Object.defineProperty;var yA=(i,e,n)=>e in i?bA(i,e,{enumerable:!0,config
|
|
|
40
40
|
Error generating stack: `+Y.message+`
|
|
41
41
|
`+Y.stack}return{value:h,source:v,stack:G,digest:null}}function bh(h,v,T){return{value:h,source:null,stack:T??null,digest:v??null}}function yh(h,v){try{console.error(v.value)}catch(T){setTimeout(function(){throw T})}}var vv=typeof WeakMap=="function"?WeakMap:Map;function Rf(h,v,T){T=ho(-1,T),T.tag=3,T.payload={element:null};var R=v.value;return T.callback=function(){Od||(Od=!0,Fh=R),yh(h,v)},T}function If(h,v,T){T=ho(-1,T),T.tag=3;var R=h.type.getDerivedStateFromError;if(typeof R=="function"){var G=v.value;T.payload=function(){return R(G)},T.callback=function(){yh(h,v)}}var Y=h.stateNode;return Y!==null&&typeof Y.componentDidCatch=="function"&&(T.callback=function(){yh(h,v),typeof R!="function"&&(Vo===null?Vo=new Set([this]):Vo.add(this));var de=v.stack;this.componentDidCatch(v.value,{componentStack:de!==null?de:""})}),T}function Mf(h,v,T){var R=h.pingCache;if(R===null){R=h.pingCache=new vv;var G=new Set;R.set(v,G)}else G=R.get(v),G===void 0&&(G=new Set,R.set(v,G));G.has(T)||(G.add(T),h=Dv.bind(null,h,v,T),v.then(h,h))}function xv(h){do{var v;if((v=h.tag===13)&&(v=h.memoizedState,v=v!==null?v.dehydrated!==null:!0),v)return h;h=h.return}while(h!==null);return null}function dr(h,v,T,R,G){return(h.mode&1)===0?(h===v?h.flags|=65536:(h.flags|=128,T.flags|=131072,T.flags&=-52805,T.tag===1&&(T.alternate===null?T.tag=17:(v=ho(-1,1),v.tag=2,Go(T,v,1))),T.lanes|=1),h):(h.flags|=65536,h.lanes=G,h)}var bv=j.ReactCurrentOwner,Ar=!1;function qn(h,v,T,R){v.child=h===null?Qu(v,null,T,R):cl(v,h.child,T,R)}function Of(h,v,T,R,G){T=T.render;var Y=v.ref;return dl(v,G),R=ph(h,v,T,R,Y,G),T=fh(),h!==null&&!Ar?(v.updateQueue=h.updateQueue,v.flags&=-2053,h.lanes&=~G,fo(h,v,G)):(Ji&&T&&xn(v),v.flags|=1,qn(h,v,R,G),v.child)}function uc(h,v,T,R,G){if(h===null){var Y=T.type;return typeof Y=="function"&&!Kh(Y)&&Y.defaultProps===void 0&&T.compare===null&&T.defaultProps===void 0?(v.tag=15,v.type=Y,Lf(h,v,Y,R,G)):(h=Gd(T.type,null,R,v,v.mode,G),h.ref=v.ref,h.return=v,v.child=h)}if(Y=h.child,(h.lanes&G)===0){var de=Y.memoizedProps;if(T=T.compare,T=T!==null?T:Zl,T(de,R)&&h.ref===v.ref)return fo(h,v,G)}return v.flags|=1,h=Yo(Y,R),h.ref=v.ref,h.return=v,v.child=h}function Lf(h,v,T,R,G){if(h!==null){var Y=h.memoizedProps;if(Zl(Y,R)&&h.ref===v.ref)if(Ar=!1,v.pendingProps=R=Y,(h.lanes&G)!==0)(h.flags&131072)!==0&&(Ar=!0);else return v.lanes=h.lanes,fo(h,v,G)}return _h(h,v,T,R,G)}function zf(h,v,T){var R=v.pendingProps,G=R.children,Y=h!==null?h.memoizedState:null;if(R.mode==="hidden")if((v.mode&1)===0)v.memoizedState={baseLanes:0,cachePool:null,transitions:null},Oi(ml,Gr),Gr|=T;else{if((T&1073741824)===0)return h=Y!==null?Y.baseLanes|T:T,v.lanes=v.childLanes=1073741824,v.memoizedState={baseLanes:h,cachePool:null,transitions:null},v.updateQueue=null,Oi(ml,Gr),Gr|=h,null;v.memoizedState={baseLanes:0,cachePool:null,transitions:null},R=Y!==null?Y.baseLanes:T,Oi(ml,Gr),Gr|=R}else Y!==null?(R=Y.baseLanes|T,v.memoizedState=null):R=T,Oi(ml,Gr),Gr|=R;return qn(h,v,G,T),v.child}function Bf(h,v){var T=v.ref;(h===null&&T!==null||h!==null&&h.ref!==T)&&(v.flags|=512,v.flags|=2097152)}function _h(h,v,T,R,G){var Y=Cr(T)?va:lr.current;return Y=cr(v,Y),dl(v,G),T=ph(h,v,T,R,Y,G),R=fh(),h!==null&&!Ar?(v.updateQueue=h.updateQueue,v.flags&=-2053,h.lanes&=~G,fo(h,v,G)):(Ji&&R&&xn(v),v.flags|=1,qn(h,v,T,G),v.child)}function Ff(h,v,T,R,G){if(Cr(T)){var Y=!0;gd(v)}else Y=!1;if(dl(v,G),v.stateNode===null)Nd(h,v),$f(v,T,R),xh(v,T,R,G),R=!0;else if(h===null){var de=v.stateNode,we=v.memoizedProps;de.props=we;var Ae=de.context,We=T.contextType;typeof We=="object"&&We!==null?We=ts(We):(We=Cr(T)?va:lr.current,We=cr(v,We));var lt=T.getDerivedStateFromProps,ct=typeof lt=="function"||typeof de.getSnapshotBeforeUpdate=="function";ct||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(we!==R||Ae!==We)&&Pf(v,de,R,We),qs=!1;var at=v.memoizedState;de.state=at,kd(v,R,de,G),Ae=v.memoizedState,we!==R||at!==Ae||kr.current||qs?(typeof lt=="function"&&(Ys(v,T,lt,R),Ae=v.memoizedState),(we=qs||Ea(v,T,we,R,at,Ae,We))?(ct||typeof de.UNSAFE_componentWillMount!="function"&&typeof de.componentWillMount!="function"||(typeof de.componentWillMount=="function"&&de.componentWillMount(),typeof de.UNSAFE_componentWillMount=="function"&&de.UNSAFE_componentWillMount()),typeof de.componentDidMount=="function"&&(v.flags|=4194308)):(typeof de.componentDidMount=="function"&&(v.flags|=4194308),v.memoizedProps=R,v.memoizedState=Ae),de.props=R,de.state=Ae,de.context=We,R=we):(typeof de.componentDidMount=="function"&&(v.flags|=4194308),R=!1)}else{de=v.stateNode,rh(h,v),we=v.memoizedProps,We=v.type===v.elementType?we:yn(v.type,we),de.props=We,ct=v.pendingProps,at=de.context,Ae=T.contextType,typeof Ae=="object"&&Ae!==null?Ae=ts(Ae):(Ae=Cr(T)?va:lr.current,Ae=cr(v,Ae));var Tt=T.getDerivedStateFromProps;(lt=typeof Tt=="function"||typeof de.getSnapshotBeforeUpdate=="function")||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(we!==ct||at!==Ae)&&Pf(v,de,R,Ae),qs=!1,at=v.memoizedState,de.state=at,kd(v,R,de,G);var Mt=v.memoizedState;we!==ct||at!==Mt||kr.current||qs?(typeof Tt=="function"&&(Ys(v,T,Tt,R),Mt=v.memoizedState),(We=qs||Ea(v,T,We,R,at,Mt,Ae)||!1)?(lt||typeof de.UNSAFE_componentWillUpdate!="function"&&typeof de.componentWillUpdate!="function"||(typeof de.componentWillUpdate=="function"&&de.componentWillUpdate(R,Mt,Ae),typeof de.UNSAFE_componentWillUpdate=="function"&&de.UNSAFE_componentWillUpdate(R,Mt,Ae)),typeof de.componentDidUpdate=="function"&&(v.flags|=4),typeof de.getSnapshotBeforeUpdate=="function"&&(v.flags|=1024)):(typeof de.componentDidUpdate!="function"||we===h.memoizedProps&&at===h.memoizedState||(v.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||we===h.memoizedProps&&at===h.memoizedState||(v.flags|=1024),v.memoizedProps=R,v.memoizedState=Mt),de.props=R,de.state=Mt,de.context=Ae,R=We):(typeof de.componentDidUpdate!="function"||we===h.memoizedProps&&at===h.memoizedState||(v.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||we===h.memoizedProps&&at===h.memoizedState||(v.flags|=1024),R=!1)}return wh(h,v,T,R,Y,G)}function wh(h,v,T,R,G,Y){Bf(h,v);var de=(v.flags&128)!==0;if(!R&&!de)return G&&of(v,T,!1),fo(h,v,Y);R=v.stateNode,bv.current=v;var we=de&&typeof T.getDerivedStateFromError!="function"?null:R.render();return v.flags|=1,h!==null&&de?(v.child=cl(v,h.child,null,Y),v.child=cl(v,null,we,Y)):qn(h,v,we,Y),v.memoizedState=R.state,G&&of(v,T,!0),v.child}function Sh(h){var v=h.stateNode;v.pendingContext?rf(h,v.pendingContext,v.pendingContext!==v.context):v.context&&rf(h,v.context,!1),sh(h,v.containerInfo)}function Gf(h,v,T,R,G){return ba(),Ju(G),v.flags|=256,qn(h,v,T,R),v.child}var kh={dehydrated:null,treeContext:null,retryLane:0};function Ch(h){return{baseLanes:h,cachePool:null,transitions:null}}function Uf(h,v,T){var R=v.pendingProps,G=Qi.current,Y=!1,de=(v.flags&128)!==0,we;if((we=de)||(we=h!==null&&h.memoizedState===null?!1:(G&2)!==0),we?(Y=!0,v.flags&=-129):(h===null||h.memoizedState!==null)&&(G|=1),Oi(Qi,G&1),h===null)return Yu(v),h=v.memoizedState,h!==null&&(h=h.dehydrated,h!==null)?((v.mode&1)===0?v.lanes=1:h.data==="$!"?v.lanes=8:v.lanes=1073741824,null):(de=R.children,h=R.fallback,Y?(R=v.mode,Y=v.child,de={mode:"hidden",children:de},(R&1)===0&&Y!==null?(Y.childLanes=0,Y.pendingProps=de):Y=Ud(de,R,0,null),h=xl(h,R,T,null),Y.return=v,h.return=v,Y.sibling=h,v.child=Y,v.child.memoizedState=Ch(T),v.memoizedState=kh,h):hc(v,de));if(G=h.memoizedState,G!==null&&(we=G.dehydrated,we!==null))return yv(h,v,de,R,we,G,T);if(Y){Y=R.fallback,de=v.mode,G=h.child,we=G.sibling;var Ae={mode:"hidden",children:R.children};return(de&1)===0&&v.child!==G?(R=v.child,R.childLanes=0,R.pendingProps=Ae,v.deletions=null):(R=Yo(G,Ae),R.subtreeFlags=G.subtreeFlags&14680064),we!==null?Y=Yo(we,Y):(Y=xl(Y,de,T,null),Y.flags|=2),Y.return=v,R.return=v,R.sibling=Y,v.child=R,R=Y,Y=v.child,de=h.child.memoizedState,de=de===null?Ch(T):{baseLanes:de.baseLanes|T,cachePool:null,transitions:de.transitions},Y.memoizedState=de,Y.childLanes=h.childLanes&~T,v.memoizedState=kh,R}return Y=h.child,h=Y.sibling,R=Yo(Y,{mode:"visible",children:R.children}),(v.mode&1)===0&&(R.lanes=T),R.return=v,R.sibling=null,h!==null&&(T=v.deletions,T===null?(v.deletions=[h],v.flags|=16):T.push(h)),v.child=R,v.memoizedState=null,R}function hc(h,v){return v=Ud({mode:"visible",children:v},h.mode,0,null),v.return=h,h.child=v}function Ad(h,v,T,R){return R!==null&&Ju(R),cl(v,h.child,null,T),h=hc(v,v.pendingProps.children),h.flags|=2,v.memoizedState=null,h}function yv(h,v,T,R,G,Y,de){if(T)return v.flags&256?(v.flags&=-257,R=bh(Error(n(422))),Ad(h,v,de,R)):v.memoizedState!==null?(v.child=h.child,v.flags|=128,null):(Y=R.fallback,G=v.mode,R=Ud({mode:"visible",children:R.children},G,0,null),Y=xl(Y,G,de,null),Y.flags|=2,R.return=v,Y.return=v,R.sibling=Y,v.child=R,(v.mode&1)!==0&&cl(v,h.child,null,de),v.child.memoizedState=Ch(de),v.memoizedState=kh,Y);if((v.mode&1)===0)return Ad(h,v,de,null);if(G.data==="$!"){if(R=G.nextSibling&&G.nextSibling.dataset,R)var we=R.dgst;return R=we,Y=Error(n(419)),R=bh(Y,R,void 0),Ad(h,v,de,R)}if(we=(de&h.childLanes)!==0,Ar||we){if(R=_n,R!==null){switch(de&-de){case 4:G=2;break;case 16:G=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:G=32;break;case 536870912:G=268435456;break;default:G=0}G=(G&(R.suspendedLanes|de))!==0?0:G,G!==0&&G!==Y.retryLane&&(Y.retryLane=G,uo(h,G),Es(R,h,G,-1))}return qh(),R=bh(Error(n(421))),Ad(h,v,de,R)}return G.data==="$?"?(v.flags|=128,v.child=h.child,v=Nv.bind(null,h),G._reactRetry=v,null):(h=Y.treeContext,Fr=Lo(G.nextSibling),jr=v,Ji=!0,Dr=null,h!==null&&(Qr[ws++]=Er,Qr[ws++]=Tr,Qr[ws++]=es,Er=h.id,Tr=h.overflow,es=v),v=hc(v,R.children),v.flags|=4096,v)}function Hf(h,v,T){h.lanes|=v;var R=h.alternate;R!==null&&(R.lanes|=v),df(h.return,v,T)}function Eh(h,v,T,R,G){var Y=h.memoizedState;Y===null?h.memoizedState={isBackwards:v,rendering:null,renderingStartTime:0,last:R,tail:T,tailMode:G}:(Y.isBackwards=v,Y.rendering=null,Y.renderingStartTime=0,Y.last=R,Y.tail=T,Y.tailMode=G)}function Th(h,v,T){var R=v.pendingProps,G=R.revealOrder,Y=R.tail;if(qn(h,v,R.children,T),R=Qi.current,(R&2)!==0)R=R&1|2,v.flags|=128;else{if(h!==null&&(h.flags&128)!==0)e:for(h=v.child;h!==null;){if(h.tag===13)h.memoizedState!==null&&Hf(h,T,v);else if(h.tag===19)Hf(h,T,v);else if(h.child!==null){h.child.return=h,h=h.child;continue}if(h===v)break e;for(;h.sibling===null;){if(h.return===null||h.return===v)break e;h=h.return}h.sibling.return=h.return,h=h.sibling}R&=1}if(Oi(Qi,R),(v.mode&1)===0)v.memoizedState=null;else switch(G){case"forwards":for(T=v.child,G=null;T!==null;)h=T.alternate,h!==null&&Cd(h)===null&&(G=T),T=T.sibling;T=G,T===null?(G=v.child,v.child=null):(G=T.sibling,T.sibling=null),Eh(v,!1,G,T,Y);break;case"backwards":for(T=null,G=v.child,v.child=null;G!==null;){if(h=G.alternate,h!==null&&Cd(h)===null){v.child=G;break}h=G.sibling,G.sibling=T,T=G,G=h}Eh(v,!0,T,null,Y);break;case"together":Eh(v,!1,null,null,void 0);break;default:v.memoizedState=null}return v.child}function Nd(h,v){(v.mode&1)===0&&h!==null&&(h.alternate=null,v.alternate=null,v.flags|=2)}function fo(h,v,T){if(h!==null&&(v.dependencies=h.dependencies),Ta|=v.lanes,(T&v.childLanes)===0)return null;if(h!==null&&v.child!==h.child)throw Error(n(153));if(v.child!==null){for(h=v.child,T=Yo(h,h.pendingProps),v.child=T,T.return=v;h.sibling!==null;)h=h.sibling,T=T.sibling=Yo(h,h.pendingProps),T.return=v;T.sibling=null}return v.child}function oy(h,v,T){switch(v.tag){case 3:Sh(v),ba();break;case 5:uf(v);break;case 1:Cr(v.type)&&gd(v);break;case 4:sh(v,v.stateNode.containerInfo);break;case 10:var R=v.type._context,G=v.memoizedProps.value;Oi(ya,R._currentValue),R._currentValue=G;break;case 13:if(R=v.memoizedState,R!==null)return R.dehydrated!==null?(Oi(Qi,Qi.current&1),v.flags|=128,null):(T&v.child.childLanes)!==0?Uf(h,v,T):(Oi(Qi,Qi.current&1),h=fo(h,v,T),h!==null?h.sibling:null);Oi(Qi,Qi.current&1);break;case 19:if(R=(T&v.childLanes)!==0,(h.flags&128)!==0){if(R)return Th(h,v,T);v.flags|=128}if(G=v.memoizedState,G!==null&&(G.rendering=null,G.tail=null,G.lastEffect=null),Oi(Qi,Qi.current),R)break;return null;case 22:case 23:return v.lanes=0,zf(h,v,T)}return fo(h,v,T)}var jh,Dh,Wf,Vf;jh=function(h,v){for(var T=v.child;T!==null;){if(T.tag===5||T.tag===6)h.appendChild(T.stateNode);else if(T.tag!==4&&T.child!==null){T.child.return=T,T=T.child;continue}if(T===v)break;for(;T.sibling===null;){if(T.return===null||T.return===v)return;T=T.return}T.sibling.return=T.return,T=T.sibling}},Dh=function(){},Wf=function(h,v,T,R){var G=h.memoizedProps;if(G!==R){h=v.stateNode,wa(Ks.current);var Y=null;switch(T){case"input":G=qt(h,G),R=qt(h,R),Y=[];break;case"select":G=ie({},G,{value:void 0}),R=ie({},R,{value:void 0}),Y=[];break;case"textarea":G=_t(h,G),R=_t(h,R),Y=[];break;default:typeof G.onClick!="function"&&typeof R.onClick=="function"&&(h.onclick=pd)}Ps(T,R);var de;T=null;for(We in G)if(!R.hasOwnProperty(We)&&G.hasOwnProperty(We)&&G[We]!=null)if(We==="style"){var we=G[We];for(de in we)we.hasOwnProperty(de)&&(T||(T={}),T[de]="")}else We!=="dangerouslySetInnerHTML"&&We!=="children"&&We!=="suppressContentEditableWarning"&&We!=="suppressHydrationWarning"&&We!=="autoFocus"&&(s.hasOwnProperty(We)?Y||(Y=[]):(Y=Y||[]).push(We,null));for(We in R){var Ae=R[We];if(we=G!=null?G[We]:void 0,R.hasOwnProperty(We)&&Ae!==we&&(Ae!=null||we!=null))if(We==="style")if(we){for(de in we)!we.hasOwnProperty(de)||Ae&&Ae.hasOwnProperty(de)||(T||(T={}),T[de]="");for(de in Ae)Ae.hasOwnProperty(de)&&we[de]!==Ae[de]&&(T||(T={}),T[de]=Ae[de])}else T||(Y||(Y=[]),Y.push(We,T)),T=Ae;else We==="dangerouslySetInnerHTML"?(Ae=Ae?Ae.__html:void 0,we=we?we.__html:void 0,Ae!=null&&we!==Ae&&(Y=Y||[]).push(We,Ae)):We==="children"?typeof Ae!="string"&&typeof Ae!="number"||(Y=Y||[]).push(We,""+Ae):We!=="suppressContentEditableWarning"&&We!=="suppressHydrationWarning"&&(s.hasOwnProperty(We)?(Ae!=null&&We==="onScroll"&&Fi("scroll",h),Y||we===Ae||(Y=[])):(Y=Y||[]).push(We,Ae))}T&&(Y=Y||[]).push("style",T);var We=Y;(v.updateQueue=We)&&(v.flags|=4)}},Vf=function(h,v,T,R){T!==R&&(v.flags|=4)};function $d(h,v){if(!Ji)switch(h.tailMode){case"hidden":v=h.tail;for(var T=null;v!==null;)v.alternate!==null&&(T=v),v=v.sibling;T===null?h.tail=null:T.sibling=null;break;case"collapsed":T=h.tail;for(var R=null;T!==null;)T.alternate!==null&&(R=T),T=T.sibling;R===null?v||h.tail===null?h.tail=null:h.tail.sibling=null:R.sibling=null}}function Kn(h){var v=h.alternate!==null&&h.alternate.child===h.child,T=0,R=0;if(v)for(var G=h.child;G!==null;)T|=G.lanes|G.childLanes,R|=G.subtreeFlags&14680064,R|=G.flags&14680064,G.return=h,G=G.sibling;else for(G=h.child;G!==null;)T|=G.lanes|G.childLanes,R|=G.subtreeFlags,R|=G.flags,G.return=h,G=G.sibling;return h.subtreeFlags|=R,h.childLanes=T,v}function _v(h,v,T){var R=v.pendingProps;switch(Wu(v),v.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Kn(v),null;case 1:return Cr(v.type)&&md(),Kn(v),null;case 3:return R=v.stateNode,Sa(),Gi(kr),Gi(lr),lh(),R.pendingContext&&(R.context=R.pendingContext,R.pendingContext=null),(h===null||h.child===null)&&(oc(v)?v.flags|=4:h===null||h.memoizedState.isDehydrated&&(v.flags&256)===0||(v.flags|=1024,Dr!==null&&(Hh(Dr),Dr=null))),Dh(h,v),Kn(v),null;case 5:oh(v);var G=wa(hl.current);if(T=v.type,h!==null&&v.stateNode!=null)Wf(h,v,T,R,G),h.ref!==v.ref&&(v.flags|=512,v.flags|=2097152);else{if(!R){if(v.stateNode===null)throw Error(n(166));return Kn(v),null}if(h=wa(Ks.current),oc(v)){R=v.stateNode,T=v.type;var Y=v.memoizedProps;switch(R[Ws]=v,R[rc]=Y,h=(v.mode&1)!==0,T){case"dialog":Fi("cancel",R),Fi("close",R);break;case"iframe":case"object":case"embed":Fi("load",R);break;case"video":case"audio":for(G=0;G<tc.length;G++)Fi(tc[G],R);break;case"source":Fi("error",R);break;case"img":case"image":case"link":Fi("error",R),Fi("load",R);break;case"details":Fi("toggle",R);break;case"input":ut(R,Y),Fi("invalid",R);break;case"select":R._wrapperState={wasMultiple:!!Y.multiple},Fi("invalid",R);break;case"textarea":ft(R,Y),Fi("invalid",R)}Ps(T,Y),G=null;for(var de in Y)if(Y.hasOwnProperty(de)){var we=Y[de];de==="children"?typeof we=="string"?R.textContent!==we&&(Y.suppressHydrationWarning!==!0&&hd(R.textContent,we,h),G=["children",we]):typeof we=="number"&&R.textContent!==""+we&&(Y.suppressHydrationWarning!==!0&&hd(R.textContent,we,h),G=["children",""+we]):s.hasOwnProperty(de)&&we!=null&&de==="onScroll"&&Fi("scroll",R)}switch(T){case"input":Qe(R),ht(R,Y,!0);break;case"textarea":Qe(R),ji(R);break;case"select":case"option":break;default:typeof Y.onClick=="function"&&(R.onclick=pd)}R=G,v.updateQueue=R,R!==null&&(v.flags|=4)}else{de=G.nodeType===9?G:G.ownerDocument,h==="http://www.w3.org/1999/xhtml"&&(h=Jn(T)),h==="http://www.w3.org/1999/xhtml"?T==="script"?(h=de.createElement("div"),h.innerHTML="<script><\/script>",h=h.removeChild(h.firstChild)):typeof R.is=="string"?h=de.createElement(T,{is:R.is}):(h=de.createElement(T),T==="select"&&(de=h,R.multiple?de.multiple=!0:R.size&&(de.size=R.size))):h=de.createElementNS(h,T),h[Ws]=v,h[rc]=R,jh(h,v,!1,!1),v.stateNode=h;e:{switch(de=_i(T,R),T){case"dialog":Fi("cancel",h),Fi("close",h),G=R;break;case"iframe":case"object":case"embed":Fi("load",h),G=R;break;case"video":case"audio":for(G=0;G<tc.length;G++)Fi(tc[G],h);G=R;break;case"source":Fi("error",h),G=R;break;case"img":case"image":case"link":Fi("error",h),Fi("load",h),G=R;break;case"details":Fi("toggle",h),G=R;break;case"input":ut(h,R),G=qt(h,R),Fi("invalid",h);break;case"option":G=R;break;case"select":h._wrapperState={wasMultiple:!!R.multiple},G=ie({},R,{value:void 0}),Fi("invalid",h);break;case"textarea":ft(h,R),G=_t(h,R),Fi("invalid",h);break;default:G=R}Ps(T,G),we=G;for(Y in we)if(we.hasOwnProperty(Y)){var Ae=we[Y];Y==="style"?Xa(h,Ae):Y==="dangerouslySetInnerHTML"?(Ae=Ae?Ae.__html:void 0,Ae!=null&&Bn(h,Ae)):Y==="children"?typeof Ae=="string"?(T!=="textarea"||Ae!=="")&&Wi(h,Ae):typeof Ae=="number"&&Wi(h,""+Ae):Y!=="suppressContentEditableWarning"&&Y!=="suppressHydrationWarning"&&Y!=="autoFocus"&&(s.hasOwnProperty(Y)?Ae!=null&&Y==="onScroll"&&Fi("scroll",h):Ae!=null&&E(h,Y,Ae,de))}switch(T){case"input":Qe(h),ht(h,R,!1);break;case"textarea":Qe(h),ji(h);break;case"option":R.value!=null&&h.setAttribute("value",""+re(R.value));break;case"select":h.multiple=!!R.multiple,Y=R.value,Y!=null?Ue(h,!!R.multiple,Y,!1):R.defaultValue!=null&&Ue(h,!!R.multiple,R.defaultValue,!0);break;default:typeof G.onClick=="function"&&(h.onclick=pd)}switch(T){case"button":case"input":case"select":case"textarea":R=!!R.autoFocus;break e;case"img":R=!0;break e;default:R=!1}}R&&(v.flags|=4)}v.ref!==null&&(v.flags|=512,v.flags|=2097152)}return Kn(v),null;case 6:if(h&&v.stateNode!=null)Vf(h,v,h.memoizedProps,R);else{if(typeof R!="string"&&v.stateNode===null)throw Error(n(166));if(T=wa(hl.current),wa(Ks.current),oc(v)){if(R=v.stateNode,T=v.memoizedProps,R[Ws]=v,(Y=R.nodeValue!==T)&&(h=jr,h!==null))switch(h.tag){case 3:hd(R.nodeValue,T,(h.mode&1)!==0);break;case 5:h.memoizedProps.suppressHydrationWarning!==!0&&hd(R.nodeValue,T,(h.mode&1)!==0)}Y&&(v.flags|=4)}else R=(T.nodeType===9?T:T.ownerDocument).createTextNode(R),R[Ws]=v,v.stateNode=R}return Kn(v),null;case 13:if(Gi(Qi),R=v.memoizedState,h===null||h.memoizedState!==null&&h.memoizedState.dehydrated!==null){if(Ji&&Fr!==null&&(v.mode&1)!==0&&(v.flags&128)===0)lf(),ba(),v.flags|=98560,Y=!1;else if(Y=oc(v),R!==null&&R.dehydrated!==null){if(h===null){if(!Y)throw Error(n(318));if(Y=v.memoizedState,Y=Y!==null?Y.dehydrated:null,!Y)throw Error(n(317));Y[Ws]=v}else ba(),(v.flags&128)===0&&(v.memoizedState=null),v.flags|=4;Kn(v),Y=!1}else Dr!==null&&(Hh(Dr),Dr=null),Y=!0;if(!Y)return v.flags&65536?v:null}return(v.flags&128)!==0?(v.lanes=T,v):(R=R!==null,R!==(h!==null&&h.memoizedState!==null)&&R&&(v.child.flags|=8192,(v.mode&1)!==0&&(h===null||(Qi.current&1)!==0?jn===0&&(jn=3):qh())),v.updateQueue!==null&&(v.flags|=4),Kn(v),null);case 4:return Sa(),Dh(h,v),h===null&&ic(v.stateNode.containerInfo),Kn(v),null;case 10:return ih(v.type._context),Kn(v),null;case 17:return Cr(v.type)&&md(),Kn(v),null;case 19:if(Gi(Qi),Y=v.memoizedState,Y===null)return Kn(v),null;if(R=(v.flags&128)!==0,de=Y.rendering,de===null)if(R)$d(Y,!1);else{if(jn!==0||h!==null&&(h.flags&128)!==0)for(h=v.child;h!==null;){if(de=Cd(h),de!==null){for(v.flags|=128,$d(Y,!1),R=de.updateQueue,R!==null&&(v.updateQueue=R,v.flags|=4),v.subtreeFlags=0,R=T,T=v.child;T!==null;)Y=T,h=R,Y.flags&=14680066,de=Y.alternate,de===null?(Y.childLanes=0,Y.lanes=h,Y.child=null,Y.subtreeFlags=0,Y.memoizedProps=null,Y.memoizedState=null,Y.updateQueue=null,Y.dependencies=null,Y.stateNode=null):(Y.childLanes=de.childLanes,Y.lanes=de.lanes,Y.child=de.child,Y.subtreeFlags=0,Y.deletions=null,Y.memoizedProps=de.memoizedProps,Y.memoizedState=de.memoizedState,Y.updateQueue=de.updateQueue,Y.type=de.type,h=de.dependencies,Y.dependencies=h===null?null:{lanes:h.lanes,firstContext:h.firstContext}),T=T.sibling;return Oi(Qi,Qi.current&1|2),v.child}h=h.sibling}Y.tail!==null&&Ei()>gl&&(v.flags|=128,R=!0,$d(Y,!1),v.lanes=4194304)}else{if(!R)if(h=Cd(de),h!==null){if(v.flags|=128,R=!0,T=h.updateQueue,T!==null&&(v.updateQueue=T,v.flags|=4),$d(Y,!0),Y.tail===null&&Y.tailMode==="hidden"&&!de.alternate&&!Ji)return Kn(v),null}else 2*Ei()-Y.renderingStartTime>gl&&T!==1073741824&&(v.flags|=128,R=!0,$d(Y,!1),v.lanes=4194304);Y.isBackwards?(de.sibling=v.child,v.child=de):(T=Y.last,T!==null?T.sibling=de:v.child=de,Y.last=de)}return Y.tail!==null?(v=Y.tail,Y.rendering=v,Y.tail=v.sibling,Y.renderingStartTime=Ei(),v.sibling=null,T=Qi.current,Oi(Qi,R?T&1|2:T&1),v):(Kn(v),null);case 22:case 23:return Vh(),R=v.memoizedState!==null,h!==null&&h.memoizedState!==null!==R&&(v.flags|=8192),R&&(v.mode&1)!==0?(Gr&1073741824)!==0&&(Kn(v),v.subtreeFlags&6&&(v.flags|=8192)):Kn(v),null;case 24:return null;case 25:return null}throw Error(n(156,v.tag))}function wv(h,v){switch(Wu(v),v.tag){case 1:return Cr(v.type)&&md(),h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 3:return Sa(),Gi(kr),Gi(lr),lh(),h=v.flags,(h&65536)!==0&&(h&128)===0?(v.flags=h&-65537|128,v):null;case 5:return oh(v),null;case 13:if(Gi(Qi),h=v.memoizedState,h!==null&&h.dehydrated!==null){if(v.alternate===null)throw Error(n(340));ba()}return h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 19:return Gi(Qi),null;case 4:return Sa(),null;case 10:return ih(v.type._context),null;case 22:case 23:return Vh(),null;case 24:return null;default:return null}}var Ah=!1,Yn=!1,Sv=typeof WeakSet=="function"?WeakSet:Set,It=null;function fl(h,v){var T=h.ref;if(T!==null)if(typeof T=="function")try{T(null)}catch(R){en(h,v,R)}else T.current=null}function Nh(h,v,T){try{T()}catch(R){en(h,v,R)}}var qf=!1;function kv(h,v){if(Ou=Mo,h=Du(),Au(h)){if("selectionStart"in h)var T={start:h.selectionStart,end:h.selectionEnd};else e:{T=(T=h.ownerDocument)&&T.defaultView||window;var R=T.getSelection&&T.getSelection();if(R&&R.rangeCount!==0){T=R.anchorNode;var G=R.anchorOffset,Y=R.focusNode;R=R.focusOffset;try{T.nodeType,Y.nodeType}catch{T=null;break e}var de=0,we=-1,Ae=-1,We=0,lt=0,ct=h,at=null;t:for(;;){for(var Tt;ct!==T||G!==0&&ct.nodeType!==3||(we=de+G),ct!==Y||R!==0&&ct.nodeType!==3||(Ae=de+R),ct.nodeType===3&&(de+=ct.nodeValue.length),(Tt=ct.firstChild)!==null;)at=ct,ct=Tt;for(;;){if(ct===h)break t;if(at===T&&++We===G&&(we=de),at===Y&&++lt===R&&(Ae=de),(Tt=ct.nextSibling)!==null)break;ct=at,at=ct.parentNode}ct=Tt}T=we===-1||Ae===-1?null:{start:we,end:Ae}}else T=null}T=T||{start:0,end:0}}else T=null;for(Lu={focusedElem:h,selectionRange:T},Mo=!1,It=v;It!==null;)if(v=It,h=v.child,(v.subtreeFlags&1028)!==0&&h!==null)h.return=v,It=h;else for(;It!==null;){v=It;try{var Mt=v.alternate;if((v.flags&1024)!==0)switch(v.tag){case 0:case 11:case 15:break;case 1:if(Mt!==null){var Ot=Mt.memoizedProps,Li=Mt.memoizedState,Ge=v.stateNode,Re=Ge.getSnapshotBeforeUpdate(v.elementType===v.type?Ot:yn(v.type,Ot),Li);Ge.__reactInternalSnapshotBeforeUpdate=Re}break;case 3:var qe=v.stateNode.containerInfo;qe.nodeType===1?qe.textContent="":qe.nodeType===9&&qe.documentElement&&qe.removeChild(qe.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}catch(mt){en(v,v.return,mt)}if(h=v.sibling,h!==null){h.return=v.return,It=h;break}It=v.return}return Mt=qf,qf=!1,Mt}function pc(h,v,T){var R=v.updateQueue;if(R=R!==null?R.lastEffect:null,R!==null){var G=R=R.next;do{if((G.tag&h)===h){var Y=G.destroy;G.destroy=void 0,Y!==void 0&&Nh(v,T,Y)}G=G.next}while(G!==R)}}function $h(h,v){if(v=v.updateQueue,v=v!==null?v.lastEffect:null,v!==null){var T=v=v.next;do{if((T.tag&h)===h){var R=T.create;T.destroy=R()}T=T.next}while(T!==v)}}function Ph(h){var v=h.ref;if(v!==null){var T=h.stateNode;switch(h.tag){case 5:h=T;break;default:h=T}typeof v=="function"?v(h):v.current=h}}function Kf(h){var v=h.alternate;v!==null&&(h.alternate=null,Kf(v)),h.child=null,h.deletions=null,h.sibling=null,h.tag===5&&(v=h.stateNode,v!==null&&(delete v[Ws],delete v[rc],delete v[Gu],delete v[tf],delete v[nf])),h.stateNode=null,h.return=null,h.dependencies=null,h.memoizedProps=null,h.memoizedState=null,h.pendingProps=null,h.stateNode=null,h.updateQueue=null}function Yf(h){return h.tag===5||h.tag===3||h.tag===4}function Xf(h){e:for(;;){for(;h.sibling===null;){if(h.return===null||Yf(h.return))return null;h=h.return}for(h.sibling.return=h.return,h=h.sibling;h.tag!==5&&h.tag!==6&&h.tag!==18;){if(h.flags&2||h.child===null||h.tag===4)continue e;h.child.return=h,h=h.child}if(!(h.flags&2))return h.stateNode}}function Rh(h,v,T){var R=h.tag;if(R===5||R===6)h=h.stateNode,v?T.nodeType===8?T.parentNode.insertBefore(h,v):T.insertBefore(h,v):(T.nodeType===8?(v=T.parentNode,v.insertBefore(h,T)):(v=T,v.appendChild(h)),T=T._reactRootContainer,T!=null||v.onclick!==null||(v.onclick=pd));else if(R!==4&&(h=h.child,h!==null))for(Rh(h,v,T),h=h.sibling;h!==null;)Rh(h,v,T),h=h.sibling}function Ih(h,v,T){var R=h.tag;if(R===5||R===6)h=h.stateNode,v?T.insertBefore(h,v):T.appendChild(h);else if(R!==4&&(h=h.child,h!==null))for(Ih(h,v,T),h=h.sibling;h!==null;)Ih(h,v,T),h=h.sibling}var Pn=null,ks=!1;function Ho(h,v,T){for(T=T.child;T!==null;)Cv(h,v,T),T=T.sibling}function Cv(h,v,T){if(kn&&typeof kn.onCommitFiberUnmount=="function")try{kn.onCommitFiberUnmount(_r,T)}catch{}switch(T.tag){case 5:Yn||fl(T,v);case 6:var R=Pn,G=ks;Pn=null,Ho(h,v,T),Pn=R,ks=G,Pn!==null&&(ks?(h=Pn,T=T.stateNode,h.nodeType===8?h.parentNode.removeChild(T):h.removeChild(T)):Pn.removeChild(T.stateNode));break;case 18:Pn!==null&&(ks?(h=Pn,T=T.stateNode,h.nodeType===8?Fu(h.parentNode,T):h.nodeType===1&&Fu(h,T),oo(h)):Fu(Pn,T.stateNode));break;case 4:R=Pn,G=ks,Pn=T.stateNode.containerInfo,ks=!0,Ho(h,v,T),Pn=R,ks=G;break;case 0:case 11:case 14:case 15:if(!Yn&&(R=T.updateQueue,R!==null&&(R=R.lastEffect,R!==null))){G=R=R.next;do{var Y=G,de=Y.destroy;Y=Y.tag,de!==void 0&&((Y&2)!==0||(Y&4)!==0)&&Nh(T,v,de),G=G.next}while(G!==R)}Ho(h,v,T);break;case 1:if(!Yn&&(fl(T,v),R=T.stateNode,typeof R.componentWillUnmount=="function"))try{R.props=T.memoizedProps,R.state=T.memoizedState,R.componentWillUnmount()}catch(we){en(T,v,we)}Ho(h,v,T);break;case 21:Ho(h,v,T);break;case 22:T.mode&1?(Yn=(R=Yn)||T.memoizedState!==null,Ho(h,v,T),Yn=R):Ho(h,v,T);break;default:Ho(h,v,T)}}function fc(h){var v=h.updateQueue;if(v!==null){h.updateQueue=null;var T=h.stateNode;T===null&&(T=h.stateNode=new Sv),v.forEach(function(R){var G=$v.bind(null,h,R);T.has(R)||(T.add(R),R.then(G,G))})}}function ns(h,v){var T=v.deletions;if(T!==null)for(var R=0;R<T.length;R++){var G=T[R];try{var Y=h,de=v,we=de;e:for(;we!==null;){switch(we.tag){case 5:Pn=we.stateNode,ks=!1;break e;case 3:Pn=we.stateNode.containerInfo,ks=!0;break e;case 4:Pn=we.stateNode.containerInfo,ks=!0;break e}we=we.return}if(Pn===null)throw Error(n(160));Cv(Y,de,G),Pn=null,ks=!1;var Ae=G.alternate;Ae!==null&&(Ae.return=null),G.return=null}catch(We){en(G,v,We)}}if(v.subtreeFlags&12854)for(v=v.child;v!==null;)Mh(v,h),v=v.sibling}function Mh(h,v){var T=h.alternate,R=h.flags;switch(h.tag){case 0:case 11:case 14:case 15:if(ns(v,h),Cs(h),R&4){try{pc(3,h,h.return),$h(3,h)}catch(Ot){en(h,h.return,Ot)}try{pc(5,h,h.return)}catch(Ot){en(h,h.return,Ot)}}break;case 1:ns(v,h),Cs(h),R&512&&T!==null&&fl(T,T.return);break;case 5:if(ns(v,h),Cs(h),R&512&&T!==null&&fl(T,T.return),h.flags&32){var G=h.stateNode;try{Wi(G,"")}catch(Ot){en(h,h.return,Ot)}}if(R&4&&(G=h.stateNode,G!=null)){var Y=h.memoizedProps,de=T!==null?T.memoizedProps:Y,we=h.type,Ae=h.updateQueue;if(h.updateQueue=null,Ae!==null)try{we==="input"&&Y.type==="radio"&&Y.name!=null&&nt(G,Y),_i(we,de);var We=_i(we,Y);for(de=0;de<Ae.length;de+=2){var lt=Ae[de],ct=Ae[de+1];lt==="style"?Xa(G,ct):lt==="dangerouslySetInnerHTML"?Bn(G,ct):lt==="children"?Wi(G,ct):E(G,lt,ct,We)}switch(we){case"input":Le(G,Y);break;case"textarea":ui(G,Y);break;case"select":var at=G._wrapperState.wasMultiple;G._wrapperState.wasMultiple=!!Y.multiple;var Tt=Y.value;Tt!=null?Ue(G,!!Y.multiple,Tt,!1):at!==!!Y.multiple&&(Y.defaultValue!=null?Ue(G,!!Y.multiple,Y.defaultValue,!0):Ue(G,!!Y.multiple,Y.multiple?[]:"",!1))}G[rc]=Y}catch(Ot){en(h,h.return,Ot)}}break;case 6:if(ns(v,h),Cs(h),R&4){if(h.stateNode===null)throw Error(n(162));G=h.stateNode,Y=h.memoizedProps;try{G.nodeValue=Y}catch(Ot){en(h,h.return,Ot)}}break;case 3:if(ns(v,h),Cs(h),R&4&&T!==null&&T.memoizedState.isDehydrated)try{oo(v.containerInfo)}catch(Ot){en(h,h.return,Ot)}break;case 4:ns(v,h),Cs(h);break;case 13:ns(v,h),Cs(h),G=h.child,G.flags&8192&&(Y=G.memoizedState!==null,G.stateNode.isHidden=Y,!Y||G.alternate!==null&&G.alternate.memoizedState!==null||(Bh=Ei())),R&4&&fc(h);break;case 22:if(lt=T!==null&&T.memoizedState!==null,h.mode&1?(Yn=(We=Yn)||lt,ns(v,h),Yn=We):ns(v,h),Cs(h),R&8192){if(We=h.memoizedState!==null,(h.stateNode.isHidden=We)&&!lt&&(h.mode&1)!==0)for(It=h,lt=h.child;lt!==null;){for(ct=It=lt;It!==null;){switch(at=It,Tt=at.child,at.tag){case 0:case 11:case 14:case 15:pc(4,at,at.return);break;case 1:fl(at,at.return);var Mt=at.stateNode;if(typeof Mt.componentWillUnmount=="function"){R=at,T=at.return;try{v=R,Mt.props=v.memoizedProps,Mt.state=v.memoizedState,Mt.componentWillUnmount()}catch(Ot){en(R,T,Ot)}}break;case 5:fl(at,at.return);break;case 22:if(at.memoizedState!==null){Oh(ct);continue}}Tt!==null?(Tt.return=at,It=Tt):Oh(ct)}lt=lt.sibling}e:for(lt=null,ct=h;;){if(ct.tag===5){if(lt===null){lt=ct;try{G=ct.stateNode,We?(Y=G.style,typeof Y.setProperty=="function"?Y.setProperty("display","none","important"):Y.display="none"):(we=ct.stateNode,Ae=ct.memoizedProps.style,de=Ae!=null&&Ae.hasOwnProperty("display")?Ae.display:null,we.style.display=$s("display",de))}catch(Ot){en(h,h.return,Ot)}}}else if(ct.tag===6){if(lt===null)try{ct.stateNode.nodeValue=We?"":ct.memoizedProps}catch(Ot){en(h,h.return,Ot)}}else if((ct.tag!==22&&ct.tag!==23||ct.memoizedState===null||ct===h)&&ct.child!==null){ct.child.return=ct,ct=ct.child;continue}if(ct===h)break e;for(;ct.sibling===null;){if(ct.return===null||ct.return===h)break e;lt===ct&&(lt=null),ct=ct.return}lt===ct&&(lt=null),ct.sibling.return=ct.return,ct=ct.sibling}}break;case 19:ns(v,h),Cs(h),R&4&&fc(h);break;case 21:break;default:ns(v,h),Cs(h)}}function Cs(h){var v=h.flags;if(v&2){try{e:{for(var T=h.return;T!==null;){if(Yf(T)){var R=T;break e}T=T.return}throw Error(n(160))}switch(R.tag){case 5:var G=R.stateNode;R.flags&32&&(Wi(G,""),R.flags&=-33);var Y=Xf(h);Ih(h,Y,G);break;case 3:case 4:var de=R.stateNode.containerInfo,we=Xf(h);Rh(h,we,de);break;default:throw Error(n(161))}}catch(Ae){en(h,h.return,Ae)}h.flags&=-3}v&4096&&(h.flags&=-4097)}function Jf(h,v,T){It=h,Zf(h)}function Zf(h,v,T){for(var R=(h.mode&1)!==0;It!==null;){var G=It,Y=G.child;if(G.tag===22&&R){var de=G.memoizedState!==null||Ah;if(!de){var we=G.alternate,Ae=we!==null&&we.memoizedState!==null||Yn;we=Ah;var We=Yn;if(Ah=de,(Yn=Ae)&&!We)for(It=G;It!==null;)de=It,Ae=de.child,de.tag===22&&de.memoizedState!==null?Lh(G):Ae!==null?(Ae.return=de,It=Ae):Lh(G);for(;Y!==null;)It=Y,Zf(Y),Y=Y.sibling;It=G,Ah=we,Yn=We}Qf(h)}else(G.subtreeFlags&8772)!==0&&Y!==null?(Y.return=G,It=Y):Qf(h)}}function Qf(h){for(;It!==null;){var v=It;if((v.flags&8772)!==0){var T=v.alternate;try{if((v.flags&8772)!==0)switch(v.tag){case 0:case 11:case 15:Yn||$h(5,v);break;case 1:var R=v.stateNode;if(v.flags&4&&!Yn)if(T===null)R.componentDidMount();else{var G=v.elementType===v.type?T.memoizedProps:yn(v.type,T.memoizedProps);R.componentDidUpdate(G,T.memoizedState,R.__reactInternalSnapshotBeforeUpdate)}var Y=v.updateQueue;Y!==null&&cv(v,Y,R);break;case 3:var de=v.updateQueue;if(de!==null){if(T=null,v.child!==null)switch(v.child.tag){case 5:T=v.child.stateNode;break;case 1:T=v.child.stateNode}cv(v,de,T)}break;case 5:var we=v.stateNode;if(T===null&&v.flags&4){T=we;var Ae=v.memoizedProps;switch(v.type){case"button":case"input":case"select":case"textarea":Ae.autoFocus&&T.focus();break;case"img":Ae.src&&(T.src=Ae.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(v.memoizedState===null){var We=v.alternate;if(We!==null){var lt=We.memoizedState;if(lt!==null){var ct=lt.dehydrated;ct!==null&&oo(ct)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(n(163))}Yn||v.flags&512&&Ph(v)}catch(at){en(v,v.return,at)}}if(v===h){It=null;break}if(T=v.sibling,T!==null){T.return=v.return,It=T;break}It=v.return}}function Oh(h){for(;It!==null;){var v=It;if(v===h){It=null;break}var T=v.sibling;if(T!==null){T.return=v.return,It=T;break}It=v.return}}function Lh(h){for(;It!==null;){var v=It;try{switch(v.tag){case 0:case 11:case 15:var T=v.return;try{$h(4,v)}catch(Ae){en(v,T,Ae)}break;case 1:var R=v.stateNode;if(typeof R.componentDidMount=="function"){var G=v.return;try{R.componentDidMount()}catch(Ae){en(v,G,Ae)}}var Y=v.return;try{Ph(v)}catch(Ae){en(v,Y,Ae)}break;case 5:var de=v.return;try{Ph(v)}catch(Ae){en(v,de,Ae)}}}catch(Ae){en(v,v.return,Ae)}if(v===h){It=null;break}var we=v.sibling;if(we!==null){we.return=v.return,It=we;break}It=v.return}}var Ev=Math.ceil,Pd=j.ReactCurrentDispatcher,Rd=j.ReactCurrentOwner,rs=j.ReactCurrentBatchConfig,bi=0,_n=null,vn=null,Rn=0,Gr=0,ml=lo(0),jn=0,mc=null,Ta=0,Id=0,zh=0,Md=null,Nr=null,Bh=0,gl=1/0,Wo=null,Od=!1,Fh=null,Vo=null,Ld=!1,ja=null,zd=0,gc=0,Gh=null,vc=-1,Bd=0;function ur(){return(bi&6)!==0?Ei():vc!==-1?vc:vc=Ei()}function qo(h){return(h.mode&1)===0?1:(bi&2)!==0&&Rn!==0?Rn&-Rn:Zu.transition!==null?(Bd===0&&(Bd=Br()),Bd):(h=Ie,h!==0||(h=window.event,h=h===void 0?16:pe(h.type)),h)}function Es(h,v,T,R){if(50<gc)throw gc=0,Gh=null,Error(n(185));ir(h,T,R),((bi&2)===0||h!==_n)&&(h===_n&&((bi&2)===0&&(Id|=T),jn===4&&Ko(h,Rn)),$r(h,R),T===1&&bi===0&&(v.mode&1)===0&&(gl=Ei()+500,vd&&Bo()))}function $r(h,v){var T=h.callbackNode;Sr(h,v);var R=Bs(h,h===_n?Rn:0);if(R===0)T!==null&&$n(T),h.callbackNode=null,h.callbackPriority=0;else if(v=R&-R,h.callbackPriority!==v){if(T!=null&&$n(T),v===1)h.tag===0?ny(im.bind(null,h)):af(im.bind(null,h)),sv(function(){(bi&6)===0&&Bo()}),T=null;else{switch(Ze(R)){case 1:T=Yi;break;case 4:T=Hn;break;case 16:T=ms;break;case 536870912:T=Os;break;default:T=ms}T=lm(T,em.bind(null,h))}h.callbackPriority=v,h.callbackNode=T}}function em(h,v){if(vc=-1,Bd=0,(bi&6)!==0)throw Error(n(327));var T=h.callbackNode;if(vl()&&h.callbackNode!==T)return null;var R=Bs(h,h===_n?Rn:0);if(R===0)return null;if((R&30)!==0||(R&h.expiredLanes)!==0||v)v=Fd(h,R);else{v=R;var G=bi;bi|=2;var Y=Tv();(_n!==h||Rn!==v)&&(Wo=null,gl=Ei()+500,Aa(h,v));do try{ay();break}catch(we){nm(h,we)}while(!0);th(),Pd.current=Y,bi=G,vn!==null?v=0:(_n=null,Rn=0,v=jn)}if(v!==0){if(v===2&&(G=ro(h),G!==0&&(R=G,v=Uh(h,G))),v===1)throw T=mc,Aa(h,0),Ko(h,R),$r(h,Ei()),T;if(v===6)Ko(h,R);else{if(G=h.current.alternate,(R&30)===0&&!tm(G)&&(v=Fd(h,R),v===2&&(Y=ro(h),Y!==0&&(R=Y,v=Uh(h,Y))),v===1))throw T=mc,Aa(h,0),Ko(h,R),$r(h,Ei()),T;switch(h.finishedWork=G,h.finishedLanes=R,v){case 0:case 1:throw Error(n(345));case 2:Na(h,Nr,Wo);break;case 3:if(Ko(h,R),(R&130023424)===R&&(v=Bh+500-Ei(),10<v)){if(Bs(h,0)!==0)break;if(G=h.suspendedLanes,(G&R)!==R){ur(),h.pingedLanes|=h.suspendedLanes&G;break}h.timeoutHandle=Bu(Na.bind(null,h,Nr,Wo),v);break}Na(h,Nr,Wo);break;case 4:if(Ko(h,R),(R&4194240)===R)break;for(v=h.eventTimes,G=-1;0<R;){var de=31-Xi(R);Y=1<<de,de=v[de],de>G&&(G=de),R&=~Y}if(R=G,R=Ei()-R,R=(120>R?120:480>R?480:1080>R?1080:1920>R?1920:3e3>R?3e3:4320>R?4320:1960*Ev(R/1960))-R,10<R){h.timeoutHandle=Bu(Na.bind(null,h,Nr,Wo),R);break}Na(h,Nr,Wo);break;case 5:Na(h,Nr,Wo);break;default:throw Error(n(329))}}}return $r(h,Ei()),h.callbackNode===T?em.bind(null,h):null}function Uh(h,v){var T=Md;return h.current.memoizedState.isDehydrated&&(Aa(h,v).flags|=256),h=Fd(h,v),h!==2&&(v=Nr,Nr=T,v!==null&&Hh(v)),h}function Hh(h){Nr===null?Nr=h:Nr.push.apply(Nr,h)}function tm(h){for(var v=h;;){if(v.flags&16384){var T=v.updateQueue;if(T!==null&&(T=T.stores,T!==null))for(var R=0;R<T.length;R++){var G=T[R],Y=G.getSnapshot;G=G.value;try{if(!_s(Y(),G))return!1}catch{return!1}}}if(T=v.child,v.subtreeFlags&16384&&T!==null)T.return=v,v=T;else{if(v===h)break;for(;v.sibling===null;){if(v.return===null||v.return===h)return!0;v=v.return}v.sibling.return=v.return,v=v.sibling}}return!0}function Ko(h,v){for(v&=~zh,v&=~Id,h.suspendedLanes|=v,h.pingedLanes&=~v,h=h.expirationTimes;0<v;){var T=31-Xi(v),R=1<<T;h[T]=-1,v&=~R}}function im(h){if((bi&6)!==0)throw Error(n(327));vl();var v=Bs(h,0);if((v&1)===0)return $r(h,Ei()),null;var T=Fd(h,v);if(h.tag!==0&&T===2){var R=ro(h);R!==0&&(v=R,T=Uh(h,R))}if(T===1)throw T=mc,Aa(h,0),Ko(h,v),$r(h,Ei()),T;if(T===6)throw Error(n(345));return h.finishedWork=h.current.alternate,h.finishedLanes=v,Na(h,Nr,Wo),$r(h,Ei()),null}function Wh(h,v){var T=bi;bi|=1;try{return h(v)}finally{bi=T,bi===0&&(gl=Ei()+500,vd&&Bo())}}function Da(h){ja!==null&&ja.tag===0&&(bi&6)===0&&vl();var v=bi;bi|=1;var T=rs.transition,R=Ie;try{if(rs.transition=null,Ie=1,h)return h()}finally{Ie=R,rs.transition=T,bi=v,(bi&6)===0&&Bo()}}function Vh(){Gr=ml.current,Gi(ml)}function Aa(h,v){h.finishedWork=null,h.finishedLanes=0;var T=h.timeoutHandle;if(T!==-1&&(h.timeoutHandle=-1,rv(T)),vn!==null)for(T=vn.return;T!==null;){var R=T;switch(Wu(R),R.tag){case 1:R=R.type.childContextTypes,R!=null&&md();break;case 3:Sa(),Gi(kr),Gi(lr),lh();break;case 5:oh(R);break;case 4:Sa();break;case 13:Gi(Qi);break;case 19:Gi(Qi);break;case 10:ih(R.type._context);break;case 22:case 23:Vh()}T=T.return}if(_n=h,vn=h=Yo(h.current,null),Rn=Gr=v,jn=0,mc=null,zh=Id=Ta=0,Nr=Md=null,ul!==null){for(v=0;v<ul.length;v++)if(T=ul[v],R=T.interleaved,R!==null){T.interleaved=null;var G=R.next,Y=T.pending;if(Y!==null){var de=Y.next;Y.next=G,R.next=de}T.pending=R}ul=null}return h}function nm(h,v){do{var T=vn;try{if(th(),ch.current=Dd,uh){for(var R=Zi.memoizedState;R!==null;){var G=R.queue;G!==null&&(G.pending=null),R=R.next}uh=!1}if(ka=0,Tn=bn=Zi=null,Ca=!1,Uo=0,Rd.current=null,T===null||T.return===null){jn=1,mc=v,vn=null;break}e:{var Y=h,de=T.return,we=T,Ae=v;if(v=Rn,we.flags|=32768,Ae!==null&&typeof Ae=="object"&&typeof Ae.then=="function"){var We=Ae,lt=we,ct=lt.tag;if((lt.mode&1)===0&&(ct===0||ct===11||ct===15)){var at=lt.alternate;at?(lt.updateQueue=at.updateQueue,lt.memoizedState=at.memoizedState,lt.lanes=at.lanes):(lt.updateQueue=null,lt.memoizedState=null)}var Tt=xv(de);if(Tt!==null){Tt.flags&=-257,dr(Tt,de,we,Y,v),Tt.mode&1&&Mf(Y,We,v),v=Tt,Ae=We;var Mt=v.updateQueue;if(Mt===null){var Ot=new Set;Ot.add(Ae),v.updateQueue=Ot}else Mt.add(Ae);break e}else{if((v&1)===0){Mf(Y,We,v),qh();break e}Ae=Error(n(426))}}else if(Ji&&we.mode&1){var Li=xv(de);if(Li!==null){(Li.flags&65536)===0&&(Li.flags|=256),dr(Li,de,we,Y,v),Ju(pl(Ae,we));break e}}Y=Ae=pl(Ae,we),jn!==4&&(jn=2),Md===null?Md=[Y]:Md.push(Y),Y=de;do{switch(Y.tag){case 3:Y.flags|=65536,v&=-v,Y.lanes|=v;var Ge=Rf(Y,Ae,v);lv(Y,Ge);break e;case 1:we=Ae;var Re=Y.type,qe=Y.stateNode;if((Y.flags&128)===0&&(typeof Re.getDerivedStateFromError=="function"||qe!==null&&typeof qe.componentDidCatch=="function"&&(Vo===null||!Vo.has(qe)))){Y.flags|=65536,v&=-v,Y.lanes|=v;var mt=If(Y,we,v);lv(Y,mt);break e}}Y=Y.return}while(Y!==null)}xc(T)}catch(Ut){v=Ut,vn===T&&T!==null&&(vn=T=T.return);continue}break}while(!0)}function Tv(){var h=Pd.current;return Pd.current=Dd,h===null?Dd:h}function qh(){(jn===0||jn===3||jn===2)&&(jn=4),_n===null||(Ta&268435455)===0&&(Id&268435455)===0||Ko(_n,Rn)}function Fd(h,v){var T=bi;bi|=2;var R=Tv();(_n!==h||Rn!==v)&&(Wo=null,Aa(h,v));do try{jv();break}catch(G){nm(h,G)}while(!0);if(th(),bi=T,Pd.current=R,vn!==null)throw Error(n(261));return _n=null,Rn=0,jn}function jv(){for(;vn!==null;)rm(vn)}function ay(){for(;vn!==null&&!Za();)rm(vn)}function rm(h){var v=am(h.alternate,h,Gr);h.memoizedProps=h.pendingProps,v===null?xc(h):vn=v,Rd.current=null}function xc(h){var v=h;do{var T=v.alternate;if(h=v.return,(v.flags&32768)===0){if(T=_v(T,v,Gr),T!==null){vn=T;return}}else{if(T=wv(T,v),T!==null){T.flags&=32767,vn=T;return}if(h!==null)h.flags|=32768,h.subtreeFlags=0,h.deletions=null;else{jn=6,vn=null;return}}if(v=v.sibling,v!==null){vn=v;return}vn=v=h}while(v!==null);jn===0&&(jn=5)}function Na(h,v,T){var R=Ie,G=rs.transition;try{rs.transition=null,Ie=1,sm(h,v,T,R)}finally{rs.transition=G,Ie=R}return null}function sm(h,v,T,R){do vl();while(ja!==null);if((bi&6)!==0)throw Error(n(327));T=h.finishedWork;var G=h.finishedLanes;if(T===null)return null;if(h.finishedWork=null,h.finishedLanes=0,T===h.current)throw Error(n(177));h.callbackNode=null,h.callbackPriority=0;var Y=T.lanes|T.childLanes;if(gt(h,Y),h===_n&&(vn=_n=null,Rn=0),(T.subtreeFlags&2064)===0&&(T.flags&2064)===0||Ld||(Ld=!0,lm(ms,function(){return vl(),null})),Y=(T.flags&15990)!==0,(T.subtreeFlags&15990)!==0||Y){Y=rs.transition,rs.transition=null;var de=Ie;Ie=1;var we=bi;bi|=4,Rd.current=null,kv(h,T),Mh(T,h),Qg(Lu),Mo=!!Ou,Lu=Ou=null,h.current=T,Jf(T),Qa(),bi=we,Ie=de,rs.transition=Y}else h.current=T;if(Ld&&(Ld=!1,ja=h,zd=G),Y=h.pendingLanes,Y===0&&(Vo=null),Ft(T.stateNode),$r(h,Ei()),v!==null)for(R=h.onRecoverableError,T=0;T<v.length;T++)G=v[T],R(G.value,{componentStack:G.stack,digest:G.digest});if(Od)throw Od=!1,h=Fh,Fh=null,h;return(zd&1)!==0&&h.tag!==0&&vl(),Y=h.pendingLanes,(Y&1)!==0?h===Gh?gc++:(gc=0,Gh=h):gc=0,Bo(),null}function vl(){if(ja!==null){var h=Ze(zd),v=rs.transition,T=Ie;try{if(rs.transition=null,Ie=16>h?16:h,ja===null)var R=!1;else{if(h=ja,ja=null,zd=0,(bi&6)!==0)throw Error(n(331));var G=bi;for(bi|=4,It=h.current;It!==null;){var Y=It,de=Y.child;if((It.flags&16)!==0){var we=Y.deletions;if(we!==null){for(var Ae=0;Ae<we.length;Ae++){var We=we[Ae];for(It=We;It!==null;){var lt=It;switch(lt.tag){case 0:case 11:case 15:pc(8,lt,Y)}var ct=lt.child;if(ct!==null)ct.return=lt,It=ct;else for(;It!==null;){lt=It;var at=lt.sibling,Tt=lt.return;if(Kf(lt),lt===We){It=null;break}if(at!==null){at.return=Tt,It=at;break}It=Tt}}}var Mt=Y.alternate;if(Mt!==null){var Ot=Mt.child;if(Ot!==null){Mt.child=null;do{var Li=Ot.sibling;Ot.sibling=null,Ot=Li}while(Ot!==null)}}It=Y}}if((Y.subtreeFlags&2064)!==0&&de!==null)de.return=Y,It=de;else e:for(;It!==null;){if(Y=It,(Y.flags&2048)!==0)switch(Y.tag){case 0:case 11:case 15:pc(9,Y,Y.return)}var Ge=Y.sibling;if(Ge!==null){Ge.return=Y.return,It=Ge;break e}It=Y.return}}var Re=h.current;for(It=Re;It!==null;){de=It;var qe=de.child;if((de.subtreeFlags&2064)!==0&&qe!==null)qe.return=de,It=qe;else e:for(de=Re;It!==null;){if(we=It,(we.flags&2048)!==0)try{switch(we.tag){case 0:case 11:case 15:$h(9,we)}}catch(Ut){en(we,we.return,Ut)}if(we===de){It=null;break e}var mt=we.sibling;if(mt!==null){mt.return=we.return,It=mt;break e}It=we.return}}if(bi=G,Bo(),kn&&typeof kn.onPostCommitFiberRoot=="function")try{kn.onPostCommitFiberRoot(_r,h)}catch{}R=!0}return R}finally{Ie=T,rs.transition=v}}return!1}function om(h,v,T){v=pl(T,v),v=Rf(h,v,1),h=Go(h,v,1),v=ur(),h!==null&&(ir(h,1,v),$r(h,v))}function en(h,v,T){if(h.tag===3)om(h,h,T);else for(;v!==null;){if(v.tag===3){om(v,h,T);break}else if(v.tag===1){var R=v.stateNode;if(typeof v.type.getDerivedStateFromError=="function"||typeof R.componentDidCatch=="function"&&(Vo===null||!Vo.has(R))){h=pl(T,h),h=If(v,h,1),v=Go(v,h,1),h=ur(),v!==null&&(ir(v,1,h),$r(v,h));break}}v=v.return}}function Dv(h,v,T){var R=h.pingCache;R!==null&&R.delete(v),v=ur(),h.pingedLanes|=h.suspendedLanes&T,_n===h&&(Rn&T)===T&&(jn===4||jn===3&&(Rn&130023424)===Rn&&500>Ei()-Bh?Aa(h,0):zh|=T),$r(h,v)}function Av(h,v){v===0&&((h.mode&1)===0?v=1:(v=tr,tr<<=1,(tr&130023424)===0&&(tr=4194304)));var T=ur();h=uo(h,v),h!==null&&(ir(h,v,T),$r(h,T))}function Nv(h){var v=h.memoizedState,T=0;v!==null&&(T=v.retryLane),Av(h,T)}function $v(h,v){var T=0;switch(h.tag){case 13:var R=h.stateNode,G=h.memoizedState;G!==null&&(T=G.retryLane);break;case 19:R=h.stateNode;break;default:throw Error(n(314))}R!==null&&R.delete(v),Av(h,T)}var am;am=function(h,v,T){if(h!==null)if(h.memoizedProps!==v.pendingProps||kr.current)Ar=!0;else{if((h.lanes&T)===0&&(v.flags&128)===0)return Ar=!1,oy(h,v,T);Ar=(h.flags&131072)!==0}else Ar=!1,Ji&&(v.flags&1048576)!==0&&xa(v,bd,v.index);switch(v.lanes=0,v.tag){case 2:var R=v.type;Nd(h,v),h=v.pendingProps;var G=cr(v,lr.current);dl(v,T),G=ph(null,v,R,h,G,T);var Y=fh();return v.flags|=1,typeof G=="object"&&G!==null&&typeof G.render=="function"&&G.$$typeof===void 0?(v.tag=1,v.memoizedState=null,v.updateQueue=null,Cr(R)?(Y=!0,gd(v)):Y=!1,v.memoizedState=G.state!==null&&G.state!==void 0?G.state:null,Sd(v),G.updater=po,v.stateNode=G,G._reactInternals=v,xh(v,R,h,T),v=wh(null,v,R,!0,Y,T)):(v.tag=0,Ji&&Y&&xn(v),qn(null,v,G,T),v=v.child),v;case 16:R=v.elementType;e:{switch(Nd(h,v),h=v.pendingProps,G=R._init,R=G(R._payload),v.type=R,G=v.tag=Pv(R),h=yn(R,h),G){case 0:v=_h(null,v,R,h,T);break e;case 1:v=Ff(null,v,R,h,T);break e;case 11:v=Of(null,v,R,h,T);break e;case 14:v=uc(null,v,R,yn(R.type,h),T);break e}throw Error(n(306,R,""))}return v;case 0:return R=v.type,G=v.pendingProps,G=v.elementType===R?G:yn(R,G),_h(h,v,R,G,T);case 1:return R=v.type,G=v.pendingProps,G=v.elementType===R?G:yn(R,G),Ff(h,v,R,G,T);case 3:e:{if(Sh(v),h===null)throw Error(n(387));R=v.pendingProps,Y=v.memoizedState,G=Y.element,rh(h,v),kd(v,R,null,T);var de=v.memoizedState;if(R=de.element,Y.isDehydrated)if(Y={element:R,isDehydrated:!1,cache:de.cache,pendingSuspenseBoundaries:de.pendingSuspenseBoundaries,transitions:de.transitions},v.updateQueue.baseState=Y,v.memoizedState=Y,v.flags&256){G=pl(Error(n(423)),v),v=Gf(h,v,R,T,G);break e}else if(R!==G){G=pl(Error(n(424)),v),v=Gf(h,v,R,T,G);break e}else for(Fr=Lo(v.stateNode.containerInfo.firstChild),jr=v,Ji=!0,Dr=null,T=Qu(v,null,R,T),v.child=T;T;)T.flags=T.flags&-3|4096,T=T.sibling;else{if(ba(),R===G){v=fo(h,v,T);break e}qn(h,v,R,T)}v=v.child}return v;case 5:return uf(v),h===null&&Yu(v),R=v.type,G=v.pendingProps,Y=h!==null?h.memoizedProps:null,de=G.children,zu(R,G)?de=null:Y!==null&&zu(R,Y)&&(v.flags|=32),Bf(h,v),qn(h,v,de,T),v.child;case 6:return h===null&&Yu(v),null;case 13:return Uf(h,v,T);case 4:return sh(v,v.stateNode.containerInfo),R=v.pendingProps,h===null?v.child=cl(v,null,R,T):qn(h,v,R,T),v.child;case 11:return R=v.type,G=v.pendingProps,G=v.elementType===R?G:yn(R,G),Of(h,v,R,G,T);case 7:return qn(h,v,v.pendingProps,T),v.child;case 8:return qn(h,v,v.pendingProps.children,T),v.child;case 12:return qn(h,v,v.pendingProps.children,T),v.child;case 10:e:{if(R=v.type._context,G=v.pendingProps,Y=v.memoizedProps,de=G.value,Oi(ya,R._currentValue),R._currentValue=de,Y!==null)if(_s(Y.value,de)){if(Y.children===G.children&&!kr.current){v=fo(h,v,T);break e}}else for(Y=v.child,Y!==null&&(Y.return=v);Y!==null;){var we=Y.dependencies;if(we!==null){de=Y.child;for(var Ae=we.firstContext;Ae!==null;){if(Ae.context===R){if(Y.tag===1){Ae=ho(-1,T&-T),Ae.tag=2;var We=Y.updateQueue;if(We!==null){We=We.shared;var lt=We.pending;lt===null?Ae.next=Ae:(Ae.next=lt.next,lt.next=Ae),We.pending=Ae}}Y.lanes|=T,Ae=Y.alternate,Ae!==null&&(Ae.lanes|=T),df(Y.return,T,v),we.lanes|=T;break}Ae=Ae.next}}else if(Y.tag===10)de=Y.type===v.type?null:Y.child;else if(Y.tag===18){if(de=Y.return,de===null)throw Error(n(341));de.lanes|=T,we=de.alternate,we!==null&&(we.lanes|=T),df(de,T,v),de=Y.sibling}else de=Y.child;if(de!==null)de.return=Y;else for(de=Y;de!==null;){if(de===v){de=null;break}if(Y=de.sibling,Y!==null){Y.return=de.return,de=Y;break}de=de.return}Y=de}qn(h,v,G.children,T),v=v.child}return v;case 9:return G=v.type,R=v.pendingProps.children,dl(v,T),G=ts(G),R=R(G),v.flags|=1,qn(h,v,R,T),v.child;case 14:return R=v.type,G=yn(R,v.pendingProps),G=yn(R.type,G),uc(h,v,R,G,T);case 15:return Lf(h,v,v.type,v.pendingProps,T);case 17:return R=v.type,G=v.pendingProps,G=v.elementType===R?G:yn(R,G),Nd(h,v),v.tag=1,Cr(R)?(h=!0,gd(v)):h=!1,dl(v,T),$f(v,R,G),xh(v,R,G,T),wh(null,v,R,!0,h,T);case 19:return Th(h,v,T);case 22:return zf(h,v,T)}throw Error(n(156,v.tag))};function lm(h,v){return ha(h,v)}function ly(h,v,T,R){this.tag=h,this.key=T,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=v,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=R,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Ur(h,v,T,R){return new ly(h,v,T,R)}function Kh(h){return h=h.prototype,!(!h||!h.isReactComponent)}function Pv(h){if(typeof h=="function")return Kh(h)?1:0;if(h!=null){if(h=h.$$typeof,h===Z)return 11;if(h===J)return 14}return 2}function Yo(h,v){var T=h.alternate;return T===null?(T=Ur(h.tag,v,h.key,h.mode),T.elementType=h.elementType,T.type=h.type,T.stateNode=h.stateNode,T.alternate=h,h.alternate=T):(T.pendingProps=v,T.type=h.type,T.flags=0,T.subtreeFlags=0,T.deletions=null),T.flags=h.flags&14680064,T.childLanes=h.childLanes,T.lanes=h.lanes,T.child=h.child,T.memoizedProps=h.memoizedProps,T.memoizedState=h.memoizedState,T.updateQueue=h.updateQueue,v=h.dependencies,T.dependencies=v===null?null:{lanes:v.lanes,firstContext:v.firstContext},T.sibling=h.sibling,T.index=h.index,T.ref=h.ref,T}function Gd(h,v,T,R,G,Y){var de=2;if(R=h,typeof h=="function")Kh(h)&&(de=1);else if(typeof h=="string")de=5;else e:switch(h){case I:return xl(T.children,G,Y,v);case P:de=8,G|=8;break;case L:return h=Ur(12,T,v,G|2),h.elementType=L,h.lanes=Y,h;case X:return h=Ur(13,T,v,G),h.elementType=X,h.lanes=Y,h;case W:return h=Ur(19,T,v,G),h.elementType=W,h.lanes=Y,h;case le:return Ud(T,G,Y,v);default:if(typeof h=="object"&&h!==null)switch(h.$$typeof){case B:de=10;break e;case U:de=9;break e;case Z:de=11;break e;case J:de=14;break e;case te:de=16,R=null;break e}throw Error(n(130,h==null?h:typeof h,""))}return v=Ur(de,T,v,G),v.elementType=h,v.type=R,v.lanes=Y,v}function xl(h,v,T,R){return h=Ur(7,h,R,v),h.lanes=T,h}function Ud(h,v,T,R){return h=Ur(22,h,R,v),h.elementType=le,h.lanes=T,h.stateNode={isHidden:!1},h}function Yh(h,v,T){return h=Ur(6,h,null,v),h.lanes=T,h}function Xh(h,v,T){return v=Ur(4,h.children!==null?h.children:[],h.key,v),v.lanes=T,v.stateNode={containerInfo:h.containerInfo,pendingChildren:null,implementation:h.implementation},v}function cy(h,v,T,R,G){this.tag=v,this.containerInfo=h,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Xe(0),this.expirationTimes=Xe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Xe(0),this.identifierPrefix=R,this.onRecoverableError=G,this.mutableSourceEagerHydrationData=null}function Jh(h,v,T,R,G,Y,de,we,Ae){return h=new cy(h,v,T,we,Ae),v===1?(v=1,Y===!0&&(v|=8)):v=0,Y=Ur(3,null,null,v),h.current=Y,Y.stateNode=h,Y.memoizedState={element:R,isDehydrated:T,cache:null,transitions:null,pendingSuspenseBoundaries:null},Sd(Y),h}function dy(h,v,T){var R=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:$,key:R==null?null:""+R,children:h,containerInfo:v,implementation:T}}function cm(h){if(!h)return zo;h=h._reactInternals;e:{if(Et(h)!==h||h.tag!==1)throw Error(n(170));var v=h;do{switch(v.tag){case 3:v=v.stateNode.context;break e;case 1:if(Cr(v.type)){v=v.stateNode.__reactInternalMemoizedMergedChildContext;break e}}v=v.return}while(v!==null);throw Error(n(171))}if(h.tag===1){var T=h.type;if(Cr(T))return sf(h,T,v)}return v}function Rv(h,v,T,R,G,Y,de,we,Ae){return h=Jh(T,R,!0,h,G,Y,de,we,Ae),h.context=cm(null),T=h.current,R=ur(),G=qo(T),Y=ho(R,G),Y.callback=v??null,Go(T,Y,G),h.current.lanes=G,ir(h,G,R),$r(h,R),h}function Hd(h,v,T,R){var G=v.current,Y=ur(),de=qo(G);return T=cm(T),v.context===null?v.context=T:v.pendingContext=T,v=ho(Y,de),v.payload={element:h},R=R===void 0?null:R,R!==null&&(v.callback=R),h=Go(G,v,de),h!==null&&(Es(h,G,de,Y),ac(h,G,de)),de}function Wd(h){if(h=h.current,!h.child)return null;switch(h.child.tag){case 5:return h.child.stateNode;default:return h.child.stateNode}}function dm(h,v){if(h=h.memoizedState,h!==null&&h.dehydrated!==null){var T=h.retryLane;h.retryLane=T!==0&&T<v?T:v}}function Zh(h,v){dm(h,v),(h=h.alternate)&&dm(h,v)}function Iv(){return null}var Mv=typeof reportError=="function"?reportError:function(h){console.error(h)};function Qh(h){this._internalRoot=h}bl.prototype.render=Qh.prototype.render=function(h){var v=this._internalRoot;if(v===null)throw Error(n(409));Hd(h,v,null,null)},bl.prototype.unmount=Qh.prototype.unmount=function(){var h=this._internalRoot;if(h!==null){this._internalRoot=null;var v=h.containerInfo;Da(function(){Hd(null,h,null,null)}),v[Vs]=null}};function bl(h){this._internalRoot=h}bl.prototype.unstable_scheduleHydration=function(h){if(h){var v=Ri();h={blockedOn:null,target:h,priority:v};for(var T=0;T<gs.length&&v!==0&&v<gs[T].priority;T++);gs.splice(T,0,h),T===0&&Hl(h)}};function ep(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)}function Vd(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11&&(h.nodeType!==8||h.nodeValue!==" react-mount-point-unstable "))}function Ov(){}function Lv(h,v,T,R,G){if(G){if(typeof R=="function"){var Y=R;R=function(){var We=Wd(de);Y.call(We)}}var de=Rv(v,R,h,0,null,!1,!1,"",Ov);return h._reactRootContainer=de,h[Vs]=de.current,ic(h.nodeType===8?h.parentNode:h),Da(),de}for(;G=h.lastChild;)h.removeChild(G);if(typeof R=="function"){var we=R;R=function(){var We=Wd(Ae);we.call(We)}}var Ae=Jh(h,0,!1,null,null,!1,!1,"",Ov);return h._reactRootContainer=Ae,h[Vs]=Ae.current,ic(h.nodeType===8?h.parentNode:h),Da(function(){Hd(v,Ae,T,R)}),Ae}function bc(h,v,T,R,G){var Y=T._reactRootContainer;if(Y){var de=Y;if(typeof G=="function"){var we=G;G=function(){var Ae=Wd(de);we.call(Ae)}}Hd(v,de,h,G)}else de=Lv(T,v,h,G,R);return Wd(de)}jt=function(h){switch(h.tag){case 3:var v=h.stateNode;if(v.current.memoizedState.isDehydrated){var T=Kr(v.pendingLanes);T!==0&&(ye(v,T|1),$r(v,Ei()),(bi&6)===0&&(gl=Ei()+500,Bo()))}break;case 13:Da(function(){var R=uo(h,1);if(R!==null){var G=ur();Es(R,h,1,G)}}),Zh(h,1)}},ri=function(h){if(h.tag===13){var v=uo(h,134217728);if(v!==null){var T=ur();Es(v,h,134217728,T)}Zh(h,134217728)}},ai=function(h){if(h.tag===13){var v=qo(h),T=uo(h,v);if(T!==null){var R=ur();Es(T,h,v,R)}Zh(h,v)}},Ri=function(){return Ie},$i=function(h,v){var T=Ie;try{return Ie=h,v()}finally{Ie=T}},Rs=function(h,v,T){switch(v){case"input":if(Le(h,T),v=T.name,T.type==="radio"&&v!=null){for(T=h;T.parentNode;)T=T.parentNode;for(T=T.querySelectorAll("input[name="+JSON.stringify(""+v)+'][type="radio"]'),v=0;v<T.length;v++){var R=T[v];if(R!==h&&R.form===h.form){var G=fd(R);if(!G)throw Error(n(90));st(R),Le(R,G)}}}break;case"textarea":ui(h,T);break;case"select":v=T.value,v!=null&&Ue(h,!!T.multiple,v,!1)}},qr=Wh,Fn=Da;var um={usingClientEntryPoint:!1,Events:[sc,rl,fd,Is,Ms,Wh]},Ts={findFiberByHostInstance:ga,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},zv={bundleType:Ts.bundleType,version:Ts.version,rendererPackageName:Ts.rendererPackageName,rendererConfig:Ts.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:j.ReactCurrentDispatcher,findHostInstanceByFiber:function(h){return h=Ao(h),h===null?null:h.stateNode},findFiberByHostInstance:Ts.findFiberByHostInstance||Iv,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var yc=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!yc.isDisabled&&yc.supportsFiber)try{_r=yc.inject(zv),kn=yc}catch{}}return js.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=um,js.createPortal=function(h,v){var T=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!ep(v))throw Error(n(200));return dy(h,v,null,T)},js.createRoot=function(h,v){if(!ep(h))throw Error(n(299));var T=!1,R="",G=Mv;return v!=null&&(v.unstable_strictMode===!0&&(T=!0),v.identifierPrefix!==void 0&&(R=v.identifierPrefix),v.onRecoverableError!==void 0&&(G=v.onRecoverableError)),v=Jh(h,1,!1,null,null,T,!1,R,G),h[Vs]=v.current,ic(h.nodeType===8?h.parentNode:h),new Qh(v)},js.findDOMNode=function(h){if(h==null)return null;if(h.nodeType===1)return h;var v=h._reactInternals;if(v===void 0)throw typeof h.render=="function"?Error(n(188)):(h=Object.keys(h).join(","),Error(n(268,h)));return h=Ao(v),h=h===null?null:h.stateNode,h},js.flushSync=function(h){return Da(h)},js.hydrate=function(h,v,T){if(!Vd(v))throw Error(n(200));return bc(null,h,v,!0,T)},js.hydrateRoot=function(h,v,T){if(!ep(h))throw Error(n(405));var R=T!=null&&T.hydratedSources||null,G=!1,Y="",de=Mv;if(T!=null&&(T.unstable_strictMode===!0&&(G=!0),T.identifierPrefix!==void 0&&(Y=T.identifierPrefix),T.onRecoverableError!==void 0&&(de=T.onRecoverableError)),v=Rv(v,null,h,1,T??null,G,!1,Y,de),h[Vs]=v.current,ic(h),R)for(h=0;h<R.length;h++)T=R[h],G=T._getVersion,G=G(T._source),v.mutableSourceEagerHydrationData==null?v.mutableSourceEagerHydrationData=[T,G]:v.mutableSourceEagerHydrationData.push(T,G);return new bl(v)},js.render=function(h,v,T){if(!Vd(v))throw Error(n(200));return bc(null,h,v,!1,T)},js.unmountComponentAtNode=function(h){if(!Vd(h))throw Error(n(40));return h._reactRootContainer?(Da(function(){bc(null,null,h,!1,function(){h._reactRootContainer=null,h[Vs]=null})}),!0):!1},js.unstable_batchedUpdates=Wh,js.unstable_renderSubtreeIntoContainer=function(h,v,T,R){if(!Vd(T))throw Error(n(200));if(h==null||h._reactInternals===void 0)throw Error(n(38));return bc(h,v,T,!1,R)},js.version="18.3.1-next-f1338f8080-20240426",js}var l1;function H2(){if(l1)return my.exports;l1=1;function i(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(e){console.error(e)}}return i(),my.exports=EA(),my.exports}var c1;function TA(){if(c1)return Fv;c1=1;var i=H2();return Fv.createRoot=i.createRoot,Fv.hydrateRoot=i.hydrateRoot,Fv}var jA=TA();const DA=zb(jA);var z=Ww();const Rt=zb(z),d1=i=>{let e;const n=new Set,r=(p,m)=>{const f=typeof p=="function"?p(e):p;if(!Object.is(f,e)){const b=e;e=m??(typeof f!="object"||f===null)?f:Object.assign({},e,f),n.forEach(S=>S(e,b))}},s=()=>e,l={setState:r,getState:s,getInitialState:()=>d,subscribe:p=>(n.add(p),()=>n.delete(p))},d=e=i(r,s,l);return l},AA=(i=>i?d1(i):d1),NA=i=>i;function $A(i,e=NA){const n=Rt.useSyncExternalStore(i.subscribe,Rt.useCallback(()=>e(i.getState()),[i,e]),Rt.useCallback(()=>e(i.getInitialState()),[i,e]));return Rt.useDebugValue(n),n}const u1=i=>{const e=AA(i),n=r=>$A(e,r);return Object.assign(n,e),n},Xn=(i=>i?u1(i):u1);function Vc(i){return"'"+i.replace(/'/g,"'\\''")+"'"}const xy=({sessionId:i})=>`claude --dangerously-skip-permissions --session-id ${Vc(i)}`,h1=({sessionId:i})=>`claude --session-id ${Vc(i)}`,PA=()=>"claude --resume",W2=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:xy},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:h1},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:xy},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:xy},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:h1},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:PA},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let go=null;async function RA(){if(go)return go;try{const i=await window.api.app.engageRulesPath();if(!i)return go=[],go;const e=await window.api.config.readJson(i);if(!e.exists||e.parseError||!e.data)return go=[],go;const n=e.data;if(!n.presets||!Array.isArray(n.presets))return go=[],go;const r=n.projectPath;return go=n.presets.map(s=>({id:s.id,label:s.label,description:s.description,category:"engage",cwd:r,platform:s.platform,pipeline:s.pipeline,rules:s.rules,command:()=>`cd ${Vc(r)} && ${s.cliEntry}`})),go}catch(i){return console.warn("[presets] Failed to load engage presets:",i),go=[],go}}async function V2(i){const e=W2.find(r=>r.id===i);return e||((await RA()).find(r=>r.id===i)??null)}async function p1(i){return i.cwd==="app-cwd"?window.api.app.cwd():i.cwd==="home"?window.api.app.homeDir():i.cwd==="pick"?window.api.app.pickDirectory():i.cwd}function q2(i,e){return i.command?i.command(e):null}const Vw=["opus","sonnet","haiku"],K2="sm.rawSessionModel",IA="opus";function MA(i){return Vw.includes(i)}function OA(){try{const i=localStorage.getItem(K2);if(i&&MA(i))return i}catch{}return IA}let mp=OA();const C_=new Set;function Y2(){return mp}function LA(i){if(i!==mp){mp=i;try{localStorage.setItem(K2,i)}catch{}C_.forEach(e=>e(i))}}function zA(){const[i,e]=z.useState(mp);z.useEffect(()=>{const r=s=>e(s);return C_.add(r),mp!==i&&e(mp),()=>{C_.delete(r)}},[]);const n=z.useCallback(r=>LA(r),[]);return{model:i,setModel:n}}async function X2(i,e){const n=await window.api.transcripts.pathFor(i,e);return window.api.config.exists(n)}const BA=5,f1=100,FA=5e3,E_=new Map;function m1(i){const e=E_.get(i);e!==void 0&&(clearTimeout(e),E_.delete(i))}function GA(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const iu=Xn((i,e)=>({toasts:[],history:[],unreadCount:0,show:(n,r)=>{const s=GA(),a=Date.now();i(l=>{const d=[...l.toasts,{id:s,kind:n,message:r,createdAt:a}];for(;d.length>BA;){const f=d.shift();f&&m1(f.id)}const m=[{id:s,kind:n,message:r,createdAt:a,read:!1},...l.history];return m.length>f1&&(m.length=f1),{toasts:d,history:m,unreadCount:l.unreadCount+1}});const u=setTimeout(()=>e().dismiss(s),FA);return E_.set(s,u),s},dismiss:n=>{m1(n),i(r=>({toasts:r.toasts.filter(s=>s.id!==n)}))},markAllRead:()=>{i(n=>n.unreadCount===0?n:{history:n.history.map(r=>r.read?r:{...r,read:!0}),unreadCount:0})},clearHistory:()=>{i({history:[],unreadCount:0})},dismissHistoryEntry:n=>{i(r=>{const s=r.history.filter(u=>u.id!==n);if(s.length===r.history.length)return r;const a=r.history.find(u=>u.id===n&&!u.read);return{history:s,unreadCount:a?Math.max(0,r.unreadCount-1):r.unreadCount}})}})),Ve={info:i=>iu.getState().show("info",i),warn:i=>iu.getState().show("warn",i),error:i=>iu.getState().show("error",i),fromOutcome:i=>iu.getState().show(i.kind??(i.ok?"info":"warn"),i.message)},J2=Object.freeze(Object.defineProperty({__proto__:null,toast:Ve,useToast:iu},Symbol.toStringTag,{value:"Module"}));async function UA(i){var e,n;if(typeof window>"u"||typeof((n=(e=window.api)==null?void 0:e.chat)==null?void 0:n.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:i})==="develop"?"develop":"inline"}catch{return"inline"}}function HA(i,e){const n=i.prdSlugs??[];return n.length===0?!1:n.every(r=>{var s;return((s=e.find(a=>a.slug===r))==null?void 0:s.status)==="completed"})}const nu={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},g1=20;function Qx(i,e){const n=[...i,e];return n.length>g1?n.slice(n.length-g1):n}let v1=0;function Uc(){return v1+=1,`t${Date.now().toString(36)}-${v1}`}const x1=60;function WA(i){const e=i.trim();if(e.length<=x1)return e;const n=e.slice(0,x1),r=n.lastIndexOf(" ");return(r>0?n.slice(0,r):n).trim()}const dn=Xn((i,e)=>({chats:{},hydratedTabs:{},get:n=>e().chats[n]??nu,hydrate:async({tabId:n,cwd:r,sessionId:s})=>{var a,u,l;if(!e().hydratedTabs[n]&&(i({hydratedTabs:{...e().hydratedTabs,[n]:!0}}),!(typeof window>"u"||!((a=window.api)!=null&&a.exchanges))))try{const d=await window.api.exchanges.list({cwd:r,sessionId:s});if(!d.length)return;const p=[];for(const f of[...d].reverse()){const b=new Date(f.ts).getTime();p.push({id:Uc(),role:"user",text:f.prompt,at:b}),p.push({id:Uc(),role:"assistant",text:f.result,at:b})}const m=e().chats[n]??nu;i({chats:{...e().chats,[n]:{...m,turns:[...p,...m.turns],started:!0}}})}catch(d){const p=d instanceof Error?d.message:String(d);(l=(u=window.api)==null?void 0:u.logs)==null||l.write("chat","warn",`exchange hydration failed for tab ${n}: ${p}`)}},send:({tabId:n,sessionId:r,cwd:s,prompt:a,tag:u,chainRootId:l,external:d})=>{const p=a.trim();if(!p)return;const m=e().chats[n]??nu;if(m.running){const f={id:crypto.randomUUID(),tabId:n,sessionId:r,cwd:s,text:p,status:"queued",createdAt:Date.now(),tag:u,chainRootId:l,external:d};i({chats:{...e().chats,[n]:{...m,queue:[...m.queue,f]}}});return}VA(n),Z2({tabId:n,sessionId:r,cwd:s,text:p,tag:u,chainRootId:l})},resetThread:n=>{i({chats:{...e().chats,[n]:{...nu}}})},pushNotice:(n,r)=>{eb(n,"",r)},setPendingVoiceText:(n,r)=>{os(n,s=>({...s,pendingVoiceText:r}))},clearPendingVoiceText:n=>{os(n,r=>({...r,pendingVoiceText:void 0}))}}));function os(i,e){const n=dn.getState().chats[i]??nu;dn.setState({chats:{...dn.getState().chats,[i]:e(n)}})}function Px(i,e,n={},r="done",s={}){os(i,a=>{const u=a.activeTicket?Qx(a.ticketHistory??[],{...a.activeTicket,status:r,completedAt:Date.now(),...s}):a.ticketHistory??[];return{...a,turns:[...a.turns,{...e,toolUses:a.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:u,...n}}),T_(i)}function VA(i){os(i,e=>{const n=e.ticketHistory??[];return n.some(r=>r.status==="needs-input")?{...e,ticketHistory:n.map(r=>r.status==="needs-input"?{...r,status:"done"}:r)}:e})}function Z2(i){const{tabId:e,sessionId:n,cwd:r,text:s,promptId:a,tag:u,chainRootId:l}=i,d=dn.getState().chats[e]??nu,p={id:Uc(),role:"user",text:s,at:Date.now()},m=d.activeTicket??{id:a??crypto.randomUUID(),tabId:e,sessionId:n,cwd:r,text:s,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:u,chainRootId:l};dn.setState({chats:{...dn.getState().chats,[e]:{...d,turns:[...d.turns,p],running:!0,queuedPosition:0,stream:"",activeTicket:m}}}),X2(r,n).catch(f=>{var S,w;const b=f instanceof Error?f.message:String(f);return(w=(S=window.api)==null?void 0:S.logs)==null||w.write("chat","warn",`transcript-exists check failed for tab ${e}: ${b}`),d.started}).then(f=>window.api.chat.run({tabId:e,sessionId:n,prompt:s,cwd:r,resume:f,promptId:a})).catch(f=>{const b=f instanceof Error?f.message:String(f);Q2(e,n,b)})}function T_(i){const e=dn.getState().chats[i]??nu;if(e.queue.length===0)return;const[n,...r]=e.queue;if(os(i,s=>({...s,queue:r,running:!0,queuedPosition:0,activeTicket:n})),n.external){b1(i,n);return}UA(n.text).then(s=>{if(s==="develop"){qA(i,n);return}b1(i,n)})}function b1(i,e){const n={...e,status:"running",startedAt:Date.now()};os(i,r=>({...r,activeTicket:n})),Z2({tabId:n.tabId,sessionId:n.sessionId,cwd:n.cwd,text:n.text,promptId:n.id,tag:n.tag,chainRootId:n.chainRootId})}function qA(i,e){const n=r=>{os(i,s=>({...s,running:!1,queuedPosition:0,activeTicket:null,ticketHistory:Qx(s.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),eb(i,e.sessionId,r),Ve.error(r),T_(i)};window.api.chat.createPrd({title:WA(e.text),cwd:e.cwd,estimateMinutes:15,goal:e.text,acceptanceCriteria:["Implement the request described in Goal.","timeout 300 npm run typecheck passes"],implementationNotes:`Target project: ${e.cwd}`,sourcePromptId:e.chainRootId??e.id,sourceTabId:e.tabId,tag:e.tag}).then(r=>{if(!(r!=null&&r.ok)){n(`→ PRD authoring failed for ticket ${e.id}: ${(r==null?void 0:r.error)??"unknown error"}`);return}const s=r.filename,a=s.endsWith(".md")?s.slice(0,-3):s,u={...e,status:"dispatched-to-prd",completedAt:Date.now(),...e.chainRootId?{}:{prdSlugs:[a]}};eb(i,u.sessionId,`→ dispatched to PRD ${s} (ticket ${u.id})`),os(i,l=>{let d=Qx(l.ticketHistory??[],u);if(e.chainRootId){const p=e.chainRootId;d=d.map(m=>m.id===p?{...m,prdSlugs:[...m.prdSlugs??[],a]}:m)}return{...l,running:!1,queuedPosition:0,activeTicket:null,ticketHistory:d}}),T_(i)}).catch(r=>{const s=r instanceof Error?r.message:String(r);n(`→ PRD authoring failed for ticket ${e.id}: ${s}`)})}function Q2(i,e,n){os(i,r=>r.activeTicket?{...r,activeTicket:null,ticketHistory:Qx(r.ticketHistory??[],{...r.activeTicket,status:"failed",completedAt:Date.now()})}:r),Px(i,{id:Uc(),role:"error",text:n,at:Date.now()}),Ve.error(n)}function eb(i,e,n){os(i,r=>({...r,turns:[...r.turns,{id:Uc(),role:"notice",text:n,at:Date.now()}]}))}var U2;typeof window<"u"&&((U2=window.api)!=null&&U2.chat)&&(window.api.chat.onQueued(({tabId:i,position:e})=>{os(i,n=>({...n,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:i})=>{os(i,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:i,delta:e})=>{os(i,n=>({...n,stream:n.stream+e}))}),window.api.chat.onToolUse(({tabId:i,id:e,kind:n,label:r})=>{os(i,s=>({...s,liveToolUses:[...s.liveToolUses,{id:e,kind:n,label:r}]}))}),window.api.chat.onComplete(({tabId:i,finalMessage:e})=>{Px(i,{id:Uc(),role:"assistant",text:e,at:Date.now()})}),window.api.chat.onNeedsInput(({tabId:i,questions:e,answerBody:n})=>{const r=Uc();if(n&&n.trim()){os(i,s=>({...s,turns:[...s.turns,{id:Uc(),role:"assistant",text:n,at:Date.now(),toolUses:s.liveToolUses}],liveToolUses:[]})),Px(i,{id:r,role:"question",text:e.join(`
|
|
42
42
|
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r});return}Px(i,{id:r,role:"question",text:e.join(`
|
|
43
|
-
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:i,sessionId:e,message:n})=>{Q2(i,e,n)}),window.api.chat.onNotice(({tabId:i,sessionId:e,message:n})=>{eb(i,e,n)}),window.api.chat.onExternalSend(({tabId:i,prompt:e})=>{var r,s;const n=Ct.getState().tabs.find(a=>a.id===i);if(!n){(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`external send ignored: tab ${i} is not open`);return}dn.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:e,external:!0})}));function KA(i){const e=i.split("/").filter(Boolean);return e[e.length-1]||i}async function eE(i,e=!1,n=Y2()){let r=!e;r&&(r=await X2(i.cwd,i.sessionId));const s=e&&!r?crypto.randomUUID():i.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Vc(s)} --model ${n}`:`claude --dangerously-skip-permissions --session-id ${Vc(s)} --model ${n}`;return{sessionId:s,startupCommand:a}}const Ct=Xn((i,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(n,r)=>{i(s=>({pendingRawCommand:{...s.pendingRawCommand,[n]:r}}))},consumeRawCommand:n=>{const r=e().pendingRawCommand[n];return r===void 0?null:(i(s=>{const a={...s.pendingRawCommand};return delete a[n],{pendingRawCommand:a}}),r)},addTab:({id:n,cwd:r,startupCommand:s,presetId:a=null,label:u,dormant:l=!1})=>{const d=n??crypto.randomUUID();if(e().tabs.find(f=>f.id===d))return i({activeTabId:d}),d;const m={id:d,sessionId:d,label:u??KA(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return i({tabs:[...e().tabs,m],activeTabId:d}),d},setTabRunning:(n,r)=>i({tabs:e().tabs.map(s=>s.id===n?{...s,pid:r,status:"running"}:s)}),setTabExited:(n,r)=>i({tabs:e().tabs.map(s=>s.id===n?{...s,status:"exited",exitCode:r}:s)}),closeTab:n=>{var a;window.api.pty.kill(n),window.api.watchers.killTab(n).catch(()=>{}),window.api.transcripts.closeTab(n).catch(()=>{});const r=e().tabs.filter(u=>u.id!==n),s=e().activeTabId===n?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;i({tabs:r,activeTabId:s})},setActive:n=>i({activeTabId:n}),restartTab:n=>{const r=e().tabs.find(u=>u.id===n);if(!r)return;window.api.pty.kill(n);const s=crypto.randomUUID(),a=u=>{i({tabs:e().tabs.map(l=>l.id===n?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:u,generation:l.generation+1}:l)})};r.presetId?V2(r.presetId).then(u=>{a(u?q2(u,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Vc(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Vc(s)}`)},reorderTab:(n,r)=>{const s=[...e().tabs];if(n<0||n>=s.length||r<0||r>=s.length||n===r)return;const[a]=s.splice(n,1);s.splice(r,0,a),i({tabs:s})},restoreTabs:(n,r)=>i({tabs:n,activeTabId:r,hydrated:!0}),wakeTab:async(n,r)=>{var l;const s=e().tabs.find(d=>d.id===n);if(!s||s.status!=="dormant")return;(l=dn.getState().chats[n])!=null&&l.running&&(await window.api.chat.cancel(n),Ve.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:u}=await eE({cwd:s.cwd,sessionId:s.sessionId},!1,r??Y2());i({tabs:e().tabs.map(d=>d.id===n?{...d,sessionId:a,status:"spawning",startupCommand:u,generation:d.generation+1}:d)})},sleepTab:n=>{const r=e().tabs.find(s=>s.id===n);!r||r.status==="dormant"||(window.api.pty.kill(n),i({tabs:e().tabs.map(s=>s.id===n?{...s,pid:null,status:"dormant"}:s)}))},newSession:n=>{e().tabs.find(s=>s.id===n)&&i({tabs:e().tabs.map(s=>s.id===n?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(n,r)=>e().addTab({cwd:n,startupCommand:null,dormant:!0,...r})}));async function j_(){var n;if(Ct.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async p=>{try{const{sessionId:m}=await eE(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),d=s&&l.find(p=>p.id===s)?s:((n=l[0])==null?void 0:n.id)??null;Ct.getState().restoreTabs(l,d)}else Ct.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),Ct.setState({hydrated:!0})}const i=()=>{const{tabs:r,activeTabId:s}=Ct.getState(),a=r.map(u=>({id:u.id,sessionId:u.sessionId,cwd:u.cwd,label:u.label,presetId:u.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(u=>{console.warn("[sessions] save failed:",u)})};let e=null;Ct.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(i,200)))}),i()}const YA=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:j_,useSessions:Ct},Symbol.toStringTag,{value:"Module"})),y1=200,XA=/\x1b\[[0-9;]*m/g;function JA(i){return i.replace(XA,"")}const tg=Xn((i,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(i({initialized:!0}),window.api.watchers.onLine(n=>e().ingestLine(n)),window.api.watchers.onClosed(({watcherId:n})=>e().closed(n)))},add:async({tabId:n,label:r,command:s,cwd:a})=>{try{const u=await window.api.watchers.add({tabId:n,label:r,command:s,cwd:a??null}),l={watcherId:u.watcherId,tabId:u.tabId,label:u.label,command:u.command,cwd:u.cwd,pid:u.pid,startedAt:u.startedAt,lineCount:0,lines:[],lastLineAt:null};return i({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(u){return console.error("[watchers] add failed:",u),Ve.error("Failed to add watcher"),null}},remove:async n=>{try{await window.api.watchers.remove(n)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Ve.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[n],i({watchers:r})},watchersForTab:n=>Object.values(e().watchers).filter(r=>r.tabId===n),ingestLine:n=>{const r=e().watchers[n.watcherId];if(!r)return;const s=JA(n.line),a=r.lines.length>=y1?[...r.lines.slice(r.lines.length-y1+1),{line:s,ts:n.ts}]:[...r.lines,{line:s,ts:n.ts}];i({watchers:{...e().watchers,[n.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:n.ts}}})},closed:n=>{if(!e().watchers[n])return;const r={...e().watchers};delete r[n],i({watchers:r})}})),ZA="~/.claude/session-manager/browser/history.json",_1="~/.claude/session-manager/browser/bookmarks.json",QA=.25,eN=3,w1=.1,S1=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let k1=0;function tN(){const i=S1[k1%S1.length];return k1+=1,i}const tb=new Map;function iN(i){if(tb.has(i))return;const e=window.api.browser.onNavState(i,n=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===i?{...s,url:n.url,title:n.title||s.title,canGoBack:n.canGoBack,canGoForward:n.canGoForward,loading:n.loading,isSecure:n.isSecure}:s)}))});tb.set(i,e)}function nN(i){const e=tb.get(i);e&&(e(),tb.delete(i))}const D_=new Map;let Rx=null;function C1(i){const e=D_.get(i);e&&(e(),D_.delete(i))}function E1(){Rx&&(clearInterval(Rx),Rx=null)}const A_=new Map;function by(i){const e=A_.get(i);e&&(e(),A_.delete(i))}const Pt=Xn((i,e)=>({tabs:[],activeTabId:null,openTab:n=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(n==null?void 0:n.url)??"about:blank",color:(n==null?void 0:n.color)??tN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return i(u=>({tabs:[...u.tabs,a],activeTabId:r})),iN(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{n!=null&&n.url&&window.api.browser.navigate({viewId:s,url:n.url}).catch(()=>{})}).catch(u=>{var d,p;const l=u instanceof Error?u.message:String(u);(p=(d=window.api)==null?void 0:d.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:n=>{const r=e().tabs.find(s=>s.id===n);r&&(nN(r.viewId),by(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),i(s=>{const a=s.tabs.filter(l=>l.id!==n),u=s.activeTabId===n?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:u}}))},setActive:n=>{i({activeTabId:n})},navigate:(n,r)=>{const s=e().tabs.find(a=>a.id===n);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:n=>i(r=>({mode:n,captured:n==="capture"?r.captured:null})),setCaptureMode:n=>i({captureMode:n,captured:null}),onVerb:n=>{const{mode:r}=e();if(n==="shot"){i({mode:"capture",captureMode:"shot",captured:null});return}if(r===n){i({mode:"browse",captured:n==="capture"?null:e().captured});return}i({mode:n,captureMode:n==="capture"?"agent":e().captureMode,captured:n==="capture"?e().captured:null})},captured:null,capture:async n=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),u=s.find(d=>d.id===r);if(!u)throw new Error("No active browser tab");if(a==="shot"){const d=await window.api.browser.captureShot(u.viewId);if(!d.ok)throw new Error(d.error);i({captured:{mode:a,url:d.url,title:d.title,dataUrl:d.dataUrl,at:Date.now()}});return}if(!n||!n.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:u.viewId,selectors:n,mode:a});if(!l.ok)throw new Error(l.error);i({captured:{mode:a,url:u.url,title:u.title,text:l.text,meta:l.meta,selectors:n,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:n=>{if(e().recorderActive)return;i({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(n).catch(()=>{}),C1(n);const r=window.api.browser.onRecordStep(n,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});D_.set(n,r),E1(),Rx=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:n=>{e().recorderActive&&(window.api.browser.recordStop(n).catch(()=>{}),C1(n),E1(),i({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&i(n=>({recording:!n.recording}))},toggleStepVariable:n=>{i(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===n?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const n=await window.api.config.readJson(_1),r=n.exists&&Array.isArray(n.data)?n.data:[];i({bookmarks:r,bookmarksHydrated:!0})}catch{i({bookmarksHydrated:!0})}},toggleBookmark:n=>{const r=e().tabs.find(l=>l.id===n);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,u=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];i({bookmarks:u}),window.api.config.writeJson(_1,u).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const n=await window.api.config.readJson(ZA),r=n.exists&&Array.isArray(n.data)?n.data:[];i({historyEntries:r})}catch{}},setZoom:(n,r)=>{const s=e().tabs.find(u=>u.id===n);if(!s)return;const a=Math.min(eN,Math.max(QA,r));i(u=>({tabs:u.tabs.map(l=>l.id===n?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:n=>{const r=e().tabs.find(s=>s.id===n);r&&e().setZoom(n,r.zoomFactor+w1)},zoomOut:n=>{const r=e().tabs.find(s=>s.id===n);r&&e().setZoom(n,r.zoomFactor-w1)},zoomReset:n=>e().setZoom(n,1),findOpen:!1,findText:"",findMatches:null,openFind:n=>{const r=e().tabs.find(a=>a.id===n);if(!r)return;i({findOpen:!0,findText:"",findMatches:null}),by(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});A_.set(r.viewId,s)},closeFind:n=>{const r=e().tabs.find(s=>s.id===n);i({findOpen:!1,findText:"",findMatches:null}),r&&(by(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(n,r)=>{const s=e().tabs.find(a=>a.id===n);if(i({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:n=>{const r=e().tabs.find(a=>a.id===n),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:n=>{const r=e().tabs.find(a=>a.id===n),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),rN=4,T1=40,j1=6;function sN(i){const{onReorder:e,onActivate:n}=i,r=z.useRef(null),s=z.useRef(null),a=z.useRef(0),u=z.useRef(0),[l,d]=z.useState(!1),[,p]=z.useState(0),m=z.useRef(n);m.current=n;const f=z.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=z.useCallback((x,y,_)=>{for(let E=0;E<y.length;E++){const j=y[E].left+y[E].width/2;if(x<j)return E<=_?E:E-1}return y.length-1},[]),S=z.useCallback(()=>{const x=s.current,y=r.current;if(!(x!=null&&x.active)||!y)return;const _=y.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-_.left,D=_.right-E;j<T1?y.scrollLeft-=j1:D<T1&&(y.scrollLeft+=j1),a.current=requestAnimationFrame(S)},[]);z.useEffect(()=>{const x=r.current;if(!x)return;let y=!1;const _=()=>{y||(y=!0,u.current=requestAnimationFrame(()=>{y=!1,p(D=>D+1)}))},E=D=>{var B;const $=s.current;if(!$)return;const I=D.clientX-$.startX;if(!$.active&&Math.abs(I)<rN)return;if(!$.active){$.active=!0,$.tabRects=f().map(U=>U.getBoundingClientRect()),d(!0);try{(B=r.current)==null||B.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(S)}$.deltaX=I;const P=$.tabRects[$.fromIndex],L=P.left+P.width/2+I;$.currentIndex=b(L,$.tabRects,$.fromIndex),_()},j=D=>{const $=s.current;if($&&$.pointerId===D.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(u.current);try{x.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,d(!1),p(I=>I+1)}};return x.addEventListener("pointermove",E),x.addEventListener("pointerup",j),x.addEventListener("pointercancel",j),()=>{x.removeEventListener("pointermove",E),x.removeEventListener("pointerup",j),x.removeEventListener("pointercancel",j),cancelAnimationFrame(a.current),cancelAnimationFrame(u.current)}},[e,f,b,S]);const w=z.useCallback((x,y)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:y,currentIndex:y,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:z.useCallback(x=>{var E;const y=s.current,_={};if(y!=null&&y.active)if(x===y.fromIndex)_.transform=`translateX(${y.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const j=y.fromIndex,D=y.currentIndex,I=(((E=y.tabRects[j])==null?void 0:E.width)??0)+4;_.transition="transform 0.15s ease",j<D&&x>j&&x<=D?_.transform=`translateX(-${I}px)`:j>D&&x>=D&&x<j?_.transform=`translateX(${I}px)`:_.transform="translateX(0)"}return{onPointerDown:j=>w(j,x),style:_,"data-drag-index":x}},[w]),isDragging:l,containerRef:r}}const oN=3e4;function aN({onToggleSplitView:i,splitViewActive:e}={}){const n=Ct(y=>y.tabs),r=Ct(y=>y.activeTabId),s=Ct(y=>y.closeTab),a=Ct(y=>y.setActive),u=Ct(y=>y.reorderTab),l=tg(y=>y.watchers),d=Pt(y=>y.tabs.length>0),p=r!=null&&d,[m,f]=z.useState(()=>Date.now());z.useEffect(()=>{const y=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(y)},[]);const b=y=>{for(const _ of Object.values(l))if(_.tabId===y&&_.lastLineAt&&m-_.lastLineAt<oN)return!0;return!1},{getTabDragProps:S,isDragging:w,containerRef:C}=sN({tabCount:n.length,onReorder:u,onActivate:y=>{const _=n[y];_&&a(_.id)}}),x=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[o.jsx("div",{ref:C,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${w?"cursor-grabbing":""}`,children:n.map((y,_)=>{const E=y.id===r,j=S(_),D=x[_%x.length];return o.jsxs("div",{...j,style:j.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${w?"":"cursor-grab"} ${E?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:y.cwd,"aria-current":E?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:D,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:y.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:y.label}),y.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),b(y.id)&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),o.jsx("button",{onClick:$=>{$.stopPropagation(),s(y.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${y.label}`,children:"×"})]},y.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&i&&o.jsxs("button",{onClick:i,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.39.0"]})]})]})}var yy={},fm={},D1;function tE(){if(D1)return fm;D1=1,Object.defineProperty(fm,"__esModule",{value:!0}),fm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let n="/";return e&&(n=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),fm.baseAssetPath=n,fm}var mm={},A1;function qw(){if(A1)return mm;A1=1,Object.defineProperty(mm,"__esModule",{value:!0}),mm.defaultModelFetcher=void 0;const i=e=>fetch(e).then(n=>n.arrayBuffer());return mm.defaultModelFetcher=i,mm}var wl={},gm={},N1;function Ag(){if(N1)return gm;N1=1,Object.defineProperty(gm,"__esModule",{value:!0}),gm.log=void 0;const i=e=>n=>{console.log(`VAD | ${e} >`,n)};return gm.log={error:i("error"),debug:i("debug"),warn:i("warn")},gm}var vm={},$1;function Bb(){if($1)return vm;$1=1,Object.defineProperty(vm,"__esModule",{value:!0}),vm.Message=void 0;var i;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(i||(vm.Message=i={})),vm}var P1;function Kw(){if(P1)return wl;P1=1,Object.defineProperty(wl,"__esModule",{value:!0}),wl.FrameProcessor=wl.validateOptions=wl.defaultFrameProcessorOptions=void 0;const i=Ag(),e=Bb();wl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(u){(u.positiveSpeechThreshold<0||u.positiveSpeechThreshold>1)&&i.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(u.negativeSpeechThreshold<0||u.negativeSpeechThreshold>u.positiveSpeechThreshold)&&i.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),u.preSpeechPadMs<0&&i.log.error("preSpeechPadMs should be positive"),u.redemptionMs<0&&i.log.error("redemptionMs should be positive"),u.minSpeechMs<0&&i.log.error("minSpeechMs should be positive")}wl.validateOptions=n;const r=u=>{const l=u.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),d=new Float32Array(l.at(-1));return u.forEach((p,m)=>{const f=l[m];d.set(p,f)}),d};function s(u,l){const d=Math.floor(u.redemptionMs/l),p=Math.floor(u.preSpeechPadMs/l),m=Math.floor(u.minSpeechMs/l);return{redemptionFrames:d,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,d,p,m){this.modelProcessFunc=l,this.modelResetFunc=d,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=w=>{this.options={...this.options,...w};const{redemptionFrames:C,preSpeechPadFrames:x,minSpeechFrames:y}=s(this.options,this.msPerFrame);this.redemptionFrames=C,this.preSpeechPadFrames=x,this.minSpeechFrames=y},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=w=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(w):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=w=>{const C=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(C.reduce((_,E)=>E.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=r(C.map(E=>E.frame));w({msg:e.Message.SpeechEnd,audio:_})}else w({msg:e.Message.VADMisfire});return{}},this.process=async(w,C)=>{if(!this.active)return;const x=await this.modelProcessFunc(w),y=x.isSpeech>=this.options.positiveSpeechThreshold;if(C({probs:x,msg:e.Message.FrameProcessed,frame:w}),this.audioBuffer.push({frame:w,isSpeech:y}),y&&(this.speechFrameCount++,this.redemptionCounter=0),y&&!this.speaking&&(this.speaking=!0,C({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,C({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((j,D)=>D.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(_.map(D=>D.frame));C({msg:e.Message.SpeechEnd,audio:j})}else C({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:S}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=S,this.reset()}}return wl.FrameProcessor=a,wl}var Sl={};function So(i){throw new Error('Could not dynamically require "'+i+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _y={exports:{}};/*!
|
|
43
|
+
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:i,sessionId:e,message:n})=>{Q2(i,e,n)}),window.api.chat.onNotice(({tabId:i,sessionId:e,message:n})=>{eb(i,e,n)}),window.api.chat.onExternalSend(({tabId:i,prompt:e})=>{var r,s;const n=Ct.getState().tabs.find(a=>a.id===i);if(!n){(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`external send ignored: tab ${i} is not open`);return}dn.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:e,external:!0})}));function KA(i){const e=i.split("/").filter(Boolean);return e[e.length-1]||i}async function eE(i,e=!1,n=Y2()){let r=!e;r&&(r=await X2(i.cwd,i.sessionId));const s=e&&!r?crypto.randomUUID():i.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Vc(s)} --model ${n}`:`claude --dangerously-skip-permissions --session-id ${Vc(s)} --model ${n}`;return{sessionId:s,startupCommand:a}}const Ct=Xn((i,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(n,r)=>{i(s=>({pendingRawCommand:{...s.pendingRawCommand,[n]:r}}))},consumeRawCommand:n=>{const r=e().pendingRawCommand[n];return r===void 0?null:(i(s=>{const a={...s.pendingRawCommand};return delete a[n],{pendingRawCommand:a}}),r)},addTab:({id:n,cwd:r,startupCommand:s,presetId:a=null,label:u,dormant:l=!1})=>{const d=n??crypto.randomUUID();if(e().tabs.find(f=>f.id===d))return i({activeTabId:d}),d;const m={id:d,sessionId:d,label:u??KA(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return i({tabs:[...e().tabs,m],activeTabId:d}),d},setTabRunning:(n,r)=>i({tabs:e().tabs.map(s=>s.id===n?{...s,pid:r,status:"running"}:s)}),setTabExited:(n,r)=>i({tabs:e().tabs.map(s=>s.id===n?{...s,status:"exited",exitCode:r}:s)}),closeTab:n=>{var a;window.api.pty.kill(n),window.api.watchers.killTab(n).catch(()=>{}),window.api.transcripts.closeTab(n).catch(()=>{});const r=e().tabs.filter(u=>u.id!==n),s=e().activeTabId===n?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;i({tabs:r,activeTabId:s})},setActive:n=>i({activeTabId:n}),restartTab:n=>{const r=e().tabs.find(u=>u.id===n);if(!r)return;window.api.pty.kill(n);const s=crypto.randomUUID(),a=u=>{i({tabs:e().tabs.map(l=>l.id===n?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:u,generation:l.generation+1}:l)})};r.presetId?V2(r.presetId).then(u=>{a(u?q2(u,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Vc(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Vc(s)}`)},reorderTab:(n,r)=>{const s=[...e().tabs];if(n<0||n>=s.length||r<0||r>=s.length||n===r)return;const[a]=s.splice(n,1);s.splice(r,0,a),i({tabs:s})},restoreTabs:(n,r)=>i({tabs:n,activeTabId:r,hydrated:!0}),wakeTab:async(n,r)=>{var l;const s=e().tabs.find(d=>d.id===n);if(!s||s.status!=="dormant")return;(l=dn.getState().chats[n])!=null&&l.running&&(await window.api.chat.cancel(n),Ve.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:u}=await eE({cwd:s.cwd,sessionId:s.sessionId},!1,r??Y2());i({tabs:e().tabs.map(d=>d.id===n?{...d,sessionId:a,status:"spawning",startupCommand:u,generation:d.generation+1}:d)})},sleepTab:n=>{const r=e().tabs.find(s=>s.id===n);!r||r.status==="dormant"||(window.api.pty.kill(n),i({tabs:e().tabs.map(s=>s.id===n?{...s,pid:null,status:"dormant"}:s)}))},newSession:n=>{e().tabs.find(s=>s.id===n)&&i({tabs:e().tabs.map(s=>s.id===n?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(n,r)=>e().addTab({cwd:n,startupCommand:null,dormant:!0,...r})}));async function j_(){var n;if(Ct.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async p=>{try{const{sessionId:m}=await eE(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),d=s&&l.find(p=>p.id===s)?s:((n=l[0])==null?void 0:n.id)??null;Ct.getState().restoreTabs(l,d)}else Ct.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),Ct.setState({hydrated:!0})}const i=()=>{const{tabs:r,activeTabId:s}=Ct.getState(),a=r.map(u=>({id:u.id,sessionId:u.sessionId,cwd:u.cwd,label:u.label,presetId:u.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(u=>{console.warn("[sessions] save failed:",u)})};let e=null;Ct.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(i,200)))}),i()}const YA=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:j_,useSessions:Ct},Symbol.toStringTag,{value:"Module"})),y1=200,XA=/\x1b\[[0-9;]*m/g;function JA(i){return i.replace(XA,"")}const tg=Xn((i,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(i({initialized:!0}),window.api.watchers.onLine(n=>e().ingestLine(n)),window.api.watchers.onClosed(({watcherId:n})=>e().closed(n)))},add:async({tabId:n,label:r,command:s,cwd:a})=>{try{const u=await window.api.watchers.add({tabId:n,label:r,command:s,cwd:a??null}),l={watcherId:u.watcherId,tabId:u.tabId,label:u.label,command:u.command,cwd:u.cwd,pid:u.pid,startedAt:u.startedAt,lineCount:0,lines:[],lastLineAt:null};return i({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(u){return console.error("[watchers] add failed:",u),Ve.error("Failed to add watcher"),null}},remove:async n=>{try{await window.api.watchers.remove(n)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Ve.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[n],i({watchers:r})},watchersForTab:n=>Object.values(e().watchers).filter(r=>r.tabId===n),ingestLine:n=>{const r=e().watchers[n.watcherId];if(!r)return;const s=JA(n.line),a=r.lines.length>=y1?[...r.lines.slice(r.lines.length-y1+1),{line:s,ts:n.ts}]:[...r.lines,{line:s,ts:n.ts}];i({watchers:{...e().watchers,[n.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:n.ts}}})},closed:n=>{if(!e().watchers[n])return;const r={...e().watchers};delete r[n],i({watchers:r})}})),ZA="~/.claude/session-manager/browser/history.json",_1="~/.claude/session-manager/browser/bookmarks.json",QA=.25,eN=3,w1=.1,S1=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let k1=0;function tN(){const i=S1[k1%S1.length];return k1+=1,i}const tb=new Map;function iN(i){if(tb.has(i))return;const e=window.api.browser.onNavState(i,n=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===i?{...s,url:n.url,title:n.title||s.title,canGoBack:n.canGoBack,canGoForward:n.canGoForward,loading:n.loading,isSecure:n.isSecure}:s)}))});tb.set(i,e)}function nN(i){const e=tb.get(i);e&&(e(),tb.delete(i))}const D_=new Map;let Rx=null;function C1(i){const e=D_.get(i);e&&(e(),D_.delete(i))}function E1(){Rx&&(clearInterval(Rx),Rx=null)}const A_=new Map;function by(i){const e=A_.get(i);e&&(e(),A_.delete(i))}const Pt=Xn((i,e)=>({tabs:[],activeTabId:null,openTab:n=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(n==null?void 0:n.url)??"about:blank",color:(n==null?void 0:n.color)??tN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return i(u=>({tabs:[...u.tabs,a],activeTabId:r})),iN(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{n!=null&&n.url&&window.api.browser.navigate({viewId:s,url:n.url}).catch(()=>{})}).catch(u=>{var d,p;const l=u instanceof Error?u.message:String(u);(p=(d=window.api)==null?void 0:d.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:n=>{const r=e().tabs.find(s=>s.id===n);r&&(nN(r.viewId),by(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),i(s=>{const a=s.tabs.filter(l=>l.id!==n),u=s.activeTabId===n?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:u}}))},setActive:n=>{i({activeTabId:n})},navigate:(n,r)=>{const s=e().tabs.find(a=>a.id===n);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:n=>{const r=e().tabs.find(s=>s.id===n);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:n=>i(r=>({mode:n,captured:n==="capture"?r.captured:null})),setCaptureMode:n=>i({captureMode:n,captured:null}),onVerb:n=>{const{mode:r}=e();if(n==="shot"){i({mode:"capture",captureMode:"shot",captured:null});return}if(r===n){i({mode:"browse",captured:n==="capture"?null:e().captured});return}i({mode:n,captureMode:n==="capture"?"agent":e().captureMode,captured:n==="capture"?e().captured:null})},captured:null,capture:async n=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),u=s.find(d=>d.id===r);if(!u)throw new Error("No active browser tab");if(a==="shot"){const d=await window.api.browser.captureShot(u.viewId);if(!d.ok)throw new Error(d.error);i({captured:{mode:a,url:d.url,title:d.title,dataUrl:d.dataUrl,at:Date.now()}});return}if(!n||!n.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:u.viewId,selectors:n,mode:a});if(!l.ok)throw new Error(l.error);i({captured:{mode:a,url:u.url,title:u.title,text:l.text,meta:l.meta,selectors:n,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:n=>{if(e().recorderActive)return;i({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(n).catch(()=>{}),C1(n);const r=window.api.browser.onRecordStep(n,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});D_.set(n,r),E1(),Rx=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:n=>{e().recorderActive&&(window.api.browser.recordStop(n).catch(()=>{}),C1(n),E1(),i({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&i(n=>({recording:!n.recording}))},toggleStepVariable:n=>{i(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===n?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const n=await window.api.config.readJson(_1),r=n.exists&&Array.isArray(n.data)?n.data:[];i({bookmarks:r,bookmarksHydrated:!0})}catch{i({bookmarksHydrated:!0})}},toggleBookmark:n=>{const r=e().tabs.find(l=>l.id===n);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,u=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];i({bookmarks:u}),window.api.config.writeJson(_1,u).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const n=await window.api.config.readJson(ZA),r=n.exists&&Array.isArray(n.data)?n.data:[];i({historyEntries:r})}catch{}},setZoom:(n,r)=>{const s=e().tabs.find(u=>u.id===n);if(!s)return;const a=Math.min(eN,Math.max(QA,r));i(u=>({tabs:u.tabs.map(l=>l.id===n?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:n=>{const r=e().tabs.find(s=>s.id===n);r&&e().setZoom(n,r.zoomFactor+w1)},zoomOut:n=>{const r=e().tabs.find(s=>s.id===n);r&&e().setZoom(n,r.zoomFactor-w1)},zoomReset:n=>e().setZoom(n,1),findOpen:!1,findText:"",findMatches:null,openFind:n=>{const r=e().tabs.find(a=>a.id===n);if(!r)return;i({findOpen:!0,findText:"",findMatches:null}),by(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});A_.set(r.viewId,s)},closeFind:n=>{const r=e().tabs.find(s=>s.id===n);i({findOpen:!1,findText:"",findMatches:null}),r&&(by(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(n,r)=>{const s=e().tabs.find(a=>a.id===n);if(i({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:n=>{const r=e().tabs.find(a=>a.id===n),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:n=>{const r=e().tabs.find(a=>a.id===n),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),rN=4,T1=40,j1=6;function sN(i){const{onReorder:e,onActivate:n}=i,r=z.useRef(null),s=z.useRef(null),a=z.useRef(0),u=z.useRef(0),[l,d]=z.useState(!1),[,p]=z.useState(0),m=z.useRef(n);m.current=n;const f=z.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=z.useCallback((x,y,_)=>{for(let E=0;E<y.length;E++){const j=y[E].left+y[E].width/2;if(x<j)return E<=_?E:E-1}return y.length-1},[]),S=z.useCallback(()=>{const x=s.current,y=r.current;if(!(x!=null&&x.active)||!y)return;const _=y.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-_.left,D=_.right-E;j<T1?y.scrollLeft-=j1:D<T1&&(y.scrollLeft+=j1),a.current=requestAnimationFrame(S)},[]);z.useEffect(()=>{const x=r.current;if(!x)return;let y=!1;const _=()=>{y||(y=!0,u.current=requestAnimationFrame(()=>{y=!1,p(D=>D+1)}))},E=D=>{var B;const $=s.current;if(!$)return;const I=D.clientX-$.startX;if(!$.active&&Math.abs(I)<rN)return;if(!$.active){$.active=!0,$.tabRects=f().map(U=>U.getBoundingClientRect()),d(!0);try{(B=r.current)==null||B.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(S)}$.deltaX=I;const P=$.tabRects[$.fromIndex],L=P.left+P.width/2+I;$.currentIndex=b(L,$.tabRects,$.fromIndex),_()},j=D=>{const $=s.current;if($&&$.pointerId===D.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(u.current);try{x.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,d(!1),p(I=>I+1)}};return x.addEventListener("pointermove",E),x.addEventListener("pointerup",j),x.addEventListener("pointercancel",j),()=>{x.removeEventListener("pointermove",E),x.removeEventListener("pointerup",j),x.removeEventListener("pointercancel",j),cancelAnimationFrame(a.current),cancelAnimationFrame(u.current)}},[e,f,b,S]);const w=z.useCallback((x,y)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:y,currentIndex:y,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:z.useCallback(x=>{var E;const y=s.current,_={};if(y!=null&&y.active)if(x===y.fromIndex)_.transform=`translateX(${y.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const j=y.fromIndex,D=y.currentIndex,I=(((E=y.tabRects[j])==null?void 0:E.width)??0)+4;_.transition="transform 0.15s ease",j<D&&x>j&&x<=D?_.transform=`translateX(-${I}px)`:j>D&&x>=D&&x<j?_.transform=`translateX(${I}px)`:_.transform="translateX(0)"}return{onPointerDown:j=>w(j,x),style:_,"data-drag-index":x}},[w]),isDragging:l,containerRef:r}}const oN=3e4;function aN({onToggleSplitView:i,splitViewActive:e}={}){const n=Ct(y=>y.tabs),r=Ct(y=>y.activeTabId),s=Ct(y=>y.closeTab),a=Ct(y=>y.setActive),u=Ct(y=>y.reorderTab),l=tg(y=>y.watchers),d=Pt(y=>y.tabs.length>0),p=r!=null&&d,[m,f]=z.useState(()=>Date.now());z.useEffect(()=>{const y=window.setInterval(()=>f(Date.now()),1e3);return()=>window.clearInterval(y)},[]);const b=y=>{for(const _ of Object.values(l))if(_.tabId===y&&_.lastLineAt&&m-_.lastLineAt<oN)return!0;return!1},{getTabDragProps:S,isDragging:w,containerRef:C}=sN({tabCount:n.length,onReorder:u,onActivate:y=>{const _=n[y];_&&a(_.id)}}),x=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[o.jsx("div",{ref:C,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${w?"cursor-grabbing":""}`,children:n.map((y,_)=>{const E=y.id===r,j=S(_),D=x[_%x.length];return o.jsxs("div",{...j,style:j.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${w?"":"cursor-grab"} ${E?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:y.cwd,"aria-current":E?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:D,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:y.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:y.label}),y.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),b(y.id)&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),o.jsx("button",{onClick:$=>{$.stopPropagation(),s(y.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${y.label}`,children:"×"})]},y.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&i&&o.jsxs("button",{onClick:i,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.39.1"]})]})]})}var yy={},fm={},D1;function tE(){if(D1)return fm;D1=1,Object.defineProperty(fm,"__esModule",{value:!0}),fm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let n="/";return e&&(n=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),fm.baseAssetPath=n,fm}var mm={},A1;function qw(){if(A1)return mm;A1=1,Object.defineProperty(mm,"__esModule",{value:!0}),mm.defaultModelFetcher=void 0;const i=e=>fetch(e).then(n=>n.arrayBuffer());return mm.defaultModelFetcher=i,mm}var wl={},gm={},N1;function Ag(){if(N1)return gm;N1=1,Object.defineProperty(gm,"__esModule",{value:!0}),gm.log=void 0;const i=e=>n=>{console.log(`VAD | ${e} >`,n)};return gm.log={error:i("error"),debug:i("debug"),warn:i("warn")},gm}var vm={},$1;function Bb(){if($1)return vm;$1=1,Object.defineProperty(vm,"__esModule",{value:!0}),vm.Message=void 0;var i;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(i||(vm.Message=i={})),vm}var P1;function Kw(){if(P1)return wl;P1=1,Object.defineProperty(wl,"__esModule",{value:!0}),wl.FrameProcessor=wl.validateOptions=wl.defaultFrameProcessorOptions=void 0;const i=Ag(),e=Bb();wl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function n(u){(u.positiveSpeechThreshold<0||u.positiveSpeechThreshold>1)&&i.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(u.negativeSpeechThreshold<0||u.negativeSpeechThreshold>u.positiveSpeechThreshold)&&i.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),u.preSpeechPadMs<0&&i.log.error("preSpeechPadMs should be positive"),u.redemptionMs<0&&i.log.error("redemptionMs should be positive"),u.minSpeechMs<0&&i.log.error("minSpeechMs should be positive")}wl.validateOptions=n;const r=u=>{const l=u.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),d=new Float32Array(l.at(-1));return u.forEach((p,m)=>{const f=l[m];d.set(p,f)}),d};function s(u,l){const d=Math.floor(u.redemptionMs/l),p=Math.floor(u.preSpeechPadMs/l),m=Math.floor(u.minSpeechMs/l);return{redemptionFrames:d,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,d,p,m){this.modelProcessFunc=l,this.modelResetFunc=d,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=w=>{this.options={...this.options,...w};const{redemptionFrames:C,preSpeechPadFrames:x,minSpeechFrames:y}=s(this.options,this.msPerFrame);this.redemptionFrames=C,this.preSpeechPadFrames=x,this.minSpeechFrames=y},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=w=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(w):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=w=>{const C=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(C.reduce((_,E)=>E.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=r(C.map(E=>E.frame));w({msg:e.Message.SpeechEnd,audio:_})}else w({msg:e.Message.VADMisfire});return{}},this.process=async(w,C)=>{if(!this.active)return;const x=await this.modelProcessFunc(w),y=x.isSpeech>=this.options.positiveSpeechThreshold;if(C({probs:x,msg:e.Message.FrameProcessed,frame:w}),this.audioBuffer.push({frame:w,isSpeech:y}),y&&(this.speechFrameCount++,this.redemptionCounter=0),y&&!this.speaking&&(this.speaking=!0,C({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,C({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((j,D)=>D.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(_.map(D=>D.frame));C({msg:e.Message.SpeechEnd,audio:j})}else C({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:S}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=S,this.reset()}}return wl.FrameProcessor=a,wl}var Sl={};function So(i){throw new Error('Could not dynamically require "'+i+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var _y={exports:{}};/*!
|
|
44
44
|
* ONNX Runtime Web v1.26.0
|
|
45
45
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
46
46
|
* Licensed under the MIT License.
|
|
@@ -2894,7 +2894,7 @@ ${M}`,F=k.createShaderModule({code:O,label:c.name});oi("verbose",()=>`[WebGPU] $
|
|
|
2894
2894
|
* ONNX Runtime Web v1.26.0
|
|
2895
2895
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2896
2896
|
* Licensed under the MIT License.
|
|
2897
|
-
*/var G1;function fN(){return G1||(G1=1,(function(i,e){var n=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,l=(ne=>typeof So<"u"?So:typeof Proxy<"u"?new Proxy(ne,{get:(pe,xe)=>(typeof So<"u"?So:pe)[xe]}):ne)(function(ne){if(typeof So<"u")return So.apply(this,arguments);throw Error('Dynamic require of "'+ne+'" is not supported')}),d=(ne,pe)=>()=>(ne&&(pe=ne(ne=0)),pe),p=(ne,pe)=>{for(var xe in pe)r(ne,xe,{get:pe[xe],enumerable:!0})},m=(ne,pe,xe,De)=>{if(pe&&typeof pe=="object"||typeof pe=="function")for(let ke of a(pe))!u.call(ne,ke)&&ke!==xe&&r(ne,ke,{get:()=>pe[ke],enumerable:!(De=s(pe,ke))||De.enumerable});return ne},f=ne=>m(r({},"__esModule",{value:!0}),ne),b,S,w,C,x,y=d(()=>{b=new Map,S=[],w=(ne,pe,xe)=>{if(pe&&typeof pe.init=="function"&&typeof pe.createInferenceSessionHandler=="function"){let De=b.get(ne);if(De===void 0)b.set(ne,{backend:pe,priority:xe});else{if(De.priority>xe)return;if(De.priority===xe&&De.backend!==pe)throw new Error(`cannot register backend "${ne}" using priority ${xe}`)}if(xe>=0){let ke=S.indexOf(ne);ke!==-1&&S.splice(ke,1);for(let Be=0;Be<S.length;Be++)if(b.get(S[Be]).priority<=xe){S.splice(Be,0,ne);return}S.push(ne)}return}throw new TypeError("not a valid backend")},C=async ne=>{let pe=b.get(ne);if(!pe)return"backend not found.";if(pe.initialized)return pe.backend;if(pe.aborted)return pe.error;{let xe=!!pe.initPromise;try{return xe||(pe.initPromise=pe.backend.init(ne)),await pe.initPromise,pe.initialized=!0,pe.backend}catch(De){return xe||(pe.error=`${De}`,pe.aborted=!0),pe.error}finally{delete pe.initPromise}}},x=async ne=>{let pe=ne.executionProviders||[],xe=pe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=xe.length===0?S:xe,ke,Be=[],Ne=new Set;for(let Fe of De){let tt=await C(Fe);typeof tt=="string"?Be.push({name:Fe,err:tt}):(ke||(ke=tt),ke===tt&&Ne.add(Fe))}if(!ke)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:tt}of Be)xe.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${tt}`);let $e=pe.filter(Fe=>Ne.has(typeof Fe=="string"?Fe:Fe.name));return[ke,new Proxy(ne,{get:(Fe,tt)=>tt==="executionProviders"?$e:Reflect.get(Fe,tt)})]}}),_=d(()=>{y()}),E,j=d(()=>{E="1.26.0"}),D,$,I=d(()=>{j(),D="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(ne){if(ne!==void 0){if(typeof ne!="string"||["verbose","info","warning","error","fatal"].indexOf(ne)===-1)throw new Error(`Unsupported logging level: ${ne}`);D=ne}},get logLevel(){return D}},Object.defineProperty($,"logLevel",{enumerable:!0})}),P,L=d(()=>{I(),P=$}),B,U,Z=d(()=>{B=(ne,pe)=>{let xe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);xe.width=ne.dims[3],xe.height=ne.dims[2];let De=xe.getContext("2d");if(De!=null){let ke,Be;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(ke=ne.dims[2],Be=ne.dims[3]):(ke=ne.dims[3],Be=ne.dims[2]);let Ne=(pe==null?void 0:pe.format)!==void 0?pe.format:"RGB",$e=pe==null?void 0:pe.norm,Fe,tt;$e===void 0||$e.mean===void 0?Fe=[255,255,255,255]:typeof $e.mean=="number"?Fe=[$e.mean,$e.mean,$e.mean,$e.mean]:(Fe=[$e.mean[0],$e.mean[1],$e.mean[2],0],$e.mean[3]!==void 0&&(Fe[3]=$e.mean[3])),$e===void 0||$e.bias===void 0?tt=[0,0,0,0]:typeof $e.bias=="number"?tt=[$e.bias,$e.bias,$e.bias,$e.bias]:(tt=[$e.bias[0],$e.bias[1],$e.bias[2],0],$e.bias[3]!==void 0&&(tt[3]=$e.bias[3]));let ot=Be*ke,it=0,Je=ot,$t=ot*2,ze=-1;Ne==="RGBA"?(it=0,Je=ot,$t=ot*2,ze=ot*3):Ne==="RGB"?(it=0,Je=ot,$t=ot*2):Ne==="RBG"&&(it=0,$t=ot,Je=ot*2);for(let dt=0;dt<Be;dt++)for(let Ai=0;Ai<ke;Ai++){let ti=(ne.data[it++]-tt[0])*Fe[0],ii=(ne.data[Je++]-tt[1])*Fe[1],Ni=(ne.data[$t++]-tt[2])*Fe[2],Lt=ze===-1?255:(ne.data[ze++]-tt[3])*Fe[3];De.fillStyle="rgba("+ti+","+ii+","+Ni+","+Lt+")",De.fillRect(Ai,dt,1,1)}if("toDataURL"in xe)return xe.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},U=(ne,pe)=>{let xe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(xe!=null){let ke,Be,Ne;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(ke=ne.dims[2],Be=ne.dims[1],Ne=ne.dims[3]):(ke=ne.dims[3],Be=ne.dims[2],Ne=ne.dims[1]);let $e=pe!==void 0&&pe.format!==void 0?pe.format:"RGB",Fe=pe==null?void 0:pe.norm,tt,ot;Fe===void 0||Fe.mean===void 0?tt=[255,255,255,255]:typeof Fe.mean=="number"?tt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(tt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(tt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?ot=[0,0,0,0]:typeof Fe.bias=="number"?ot=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(ot=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(ot[3]=Fe.bias[3]));let it=Be*ke;if(pe!==void 0&&(pe.format!==void 0&&Ne===4&&pe.format!=="RGBA"||Ne===3&&pe.format!=="RGB"&&pe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Je=4,$t=0,ze=1,dt=2,Ai=3,ti=0,ii=it,Ni=it*2,Lt=-1;$e==="RGBA"?(ti=0,ii=it,Ni=it*2,Lt=it*3):$e==="RGB"?(ti=0,ii=it,Ni=it*2):$e==="RBG"&&(ti=0,Ni=it,ii=it*2),De=xe.createImageData(ke,Be);for(let Mi=0;Mi<Be*ke;$t+=Je,ze+=Je,dt+=Je,Ai+=Je,Mi++)De.data[$t]=(ne.data[ti++]-ot[0])*tt[0],De.data[ze]=(ne.data[ii++]-ot[1])*tt[1],De.data[dt]=(ne.data[Ni++]-ot[2])*tt[2],De.data[Ai]=Lt===-1?255:(ne.data[Lt++]-ot[3])*tt[3]}else throw new Error("Can not access image data");return De}}),X,W,J,te,le,ue,V=d(()=>{Pe(),X=(ne,pe)=>{if(ne===void 0)throw new Error("Image buffer must be defined");if(pe.height===void 0||pe.width===void 0)throw new Error("Image height and width must be defined");if(pe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:xe,width:De}=pe,ke=pe.norm??{mean:255,bias:0},Be,Ne;typeof ke.mean=="number"?Be=[ke.mean,ke.mean,ke.mean,ke.mean]:Be=[ke.mean[0],ke.mean[1],ke.mean[2],ke.mean[3]??255],typeof ke.bias=="number"?Ne=[ke.bias,ke.bias,ke.bias,ke.bias]:Ne=[ke.bias[0],ke.bias[1],ke.bias[2],ke.bias[3]??0];let $e=pe.format!==void 0?pe.format:"RGBA",Fe=pe.tensorFormat!==void 0&&pe.tensorFormat!==void 0?pe.tensorFormat:"RGB",tt=xe*De,ot=Fe==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,Je=0,$t=1,ze=2,dt=3,Ai=0,ti=tt,ii=tt*2,Ni=-1;$e==="RGB"&&(it=3,Je=0,$t=1,ze=2,dt=-1),Fe==="RGBA"?Ni=tt*3:Fe==="RBG"?(Ai=0,ii=tt,ti=tt*2):Fe==="BGR"&&(ii=0,ti=tt,Ai=tt*2);for(let Lt=0;Lt<tt;Lt++,Je+=it,ze+=it,$t+=it,dt+=it)ot[Ai++]=(ne[Je]+Ne[0])/Be[0],ot[ti++]=(ne[$t]+Ne[1])/Be[1],ot[ii++]=(ne[ze]+Ne[2])/Be[2],Ni!==-1&&dt!==-1&&(ot[Ni++]=(ne[dt]+Ne[3])/Be[3]);return Fe==="RGBA"?new re("float32",ot,[1,4,xe,De]):new re("float32",ot,[1,3,xe,De])},W=async(ne,pe)=>{let xe=typeof HTMLImageElement<"u"&&ne instanceof HTMLImageElement,De=typeof ImageData<"u"&&ne instanceof ImageData,ke=typeof ImageBitmap<"u"&&ne instanceof ImageBitmap,Be=typeof ne=="string",Ne,$e=pe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=ot=>typeof HTMLCanvasElement<"u"&&ot instanceof HTMLCanvasElement||ot instanceof OffscreenCanvas?ot.getContext("2d"):null;if(xe){let ot=Fe();ot.width=ne.width,ot.height=ne.height;let it=tt(ot);if(it!=null){let Je=ne.height,$t=ne.width;if(pe!==void 0&&pe.resizedHeight!==void 0&&pe.resizedWidth!==void 0&&(Je=pe.resizedHeight,$t=pe.resizedWidth),pe!==void 0){if($e=pe,pe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$e.tensorFormat="RGBA",$e.height=Je,$e.width=$t}else $e.tensorFormat="RGBA",$e.height=Je,$e.width=$t;it.drawImage(ne,0,0),Ne=it.getImageData(0,0,$t,Je).data}else throw new Error("Can not access image data")}else if(De){let ot,it;if(pe!==void 0&&pe.resizedWidth!==void 0&&pe.resizedHeight!==void 0?(ot=pe.resizedHeight,it=pe.resizedWidth):(ot=ne.height,it=ne.width),pe!==void 0&&($e=pe),$e.format="RGBA",$e.height=ot,$e.width=it,pe!==void 0){let Je=Fe();Je.width=it,Je.height=ot;let $t=tt(Je);if($t!=null)$t.putImageData(ne,0,0),Ne=$t.getImageData(0,0,it,ot).data;else throw new Error("Can not access image data")}else Ne=ne.data}else if(ke){if(pe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ot=Fe();ot.width=ne.width,ot.height=ne.height;let it=tt(ot);if(it!=null){let Je=ne.height,$t=ne.width;return it.drawImage(ne,0,0,$t,Je),Ne=it.getImageData(0,0,$t,Je).data,$e.height=Je,$e.width=$t,X(Ne,$e)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((ot,it)=>{let Je=Fe(),$t=tt(Je);if(!ne||!$t)return it();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=ne,ze.onload=()=>{Je.width=ze.width,Je.height=ze.height,$t.drawImage(ze,0,0,Je.width,Je.height);let dt=$t.getImageData(0,0,Je.width,Je.height);$e.height=Je.height,$e.width=Je.width,ot(X(dt.data,$e))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ne!==void 0)return X(Ne,$e);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(ne,pe)=>{let{width:xe,height:De,download:ke,dispose:Be}=pe,Ne=[1,De,xe,4];return new re({location:"texture",type:"float32",texture:ne,dims:Ne,download:ke,dispose:Be})},te=(ne,pe)=>{let{dataType:xe,dims:De,download:ke,dispose:Be}=pe;return new re({location:"gpu-buffer",type:xe??"float32",gpuBuffer:ne,dims:De,download:ke,dispose:Be})},le=(ne,pe)=>{let{dataType:xe,dims:De,download:ke,dispose:Be}=pe;return new re({location:"ml-tensor",type:xe??"float32",mlTensor:ne,dims:De,download:ke,dispose:Be})},ue=(ne,pe,xe)=>new re({location:"cpu-pinned",type:ne,data:pe,dims:xe??[pe.length]})}),ie,K,se,oe,be=d(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),se=!1,oe=()=>{if(!se){se=!0;let ne=typeof BigInt64Array<"u"&&BigInt64Array.from,pe=typeof BigUint64Array<"u"&&BigUint64Array.from,xe=globalThis.Float16Array,De=typeof xe<"u"&&xe.from;ne&&(ie.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),pe&&(ie.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),De?(ie.set("float16",xe),K.set(xe,"float16")):ie.set("float16",Uint16Array)}}}),je,Te,ve=d(()=>{Pe(),je=ne=>{let pe=1;for(let xe=0;xe<ne.length;xe++){let De=ne[xe];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${xe}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${xe}] must be a non-negative integer, got: ${De}`);pe*=De}return pe},Te=(ne,pe)=>{switch(ne.location){case"cpu":return new re(ne.type,ne.data,pe);case"cpu-pinned":return new re({location:"cpu-pinned",data:ne.data,type:ne.type,dims:pe});case"texture":return new re({location:"texture",texture:ne.texture,type:ne.type,dims:pe});case"gpu-buffer":return new re({location:"gpu-buffer",gpuBuffer:ne.gpuBuffer,type:ne.type,dims:pe});case"ml-tensor":return new re({location:"ml-tensor",mlTensor:ne.mlTensor,type:ne.type,dims:pe});default:throw new Error(`tensorReshape: tensor location ${ne.location} is not supported`)}}}),re,Pe=d(()=>{Z(),V(),be(),ve(),re=class{constructor(ne,pe,xe){oe();let De,ke;if(typeof ne=="object"&&"location"in ne)switch(this.dataLocation=ne.location,De=ne.type,ke=ne.dims,ne.location){case"cpu-pinned":{let Ne=ie.get(De);if(!Ne)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(ne.data instanceof Ne))throw new TypeError(`buffer should be of type ${Ne.name}`);this.cpuData=ne.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=ne.texture,this.downloader=ne.download,this.disposer=ne.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=ne.gpuBuffer,this.downloader=ne.download,this.disposer=ne.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=ne.mlTensor,this.downloader=ne.download,this.disposer=ne.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ne,$e;if(typeof ne=="string")if(De=ne,$e=xe,ne==="string"){if(!Array.isArray(pe))throw new TypeError("A string tensor's data must be a string array.");Ne=pe}else{let Fe=ie.get(ne);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${ne}.`);if(Array.isArray(pe)){if(ne==="float16"&&Fe===Uint16Array||ne==="uint4"||ne==="int4")throw new TypeError(`Creating a ${ne} tensor from number array is not supported. Please use ${Fe.name} as data.`);ne==="uint64"||ne==="int64"?Ne=Fe.from(pe,BigInt):Ne=Fe.from(pe)}else if(pe instanceof Fe)Ne=pe;else if(pe instanceof Uint8ClampedArray)if(ne==="uint8")Ne=Uint8Array.from(pe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(ne==="float16"&&pe instanceof Uint16Array&&Fe!==Uint16Array)Ne=new globalThis.Float16Array(pe.buffer,pe.byteOffset,pe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if($e=pe,Array.isArray(ne)){if(ne.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof ne[0];if(Fe==="string")De="string",Ne=ne;else if(Fe==="boolean")De="bool",Ne=Uint8Array.from(ne);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(ne instanceof Uint8ClampedArray)De="uint8",Ne=Uint8Array.from(ne);else{let Fe=K.get(ne.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${ne.constructor}.`);De=Fe,Ne=ne}if($e===void 0)$e=[Ne.length];else if(!Array.isArray($e))throw new TypeError("A tensor's dims must be a number array");ke=$e,this.cpuData=Ne,this.dataLocation="cpu"}let Be=je(ke);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=ke,this.size=Be}static async fromImage(ne,pe){return W(ne,pe)}static fromTexture(ne,pe){return J(ne,pe)}static fromGpuBuffer(ne,pe){return te(ne,pe)}static fromMLTensor(ne,pe){return le(ne,pe)}static fromPinnedBuffer(ne,pe,xe){return ue(ne,pe,xe)}toDataURL(ne){return B(this,ne)}toImageData(ne){return U(this,ne)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(ne){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let pe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=pe,ne&&this.disposer&&(this.disposer(),this.disposer=void 0),pe}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(ne){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Te(this,ne)}}}),_e,Qe=d(()=>{Pe(),_e=re}),st,yt,qt,ut,nt,Le,ht=d(()=>{I(),st=(ne,pe)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${ne}::ORT::${pe}`)},yt=(ne,pe)=>{var ke;let xe=((ke=new Error().stack)==null?void 0:ke.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<xe.length;Be++){if(De&&!xe[Be].includes("TRACE_FUNC")){let Ne=`FUNC_${ne}::${xe[Be].trim().split(" ")[1]}`;pe&&(Ne+=`::${pe}`),st("CPU",Ne);return}xe[Be].includes("TRACE_FUNC")&&(De=!0)}},qt=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||yt("BEGIN",ne)},ut=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||yt("END",ne)},nt=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${ne}`)},Le=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${ne}`)}}),Gt,di=d(()=>{y(),Qe(),ht(),Gt=class oE{constructor(pe){this.handler=pe}async run(pe,xe,De){qt(),nt("InferenceSession.run");let ke={},Be={};if(typeof pe!="object"||pe===null||pe instanceof _e||Array.isArray(pe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ne=!0;if(typeof xe=="object"){if(xe===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(xe instanceof _e)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(xe)){if(xe.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ne=!1;for(let tt of xe){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);ke[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,ot=Object.getOwnPropertyNames(xe);for(let it of this.outputNames)if(ot.indexOf(it)!==-1){let Je=xe[it];(Je===null||Je instanceof _e)&&(tt=!0,Ne=!1,ke[it]=Je)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=xe}}else if(typeof xe<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof pe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if(Ne)for(let tt of this.outputNames)ke[tt]=null;let $e=await this.handler.run(pe,ke,Be),Fe={};for(let tt in $e)if(Object.hasOwnProperty.call($e,tt)){let ot=$e[tt];ot instanceof _e?Fe[tt]=ot:Fe[tt]=new _e(ot.type,ot.data,ot.dims)}return Le("InferenceSession.run"),ut(),Fe}async release(){return this.handler.dispose()}static async create(pe,xe,De,ke){qt(),nt("InferenceSession.create");let Be,Ne={};if(typeof pe=="string"){if(Be=pe,typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof Uint8Array){if(Be=pe,typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&pe instanceof SharedArrayBuffer){let ot=pe,it=0,Je=pe.byteLength;if(typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe=="number"){if(it=xe,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=ot.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ot.byteLength}).`);if(Je=pe.byteLength-it,typeof De=="number"){if(Je=De,!Number.isSafeInteger(Je))throw new RangeError("'byteLength' must be an integer.");if(Je<=0||it+Je>ot.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ot.byteLength-it}].`);if(typeof ke=="object"&&ke!==null)Ne=ke;else if(typeof ke<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof xe<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(ot,it,Je)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$e,Fe]=await x(Ne),tt=await $e.createInferenceSessionHandler(Be,Fe);return Le("InferenceSession.create"),ut(),new oE(tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ue,_t=d(()=>{di(),Ue=Gt}),ft=d(()=>{}),ui=d(()=>{}),ji=d(()=>{}),Jn=d(()=>{}),xr={};p(xr,{InferenceSession:()=>Ue,TRACE:()=>st,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>Le,TRACE_FUNC_BEGIN:()=>qt,TRACE_FUNC_END:()=>ut,Tensor:()=>_e,env:()=>P,registerBackend:()=>w});var fi=d(()=>{_(),L(),_t(),Qe(),ft(),ui(),ht(),ji(),Jn()}),Bn=d(()=>{}),Wi={};p(Wi,{default:()=>$s});var on,mi,$s,Xa=d(()=>{var ne;ye(),er(),Qn(),on="ort-wasm-proxy-worker",mi=((ne=globalThis.self)==null?void 0:ne.name)===on,mi&&(self.onmessage=pe=>{let{type:xe,in:De}=pe.data;try{switch(xe){case"init-wasm":fs(De.wasm).then(()=>{pa(De).then(()=>{postMessage({type:xe})},ke=>{postMessage({type:xe,err:ke})})},ke=>{postMessage({type:xe,err:ke})});break;case"init-ep":{let{epName:ke,env:Be}=De;zs(Be,ke).then(()=>{postMessage({type:xe})},Ne=>{postMessage({type:xe,err:Ne})});break}case"copy-from":{let{buffer:ke}=De,Be=oi(ke);postMessage({type:xe,out:Be});break}case"create":{let{model:ke,options:Be}=De;Sr(ke,Be).then(Ne=>{postMessage({type:xe,out:Ne})},Ne=>{postMessage({type:xe,err:Ne})});break}case"release":ro(De),postMessage({type:xe});break;case"run":{let{sessionId:ke,inputIndices:Be,inputs:Ne,outputIndices:$e,options:Fe}=De;Xe(ke,Be,Ne,$e,new Array($e.length).fill(null),Fe).then(tt=>{tt.some(ot=>ot[3]!=="cpu")?postMessage({type:xe,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:xe,out:tt},gt([...Ne,...tt]))},tt=>{postMessage({type:xe,err:tt})});break}case"end-profiling":ir(De),postMessage({type:xe});break;default:}}catch(ke){postMessage({type:xe,err:ke})}}),$s=mi?null:pe=>new Worker(pe??_i,{type:"classic",name:on})}),ua,Ps,_i,Zn,an,Rs,Vr,br,to,Is,Ms,qr,Fn,Qn=d(()=>{Bn(),ua=typeof location>"u"?void 0:location.origin,Ps=()=>{var ne,pe;return typeof document<"u"?(ne=document.currentScript)==null?void 0:ne.src:typeof self<"u"?(pe=self.location)==null?void 0:pe.href:void 0},_i=Ps(),Zn=()=>{if(_i&&!_i.startsWith("blob:"))return _i.substring(0,_i.lastIndexOf("/")+1)},an=(ne,pe)=>{try{let xe=pe??_i;return(xe?new URL(ne,xe):new URL(ne)).origin===ua}catch{return!1}},Rs=(ne,pe)=>{let xe=pe??_i;try{return(xe?new URL(ne,xe):new URL(ne)).href}catch{return}},Vr=(ne,pe)=>`${pe??"./"}${ne}`,br=async ne=>{let pe=await(await fetch(ne,{credentials:"same-origin"})).blob();return URL.createObjectURL(pe)},to=async ne=>(await import(ne)).default,Is=(Xa(),f(Wi)).default,Ms=async()=>{if(!_i)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(an(_i))return[void 0,Is()];let ne=await br(_i);return[ne,Is(ne)]},qr=void 0,Fn=async(ne,pe,xe,De)=>{let ke=qr&&!(ne||pe);if(ke)if(_i)ke=an(_i)||De&&!xe;else if(De&&!xe)ke=!0;else throw new Error("cannot determine the script source URL.");if(ke)return[void 0,qr];{let Be="ort-wasm-simd-threaded.mjs",Ne=ne??Rs(Be,pe),$e=xe&&Ne&&!an(Ne,pe),Fe=$e?await br(Ne):Ne??Vr(Be,pe);return[$e?Fe:void 0,await to(Fe)]}}}),us,Gn,yr,zr,jo,hs,ps,fs,Bt,er=d(()=>{Qn(),Gn=!1,yr=!1,zr=!1,jo=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},hs=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ps=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},fs=async ne=>{if(Gn)return Promise.resolve();if(yr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zr)throw new Error("previous call to 'initializeWebAssembly()' failed.");yr=!0;let pe=ne.initTimeout,xe=ne.numThreads;if(ne.simd!==!1){if(ne.simd==="relaxed"){if(!ps())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!hs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=jo();xe>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+xe+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),ne.numThreads=xe=1);let ke=ne.wasmPaths,Be=typeof ke=="string"?ke:void 0,Ne=ke==null?void 0:ke.mjs,$e=(Ne==null?void 0:Ne.href)??Ne,Fe=ke==null?void 0:ke.wasm,tt=(Fe==null?void 0:Fe.href)??Fe,ot=ne.wasmBinary,[it,Je]=await Fn($e,Be,xe>1,!!ot||!!tt),$t=!1,ze=[];if(pe>0&&ze.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},pe)})),ze.push(new Promise((dt,Ai)=>{let ti={numThreads:xe};if(ot)ti.wasmBinary=ot,ti.locateFile=ii=>ii;else if(tt||Be)ti.locateFile=ii=>tt??Be+ii;else if($e&&$e.indexOf("blob:")!==0)ti.locateFile=ii=>new URL(ii,$e).href;else if(it){let ii=Zn();ii&&(ti.locateFile=Ni=>ii+Ni)}Je(ti).then(ii=>{yr=!1,Gn=!0,us=ii,dt(),it&&URL.revokeObjectURL(it)},ii=>{yr=!1,zr=!0,Ai(ii)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${pe}ms`)},Bt=()=>{if(Gn&&us)return us;throw new Error("WebAssembly is not initialized yet.")}}),Vi,Ci,Et,io=d(()=>{er(),Vi=(ne,pe)=>{let xe=Bt(),De=xe.lengthBytesUTF8(ne)+1,ke=xe._malloc(De);return xe.stringToUTF8(ne,ke,De),pe.push(ke),ke},Ci=(ne,pe,xe,De)=>{if(typeof ne=="object"&&ne!==null){if(xe.has(ne))throw new Error("Circular reference in options");xe.add(ne)}Object.entries(ne).forEach(([ke,Be])=>{let Ne=pe?pe+ke:ke;if(typeof Be=="object")Ci(Be,Ne+".",xe,De);else if(typeof Be=="string"||typeof Be=="number")De(Ne,Be.toString());else if(typeof Be=="boolean")De(Ne,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=ne=>{let pe=Bt(),xe=pe.stackSave();try{let De=pe.PTR_SIZE,ke=pe.stackAlloc(2*De);pe._OrtGetLastError(ke,ke+De);let Be=Number(pe.getValue(ke,De===4?"i32":"i64")),Ne=pe.getValue(ke+De,"*"),$e=Ne?pe.UTF8ToString(Ne):"";throw new Error(`${ne} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${$e}`)}finally{pe.stackRestore(xe)}}}),Do,Ja=d(()=>{er(),io(),Do=ne=>{let pe=Bt(),xe=0,De=[],ke=ne||{};try{if((ne==null?void 0:ne.logSeverityLevel)===void 0)ke.logSeverityLevel=2;else if(typeof ne.logSeverityLevel!="number"||!Number.isInteger(ne.logSeverityLevel)||ne.logSeverityLevel<0||ne.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${ne.logSeverityLevel}`);if((ne==null?void 0:ne.logVerbosityLevel)===void 0)ke.logVerbosityLevel=0;else if(typeof ne.logVerbosityLevel!="number"||!Number.isInteger(ne.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${ne.logVerbosityLevel}`);(ne==null?void 0:ne.terminate)===void 0&&(ke.terminate=!1);let Be=0;return(ne==null?void 0:ne.tag)!==void 0&&(Be=Vi(ne.tag,De)),xe=pe._OrtCreateRunOptions(ke.logSeverityLevel,ke.logVerbosityLevel,!!ke.terminate,Be),xe===0&&Et("Can't create run options."),(ne==null?void 0:ne.extra)!==void 0&&Ci(ne.extra,"",new WeakSet,(Ne,$e)=>{let Fe=Vi(Ne,De),tt=Vi($e,De);pe._OrtAddRunConfigEntry(xe,Fe,tt)!==0&&Et(`Can't set a run config entry: ${Ne} - ${$e}.`)}),[xe,De]}catch(Be){throw xe!==0&&pe._OrtReleaseRunOptions(xe),De.forEach(Ne=>pe._free(Ne)),Be}}}),Ao,No,ha,$n,Za,Qa,Ei=d(()=>{er(),io(),Ao=ne=>{switch(ne){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${ne}`)}},No=ne=>{switch(ne){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${ne}`)}},ha=ne=>{ne.extra||(ne.extra={}),ne.extra.session||(ne.extra.session={});let pe=ne.extra.session;pe.use_ort_model_bytes_directly||(pe.use_ort_model_bytes_directly="1"),ne.executionProviders&&ne.executionProviders.some(xe=>(typeof xe=="string"?xe:xe.name)==="webgpu")&&(ne.enableMemPattern=!1)},$n=(ne,pe,xe,De)=>{let ke=Vi(pe,De),Be=Vi(xe,De);Bt()._OrtAddSessionConfigEntry(ne,ke,Be)!==0&&Et(`Can't set a session config entry: ${pe} - ${xe}.`)},Za=async(ne,pe,xe)=>{let De=pe.executionProviders;for(let ke of De){let Be=typeof ke=="string"?ke:ke.name,Ne=[];switch(Be){case"webnn":if(Be="WEBNN",$n(ne,"session.disable_quant_qdq","1",xe),$n(ne,"session.disable_qdq_constant_folding","1",xe),typeof ke!="string"){let it=ke==null?void 0:ke.deviceType;it&&$n(ne,"deviceType",it,xe)}break;case"webgpu":if(Be="JS",typeof ke!="string"){let it=ke;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);$n(ne,"preferredLayout",it.preferredLayout,xe)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let $e=Vi(Be,xe),Fe=Ne.length,tt=0,ot=0;if(Fe>0){tt=Bt()._malloc(Fe*Bt().PTR_SIZE),xe.push(tt),ot=Bt()._malloc(Fe*Bt().PTR_SIZE),xe.push(ot);for(let it=0;it<Fe;it++)Bt().setValue(tt+it*Bt().PTR_SIZE,Ne[it][0],"*"),Bt().setValue(ot+it*Bt().PTR_SIZE,Ne[it][1],"*")}await Bt()._OrtAppendExecutionProvider(ne,$e,tt,ot,Fe)!==0&&Et(`Can't append execution provider: ${Be}.`)}},Qa=async ne=>{let pe=Bt(),xe=0,De=[],ke=ne||{};ha(ke);try{let Be=Ao(ke.graphOptimizationLevel??"all"),Ne=No(ke.executionMode??"sequential"),$e=typeof ke.logId=="string"?Vi(ke.logId,De):0,Fe=ke.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let tt=ke.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let ot=typeof ke.optimizedModelFilePath=="string"?Vi(ke.optimizedModelFilePath,De):0;if(xe=pe._OrtCreateSessionOptions(Be,!!ke.enableCpuMemArena,!!ke.enableMemPattern,Ne,!!ke.enableProfiling,0,$e,Fe,tt,ot),xe===0&&Et("Can't create session options."),ke.executionProviders&&await Za(xe,ke,De),ke.enableGraphCapture!==void 0){if(typeof ke.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ke.enableGraphCapture}`);$n(xe,"enableGraphCapture",ke.enableGraphCapture.toString(),De)}if(ke.freeDimensionOverrides)for(let[it,Je]of Object.entries(ke.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof Je!="number"||!Number.isInteger(Je)||Je<0)throw new Error(`free dimension override value must be a non-negative integer: ${Je}`);let $t=Vi(it,De);pe._OrtAddFreeDimensionOverride(xe,$t,Je)!==0&&Et(`Can't set a free dimension override: ${it} - ${Je}.`)}return ke.extra!==void 0&&Ci(ke.extra,"",new WeakSet,(it,Je)=>{$n(xe,it,Je,De)}),[xe,De]}catch(Be){throw xe!==0&&pe._OrtReleaseSessionOptions(xe)!==0&&Et("Can't release session options."),De.forEach(Ne=>pe._free(Ne)),Be}}}),Un,Yi,Hn,ms,no,Os,_r,kn,Ft=d(()=>{Un=ne=>{switch(ne){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${ne}`)}},Yi=ne=>{switch(ne){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${ne}`)}},Hn=(ne,pe)=>{let xe=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][ne],De=typeof pe=="number"?pe:pe.reduce((ke,Be)=>ke*Be,1);return xe>0?Math.ceil(De*xe):void 0},ms=ne=>{switch(ne){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${ne}`)}},no=ne=>{switch(ne){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${ne}`)}},Os=ne=>ne==="float32"||ne==="float16"||ne==="int32"||ne==="int64"||ne==="uint32"||ne==="uint8"||ne==="bool"||ne==="uint4"||ne==="int4",_r=ne=>ne==="float32"||ne==="float16"||ne==="int32"||ne==="int64"||ne==="uint32"||ne==="uint64"||ne==="int8"||ne==="uint8"||ne==="bool"||ne==="uint4"||ne==="int4",kn=ne=>{switch(ne){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${ne}`)}}}),Xi,Ls=d(()=>{Bn(),Xi=async ne=>{if(typeof ne=="string"){let pe=await fetch(ne);if(!pe.ok)throw new Error(`failed to load external data file: ${ne}`);let xe=pe.headers.get("Content-Length"),De=xe?parseInt(xe,10):0;if(De<1073741824)return new Uint8Array(await pe.arrayBuffer());{if(!pe.body)throw new Error(`failed to load external data file: ${ne}, no response body.`);let ke=pe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch($e){if($e instanceof RangeError){let Fe=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw $e}let Ne=0;for(;;){let{done:$e,value:Fe}=await ke.read();if($e)break;let tt=Fe.byteLength;new Uint8Array(Be,Ne,tt).set(Fe),Ne+=tt}return new Uint8Array(Be,0,De)}}else return ne instanceof Blob?new Uint8Array(await ne.arrayBuffer()):ne instanceof Uint8Array?ne:new Uint8Array(ne)}}),wr,pa,zs,tr,Kr,Bs,oi,Sr,ro,Br,Xe,ir,gt,ye=d(()=>{fi(),Ja(),Ei(),Ft(),er(),io(),Ls(),wr=(ne,pe)=>{Bt()._OrtInit(ne,pe)!==0&&Et("Can't initialize onnxruntime.")},pa=async ne=>{wr(ne.wasm.numThreads,no(ne.logLevel))},zs=async(ne,pe)=>{var De,ke;(ke=(De=Bt()).asyncInit)==null||ke.call(De);let xe=ne.webgpu.adapter;if(pe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(xe){if(typeof xe.limits!="object"||typeof xe.features!="object"||typeof xe.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=ne.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Ne=ne.webgpu.forceFallbackAdapter;if(Ne!==void 0&&typeof Ne!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ne}"`);if(xe=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Ne}),!xe)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(pe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},tr=new Map,Kr=ne=>{let pe=Bt(),xe=pe.stackSave();try{let De=pe.PTR_SIZE,ke=pe.stackAlloc(2*De);pe._OrtGetInputOutputCount(ne,ke,ke+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(pe.getValue(ke,Be)),Number(pe.getValue(ke+De,Be))]}finally{pe.stackRestore(xe)}},Bs=(ne,pe)=>{let xe=Bt(),De=xe.stackSave(),ke=0;try{let Be=xe.PTR_SIZE,Ne=xe.stackAlloc(2*Be);xe._OrtGetInputOutputMetadata(ne,pe,Ne,Ne+Be)!==0&&Et("Can't get session input/output metadata.");let $e=Number(xe.getValue(Ne,"*"));ke=Number(xe.getValue(Ne+Be,"*"));let Fe=xe.HEAP32[ke/4];if(Fe===0)return[$e,0];let tt=xe.HEAPU32[ke/4+1],ot=[];for(let it=0;it<tt;it++){let Je=Number(xe.getValue(ke+8+it*Be,"*"));ot.push(Je!==0?xe.UTF8ToString(Je):Number(xe.getValue(ke+8+(it+tt)*Be,"*")))}return[$e,Fe,ot]}finally{xe.stackRestore(De),ke!==0&&xe._OrtFree(ke)}},oi=ne=>{let pe=Bt(),xe=pe._malloc(ne.byteLength);if(xe===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${ne.byteLength}.`);return pe.HEAPU8.set(ne,xe),[xe,ne.byteLength]},Sr=async(ne,pe)=>{var ot,it,Je;let xe,De,ke=Bt();Array.isArray(ne)?[xe,De]=ne:ne.buffer===ke.HEAPU8.buffer?[xe,De]=[ne.byteOffset,ne.byteLength]:[xe,De]=oi(ne);let Be=0,Ne=0,$e=[],Fe=[],tt=[];try{if([Ne,$e]=await Qa(pe),(pe==null?void 0:pe.externalData)&&ke.mountExternalData){let Mi=[];for(let hi of pe.externalData){let Cn=typeof hi=="string"?hi:hi.path;Mi.push(Xi(typeof hi=="string"?hi:hi.data).then(Wn=>{ke.mountExternalData(Cn,Wn)}))}await Promise.all(Mi)}for(let Mi of(pe==null?void 0:pe.executionProviders)??[])if((typeof Mi=="string"?Mi:Mi.name)==="webnn"){if(ke.shouldTransferToMLTensor=!1,typeof Mi!="string"){let hi=Mi,Cn=hi==null?void 0:hi.context,Wn=hi==null?void 0:hi.gpuDevice,nr=hi==null?void 0:hi.deviceType,tl=hi==null?void 0:hi.powerPreference;Cn?ke.currentContext=Cn:Wn?ke.currentContext=await ke.webnnCreateMLContext(Wn):ke.currentContext=await ke.webnnCreateMLContext({deviceType:nr,powerPreference:tl})}else ke.currentContext=await ke.webnnCreateMLContext();break}Be=await ke._OrtCreateSession(xe,De,Ne),(ot=ke.webgpuOnCreateSession)==null||ot.call(ke,Be),Be===0&&Et("Can't create a session."),(it=ke.jsepOnCreateSession)==null||it.call(ke),ke.currentContext&&(ke.webnnRegisterMLContext(Be,ke.currentContext),ke.currentContext=void 0,ke.shouldTransferToMLTensor=!0);let[$t,ze]=Kr(Be),dt=!!(pe!=null&&pe.enableGraphCapture),Ai=[],ti=[],ii=[],Ni=[],Lt=[];for(let Mi=0;Mi<$t;Mi++){let[hi,Cn,Wn]=Bs(Be,Mi);hi===0&&Et("Can't get an input name."),Fe.push(hi);let nr=ke.UTF8ToString(hi);Ai.push(nr),ii.push(Cn===0?{name:nr,isTensor:!1}:{name:nr,isTensor:!0,type:Yi(Cn),shape:Wn})}for(let Mi=0;Mi<ze;Mi++){let[hi,Cn,Wn]=Bs(Be,Mi+$t);hi===0&&Et("Can't get an output name."),tt.push(hi);let nr=ke.UTF8ToString(hi);ti.push(nr),Ni.push(Cn===0?{name:nr,isTensor:!1}:{name:nr,isTensor:!0,type:Yi(Cn),shape:Wn})}return tr.set(Be,[Be,Fe,tt,null,dt,!1]),[Be,Ai,ti,ii,Ni]}catch($t){throw Fe.forEach(ze=>ke._OrtFree(ze)),tt.forEach(ze=>ke._OrtFree(ze)),Be!==0&&ke._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{ke._free(xe),Ne!==0&&ke._OrtReleaseSessionOptions(Ne)!==0&&Et("Can't release session options."),$e.forEach($t=>ke._free($t)),(Je=ke.unmountExternalData)==null||Je.call(ke)}},ro=ne=>{var Fe,tt,ot;let pe=Bt(),xe=tr.get(ne);if(!xe)throw new Error(`cannot release session. invalid session id: ${ne}`);let[De,ke,Be,Ne,$e]=xe;Ne&&($e&&pe._OrtClearBoundOutputs(Ne.handle)!==0&&Et("Can't clear bound outputs."),pe._OrtReleaseBinding(Ne.handle)!==0&&Et("Can't release IO binding.")),(Fe=pe.jsepOnReleaseSession)==null||Fe.call(pe,ne),(tt=pe.webnnOnReleaseSession)==null||tt.call(pe,ne),(ot=pe.webgpuOnReleaseSession)==null||ot.call(pe,ne),ke.forEach(it=>pe._OrtFree(it)),Be.forEach(it=>pe._OrtFree(it)),pe._OrtReleaseSession(De)!==0&&Et("Can't release session."),tr.delete(ne)},Br=async(ne,pe,xe,De,ke,Be,Ne=!1)=>{if(!ne){pe.push(0);return}let $e=Bt(),Fe=$e.PTR_SIZE,tt=ne[0],ot=ne[1],it=ne[3],Je=it,$t,ze;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ne&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let ti=ne[2].gpuBuffer;ze=Hn(Un(tt),ot);{let ii=$e.jsepRegisterBuffer;if(!ii)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=ii(De,Be,ti,ze)}}else if(it==="ml-tensor"){let ti=ne[2].mlTensor;ze=Hn(Un(tt),ot);let ii=$e.webnnRegisterMLTensor;if(!ii)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=ii(De,ti,Un(tt),ot)}else{let ti=ne[2];if(Array.isArray(ti)){ze=Fe*ti.length,$t=$e._malloc(ze),xe.push($t);for(let ii=0;ii<ti.length;ii++){if(typeof ti[ii]!="string")throw new TypeError(`tensor data at index ${ii} is not a string`);$e.setValue($t+ii*Fe,Vi(ti[ii],xe),"*")}}else{let ii=$e.webnnIsGraphInput,Ni=$e.webnnIsGraphOutput;if(tt!=="string"&&ii&&Ni){let Lt=$e.UTF8ToString(ke);if(ii(De,Lt)||Ni(De,Lt)){let Mi=Un(tt);ze=Hn(Mi,ot),Je="ml-tensor";let hi=$e.webnnCreateTemporaryTensor,Cn=$e.webnnUploadTensor;if(!hi||!Cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Wn=await hi(De,Mi,ot);Cn(Wn,new Uint8Array(ti.buffer,ti.byteOffset,ti.byteLength)),$t=Wn}else ze=ti.byteLength,$t=$e._malloc(ze),xe.push($t),$e.HEAPU8.set(new Uint8Array(ti.buffer,ti.byteOffset,ze),$t)}else ze=ti.byteLength,$t=$e._malloc(ze),xe.push($t),$e.HEAPU8.set(new Uint8Array(ti.buffer,ti.byteOffset,ze),$t)}}let dt=$e.stackSave(),Ai=$e.stackAlloc(4*ot.length);try{ot.forEach((ii,Ni)=>$e.setValue(Ai+Ni*Fe,ii,Fe===4?"i32":"i64"));let ti=$e._OrtCreateTensor(Un(tt),$t,ze,Ai,ot.length,kn(Je));ti===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),pe.push(ti)}finally{$e.stackRestore(dt)}},Xe=async(ne,pe,xe,De,ke,Be)=>{var rr,Kl,td;let Ne=Bt(),$e=Ne.PTR_SIZE,Fe=tr.get(ne);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${ne}`);let tt=Fe[0],ot=Fe[1],it=Fe[2],Je=Fe[3],$t=Fe[4];Fe[5];let ze=pe.length,dt=De.length,Ai=0,ti=[],ii=[],Ni=[],Lt=[],Mi=[],hi=Ne.stackSave(),Cn=Ne.stackAlloc(ze*$e),Wn=Ne.stackAlloc(ze*$e),nr=Ne.stackAlloc(dt*$e),tl=Ne.stackAlloc(dt*$e);try{[Ai,ti]=Do(Be),nt("wasm prepareInputOutputTensor");for(let ci=0;ci<ze;ci++)await Br(xe[ci],ii,Lt,ne,ot[pe[ci]],pe[ci],$t);for(let ci=0;ci<dt;ci++)await Br(ke[ci],Ni,Lt,ne,it[De[ci]],ze+De[ci],$t);Le("wasm prepareInputOutputTensor");for(let ci=0;ci<ze;ci++)Ne.setValue(Cn+ci*$e,ii[ci],"*"),Ne.setValue(Wn+ci*$e,ot[pe[ci]],"*");for(let ci=0;ci<dt;ci++)Ne.setValue(nr+ci*$e,Ni[ci],"*"),Ne.setValue(tl+ci*$e,it[De[ci]],"*");(rr=Ne.jsepOnRunStart)==null||rr.call(Ne,tt),(Kl=Ne.webnnOnRunStart)==null||Kl.call(Ne,tt);let En;En=await Ne._OrtRun(tt,Wn,Cn,ze,tl,dt,nr,Ai),En!==0&&Et("failed to call OrtRun().");let vs=[],id=[];nt("wasm ProcessOutputTensor");for(let ci=0;ci<dt;ci++){let Xr=Number(Ne.getValue(nr+ci*$e,"*"));if(Xr===Ni[ci]||Mi.includes(Ni[ci])){vs.push(ke[ci]),Xr!==Ni[ci]&&Ne._OrtReleaseTensor(Xr)!==0&&Et("Can't release tensor.");continue}let Su=Ne.stackSave(),Us=Ne.stackAlloc(4*$e),fa=!1,mn,sr=0;try{Ne._OrtGetTensorData(Xr,Us,Us+$e,Us+2*$e,Us+3*$e)!==0&&Et(`Can't access output tensor data on index ${ci}.`);let Yl=$e===4?"i32":"i64",or=Number(Ne.getValue(Us,Yl));sr=Ne.getValue(Us+$e,"*");let nd=Ne.getValue(Us+$e*2,"*"),ku=Number(Ne.getValue(Us+$e*3,Yl)),Hs=[];for(let gn=0;gn<ku;gn++)Hs.push(Number(Ne.getValue(nd+gn*$e,Yl)));Ne._OrtFree(nd)!==0&&Et("Can't free memory for tensor dims.");let Jr=Hs.reduce((gn,qi)=>gn*qi,1);mn=Yi(or);let xs=Je==null?void 0:Je.outputPreferredLocations[De[ci]];if(mn==="string"){if(xs==="gpu-buffer"||xs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let gn=[];for(let qi=0;qi<Jr;qi++){let Zr=Ne.getValue(sr+qi*$e,"*"),rd=Ne.getValue(sr+(qi+1)*$e,"*"),sd=qi===Jr-1?void 0:rd-Zr;gn.push(Ne.UTF8ToString(Zr,sd))}vs.push([mn,Hs,gn,"cpu"])}else if(xs==="gpu-buffer"&&Jr>0){let gn=Ne.jsepGetBuffer;if(!gn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let qi=gn(sr),Zr=Hn(or,Jr);if(Zr===void 0||!Os(mn))throw new Error(`Unsupported data type: ${mn}`);fa=!0,vs.push([mn,Hs,{gpuBuffer:qi,download:Ne.jsepCreateDownloader(qi,Zr,mn),dispose:()=>{Ne._OrtReleaseTensor(Xr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(xs==="ml-tensor"&&Jr>0){let gn=Ne.webnnEnsureTensor,qi=Ne.webnnIsGraphInputOutputTypeSupported;if(!gn||!qi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Hn(or,Jr)===void 0||!_r(mn))throw new Error(`Unsupported data type: ${mn}`);if(!qi(ne,mn,!1))throw new Error(`preferredLocation "ml-tensor" for ${mn} output is not supported by current WebNN Context.`);let Zr=await gn(ne,sr,or,Hs,!1);fa=!0,vs.push([mn,Hs,{mlTensor:Zr,download:Ne.webnnCreateMLTensorDownloader(sr,mn),dispose:()=>{Ne.webnnReleaseTensorId(sr),Ne._OrtReleaseTensor(Xr)}},"ml-tensor"])}else if(xs==="ml-tensor-cpu-output"&&Jr>0){let gn=Ne.webnnCreateMLTensorDownloader(sr,mn)(),qi=vs.length;fa=!0,id.push((async()=>{let Zr=[qi,await gn];return Ne.webnnReleaseTensorId(sr),Ne._OrtReleaseTensor(Xr),Zr})()),vs.push([mn,Hs,[],"cpu"])}else{let gn=ms(mn),qi=new gn(Jr);new Uint8Array(qi.buffer,qi.byteOffset,qi.byteLength).set(Ne.HEAPU8.subarray(sr,sr+qi.byteLength)),vs.push([mn,Hs,qi,"cpu"])}}finally{Ne.stackRestore(Su),mn==="string"&&sr&&Ne._free(sr),fa||Ne._OrtReleaseTensor(Xr)}}Je&&!$t&&(Ne._OrtClearBoundOutputs(Je.handle)!==0&&Et("Can't clear bound outputs."),tr.set(ne,[tt,ot,it,Je,$t,!1]));for(let[ci,Xr]of await Promise.all(id))vs[ci][2]=Xr;return Le("wasm ProcessOutputTensor"),vs}finally{(td=Ne.webnnOnRunEnd)==null||td.call(Ne,tt),Ne.stackRestore(hi),ii.forEach(En=>Ne._OrtReleaseTensor(En)),Ni.forEach(En=>Ne._OrtReleaseTensor(En)),Lt.forEach(En=>Ne._free(En)),Ai!==0&&Ne._OrtReleaseRunOptions(Ai),ti.forEach(En=>Ne._free(En))}},ir=ne=>{let pe=Bt(),xe=tr.get(ne);if(!xe)throw new Error("invalid session id");let De=xe[0],ke=pe._OrtEndProfiling(De);ke===0&&Et("Can't get an profile file name."),pe._OrtFree(ke)},gt=ne=>{let pe=[];for(let xe of ne){let De=xe[2];!Array.isArray(De)&&"buffer"in De&&pe.push(De.buffer)}return pe}}),Ie,Ze,jt,ri,ai,Ri,$i,ln,Bi,fn,Pi,Yr,so,$o,gs,wu,Po,Ro,Zc=d(()=>{fi(),ye(),er(),Qn(),Ie=()=>!!P.wasm.proxy&&typeof document<"u",jt=!1,ri=!1,ai=!1,ln=new Map,Bi=(ne,pe)=>{let xe=ln.get(ne);xe?xe.push(pe):ln.set(ne,[pe])},fn=()=>{if(jt||!ri||ai||!Ze)throw new Error("worker not ready")},Pi=ne=>{switch(ne.data.type){case"init-wasm":jt=!1,ne.data.err?(ai=!0,$i[1](ne.data.err)):(ri=!0,$i[0]()),Ri&&(URL.revokeObjectURL(Ri),Ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let pe=ln.get(ne.data.type);ne.data.err?pe.shift()[1](ne.data.err):pe.shift()[0](ne.data.out);break}}},Yr=async()=>{if(!ri){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(ai)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Ie())return new Promise((ne,pe)=>{Ze==null||Ze.terminate(),Ms().then(([xe,De])=>{try{Ze=De,Ze.onerror=Be=>pe(Be),Ze.onmessage=Pi,$i=[ne,pe];let ke={type:"init-wasm",in:P};if(!ke.in.wasm.wasmPaths&&xe){let Be=Zn();Be&&(ke.in.wasm.wasmPaths=Be)}Ze.postMessage(ke),Ri=xe}catch(ke){pe(ke)}},pe)});try{await fs(P.wasm),await pa(P),ri=!0}catch(ne){throw ai=!0,ne}finally{jt=!1}}},so=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("init-ep",[pe,xe]);let De={type:"init-ep",in:{epName:ne,env:P}};Ze.postMessage(De)});await zs(P,ne)},$o=async ne=>Ie()?(fn(),new Promise((pe,xe)=>{Bi("copy-from",[pe,xe]);let De={type:"copy-from",in:{buffer:ne}};Ze.postMessage(De,[ne.buffer])})):oi(ne),gs=async(ne,pe)=>{if(Ie()){if(pe!=null&&pe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return fn(),new Promise((xe,De)=>{Bi("create",[xe,De]);let ke={type:"create",in:{model:ne,options:{...pe}}},Be=[];ne instanceof Uint8Array&&Be.push(ne.buffer),Ze.postMessage(ke,Be)})}else return Sr(ne,pe)},wu=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("release",[pe,xe]);let De={type:"release",in:ne};Ze.postMessage(De)});ro(ne)},Po=async(ne,pe,xe,De,ke,Be)=>{if(Ie()){if(xe.some(Ne=>Ne[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ke.some(Ne=>Ne))throw new Error("pre-allocated output tensor is not supported for proxy.");return fn(),new Promise((Ne,$e)=>{Bi("run",[Ne,$e]);let Fe=xe,tt={type:"run",in:{sessionId:ne,inputIndices:pe,inputs:Fe,outputIndices:De,options:Be}};Ze.postMessage(tt,gt(Fe))})}else return Xe(ne,pe,xe,De,ke,Be)},Ro=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("end-profiling",[pe,xe]);let De={type:"end-profiling",in:ne};Ze.postMessage(De)});ir(ne)}}),Hl,Io,el,Wl=d(()=>{fi(),Zc(),Ft(),Bn(),Ls(),Hl=(ne,pe)=>{switch(ne.location){case"cpu":return[ne.type,ne.dims,ne.data,"cpu"];case"gpu-buffer":return[ne.type,ne.dims,{gpuBuffer:ne.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[ne.type,ne.dims,{mlTensor:ne.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${ne.location} for ${pe()}`)}},Io=ne=>{switch(ne[3]){case"cpu":return new _e(ne[0],ne[2],ne[1]);case"gpu-buffer":{let pe=ne[0];if(!Os(pe))throw new Error(`not supported data type: ${pe} for deserializing GPU tensor`);let{gpuBuffer:xe,download:De,dispose:ke}=ne[2];return _e.fromGpuBuffer(xe,{dataType:pe,dims:ne[1],download:De,dispose:ke})}case"ml-tensor":{let pe=ne[0];if(!_r(pe))throw new Error(`not supported data type: ${pe} for deserializing MLTensor tensor`);let{mlTensor:xe,download:De,dispose:ke}=ne[2];return _e.fromMLTensor(xe,{dataType:pe,dims:ne[1],download:De,dispose:ke})}default:throw new Error(`invalid data location: ${ne[3]}`)}},el=class{async fetchModelAndCopyToWasmMemory(ne){return $o(await Xi(ne))}async loadModel(ne,pe){qt();let xe;typeof ne=="string"?xe=await this.fetchModelAndCopyToWasmMemory(ne):xe=ne,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await gs(xe,pe),ut()}async dispose(){return wu(this.sessionId)}async run(ne,pe,xe){qt();let De=[],ke=[];Object.entries(ne).forEach(it=>{let Je=it[0],$t=it[1],ze=this.inputNames.indexOf(Je);if(ze===-1)throw new Error(`invalid input '${Je}'`);De.push($t),ke.push(ze)});let Be=[],Ne=[];Object.entries(pe).forEach(it=>{let Je=it[0],$t=it[1],ze=this.outputNames.indexOf(Je);if(ze===-1)throw new Error(`invalid output '${Je}'`);Be.push($t),Ne.push(ze)});let $e=De.map((it,Je)=>Hl(it,()=>`input "${this.inputNames[ke[Je]]}"`)),Fe=Be.map((it,Je)=>it?Hl(it,()=>`output "${this.outputNames[Ne[Je]]}"`):null),tt=await Po(this.sessionId,ke,$e,Ne,Fe,xe),ot={};for(let it=0;it<tt.length;it++)ot[this.outputNames[Ne[it]]]=Be[it]??Io(tt[it]);return ut(),ot}startProfiling(){}endProfiling(){Ro(this.sessionId)}}}),Fs={};p(Fs,{OnnxruntimeWebAssemblyBackend:()=>Gs,initializeFlags:()=>oo,wasmBackend:()=>Mo});var oo,Gs,Mo,Qc=d(()=>{fi(),Zc(),Wl(),oo=()=>{(typeof P.wasm.initTimeout!="number"||P.wasm.initTimeout<0)&&(P.wasm.initTimeout=0);let ne=P.wasm.simd;if(typeof ne!="boolean"&&ne!==void 0&&ne!=="fixed"&&ne!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${ne}". Reset it to \`false\` and ignore SIMD feature checking.`),P.wasm.simd=!1),typeof P.wasm.proxy!="boolean"&&(P.wasm.proxy=!1),typeof P.wasm.trace!="boolean"&&(P.wasm.trace=!1),typeof P.wasm.numThreads!="number"||!Number.isInteger(P.wasm.numThreads)||P.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)P.wasm.numThreads=1;else{let pe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;P.wasm.numThreads=Math.min(4,Math.ceil((pe||1)/2))}},Gs=class{async init(ne){oo(),await Yr(),await so(ne)}async createInferenceSessionHandler(ne,pe){let xe=new el;return await xe.loadModel(ne,pe),xe}},Mo=new Gs}),ed={};p(ed,{InferenceSession:()=>Ue,TRACE:()=>st,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>Le,TRACE_FUNC_BEGIN:()=>qt,TRACE_FUNC_END:()=>ut,Tensor:()=>_e,default:()=>ql,env:()=>P,registerBackend:()=>w}),fi(),fi(),fi();var Vl="1.26.0",ql=xr;{let ne=(Qc(),f(Fs)).wasmBackend;w("cpu",ne,10),w("wasm",ne,10)}return Object.defineProperty(P.versions,"web",{value:Vl,enumerable:!0}),f(ed)})();i.exports=n})(Sy)),Sy.exports}var U1;function mN(){return U1||(U1=1,(function(i){var e=kl&&kl.__createBinding||(Object.create?(function(E,j,D,$){$===void 0&&($=D);var I=Object.getOwnPropertyDescriptor(j,D);(!I||("get"in I?!j.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return j[D]}}),Object.defineProperty(E,$,I)}):(function(E,j,D,$){$===void 0&&($=D),E[$]=j[D]})),n=kl&&kl.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=kl&&kl.__importStar||function(E){if(E&&E.__esModule)return E;var j={};if(E!=null)for(var D in E)D!=="default"&&Object.prototype.hasOwnProperty.call(E,D)&&e(j,E,D);return n(j,E),j};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const s=r(fN()),a=qw(),u=Kw(),l=Ag(),d=Bb(),p=rE(),m=sE();i.DEFAULT_MODEL="legacy",i.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",w=E=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:E,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async j=>{j.getTracks().forEach(D=>{D.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:j=>{j.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=w;const C=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,D,$,I){await D.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:$};const P=new AudioWorkletNode(D,"vad-helper-worklet",j);return P.port.onmessage=async L=>{const B=L.data;if(!(typeof B=="object"&&B&&"message"in B)){console.error("Invalid message event",B);return}switch(B.message){case d.Message.AudioFrame:{if(!("data"in B&&B.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const U=new Float32Array(B.data);await I(U);break}}},P}async function y(E,j,D){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const P=E.createScriptProcessor(4096,1,1);let L=!1;return P.onaudioprocess=async B=>{if(!L){L=!0;try{const U=B.inputBuffer.getChannelData(0);B.outputBuffer.getChannelData(0).fill(0);const X=$.process(U);for(const W of X)await D(W)}catch(U){console.error("Error processing audio:",U)}finally{L=!1}}},P.connect(E.destination),P}class _{constructor(j,D,$,I,P=!1,L=null,B=null,U=null,Z=null,X=null,W=null,J="uninitialized",te=!1){this.options=j,this.frameProcessor=D,this.model=$,this.frameSamples=I,this.listening=P,this.errored=L,this._stream=B,this._audioContext=U,this._vadNode=Z,this._mediaStreamAudioSourceNode=X,this._audioProcessorAdapterType=W,this.initializationState=J,this.ownsAudioContext=te,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=le=>{this.initializationState="errored",this.errored=le},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(le){throw le instanceof Error?this.setErrored(le.message):this.setErrored(String(le)),le}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?C(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await y(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:le,audioContext:ue,vadNode:V}=this.getAudioInstances();this._stream=await this.options.resumeStream(le);const ie=new MediaStreamAudioSourceNode(ue,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ie,ie.connect(V);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:le,mediaStreamAudioSourceNode:ue}=this.getAudioInstances();await this.options.pauseStream(le),ue.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ue;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:le}=this.getAudioInstances();le instanceof AudioWorkletNode&&le.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ue=this._audioContext)==null?void 0:ue.close())},this.setOptions=le=>{this.frameProcessor.setOptions(le)},this.processFrame=async le=>{await this.frameProcessor.process(le,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=le=>{switch(le.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(le.probs,le.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(le.audio);break}}}static async new(j={}){const D={...(0,i.getDefaultRealTimeVADOptions)(j.model??i.DEFAULT_MODEL),...j};(0,u.validateOptions)(D),i.ort.env.wasm.wasmPaths=D.onnxWASMBasePath,D.ortConfig!==void 0&&D.ortConfig(i.ort);const $=D.model==="v5"?b:S,I=D.baseAssetPath+$,P=D.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let L;try{L=await P(i.ort,()=>(0,a.defaultModelFetcher)(I))}catch(W){throw console.error(`Encountered an error while loading model file ${I}`),W}const B=D.model==="v5"?512:1536,U=B/16,Z=new u.FrameProcessor(L.process,L.reset_state,{positiveSpeechThreshold:D.positiveSpeechThreshold,negativeSpeechThreshold:D.negativeSpeechThreshold,redemptionMs:D.redemptionMs,preSpeechPadMs:D.preSpeechPadMs,minSpeechMs:D.minSpeechMs,submitUserSpeechOnPause:D.submitUserSpeechOnPause},U),X=new _(D,Z,L,B);if(D.startOnLoad)try{await X.start()}catch(W){throw console.error("Error starting micVad",W),W}return X}}i.MicVAD=_})(kl)),kl}var H1;function gN(){return H1||(H1=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=tE();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var n=qw();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var r=Kw();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=Bb();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return s.Message}});var a=hN();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const u=pN();i.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var l=mN();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(yy)),yy}var vN=gN();function Gv(i,e,n,r){var a,u;try{(u=(a=window.api)==null?void 0:a.logs)==null||u.write(i,e,n,r)}catch{}const s=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?s(`[${i}]`,n,r):s(`[${i}]`,n)}const pt={debug:(i,e,n)=>Gv(i,"debug",e,n),info:(i,e,n)=>Gv(i,"info",e,n),warn:(i,e,n)=>Gv(i,"warn",e,n),error:(i,e,n)=>Gv(i,"error",e,n)},aE=16e3,xN=6,tp=aE*xN,bN=400,yN=aE*bN/1e3,W1=300,V1=2e3,q1=1500,K1=3e3,_N=600,lE=.5,cE=.35,Y1=.85,X1=.7;let Ds=null,Ua=!1,ls=!1;const N_=new Set;function Uv(i){for(const e of Array.from(N_))try{e(i)}catch(n){pt.warn("speech","workerDeath listener threw",{error:n instanceof Error?n.message:String(n)})}}let ky=0;const J1=2;let gp=!1,dE=!1;function uE(i){i.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const n=e.data.level||"info";pt[n]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),wN(`error:${e.message||"unknown"}`)})}function ib(){return Ds||(Ds=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),uE(Ds),pt.info("speech","worker spawned"),Ds)}let Hv=!1;function wN(i){if(!gp){if(Hv){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(Hv=!0,ky+=1,dE=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:ky}),Uv({reason:i,respawned:!1,finalOnly:!0}),ky>J1){if(gp=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:J1}),Ds)try{Ds.terminate()}catch{}Ds=null,Ua=!1,ls=!1,Uv({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Hv=!1;return}if(Ds)try{Ds.terminate()}catch{}Ds=null,Ua=!1,ls=!1;try{Ds=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),uE(Ds),ls=!0,Ds.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),Uv({reason:i,respawned:!0,finalOnly:!0})}catch(e){gp=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Uv({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Hv=!1}}}function SN(i,e){if(Ua||ls)return;ls=!0;const n=ib();pt.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(i==null||i(s.data.status,s.data.message),s.data.status==="ready"&&(Ua=!0,ls=!1,pt.info("speech","preloadModel: ready"),n.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(ls=!1,pt.error("speech","preloadModel: worker reported error",{error:s.data.error}),i==null||i("error",s.data.error),n.removeEventListener("message",r))};n.addEventListener("message",r),n.postMessage({type:"load"})}function kN(){pt.info("speech","resetModel: clearing load flags"),Ua=!1,ls=!1}function Fb(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function CN(i){const e=ib();return!Ua&&!ls&&(ls=!0,e.postMessage({type:"load"})),new Promise((n,r)=>{const s=a=>{var u,l,d;((u=a.data)==null?void 0:u.type)==="result"?(e.removeEventListener("message",s),n((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((d=a.data)==null?void 0:d.type)==="status"&&a.data.status==="ready"&&(Ua=!0,ls=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function hE(i){let e=ib(),n=!1,r=null,s=null,a=null,u=null,l=null;const d=[],p=new Set;let m=null,f=0,b=!1,S=0,w=!1,C=!1,x=0,y=0,_=0,E=-1,j=W1,D=0,$=null,I="",P="",L=!1,B=0;function U(oe,be){const je=Math.min(oe.length,be.length);let Te=0;for(;Te<je&&oe.charCodeAt(Te)===be.charCodeAt(Te);)Te++;return Te}function Z(oe){const be=U(I,oe);return I=oe,be>P.length&&(P=oe.slice(0,be)),P.length>oe.length&&(P=oe),P}const X=()=>(m||(m=new Float32Array(tp)),m),W=()=>{f=0},J=oe=>{const be=X(),je=oe.length;if(je>=tp){be.set(oe.subarray(je-tp)),f=tp;return}if(f+je<=tp){be.set(oe,f),f+=je;return}const Te=f+je-tp;be.copyWithin(0,Te,f),f-=Te,be.set(oe,f),f+=je},te=()=>{$&&(clearTimeout($),$=null)},le=()=>{te(),b=!1,w=!1,C=!1,j=W1,I="",P="",L=!1,B=0,W()},ue=()=>{if(n||!b||C||w||$)return;if(f<yN){$=setTimeout(()=>{$=null,ue()},j);return}const oe=performance.now()-x;if(oe<j&&x!==0){$=setTimeout(()=>{$=null,ue()},j-oe);return}if(dE||gp||i.partialsEnabled&&!i.partialsEnabled())return;const be=X(),je=new Float32Array(f);je.set(be.subarray(0,f)),y+=1,_=y,w=!0,D=performance.now(),x=D,e.postMessage({type:"transcribe-partial",audio:je,seq:y},[je.buffer])},V=oe=>oe.length===0?Promise.resolve():gp?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),n||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(be=>{d.push(be),y+=1;const je=y;E=je,e.postMessage({type:"transcribe",audio:oe,seq:je},[oe.buffer])}),ie=oe=>{const be=V(oe);return p.add(be),be.finally(()=>{p.delete(be)}),be},K=oe=>{var be,je,Te,ve,re;if(oe.data.type==="result"){const Pe=oe.data.text,_e=oe.data.seq??0;_e&&_e<E&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:_e,latestFinalSeq:E}),!n&&Pe&&i.onFinal(Pe),(be=d.shift())==null||be()}else if(oe.data.type==="partial"){const Pe=oe.data.seq??0,_e=oe.data.text??"",Qe=performance.now()-D;w=!1,Qe>=K1?(C=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Qe),seq:Pe})):Qe>=q1&&(j=Math.min(j*2,V1),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Qe),newIntervalMs:j,seq:Pe})),L||(L=!0,Qe>_N&&j<500&&(j=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Qe),newIntervalMs:500})));const st=Pe!==_||Pe<=E;if(!n&&!st&&_e){const yt=Z(_e);yt&&((je=i.onPartial)==null||je.call(i,yt),B===0&&(B=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(B-S)})))}ue()}else if(oe.data.type==="partial-error"){const Pe=performance.now()-D;w=!1,Pe>=K1?(C=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Pe),seq:oe.data.seq})):Pe>=q1&&(j=Math.min(j*2,V1),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Pe),newIntervalMs:j,seq:oe.data.seq})),pt.warn("speech","partial encode failed",{error:oe.data.error,seq:oe.data.seq}),ue()}else oe.data.type==="error"?(n||i.onError(oe.data.error),(Te=d.shift())==null||Te()):oe.data.type==="status"?(n||(ve=i.onModelStatus)==null||ve.call(i,oe.data.status,oe.data.message),oe.data.status==="ready"&&(Ua=!0,ls=!1)):oe.data.type==="progress"&&(n||(re=i.onProgress)==null||re.call(i,oe.data.pct))};e.addEventListener("message",K);const se=oe=>{var be,je;if(!n){for(pt.warn("speech","createRecognition: worker death event",oe),(be=i.onStatusChange)==null||be.call(i,"restarting");d.length;)(je=d.shift())==null||je();if(p.clear(),te(),w=!1,oe.respawned){try{e.removeEventListener("message",K)}catch{}e=ib(),e.addEventListener("message",K)}}};return N_.add(se),{start:async()=>{if(!n){if(gp){i.onError("Speech recognition disabled — please reload the app.");return}!Ua&&!ls&&(ls=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:Ua,modelLoading:ls});try{const oe=new URL("vad/",document.baseURI).href,be=i.inputDeviceId||null,je={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};be&&(je.deviceId={exact:be}),pt.info("speech","getUserMedia",{hasDeviceId:!!be,deviceIdPrefix:be?be.slice(0,8):null});const Te=await navigator.mediaDevices.getUserMedia({audio:je});s=Te,a=new AudioContext;for(const ve of Te.getAudioTracks())ve.addEventListener("ended",()=>{n||(pt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),u=a.createAnalyser(),u.fftSize=2048,u.smoothingTimeConstant=.3,l.connect(u)}catch(ve){pt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),l=null,u=null}r=await vN.MicVAD.new({audioContext:a,getStream:async()=>Te,resumeStream:async()=>Te,pauseStream:async()=>{},baseAssetPath:oe,onnxWASMBasePath:oe,model:"v5",positiveSpeechThreshold:lE,negativeSpeechThreshold:cE,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,re)=>{var Pe;n||((Pe=i.onFrame)==null||Pe.call(i,ve),b&&(J(re),ue()))},onSpeechStart:()=>{var ve;n||(le(),b=!0,S=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var re;n||((re=i.onStatusChange)==null||re.call(i,"transcribing"),le(),ie(ve))},onVADMisfire:()=>{var ve,re;n||((ve=i.onStatusChange)==null||ve.call(i,"idle"),le(),(re=i.onMisfire)==null||re.call(i))}}),r.start()}catch(oe){const be=oe instanceof Error?oe.message:"Microphone access denied",je=oe instanceof Error?oe.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:be,stack:je}),u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Te=>Te.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}i.onError(be)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(le();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(oe,be)=>{if(r)try{r.setOptions({positiveSpeechThreshold:oe,negativeSpeechThreshold:be})}catch(je){pt.warn("speech","setVadThresholds failed",{error:je instanceof Error?je.message:String(je)})}},getAnalyser:()=>u,destroy:()=>{if(n=!0,le(),r){try{r.destroy()}catch{}r=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}N_.delete(se),e.removeEventListener("message",K)}}}let ig=null;const $_=new Set,P_=new Set;function EN(){for(const i of $_)try{i()}catch{}}function R_(){for(const i of P_)try{i()}catch{}}function TN(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function jN(i){if(!window.speechSynthesis)return;const e=TN(i);if(!e)return;const n=new SpeechSynthesisUtterance(e);n.rate=1,n.pitch=1,n.onstart=()=>{ig=performance.now(),EN()},n.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(ig=null,R_())},n.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(ig=null,R_())},window.speechSynthesis.speak(n)}function pE(){window.speechSynthesis&&(window.speechSynthesis.cancel(),ig=null,R_())}function fE(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function DN(){return ig}function AN(i){return $_.add(i),()=>{$_.delete(i)}}function NN(i){return P_.add(i),()=>{P_.delete(i)}}function $N(i){fE()&&(i.setVadThresholds(Y1,X1),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=AN(()=>{i.setVadThresholds(Y1,X1),pt.info("voice","tts.duck.on")}),n=NN(()=>{i.setVadThresholds(lE,cE),pt.info("voice","tts.duck.off")});return()=>{e(),n()}}const PN=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function RN(i){const e=i.trim();return PN.find(n=>n.match.test(e))??null}const IN=4e4;let ru=null;function vp(){ru&&clearTimeout(ru),ru=setTimeout(()=>{ru=null,At.getState().stopRecording()},IN)}function Wv(){ru&&(clearTimeout(ru),ru=null)}let Fc=null,Lc=null;const MN=.04,ON=.3;let nb=0,I_=0;function LN(i){Lc!==null&&cancelAnimationFrame(Lc);const e=()=>{if(Fc===null||At.getState().submitCountdownStartAt===null){Lc=null;return}const n=performance.now();if(n-I_<200&&nb>ON){const s=n-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:nb.toFixed(2),msIntoCountdown:Math.round(s)}),Pc(),vp();return}const r=mE();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const d=(s[l]-128)/128;a+=d*d}const u=Math.sqrt(a/s.length);if(u>MN){const l=n-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:u.toFixed(3),msIntoCountdown:Math.round(l)}),Pc(),vp();return}}Lc=requestAnimationFrame(e)};Lc=requestAnimationFrame(e)}function Z1(i){Fc&&clearTimeout(Fc);const e=At.getState().submitDelayMs,n=performance.now();At.setState({submitCountdownStartAt:n}),Fc=setTimeout(()=>{var s;Fc=null,At.setState({submitCountdownStartAt:null});const r=Ct.getState().tabs.find(a=>a.id===i);if((r==null?void 0:r.status)==="dormant"){const a=(s=dn.getState().chats[i])==null?void 0:s.pendingVoiceText;a&&(dn.getState().send({tabId:i,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),dn.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(a){pt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}vp()},e),LN(n)}function Pc(){Lc!==null&&(cancelAnimationFrame(Lc),Lc=null),Fc&&(clearTimeout(Fc),Fc=null),At.getState().submitCountdownStartAt!==null&&At.setState({submitCountdownStartAt:null})}let mr=null,Hr=null;function mE(){var i;return((i=mr==null?void 0:mr.getAnalyser)==null?void 0:i.call(mr))??null}const Vv=1e4;let ng=null;function qv(){ng&&(clearTimeout(ng),ng=null)}let Mx=null,Ox=null;function Kv(){Mx=null,Ox&&(Ox(),Ox=null)}const zN=1500,BN=9e4;let Yv=0,Lx=null,M_=-1;function Xv(){Lx&&(clearTimeout(Lx),Lx=null,M_=-1)}const FN=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),At=Xn((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const n=++Yv,r=()=>{n===Yv&&(Xv(),M_=n,Lx=setTimeout(()=>{M_===n&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},BN))};r(),SN((s,a)=>{n===Yv&&(s==="ready"?(Xv(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Xv(),pt.error("voice","modelStatus -> error",{msg:a}),i({modelStatus:"error",error:a,errorKind:"load"})):(r(),i({modelStatus:"loading"})))},s=>{n===Yv&&(r(),i({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),Xv(),kN(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:n=>{if(e().isRecording)return;if(mr){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Fb()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=s=>{try{const a=hE({inputDeviceId:s,onStatusChange:u=>{i(u==="transcribing"?{statusPill:"transcribing"}:u==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:u=>{e().partialsEnabled&&i({lastPartial:u})},partialsEnabled:()=>e().partialsEnabled,onFrame:u=>{nb=u.isSpeech,I_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),Wv(),Pc(),fE()){const l=DN(),d=l!==null?performance.now()-l:null;pE(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:n,utteranceOffsetMs:d})}else pt.debug("voice","barge-in.no-op",{tabId:n})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),vp();const u=e().lastBargeInAt;u!==null&&performance.now()-u<600&&pt.warn("voice","barge-in.misfire",{tabId:n,sinceBargeInMs:Math.round(performance.now()-u)})},onFinal:u=>{var f;vp();const l=u.trim();if(!l||FN.has(l)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((f=Ct.getState().tabs.find(b=>b.id===n))==null?void 0:f.status)==="dormant"){dn.getState().setPendingVoiceText(n,l),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Z1(n);const b=window;b.__transcripts&&(b.__transcripts.push({tabId:n,text:l}),b.__transcripts.length>500&&b.__transcripts.shift());return}const p=RN(l);if(p){pt.info("voice","voice-command",{tabId:n,label:p.label,transcript:l}),window.api.pty.write({tabId:n,data:p.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Pc();const b=window;b.__transcripts&&(b.__transcripts.push({tabId:n,text:l}),b.__transcripts.length>500&&b.__transcripts.shift());return}window.api.pty.write({tabId:n,data:l}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Z1(n);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:n,text:l}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:u=>{pt.error("voice","recognition error",{err:u}),Pc(),i({error:u,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Hr==null||Hr(),Hr=null,Wv(),mr==null||mr.destroy(),mr=null,Ve.error(`Microphone error: ${u}`)},onModelStatus:u=>{u==="ready"?i({modelStatus:"ready",loadingProgress:100}):u==="loading"&&i({modelStatus:"loading"})},onProgress:u=>i({loadingProgress:Math.round(u)})});mr=a,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),vp(),a.start().then(()=>{mr===a&&(Hr==null||Hr(),Hr=$N(a))}).catch(u=>{const l=u instanceof Error?u.message:String(u);pt.error("voice","handle.start() failed",{error:l}),Ve.error(`Could not start mic: ${l}`)})}catch(a){i({error:a instanceof Error?a.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var s,a,u;return((u=(a=(s=window.api)==null?void 0:s.voice)==null?void 0:a.getDevicePref)==null?void 0:u.call(a))??Promise.resolve(null)}).then(s=>r((s==null?void 0:s.selectedDeviceId)??null)).catch(s=>{pt.warn("voice","getDevicePref failed; using default device",{error:s instanceof Error?s.message:String(s)}),r(null)})},stopRecording:()=>{const n=mr;n&&(Wv(),Pc(),nb=0,I_=0,Hr==null||Hr(),Hr=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),n.stop().finally(()=>{n.destroy(),mr===n&&(mr=null),e().hotkeyState==="stopping"&&(qv(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const n=mr;if(!n)return;Wv(),Hr==null||Hr(),Hr=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await n.stop()}catch(a){pt.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}n.destroy(),mr===n&&(mr=null);const{useSessions:r}=await Dg(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>YA);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:n=>i({externalRecording:n}),toggleTTS:()=>i(n=>({ttsEnabled:!n.ttsEnabled})),setAutoSubmit:n=>i({autoSubmit:n}),setSubmitDelayMs:n=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(n)))}),cancelSubmit:()=>Pc(),setPartialsEnabled:n=>{e().partialsEnabled!==n&&(i({partialsEnabled:n}),n||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:n=>{e().permissionState!==n&&(pt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:n}),i({permissionState:n}))},setLevelMeterEnabled:n=>{e().levelMeterEnabled!==n&&i({levelMeterEnabled:n})},setTurnDetectorRuntimeState:n=>{e().turnDetectorState!==n&&(i({turnDetectorState:n}),n==="load_failed"?pt.warn("voice-turn","voice-turn.load_failed"):n==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):n==="disabled"&&pt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:n=>{e().wizardArmed!==n&&i({wizardArmed:n})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:n,source:r,mode:s,tabId:a})=>{const u=e(),{canRecord:l,reason:d}=O_(u);if(n==="down"){if(d==="error"||d==="load-timeout"){u.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:r,reason:d});return}if(!l&&d!=="loading"){pt.warn("voice-hotkey","miss-model-loading",{modelStatus:u.modelStatus,reason:d});return}if(u.hotkeyState==="recording"||u.isRecording){(s==="toggle"||r==="global")&&(i({hotkeyState:"stopping"}),qv(),ng=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Vv}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Vv),u.stopRecording());return}if(d==="loading"){u.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:r,modelStatus:u.modelStatus})),Kv(),Mx={tabId:a,source:r,mode:s},Ox=At.subscribe((p,m)=>{if(Mx&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=Mx;if(Kv(),!f.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",f),i({hotkeyState:"recording"}),At.getState().startRecording(f.tabId)}});return}if(!a){pt.warn("voice-hotkey","no-active-tab",{source:r});return}pt.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),u.startRecording(a),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(u.hotkeyState==="armed"){Kv(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}u.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),qv(),ng=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Vv}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Vv),u.stopRecording())}},destroyHotkey:()=>{const n=e();if(Kv(),Pc(),n.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{n.stopRecording()}catch{}}else(n.hotkeyState==="armed"||n.hotkeyState==="stopping")&&(qv(),i({hotkeyState:"destroyed"}))}})),GN=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),O_=i=>Fb()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=At,i.__transcripts=[]}function Yw(i,e,n){return new Promise((r,s)=>{const a=setTimeout(()=>s(new Error(`${n} timed out after ${e}ms`)),e);i.then(u=>{clearTimeout(a),r(u)},u=>{clearTimeout(a),s(u)})})}const UN=5e3,zl=Xn(()=>({snapshot:null,loaded:!1}));let Q1=!1,eS=!1,_m;async function HN(){var i;if(!Q1){Q1=!0;try{const e=await Yw(window.api.schedule.state(),UN,"schedule.state");zl.setState({snapshot:e,loaded:!0}),_m=((i=e.paused)==null?void 0:i.reason)??null}catch(e){if(!eS){eS=!0;const n=e instanceof Error?e.message:String(e);Ve.error(`Scheduler state hydrate failed: ${n}`)}_m=null}window.api.schedule.onState(e=>{var r;const n=((r=e.paused)==null?void 0:r.reason)??null;_m!==void 0&&n!==_m&&(n==="auth"?Ve.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):n==="network"&&Ve.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),_m=n,zl.setState({snapshot:e,loaded:!0})})}}const WN=6e4,VN=5e3,rg=Xn(()=>({data:null,refreshing:!1}));let tS=!1,zx=null,iS=null,nS=!1;async function Xw(){rg.setState({refreshing:!0});let i=WN;try{const e=await Yw(window.api.billing.fetch(),VN,"billing.fetch");rg.setState({data:e,refreshing:!1}),e.kind==="transient"?i=iS==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),iS=e.kind}catch(e){if(rg.setState({refreshing:!1}),!nS){nS=!0;const n=e instanceof Error?e.message:String(e);Ve.warn(`Billing usage fetch failed: ${n}`)}}zx=setTimeout(Xw,i)}function qN(){tS||(tS=!0,Xw())}function gE(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function KN(){zx!==null&&(clearTimeout(zx),zx=null),Xw()}function pi({name:i,size:e=17,stroke:n=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(i){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});default:return null}}function Ng(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),n=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!n)return i;const r=n[1].charAt(0).toUpperCase()+n[1].slice(1).toLowerCase(),s=n[3]?`${n[2]}.${n[3]}`:n[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const Jv=new Map,YN=3e4;function vE(i){const[e,n]=z.useState(()=>{var r;return i?((r=Jv.get(i))==null?void 0:r.value)??null:null});return z.useEffect(()=>{if(!i){n(null);return}let r=!1;return(async()=>{const a=Jv.get(i);if(a&&Date.now()-a.ts<YN){r||n(a.value);return}try{const u=await window.api.app.gitBranch(i);if(r)return;Jv.set(i,{value:u,ts:Date.now()}),n(u)}catch{if(r)return;Jv.set(i,{value:null,ts:Date.now()}),n(null)}})(),()=>{r=!0}},[i]),e}const $g=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Projects",icon:"terminal",hint:"Independent goal-scoped sessions, grouped by project"},{key:"system-prompt",group:"Workspace",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],XN=Object.fromEntries($g.map(i=>[i.key,i.group])),Cy={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},rS=$g.filter(i=>i.group==="Workspace"),sS=$g.filter(i=>i.group==="Configure"),oS=$g.filter(i=>i.group==="Tools").map(({key:i,label:e,icon:n,hint:r})=>({key:i,label:e,icon:n,hint:r})),L_="sm.almanac.sidebarWidth",xE=180,bE=480,z_=252;function JN(){try{const i=parseInt(localStorage.getItem(L_)??"",10);if(Number.isFinite(i))return Math.min(bE,Math.max(xE,i))}catch{}return z_}const ZN=52,yE="sm.almanac.sidebarCollapsed";function QN(){try{return localStorage.getItem(yE)==="1"}catch{}return!1}const _E="sm.almanac.collapsedGroups";function e$(){try{const i=localStorage.getItem(_E);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(n=>n==="Workspace"||n==="Configure"||n==="Tools")):new Set}catch{return new Set}}function t$(){return{scheduler:zl(e=>{var n;return(((n=e.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running")})}}function i$({active:i,onNavigate:e,onNewSession:n}){const[r,s]=z.useState(()=>e$()),a=z.useCallback(_=>{s(E=>{const j=new Set(E);j.has(_)?j.delete(_):j.add(_);try{localStorage.setItem(_E,JSON.stringify(Array.from(j)))}catch{}return j})},[]),[u,l]=z.useState(()=>QN()),d=z.useCallback(()=>{l(_=>{const E=!_;try{localStorage.setItem(yE,E?"1":"0")}catch{}return E})},[]),p=Ct(_=>_.tabs),m=Ct(_=>_.activeTabId),f=p.find(_=>_.id===m)??null,b=t$(),[S,w]=z.useState(()=>JN()),C=z.useRef(S);C.current=S;const x=z.useCallback(_=>{_.preventDefault();const E=_.clientX,j=C.current;let D=j;const $=P=>{D=Math.min(bE,Math.max(xE,j+(P.clientX-E))),w(D)},I=()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",I),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(L_,String(D))}catch{}};window.addEventListener("pointermove",$),window.addEventListener("pointerup",I),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),y=z.useCallback(()=>{w(z_);try{localStorage.setItem(L_,String(z_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:u?ZN:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(n$,{tab:f,onNewSession:n,rail:u,onToggleRail:d}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:u?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!u&&o.jsx(Ey,{label:"Workspace",desc:Cy.Workspace,collapsed:r.has("Workspace"),count:rS.length,onToggle:()=>a("Workspace")}),(u||!r.has("Workspace"))&&rS.map(_=>o.jsx(aS,{item:_,active:i===_.key,live:_.liveKind?b[_.liveKind]:!1,onClick:()=>e(_.key),rail:u},_.key)),!u&&o.jsx(Ey,{label:"Configure",desc:Cy.Configure,collapsed:r.has("Configure"),count:sS.length,onToggle:()=>a("Configure")}),(u||!r.has("Configure"))&&sS.map(_=>o.jsx(aS,{item:_,active:i===_.key,live:!1,onClick:()=>e(_.key),rail:u},_.key)),!u&&o.jsx(Ey,{label:"Tools",desc:Cy.Tools,collapsed:r.has("Tools"),count:oS.length,onToggle:()=>a("Tools")}),(u||!r.has("Tools"))&&oS.map(_=>o.jsx(r$,{tool:_,active:i===_.key,onClick:()=>e(_.key),rail:u},_.key))]})}),o.jsx(s$,{rail:u}),!u&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:x,onDoubleClick:y,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function n$({tab:i,onNewSession:e,rail:n,onToggleRail:r}){const s=(i==null?void 0:i.label)??"no session",a=vE((i==null?void 0:i.cwd)??null);return n?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:e,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:o.jsx(pi,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(pi,{name:"chevron",size:15,stroke:1.8})})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(pi,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:s})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:a?`⌥${a}`:i?i.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:e,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[o.jsx(pi,{name:"plus",size:13,stroke:1.8}),"New session"]})})]})}function Ey({label:i,desc:e,collapsed:n,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!n,title:n?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:n?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:i}),n&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!n&&o.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:e})]})}function aS({item:i,active:e,live:n,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(pi,{name:i.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:i.label}),i.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!s&&n&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&n&&o.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function r$({tool:i,active:e,onClick:n,rail:r}){return o.jsxs("button",{onClick:n,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(pi,{name:i.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:i.label}),i.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function s$({rail:i}){const e=At(l=>l.isRecording),n=Ct(l=>l.tabs),r=Ct(l=>l.activeTabId),s=n.find(l=>l.id===r)??null,[a,u]=z.useState(null);return z.useEffect(()=>{let l=!1;if(!(s!=null&&s.presetId)){u(null);return}return V2(s.presetId).then(d=>{l||u((d==null?void 0:d.model)??null)}).catch(()=>{l||u(null)}),()=>{l=!0}},[s==null?void 0:s.presetId]),i?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?"bg-red-500 animate-pulse":"bg-sage"}`,title:e?"recording":"idle"})}):o.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?"bg-red-500 animate-pulse":"bg-sage"}`,title:e?"recording":"idle"}),o.jsx("span",{className:"truncate",title:a??"",children:e?"recording…":a?`Claude · ${Ng(a)}`:"Claude Code"})]})}function o$(i,e,n){return e?i.map(r=>r.id===e?{...r,lastActivityAt:n}:r):i}function a$(i,e,n){return{tabId:i,sessionUuid:n,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const Bx=Xn((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(n,r,s)=>{const a={...e().refs};if(a[n]=(a[n]??0)+1,i({refs:a}),a[n]>1)return;i({tabs:{...e().tabs,[n]:a$(n,r,s)}});const u=window.api.transcripts.onEvent(n,l=>e().ingest(n,l));i({unsubs:{...e().unsubs,[n]:u}}),window.api.transcripts.subscribe({tabId:n,cwd:r,sessionUuid:s}).then(async l=>{const d=e().tabs[n];if(!d)return;if(!l.ok){const{toast:m}=await Dg(async()=>{const{toast:f}=await Promise.resolve().then(()=>J2);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),i({tabs:{...e().tabs,[n]:{...d,path:null}}});return}i({tabs:{...e().tabs,[n]:{...d,path:l.path}}});const p=await window.api.transcripts.buffer(n);for(const m of p)e().ingest(n,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",n,l))},unsubscribe:n=>{const r={...e().refs};if(!r[n])return;if(r[n]--,r[n]>0){i({refs:r});return}delete r[n];const s=e().unsubs[n];s==null||s();const a={...e().unsubs};delete a[n];const u={...e().tabs};delete u[n],window.api.transcripts.unsubscribe(n),i({refs:r,unsubs:a,tabs:u})},ingest:(n,r,s)=>{const a=e().tabs[n];if(!a)return;const u=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:u},d=[],p=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||d.push({id:0,kind:"todo-update",at:u,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])f&&S in f&&(b[S]=f[S]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:u},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const S=m.input,w=["Edit","Write","NotebookEdit"].includes(m.name),C=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,x=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,y=C?C.split("/").pop()??C:x?p(x,28):"";d.push({id:0,kind:"tool-use",at:u,label:y?`${m.name} · ${y}`:m.name,target:C??x,toolName:m.name}),w&&C&&d.push({id:0,kind:"file-edit",at:u,label:`${m.name} · ${p(C.split("/").pop()??C,34)}`,target:C,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:u,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"plan-revision",at:u,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:u,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:u},...a.agents].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"agent-spawn",at:u,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,S=m.output_tokens??m.outputTokens??0,w=f+b+S;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+S,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(w/1e3)>Math.floor(f/1e3)&&d.push({id:0,kind:"usage-tick",at:u,label:`${Math.floor(w/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=o$(a.agents,m==null?void 0:m.toolUseId,u);break}}if(d.length>0){let m=a.activitySeq;const f=d.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}i({tabs:{...e().tabs,[n]:l}})}}));function l$(i){const e=Bx(s=>s.subscribe),n=Bx(s=>s.unsubscribe),r=Bx(s=>i?s.tabs[i.id]:void 0);return z.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>n(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,n]),r}function c$({onNavigate:i}){const e=Ct(E=>E.tabs),n=Ct(E=>E.activeTabId),r=e.find(E=>E.id===n)??null,s=l$(r),a=(s==null?void 0:s.lastEventAt)??0,u=rg(E=>E.data),l=zl(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),d=vE((r==null?void 0:r.cwd)??null),[,p]=z.useState(0);z.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=z.useState(!1),S=z.useRef(null);z.useEffect(()=>{if(!f)return;const E=j=>{S.current&&!S.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),z.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const w=gE(u),C=(w==null?void 0:w.usage.five_hour)??null,x=C?Math.round(C.utilization):null,y=(u==null?void 0:u.kind)==="ok"||(u==null?void 0:u.kind)==="ok-stale",_=a>0?h$(Date.now()-a):"—";return o.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[o.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:y?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${y?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:y?"connected":"offline"})]}),o.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,d&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:_})]}),m.length>0&&o.jsx(d$,{ref:S,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.39.0"]})]})}const d$=z.forwardRef(function({todos:e,open:n,onToggle:r},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",n?"▾":"▴"]})]}),n&&o.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:o.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(u$,{status:u.status}),o.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function u$({status:i}){return i==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function h$(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const n=Math.floor(e/60);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function p$({onClose:i,onSent:e}){const n=Ct(I=>I.tabs),[r,s]=z.useState(""),[a,u]=z.useState(()=>Object.fromEntries(n.map(I=>[I.id,!0]))),[l,d]=z.useState(!1),[p,m]=z.useState({}),f=z.useRef(null),b=z.useRef(e);z.useEffect(()=>{b.current=e},[e]),z.useEffect(()=>{u(I=>{const P={};for(const L of n)P[L.id]=I[L.id]??!0;return P})},[n]),z.useEffect(()=>{var I;(I=f.current)==null||I.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(P=>{m(L=>P.tabId in L?{...L,[P.tabId]:"skipped"}:L)}),[]),z.useEffect(()=>{if(Object.keys(p).length===0)return;const I=Object.values(p).filter(L=>L==="sent").length,P=window.setTimeout(()=>b.current(I),1500);return()=>window.clearTimeout(P)},[p]);const S=n.filter(I=>a[I.id]).map(I=>I.id),w=S.length,C=Object.keys(p).length>0,x=r.length>0&&w>0&&!l&&!C,y=()=>{if(!x)return;d(!0);const I=Ct.getState().tabs,P=new Set(I.map(B=>B.id)),L={};for(const B of S)P.has(B)?(window.api.pty.write({tabId:B,data:r+"\r"}),L[B]="sent"):L[B]="skipped";m(L),d(!1)},_=I=>{if(I.key==="Escape"){I.preventDefault(),I.stopPropagation(),i();return}I.key==="Enter"&&(I.metaKey||I.ctrlKey)&&(I.preventDefault(),y())},E=n.length>0&&n.every(I=>a[I.id]),j=()=>{const I=!E;u(Object.fromEntries(n.map(P=>[P.id,I])))},D=Object.values(p).some(I=>I==="skipped"),$=C?D?"Sent (some skipped)":"Sent":`Send to ${w} tab${w===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:_,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:I=>s(I.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:E,onChange:j,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",w,"/",n.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:n.map(I=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[I.id],onChange:P=>u(L=>({...L,[I.id]:P.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:I.label}),p[I.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[I.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},I.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:y,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:$})]})]})}function f$({tabId:i,cwd:e,onClose:n}){const r=tg(w=>w.watchersForTab(i)),s=tg(w=>w.add),a=tg(w=>w.remove),u=z.useRef(null),[l,d]=z.useState(""),[p,m]=z.useState(""),[f,b]=z.useState(!1);z.useEffect(()=>{const w=C=>{C.key==="Escape"&&n()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n]),z.useEffect(()=>{const w=C=>{u.current&&!u.current.contains(C.target)&&n()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[n]);const S=async()=>{const w=p.trim();if(!w||f)return;b(!0);const C=await s({tabId:i,label:l.trim(),command:w,cwd:e});b(!1),C&&(d(""),m(""))};return o.jsxs("div",{ref:u,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:n,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:w=>d(w.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:p,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&S()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),o.jsx("button",{onClick:S,disabled:!p.trim()||f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(w=>{const C=w.lines[w.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:w.label}),o.jsxs("span",{className:"text-fg-faint",children:[w.lineCount," line",w.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(w.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${w.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:w.command,children:w.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},w.watcherId)})})]})}/**
|
|
2897
|
+
*/var G1;function fN(){return G1||(G1=1,(function(i,e){var n=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,l=(ne=>typeof So<"u"?So:typeof Proxy<"u"?new Proxy(ne,{get:(pe,xe)=>(typeof So<"u"?So:pe)[xe]}):ne)(function(ne){if(typeof So<"u")return So.apply(this,arguments);throw Error('Dynamic require of "'+ne+'" is not supported')}),d=(ne,pe)=>()=>(ne&&(pe=ne(ne=0)),pe),p=(ne,pe)=>{for(var xe in pe)r(ne,xe,{get:pe[xe],enumerable:!0})},m=(ne,pe,xe,De)=>{if(pe&&typeof pe=="object"||typeof pe=="function")for(let ke of a(pe))!u.call(ne,ke)&&ke!==xe&&r(ne,ke,{get:()=>pe[ke],enumerable:!(De=s(pe,ke))||De.enumerable});return ne},f=ne=>m(r({},"__esModule",{value:!0}),ne),b,S,w,C,x,y=d(()=>{b=new Map,S=[],w=(ne,pe,xe)=>{if(pe&&typeof pe.init=="function"&&typeof pe.createInferenceSessionHandler=="function"){let De=b.get(ne);if(De===void 0)b.set(ne,{backend:pe,priority:xe});else{if(De.priority>xe)return;if(De.priority===xe&&De.backend!==pe)throw new Error(`cannot register backend "${ne}" using priority ${xe}`)}if(xe>=0){let ke=S.indexOf(ne);ke!==-1&&S.splice(ke,1);for(let Be=0;Be<S.length;Be++)if(b.get(S[Be]).priority<=xe){S.splice(Be,0,ne);return}S.push(ne)}return}throw new TypeError("not a valid backend")},C=async ne=>{let pe=b.get(ne);if(!pe)return"backend not found.";if(pe.initialized)return pe.backend;if(pe.aborted)return pe.error;{let xe=!!pe.initPromise;try{return xe||(pe.initPromise=pe.backend.init(ne)),await pe.initPromise,pe.initialized=!0,pe.backend}catch(De){return xe||(pe.error=`${De}`,pe.aborted=!0),pe.error}finally{delete pe.initPromise}}},x=async ne=>{let pe=ne.executionProviders||[],xe=pe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=xe.length===0?S:xe,ke,Be=[],Ne=new Set;for(let Fe of De){let tt=await C(Fe);typeof tt=="string"?Be.push({name:Fe,err:tt}):(ke||(ke=tt),ke===tt&&Ne.add(Fe))}if(!ke)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:tt}of Be)xe.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${tt}`);let $e=pe.filter(Fe=>Ne.has(typeof Fe=="string"?Fe:Fe.name));return[ke,new Proxy(ne,{get:(Fe,tt)=>tt==="executionProviders"?$e:Reflect.get(Fe,tt)})]}}),_=d(()=>{y()}),E,j=d(()=>{E="1.26.0"}),D,$,I=d(()=>{j(),D="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(ne){if(ne!==void 0){if(typeof ne!="string"||["verbose","info","warning","error","fatal"].indexOf(ne)===-1)throw new Error(`Unsupported logging level: ${ne}`);D=ne}},get logLevel(){return D}},Object.defineProperty($,"logLevel",{enumerable:!0})}),P,L=d(()=>{I(),P=$}),B,U,Z=d(()=>{B=(ne,pe)=>{let xe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);xe.width=ne.dims[3],xe.height=ne.dims[2];let De=xe.getContext("2d");if(De!=null){let ke,Be;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(ke=ne.dims[2],Be=ne.dims[3]):(ke=ne.dims[3],Be=ne.dims[2]);let Ne=(pe==null?void 0:pe.format)!==void 0?pe.format:"RGB",$e=pe==null?void 0:pe.norm,Fe,tt;$e===void 0||$e.mean===void 0?Fe=[255,255,255,255]:typeof $e.mean=="number"?Fe=[$e.mean,$e.mean,$e.mean,$e.mean]:(Fe=[$e.mean[0],$e.mean[1],$e.mean[2],0],$e.mean[3]!==void 0&&(Fe[3]=$e.mean[3])),$e===void 0||$e.bias===void 0?tt=[0,0,0,0]:typeof $e.bias=="number"?tt=[$e.bias,$e.bias,$e.bias,$e.bias]:(tt=[$e.bias[0],$e.bias[1],$e.bias[2],0],$e.bias[3]!==void 0&&(tt[3]=$e.bias[3]));let ot=Be*ke,it=0,Je=ot,$t=ot*2,ze=-1;Ne==="RGBA"?(it=0,Je=ot,$t=ot*2,ze=ot*3):Ne==="RGB"?(it=0,Je=ot,$t=ot*2):Ne==="RBG"&&(it=0,$t=ot,Je=ot*2);for(let dt=0;dt<Be;dt++)for(let Ai=0;Ai<ke;Ai++){let ti=(ne.data[it++]-tt[0])*Fe[0],ii=(ne.data[Je++]-tt[1])*Fe[1],Ni=(ne.data[$t++]-tt[2])*Fe[2],Lt=ze===-1?255:(ne.data[ze++]-tt[3])*Fe[3];De.fillStyle="rgba("+ti+","+ii+","+Ni+","+Lt+")",De.fillRect(Ai,dt,1,1)}if("toDataURL"in xe)return xe.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},U=(ne,pe)=>{let xe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(xe!=null){let ke,Be,Ne;(pe==null?void 0:pe.tensorLayout)!==void 0&&pe.tensorLayout==="NHWC"?(ke=ne.dims[2],Be=ne.dims[1],Ne=ne.dims[3]):(ke=ne.dims[3],Be=ne.dims[2],Ne=ne.dims[1]);let $e=pe!==void 0&&pe.format!==void 0?pe.format:"RGB",Fe=pe==null?void 0:pe.norm,tt,ot;Fe===void 0||Fe.mean===void 0?tt=[255,255,255,255]:typeof Fe.mean=="number"?tt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(tt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(tt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?ot=[0,0,0,0]:typeof Fe.bias=="number"?ot=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(ot=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(ot[3]=Fe.bias[3]));let it=Be*ke;if(pe!==void 0&&(pe.format!==void 0&&Ne===4&&pe.format!=="RGBA"||Ne===3&&pe.format!=="RGB"&&pe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Je=4,$t=0,ze=1,dt=2,Ai=3,ti=0,ii=it,Ni=it*2,Lt=-1;$e==="RGBA"?(ti=0,ii=it,Ni=it*2,Lt=it*3):$e==="RGB"?(ti=0,ii=it,Ni=it*2):$e==="RBG"&&(ti=0,Ni=it,ii=it*2),De=xe.createImageData(ke,Be);for(let Mi=0;Mi<Be*ke;$t+=Je,ze+=Je,dt+=Je,Ai+=Je,Mi++)De.data[$t]=(ne.data[ti++]-ot[0])*tt[0],De.data[ze]=(ne.data[ii++]-ot[1])*tt[1],De.data[dt]=(ne.data[Ni++]-ot[2])*tt[2],De.data[Ai]=Lt===-1?255:(ne.data[Lt++]-ot[3])*tt[3]}else throw new Error("Can not access image data");return De}}),X,W,J,te,le,ue,V=d(()=>{Pe(),X=(ne,pe)=>{if(ne===void 0)throw new Error("Image buffer must be defined");if(pe.height===void 0||pe.width===void 0)throw new Error("Image height and width must be defined");if(pe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:xe,width:De}=pe,ke=pe.norm??{mean:255,bias:0},Be,Ne;typeof ke.mean=="number"?Be=[ke.mean,ke.mean,ke.mean,ke.mean]:Be=[ke.mean[0],ke.mean[1],ke.mean[2],ke.mean[3]??255],typeof ke.bias=="number"?Ne=[ke.bias,ke.bias,ke.bias,ke.bias]:Ne=[ke.bias[0],ke.bias[1],ke.bias[2],ke.bias[3]??0];let $e=pe.format!==void 0?pe.format:"RGBA",Fe=pe.tensorFormat!==void 0&&pe.tensorFormat!==void 0?pe.tensorFormat:"RGB",tt=xe*De,ot=Fe==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,Je=0,$t=1,ze=2,dt=3,Ai=0,ti=tt,ii=tt*2,Ni=-1;$e==="RGB"&&(it=3,Je=0,$t=1,ze=2,dt=-1),Fe==="RGBA"?Ni=tt*3:Fe==="RBG"?(Ai=0,ii=tt,ti=tt*2):Fe==="BGR"&&(ii=0,ti=tt,Ai=tt*2);for(let Lt=0;Lt<tt;Lt++,Je+=it,ze+=it,$t+=it,dt+=it)ot[Ai++]=(ne[Je]+Ne[0])/Be[0],ot[ti++]=(ne[$t]+Ne[1])/Be[1],ot[ii++]=(ne[ze]+Ne[2])/Be[2],Ni!==-1&&dt!==-1&&(ot[Ni++]=(ne[dt]+Ne[3])/Be[3]);return Fe==="RGBA"?new re("float32",ot,[1,4,xe,De]):new re("float32",ot,[1,3,xe,De])},W=async(ne,pe)=>{let xe=typeof HTMLImageElement<"u"&&ne instanceof HTMLImageElement,De=typeof ImageData<"u"&&ne instanceof ImageData,ke=typeof ImageBitmap<"u"&&ne instanceof ImageBitmap,Be=typeof ne=="string",Ne,$e=pe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=ot=>typeof HTMLCanvasElement<"u"&&ot instanceof HTMLCanvasElement||ot instanceof OffscreenCanvas?ot.getContext("2d"):null;if(xe){let ot=Fe();ot.width=ne.width,ot.height=ne.height;let it=tt(ot);if(it!=null){let Je=ne.height,$t=ne.width;if(pe!==void 0&&pe.resizedHeight!==void 0&&pe.resizedWidth!==void 0&&(Je=pe.resizedHeight,$t=pe.resizedWidth),pe!==void 0){if($e=pe,pe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$e.tensorFormat="RGBA",$e.height=Je,$e.width=$t}else $e.tensorFormat="RGBA",$e.height=Je,$e.width=$t;it.drawImage(ne,0,0),Ne=it.getImageData(0,0,$t,Je).data}else throw new Error("Can not access image data")}else if(De){let ot,it;if(pe!==void 0&&pe.resizedWidth!==void 0&&pe.resizedHeight!==void 0?(ot=pe.resizedHeight,it=pe.resizedWidth):(ot=ne.height,it=ne.width),pe!==void 0&&($e=pe),$e.format="RGBA",$e.height=ot,$e.width=it,pe!==void 0){let Je=Fe();Je.width=it,Je.height=ot;let $t=tt(Je);if($t!=null)$t.putImageData(ne,0,0),Ne=$t.getImageData(0,0,it,ot).data;else throw new Error("Can not access image data")}else Ne=ne.data}else if(ke){if(pe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ot=Fe();ot.width=ne.width,ot.height=ne.height;let it=tt(ot);if(it!=null){let Je=ne.height,$t=ne.width;return it.drawImage(ne,0,0,$t,Je),Ne=it.getImageData(0,0,$t,Je).data,$e.height=Je,$e.width=$t,X(Ne,$e)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((ot,it)=>{let Je=Fe(),$t=tt(Je);if(!ne||!$t)return it();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=ne,ze.onload=()=>{Je.width=ze.width,Je.height=ze.height,$t.drawImage(ze,0,0,Je.width,Je.height);let dt=$t.getImageData(0,0,Je.width,Je.height);$e.height=Je.height,$e.width=Je.width,ot(X(dt.data,$e))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ne!==void 0)return X(Ne,$e);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(ne,pe)=>{let{width:xe,height:De,download:ke,dispose:Be}=pe,Ne=[1,De,xe,4];return new re({location:"texture",type:"float32",texture:ne,dims:Ne,download:ke,dispose:Be})},te=(ne,pe)=>{let{dataType:xe,dims:De,download:ke,dispose:Be}=pe;return new re({location:"gpu-buffer",type:xe??"float32",gpuBuffer:ne,dims:De,download:ke,dispose:Be})},le=(ne,pe)=>{let{dataType:xe,dims:De,download:ke,dispose:Be}=pe;return new re({location:"ml-tensor",type:xe??"float32",mlTensor:ne,dims:De,download:ke,dispose:Be})},ue=(ne,pe,xe)=>new re({location:"cpu-pinned",type:ne,data:pe,dims:xe??[pe.length]})}),ie,K,se,oe,be=d(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),se=!1,oe=()=>{if(!se){se=!0;let ne=typeof BigInt64Array<"u"&&BigInt64Array.from,pe=typeof BigUint64Array<"u"&&BigUint64Array.from,xe=globalThis.Float16Array,De=typeof xe<"u"&&xe.from;ne&&(ie.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),pe&&(ie.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),De?(ie.set("float16",xe),K.set(xe,"float16")):ie.set("float16",Uint16Array)}}}),je,Te,ve=d(()=>{Pe(),je=ne=>{let pe=1;for(let xe=0;xe<ne.length;xe++){let De=ne[xe];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${xe}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${xe}] must be a non-negative integer, got: ${De}`);pe*=De}return pe},Te=(ne,pe)=>{switch(ne.location){case"cpu":return new re(ne.type,ne.data,pe);case"cpu-pinned":return new re({location:"cpu-pinned",data:ne.data,type:ne.type,dims:pe});case"texture":return new re({location:"texture",texture:ne.texture,type:ne.type,dims:pe});case"gpu-buffer":return new re({location:"gpu-buffer",gpuBuffer:ne.gpuBuffer,type:ne.type,dims:pe});case"ml-tensor":return new re({location:"ml-tensor",mlTensor:ne.mlTensor,type:ne.type,dims:pe});default:throw new Error(`tensorReshape: tensor location ${ne.location} is not supported`)}}}),re,Pe=d(()=>{Z(),V(),be(),ve(),re=class{constructor(ne,pe,xe){oe();let De,ke;if(typeof ne=="object"&&"location"in ne)switch(this.dataLocation=ne.location,De=ne.type,ke=ne.dims,ne.location){case"cpu-pinned":{let Ne=ie.get(De);if(!Ne)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(ne.data instanceof Ne))throw new TypeError(`buffer should be of type ${Ne.name}`);this.cpuData=ne.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=ne.texture,this.downloader=ne.download,this.disposer=ne.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=ne.gpuBuffer,this.downloader=ne.download,this.disposer=ne.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=ne.mlTensor,this.downloader=ne.download,this.disposer=ne.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ne,$e;if(typeof ne=="string")if(De=ne,$e=xe,ne==="string"){if(!Array.isArray(pe))throw new TypeError("A string tensor's data must be a string array.");Ne=pe}else{let Fe=ie.get(ne);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${ne}.`);if(Array.isArray(pe)){if(ne==="float16"&&Fe===Uint16Array||ne==="uint4"||ne==="int4")throw new TypeError(`Creating a ${ne} tensor from number array is not supported. Please use ${Fe.name} as data.`);ne==="uint64"||ne==="int64"?Ne=Fe.from(pe,BigInt):Ne=Fe.from(pe)}else if(pe instanceof Fe)Ne=pe;else if(pe instanceof Uint8ClampedArray)if(ne==="uint8")Ne=Uint8Array.from(pe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(ne==="float16"&&pe instanceof Uint16Array&&Fe!==Uint16Array)Ne=new globalThis.Float16Array(pe.buffer,pe.byteOffset,pe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if($e=pe,Array.isArray(ne)){if(ne.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof ne[0];if(Fe==="string")De="string",Ne=ne;else if(Fe==="boolean")De="bool",Ne=Uint8Array.from(ne);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(ne instanceof Uint8ClampedArray)De="uint8",Ne=Uint8Array.from(ne);else{let Fe=K.get(ne.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${ne.constructor}.`);De=Fe,Ne=ne}if($e===void 0)$e=[Ne.length];else if(!Array.isArray($e))throw new TypeError("A tensor's dims must be a number array");ke=$e,this.cpuData=Ne,this.dataLocation="cpu"}let Be=je(ke);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=ke,this.size=Be}static async fromImage(ne,pe){return W(ne,pe)}static fromTexture(ne,pe){return J(ne,pe)}static fromGpuBuffer(ne,pe){return te(ne,pe)}static fromMLTensor(ne,pe){return le(ne,pe)}static fromPinnedBuffer(ne,pe,xe){return ue(ne,pe,xe)}toDataURL(ne){return B(this,ne)}toImageData(ne){return U(this,ne)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(ne){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let pe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=pe,ne&&this.disposer&&(this.disposer(),this.disposer=void 0),pe}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(ne){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Te(this,ne)}}}),_e,Qe=d(()=>{Pe(),_e=re}),st,yt,qt,ut,nt,Le,ht=d(()=>{I(),st=(ne,pe)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${ne}::ORT::${pe}`)},yt=(ne,pe)=>{var ke;let xe=((ke=new Error().stack)==null?void 0:ke.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<xe.length;Be++){if(De&&!xe[Be].includes("TRACE_FUNC")){let Ne=`FUNC_${ne}::${xe[Be].trim().split(" ")[1]}`;pe&&(Ne+=`::${pe}`),st("CPU",Ne);return}xe[Be].includes("TRACE_FUNC")&&(De=!0)}},qt=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||yt("BEGIN",ne)},ut=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||yt("END",ne)},nt=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${ne}`)},Le=ne=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${ne}`)}}),Gt,di=d(()=>{y(),Qe(),ht(),Gt=class oE{constructor(pe){this.handler=pe}async run(pe,xe,De){qt(),nt("InferenceSession.run");let ke={},Be={};if(typeof pe!="object"||pe===null||pe instanceof _e||Array.isArray(pe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ne=!0;if(typeof xe=="object"){if(xe===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(xe instanceof _e)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(xe)){if(xe.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ne=!1;for(let tt of xe){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);ke[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,ot=Object.getOwnPropertyNames(xe);for(let it of this.outputNames)if(ot.indexOf(it)!==-1){let Je=xe[it];(Je===null||Je instanceof _e)&&(tt=!0,Ne=!1,ke[it]=Je)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=xe}}else if(typeof xe<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof pe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if(Ne)for(let tt of this.outputNames)ke[tt]=null;let $e=await this.handler.run(pe,ke,Be),Fe={};for(let tt in $e)if(Object.hasOwnProperty.call($e,tt)){let ot=$e[tt];ot instanceof _e?Fe[tt]=ot:Fe[tt]=new _e(ot.type,ot.data,ot.dims)}return Le("InferenceSession.run"),ut(),Fe}async release(){return this.handler.dispose()}static async create(pe,xe,De,ke){qt(),nt("InferenceSession.create");let Be,Ne={};if(typeof pe=="string"){if(Be=pe,typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof Uint8Array){if(Be=pe,typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(pe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&pe instanceof SharedArrayBuffer){let ot=pe,it=0,Je=pe.byteLength;if(typeof xe=="object"&&xe!==null)Ne=xe;else if(typeof xe=="number"){if(it=xe,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=ot.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ot.byteLength}).`);if(Je=pe.byteLength-it,typeof De=="number"){if(Je=De,!Number.isSafeInteger(Je))throw new RangeError("'byteLength' must be an integer.");if(Je<=0||it+Je>ot.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ot.byteLength-it}].`);if(typeof ke=="object"&&ke!==null)Ne=ke;else if(typeof ke<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof xe<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(ot,it,Je)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$e,Fe]=await x(Ne),tt=await $e.createInferenceSessionHandler(Be,Fe);return Le("InferenceSession.create"),ut(),new oE(tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ue,_t=d(()=>{di(),Ue=Gt}),ft=d(()=>{}),ui=d(()=>{}),ji=d(()=>{}),Jn=d(()=>{}),xr={};p(xr,{InferenceSession:()=>Ue,TRACE:()=>st,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>Le,TRACE_FUNC_BEGIN:()=>qt,TRACE_FUNC_END:()=>ut,Tensor:()=>_e,env:()=>P,registerBackend:()=>w});var fi=d(()=>{_(),L(),_t(),Qe(),ft(),ui(),ht(),ji(),Jn()}),Bn=d(()=>{}),Wi={};p(Wi,{default:()=>$s});var on,mi,$s,Xa=d(()=>{var ne;ye(),er(),Qn(),on="ort-wasm-proxy-worker",mi=((ne=globalThis.self)==null?void 0:ne.name)===on,mi&&(self.onmessage=pe=>{let{type:xe,in:De}=pe.data;try{switch(xe){case"init-wasm":fs(De.wasm).then(()=>{pa(De).then(()=>{postMessage({type:xe})},ke=>{postMessage({type:xe,err:ke})})},ke=>{postMessage({type:xe,err:ke})});break;case"init-ep":{let{epName:ke,env:Be}=De;zs(Be,ke).then(()=>{postMessage({type:xe})},Ne=>{postMessage({type:xe,err:Ne})});break}case"copy-from":{let{buffer:ke}=De,Be=oi(ke);postMessage({type:xe,out:Be});break}case"create":{let{model:ke,options:Be}=De;Sr(ke,Be).then(Ne=>{postMessage({type:xe,out:Ne})},Ne=>{postMessage({type:xe,err:Ne})});break}case"release":ro(De),postMessage({type:xe});break;case"run":{let{sessionId:ke,inputIndices:Be,inputs:Ne,outputIndices:$e,options:Fe}=De;Xe(ke,Be,Ne,$e,new Array($e.length).fill(null),Fe).then(tt=>{tt.some(ot=>ot[3]!=="cpu")?postMessage({type:xe,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:xe,out:tt},gt([...Ne,...tt]))},tt=>{postMessage({type:xe,err:tt})});break}case"end-profiling":ir(De),postMessage({type:xe});break;default:}}catch(ke){postMessage({type:xe,err:ke})}}),$s=mi?null:pe=>new Worker(pe??_i,{type:"classic",name:on})}),ua,Ps,_i,Zn,an,Rs,Vr,br,to,Is,Ms,qr,Fn,Qn=d(()=>{Bn(),ua=typeof location>"u"?void 0:location.origin,Ps=()=>{var ne,pe;return typeof document<"u"?(ne=document.currentScript)==null?void 0:ne.src:typeof self<"u"?(pe=self.location)==null?void 0:pe.href:void 0},_i=Ps(),Zn=()=>{if(_i&&!_i.startsWith("blob:"))return _i.substring(0,_i.lastIndexOf("/")+1)},an=(ne,pe)=>{try{let xe=pe??_i;return(xe?new URL(ne,xe):new URL(ne)).origin===ua}catch{return!1}},Rs=(ne,pe)=>{let xe=pe??_i;try{return(xe?new URL(ne,xe):new URL(ne)).href}catch{return}},Vr=(ne,pe)=>`${pe??"./"}${ne}`,br=async ne=>{let pe=await(await fetch(ne,{credentials:"same-origin"})).blob();return URL.createObjectURL(pe)},to=async ne=>(await import(ne)).default,Is=(Xa(),f(Wi)).default,Ms=async()=>{if(!_i)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(an(_i))return[void 0,Is()];let ne=await br(_i);return[ne,Is(ne)]},qr=void 0,Fn=async(ne,pe,xe,De)=>{let ke=qr&&!(ne||pe);if(ke)if(_i)ke=an(_i)||De&&!xe;else if(De&&!xe)ke=!0;else throw new Error("cannot determine the script source URL.");if(ke)return[void 0,qr];{let Be="ort-wasm-simd-threaded.mjs",Ne=ne??Rs(Be,pe),$e=xe&&Ne&&!an(Ne,pe),Fe=$e?await br(Ne):Ne??Vr(Be,pe);return[$e?Fe:void 0,await to(Fe)]}}}),us,Gn,yr,zr,jo,hs,ps,fs,Bt,er=d(()=>{Qn(),Gn=!1,yr=!1,zr=!1,jo=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},hs=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},ps=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},fs=async ne=>{if(Gn)return Promise.resolve();if(yr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(zr)throw new Error("previous call to 'initializeWebAssembly()' failed.");yr=!0;let pe=ne.initTimeout,xe=ne.numThreads;if(ne.simd!==!1){if(ne.simd==="relaxed"){if(!ps())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!hs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=jo();xe>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+xe+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),ne.numThreads=xe=1);let ke=ne.wasmPaths,Be=typeof ke=="string"?ke:void 0,Ne=ke==null?void 0:ke.mjs,$e=(Ne==null?void 0:Ne.href)??Ne,Fe=ke==null?void 0:ke.wasm,tt=(Fe==null?void 0:Fe.href)??Fe,ot=ne.wasmBinary,[it,Je]=await Fn($e,Be,xe>1,!!ot||!!tt),$t=!1,ze=[];if(pe>0&&ze.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},pe)})),ze.push(new Promise((dt,Ai)=>{let ti={numThreads:xe};if(ot)ti.wasmBinary=ot,ti.locateFile=ii=>ii;else if(tt||Be)ti.locateFile=ii=>tt??Be+ii;else if($e&&$e.indexOf("blob:")!==0)ti.locateFile=ii=>new URL(ii,$e).href;else if(it){let ii=Zn();ii&&(ti.locateFile=Ni=>ii+Ni)}Je(ti).then(ii=>{yr=!1,Gn=!0,us=ii,dt(),it&&URL.revokeObjectURL(it)},ii=>{yr=!1,zr=!0,Ai(ii)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${pe}ms`)},Bt=()=>{if(Gn&&us)return us;throw new Error("WebAssembly is not initialized yet.")}}),Vi,Ci,Et,io=d(()=>{er(),Vi=(ne,pe)=>{let xe=Bt(),De=xe.lengthBytesUTF8(ne)+1,ke=xe._malloc(De);return xe.stringToUTF8(ne,ke,De),pe.push(ke),ke},Ci=(ne,pe,xe,De)=>{if(typeof ne=="object"&&ne!==null){if(xe.has(ne))throw new Error("Circular reference in options");xe.add(ne)}Object.entries(ne).forEach(([ke,Be])=>{let Ne=pe?pe+ke:ke;if(typeof Be=="object")Ci(Be,Ne+".",xe,De);else if(typeof Be=="string"||typeof Be=="number")De(Ne,Be.toString());else if(typeof Be=="boolean")De(Ne,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=ne=>{let pe=Bt(),xe=pe.stackSave();try{let De=pe.PTR_SIZE,ke=pe.stackAlloc(2*De);pe._OrtGetLastError(ke,ke+De);let Be=Number(pe.getValue(ke,De===4?"i32":"i64")),Ne=pe.getValue(ke+De,"*"),$e=Ne?pe.UTF8ToString(Ne):"";throw new Error(`${ne} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${$e}`)}finally{pe.stackRestore(xe)}}}),Do,Ja=d(()=>{er(),io(),Do=ne=>{let pe=Bt(),xe=0,De=[],ke=ne||{};try{if((ne==null?void 0:ne.logSeverityLevel)===void 0)ke.logSeverityLevel=2;else if(typeof ne.logSeverityLevel!="number"||!Number.isInteger(ne.logSeverityLevel)||ne.logSeverityLevel<0||ne.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${ne.logSeverityLevel}`);if((ne==null?void 0:ne.logVerbosityLevel)===void 0)ke.logVerbosityLevel=0;else if(typeof ne.logVerbosityLevel!="number"||!Number.isInteger(ne.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${ne.logVerbosityLevel}`);(ne==null?void 0:ne.terminate)===void 0&&(ke.terminate=!1);let Be=0;return(ne==null?void 0:ne.tag)!==void 0&&(Be=Vi(ne.tag,De)),xe=pe._OrtCreateRunOptions(ke.logSeverityLevel,ke.logVerbosityLevel,!!ke.terminate,Be),xe===0&&Et("Can't create run options."),(ne==null?void 0:ne.extra)!==void 0&&Ci(ne.extra,"",new WeakSet,(Ne,$e)=>{let Fe=Vi(Ne,De),tt=Vi($e,De);pe._OrtAddRunConfigEntry(xe,Fe,tt)!==0&&Et(`Can't set a run config entry: ${Ne} - ${$e}.`)}),[xe,De]}catch(Be){throw xe!==0&&pe._OrtReleaseRunOptions(xe),De.forEach(Ne=>pe._free(Ne)),Be}}}),Ao,No,ha,$n,Za,Qa,Ei=d(()=>{er(),io(),Ao=ne=>{switch(ne){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${ne}`)}},No=ne=>{switch(ne){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${ne}`)}},ha=ne=>{ne.extra||(ne.extra={}),ne.extra.session||(ne.extra.session={});let pe=ne.extra.session;pe.use_ort_model_bytes_directly||(pe.use_ort_model_bytes_directly="1"),ne.executionProviders&&ne.executionProviders.some(xe=>(typeof xe=="string"?xe:xe.name)==="webgpu")&&(ne.enableMemPattern=!1)},$n=(ne,pe,xe,De)=>{let ke=Vi(pe,De),Be=Vi(xe,De);Bt()._OrtAddSessionConfigEntry(ne,ke,Be)!==0&&Et(`Can't set a session config entry: ${pe} - ${xe}.`)},Za=async(ne,pe,xe)=>{let De=pe.executionProviders;for(let ke of De){let Be=typeof ke=="string"?ke:ke.name,Ne=[];switch(Be){case"webnn":if(Be="WEBNN",$n(ne,"session.disable_quant_qdq","1",xe),$n(ne,"session.disable_qdq_constant_folding","1",xe),typeof ke!="string"){let it=ke==null?void 0:ke.deviceType;it&&$n(ne,"deviceType",it,xe)}break;case"webgpu":if(Be="JS",typeof ke!="string"){let it=ke;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);$n(ne,"preferredLayout",it.preferredLayout,xe)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let $e=Vi(Be,xe),Fe=Ne.length,tt=0,ot=0;if(Fe>0){tt=Bt()._malloc(Fe*Bt().PTR_SIZE),xe.push(tt),ot=Bt()._malloc(Fe*Bt().PTR_SIZE),xe.push(ot);for(let it=0;it<Fe;it++)Bt().setValue(tt+it*Bt().PTR_SIZE,Ne[it][0],"*"),Bt().setValue(ot+it*Bt().PTR_SIZE,Ne[it][1],"*")}await Bt()._OrtAppendExecutionProvider(ne,$e,tt,ot,Fe)!==0&&Et(`Can't append execution provider: ${Be}.`)}},Qa=async ne=>{let pe=Bt(),xe=0,De=[],ke=ne||{};ha(ke);try{let Be=Ao(ke.graphOptimizationLevel??"all"),Ne=No(ke.executionMode??"sequential"),$e=typeof ke.logId=="string"?Vi(ke.logId,De):0,Fe=ke.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let tt=ke.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let ot=typeof ke.optimizedModelFilePath=="string"?Vi(ke.optimizedModelFilePath,De):0;if(xe=pe._OrtCreateSessionOptions(Be,!!ke.enableCpuMemArena,!!ke.enableMemPattern,Ne,!!ke.enableProfiling,0,$e,Fe,tt,ot),xe===0&&Et("Can't create session options."),ke.executionProviders&&await Za(xe,ke,De),ke.enableGraphCapture!==void 0){if(typeof ke.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ke.enableGraphCapture}`);$n(xe,"enableGraphCapture",ke.enableGraphCapture.toString(),De)}if(ke.freeDimensionOverrides)for(let[it,Je]of Object.entries(ke.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof Je!="number"||!Number.isInteger(Je)||Je<0)throw new Error(`free dimension override value must be a non-negative integer: ${Je}`);let $t=Vi(it,De);pe._OrtAddFreeDimensionOverride(xe,$t,Je)!==0&&Et(`Can't set a free dimension override: ${it} - ${Je}.`)}return ke.extra!==void 0&&Ci(ke.extra,"",new WeakSet,(it,Je)=>{$n(xe,it,Je,De)}),[xe,De]}catch(Be){throw xe!==0&&pe._OrtReleaseSessionOptions(xe)!==0&&Et("Can't release session options."),De.forEach(Ne=>pe._free(Ne)),Be}}}),Un,Yi,Hn,ms,no,Os,_r,kn,Ft=d(()=>{Un=ne=>{switch(ne){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${ne}`)}},Yi=ne=>{switch(ne){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${ne}`)}},Hn=(ne,pe)=>{let xe=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][ne],De=typeof pe=="number"?pe:pe.reduce((ke,Be)=>ke*Be,1);return xe>0?Math.ceil(De*xe):void 0},ms=ne=>{switch(ne){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${ne}`)}},no=ne=>{switch(ne){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${ne}`)}},Os=ne=>ne==="float32"||ne==="float16"||ne==="int32"||ne==="int64"||ne==="uint32"||ne==="uint8"||ne==="bool"||ne==="uint4"||ne==="int4",_r=ne=>ne==="float32"||ne==="float16"||ne==="int32"||ne==="int64"||ne==="uint32"||ne==="uint64"||ne==="int8"||ne==="uint8"||ne==="bool"||ne==="uint4"||ne==="int4",kn=ne=>{switch(ne){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${ne}`)}}}),Xi,Ls=d(()=>{Bn(),Xi=async ne=>{if(typeof ne=="string"){let pe=await fetch(ne);if(!pe.ok)throw new Error(`failed to load external data file: ${ne}`);let xe=pe.headers.get("Content-Length"),De=xe?parseInt(xe,10):0;if(De<1073741824)return new Uint8Array(await pe.arrayBuffer());{if(!pe.body)throw new Error(`failed to load external data file: ${ne}, no response body.`);let ke=pe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch($e){if($e instanceof RangeError){let Fe=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw $e}let Ne=0;for(;;){let{done:$e,value:Fe}=await ke.read();if($e)break;let tt=Fe.byteLength;new Uint8Array(Be,Ne,tt).set(Fe),Ne+=tt}return new Uint8Array(Be,0,De)}}else return ne instanceof Blob?new Uint8Array(await ne.arrayBuffer()):ne instanceof Uint8Array?ne:new Uint8Array(ne)}}),wr,pa,zs,tr,Kr,Bs,oi,Sr,ro,Br,Xe,ir,gt,ye=d(()=>{fi(),Ja(),Ei(),Ft(),er(),io(),Ls(),wr=(ne,pe)=>{Bt()._OrtInit(ne,pe)!==0&&Et("Can't initialize onnxruntime.")},pa=async ne=>{wr(ne.wasm.numThreads,no(ne.logLevel))},zs=async(ne,pe)=>{var De,ke;(ke=(De=Bt()).asyncInit)==null||ke.call(De);let xe=ne.webgpu.adapter;if(pe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(xe){if(typeof xe.limits!="object"||typeof xe.features!="object"||typeof xe.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=ne.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Ne=ne.webgpu.forceFallbackAdapter;if(Ne!==void 0&&typeof Ne!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ne}"`);if(xe=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Ne}),!xe)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(pe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},tr=new Map,Kr=ne=>{let pe=Bt(),xe=pe.stackSave();try{let De=pe.PTR_SIZE,ke=pe.stackAlloc(2*De);pe._OrtGetInputOutputCount(ne,ke,ke+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(pe.getValue(ke,Be)),Number(pe.getValue(ke+De,Be))]}finally{pe.stackRestore(xe)}},Bs=(ne,pe)=>{let xe=Bt(),De=xe.stackSave(),ke=0;try{let Be=xe.PTR_SIZE,Ne=xe.stackAlloc(2*Be);xe._OrtGetInputOutputMetadata(ne,pe,Ne,Ne+Be)!==0&&Et("Can't get session input/output metadata.");let $e=Number(xe.getValue(Ne,"*"));ke=Number(xe.getValue(Ne+Be,"*"));let Fe=xe.HEAP32[ke/4];if(Fe===0)return[$e,0];let tt=xe.HEAPU32[ke/4+1],ot=[];for(let it=0;it<tt;it++){let Je=Number(xe.getValue(ke+8+it*Be,"*"));ot.push(Je!==0?xe.UTF8ToString(Je):Number(xe.getValue(ke+8+(it+tt)*Be,"*")))}return[$e,Fe,ot]}finally{xe.stackRestore(De),ke!==0&&xe._OrtFree(ke)}},oi=ne=>{let pe=Bt(),xe=pe._malloc(ne.byteLength);if(xe===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${ne.byteLength}.`);return pe.HEAPU8.set(ne,xe),[xe,ne.byteLength]},Sr=async(ne,pe)=>{var ot,it,Je;let xe,De,ke=Bt();Array.isArray(ne)?[xe,De]=ne:ne.buffer===ke.HEAPU8.buffer?[xe,De]=[ne.byteOffset,ne.byteLength]:[xe,De]=oi(ne);let Be=0,Ne=0,$e=[],Fe=[],tt=[];try{if([Ne,$e]=await Qa(pe),(pe==null?void 0:pe.externalData)&&ke.mountExternalData){let Mi=[];for(let hi of pe.externalData){let Cn=typeof hi=="string"?hi:hi.path;Mi.push(Xi(typeof hi=="string"?hi:hi.data).then(Wn=>{ke.mountExternalData(Cn,Wn)}))}await Promise.all(Mi)}for(let Mi of(pe==null?void 0:pe.executionProviders)??[])if((typeof Mi=="string"?Mi:Mi.name)==="webnn"){if(ke.shouldTransferToMLTensor=!1,typeof Mi!="string"){let hi=Mi,Cn=hi==null?void 0:hi.context,Wn=hi==null?void 0:hi.gpuDevice,nr=hi==null?void 0:hi.deviceType,tl=hi==null?void 0:hi.powerPreference;Cn?ke.currentContext=Cn:Wn?ke.currentContext=await ke.webnnCreateMLContext(Wn):ke.currentContext=await ke.webnnCreateMLContext({deviceType:nr,powerPreference:tl})}else ke.currentContext=await ke.webnnCreateMLContext();break}Be=await ke._OrtCreateSession(xe,De,Ne),(ot=ke.webgpuOnCreateSession)==null||ot.call(ke,Be),Be===0&&Et("Can't create a session."),(it=ke.jsepOnCreateSession)==null||it.call(ke),ke.currentContext&&(ke.webnnRegisterMLContext(Be,ke.currentContext),ke.currentContext=void 0,ke.shouldTransferToMLTensor=!0);let[$t,ze]=Kr(Be),dt=!!(pe!=null&&pe.enableGraphCapture),Ai=[],ti=[],ii=[],Ni=[],Lt=[];for(let Mi=0;Mi<$t;Mi++){let[hi,Cn,Wn]=Bs(Be,Mi);hi===0&&Et("Can't get an input name."),Fe.push(hi);let nr=ke.UTF8ToString(hi);Ai.push(nr),ii.push(Cn===0?{name:nr,isTensor:!1}:{name:nr,isTensor:!0,type:Yi(Cn),shape:Wn})}for(let Mi=0;Mi<ze;Mi++){let[hi,Cn,Wn]=Bs(Be,Mi+$t);hi===0&&Et("Can't get an output name."),tt.push(hi);let nr=ke.UTF8ToString(hi);ti.push(nr),Ni.push(Cn===0?{name:nr,isTensor:!1}:{name:nr,isTensor:!0,type:Yi(Cn),shape:Wn})}return tr.set(Be,[Be,Fe,tt,null,dt,!1]),[Be,Ai,ti,ii,Ni]}catch($t){throw Fe.forEach(ze=>ke._OrtFree(ze)),tt.forEach(ze=>ke._OrtFree(ze)),Be!==0&&ke._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{ke._free(xe),Ne!==0&&ke._OrtReleaseSessionOptions(Ne)!==0&&Et("Can't release session options."),$e.forEach($t=>ke._free($t)),(Je=ke.unmountExternalData)==null||Je.call(ke)}},ro=ne=>{var Fe,tt,ot;let pe=Bt(),xe=tr.get(ne);if(!xe)throw new Error(`cannot release session. invalid session id: ${ne}`);let[De,ke,Be,Ne,$e]=xe;Ne&&($e&&pe._OrtClearBoundOutputs(Ne.handle)!==0&&Et("Can't clear bound outputs."),pe._OrtReleaseBinding(Ne.handle)!==0&&Et("Can't release IO binding.")),(Fe=pe.jsepOnReleaseSession)==null||Fe.call(pe,ne),(tt=pe.webnnOnReleaseSession)==null||tt.call(pe,ne),(ot=pe.webgpuOnReleaseSession)==null||ot.call(pe,ne),ke.forEach(it=>pe._OrtFree(it)),Be.forEach(it=>pe._OrtFree(it)),pe._OrtReleaseSession(De)!==0&&Et("Can't release session."),tr.delete(ne)},Br=async(ne,pe,xe,De,ke,Be,Ne=!1)=>{if(!ne){pe.push(0);return}let $e=Bt(),Fe=$e.PTR_SIZE,tt=ne[0],ot=ne[1],it=ne[3],Je=it,$t,ze;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ne&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let ti=ne[2].gpuBuffer;ze=Hn(Un(tt),ot);{let ii=$e.jsepRegisterBuffer;if(!ii)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=ii(De,Be,ti,ze)}}else if(it==="ml-tensor"){let ti=ne[2].mlTensor;ze=Hn(Un(tt),ot);let ii=$e.webnnRegisterMLTensor;if(!ii)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=ii(De,ti,Un(tt),ot)}else{let ti=ne[2];if(Array.isArray(ti)){ze=Fe*ti.length,$t=$e._malloc(ze),xe.push($t);for(let ii=0;ii<ti.length;ii++){if(typeof ti[ii]!="string")throw new TypeError(`tensor data at index ${ii} is not a string`);$e.setValue($t+ii*Fe,Vi(ti[ii],xe),"*")}}else{let ii=$e.webnnIsGraphInput,Ni=$e.webnnIsGraphOutput;if(tt!=="string"&&ii&&Ni){let Lt=$e.UTF8ToString(ke);if(ii(De,Lt)||Ni(De,Lt)){let Mi=Un(tt);ze=Hn(Mi,ot),Je="ml-tensor";let hi=$e.webnnCreateTemporaryTensor,Cn=$e.webnnUploadTensor;if(!hi||!Cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Wn=await hi(De,Mi,ot);Cn(Wn,new Uint8Array(ti.buffer,ti.byteOffset,ti.byteLength)),$t=Wn}else ze=ti.byteLength,$t=$e._malloc(ze),xe.push($t),$e.HEAPU8.set(new Uint8Array(ti.buffer,ti.byteOffset,ze),$t)}else ze=ti.byteLength,$t=$e._malloc(ze),xe.push($t),$e.HEAPU8.set(new Uint8Array(ti.buffer,ti.byteOffset,ze),$t)}}let dt=$e.stackSave(),Ai=$e.stackAlloc(4*ot.length);try{ot.forEach((ii,Ni)=>$e.setValue(Ai+Ni*Fe,ii,Fe===4?"i32":"i64"));let ti=$e._OrtCreateTensor(Un(tt),$t,ze,Ai,ot.length,kn(Je));ti===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),pe.push(ti)}finally{$e.stackRestore(dt)}},Xe=async(ne,pe,xe,De,ke,Be)=>{var rr,Kl,td;let Ne=Bt(),$e=Ne.PTR_SIZE,Fe=tr.get(ne);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${ne}`);let tt=Fe[0],ot=Fe[1],it=Fe[2],Je=Fe[3],$t=Fe[4];Fe[5];let ze=pe.length,dt=De.length,Ai=0,ti=[],ii=[],Ni=[],Lt=[],Mi=[],hi=Ne.stackSave(),Cn=Ne.stackAlloc(ze*$e),Wn=Ne.stackAlloc(ze*$e),nr=Ne.stackAlloc(dt*$e),tl=Ne.stackAlloc(dt*$e);try{[Ai,ti]=Do(Be),nt("wasm prepareInputOutputTensor");for(let ci=0;ci<ze;ci++)await Br(xe[ci],ii,Lt,ne,ot[pe[ci]],pe[ci],$t);for(let ci=0;ci<dt;ci++)await Br(ke[ci],Ni,Lt,ne,it[De[ci]],ze+De[ci],$t);Le("wasm prepareInputOutputTensor");for(let ci=0;ci<ze;ci++)Ne.setValue(Cn+ci*$e,ii[ci],"*"),Ne.setValue(Wn+ci*$e,ot[pe[ci]],"*");for(let ci=0;ci<dt;ci++)Ne.setValue(nr+ci*$e,Ni[ci],"*"),Ne.setValue(tl+ci*$e,it[De[ci]],"*");(rr=Ne.jsepOnRunStart)==null||rr.call(Ne,tt),(Kl=Ne.webnnOnRunStart)==null||Kl.call(Ne,tt);let En;En=await Ne._OrtRun(tt,Wn,Cn,ze,tl,dt,nr,Ai),En!==0&&Et("failed to call OrtRun().");let vs=[],id=[];nt("wasm ProcessOutputTensor");for(let ci=0;ci<dt;ci++){let Xr=Number(Ne.getValue(nr+ci*$e,"*"));if(Xr===Ni[ci]||Mi.includes(Ni[ci])){vs.push(ke[ci]),Xr!==Ni[ci]&&Ne._OrtReleaseTensor(Xr)!==0&&Et("Can't release tensor.");continue}let Su=Ne.stackSave(),Us=Ne.stackAlloc(4*$e),fa=!1,mn,sr=0;try{Ne._OrtGetTensorData(Xr,Us,Us+$e,Us+2*$e,Us+3*$e)!==0&&Et(`Can't access output tensor data on index ${ci}.`);let Yl=$e===4?"i32":"i64",or=Number(Ne.getValue(Us,Yl));sr=Ne.getValue(Us+$e,"*");let nd=Ne.getValue(Us+$e*2,"*"),ku=Number(Ne.getValue(Us+$e*3,Yl)),Hs=[];for(let gn=0;gn<ku;gn++)Hs.push(Number(Ne.getValue(nd+gn*$e,Yl)));Ne._OrtFree(nd)!==0&&Et("Can't free memory for tensor dims.");let Jr=Hs.reduce((gn,qi)=>gn*qi,1);mn=Yi(or);let xs=Je==null?void 0:Je.outputPreferredLocations[De[ci]];if(mn==="string"){if(xs==="gpu-buffer"||xs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let gn=[];for(let qi=0;qi<Jr;qi++){let Zr=Ne.getValue(sr+qi*$e,"*"),rd=Ne.getValue(sr+(qi+1)*$e,"*"),sd=qi===Jr-1?void 0:rd-Zr;gn.push(Ne.UTF8ToString(Zr,sd))}vs.push([mn,Hs,gn,"cpu"])}else if(xs==="gpu-buffer"&&Jr>0){let gn=Ne.jsepGetBuffer;if(!gn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let qi=gn(sr),Zr=Hn(or,Jr);if(Zr===void 0||!Os(mn))throw new Error(`Unsupported data type: ${mn}`);fa=!0,vs.push([mn,Hs,{gpuBuffer:qi,download:Ne.jsepCreateDownloader(qi,Zr,mn),dispose:()=>{Ne._OrtReleaseTensor(Xr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(xs==="ml-tensor"&&Jr>0){let gn=Ne.webnnEnsureTensor,qi=Ne.webnnIsGraphInputOutputTypeSupported;if(!gn||!qi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Hn(or,Jr)===void 0||!_r(mn))throw new Error(`Unsupported data type: ${mn}`);if(!qi(ne,mn,!1))throw new Error(`preferredLocation "ml-tensor" for ${mn} output is not supported by current WebNN Context.`);let Zr=await gn(ne,sr,or,Hs,!1);fa=!0,vs.push([mn,Hs,{mlTensor:Zr,download:Ne.webnnCreateMLTensorDownloader(sr,mn),dispose:()=>{Ne.webnnReleaseTensorId(sr),Ne._OrtReleaseTensor(Xr)}},"ml-tensor"])}else if(xs==="ml-tensor-cpu-output"&&Jr>0){let gn=Ne.webnnCreateMLTensorDownloader(sr,mn)(),qi=vs.length;fa=!0,id.push((async()=>{let Zr=[qi,await gn];return Ne.webnnReleaseTensorId(sr),Ne._OrtReleaseTensor(Xr),Zr})()),vs.push([mn,Hs,[],"cpu"])}else{let gn=ms(mn),qi=new gn(Jr);new Uint8Array(qi.buffer,qi.byteOffset,qi.byteLength).set(Ne.HEAPU8.subarray(sr,sr+qi.byteLength)),vs.push([mn,Hs,qi,"cpu"])}}finally{Ne.stackRestore(Su),mn==="string"&&sr&&Ne._free(sr),fa||Ne._OrtReleaseTensor(Xr)}}Je&&!$t&&(Ne._OrtClearBoundOutputs(Je.handle)!==0&&Et("Can't clear bound outputs."),tr.set(ne,[tt,ot,it,Je,$t,!1]));for(let[ci,Xr]of await Promise.all(id))vs[ci][2]=Xr;return Le("wasm ProcessOutputTensor"),vs}finally{(td=Ne.webnnOnRunEnd)==null||td.call(Ne,tt),Ne.stackRestore(hi),ii.forEach(En=>Ne._OrtReleaseTensor(En)),Ni.forEach(En=>Ne._OrtReleaseTensor(En)),Lt.forEach(En=>Ne._free(En)),Ai!==0&&Ne._OrtReleaseRunOptions(Ai),ti.forEach(En=>Ne._free(En))}},ir=ne=>{let pe=Bt(),xe=tr.get(ne);if(!xe)throw new Error("invalid session id");let De=xe[0],ke=pe._OrtEndProfiling(De);ke===0&&Et("Can't get an profile file name."),pe._OrtFree(ke)},gt=ne=>{let pe=[];for(let xe of ne){let De=xe[2];!Array.isArray(De)&&"buffer"in De&&pe.push(De.buffer)}return pe}}),Ie,Ze,jt,ri,ai,Ri,$i,ln,Bi,fn,Pi,Yr,so,$o,gs,wu,Po,Ro,Zc=d(()=>{fi(),ye(),er(),Qn(),Ie=()=>!!P.wasm.proxy&&typeof document<"u",jt=!1,ri=!1,ai=!1,ln=new Map,Bi=(ne,pe)=>{let xe=ln.get(ne);xe?xe.push(pe):ln.set(ne,[pe])},fn=()=>{if(jt||!ri||ai||!Ze)throw new Error("worker not ready")},Pi=ne=>{switch(ne.data.type){case"init-wasm":jt=!1,ne.data.err?(ai=!0,$i[1](ne.data.err)):(ri=!0,$i[0]()),Ri&&(URL.revokeObjectURL(Ri),Ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let pe=ln.get(ne.data.type);ne.data.err?pe.shift()[1](ne.data.err):pe.shift()[0](ne.data.out);break}}},Yr=async()=>{if(!ri){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(ai)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Ie())return new Promise((ne,pe)=>{Ze==null||Ze.terminate(),Ms().then(([xe,De])=>{try{Ze=De,Ze.onerror=Be=>pe(Be),Ze.onmessage=Pi,$i=[ne,pe];let ke={type:"init-wasm",in:P};if(!ke.in.wasm.wasmPaths&&xe){let Be=Zn();Be&&(ke.in.wasm.wasmPaths=Be)}Ze.postMessage(ke),Ri=xe}catch(ke){pe(ke)}},pe)});try{await fs(P.wasm),await pa(P),ri=!0}catch(ne){throw ai=!0,ne}finally{jt=!1}}},so=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("init-ep",[pe,xe]);let De={type:"init-ep",in:{epName:ne,env:P}};Ze.postMessage(De)});await zs(P,ne)},$o=async ne=>Ie()?(fn(),new Promise((pe,xe)=>{Bi("copy-from",[pe,xe]);let De={type:"copy-from",in:{buffer:ne}};Ze.postMessage(De,[ne.buffer])})):oi(ne),gs=async(ne,pe)=>{if(Ie()){if(pe!=null&&pe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return fn(),new Promise((xe,De)=>{Bi("create",[xe,De]);let ke={type:"create",in:{model:ne,options:{...pe}}},Be=[];ne instanceof Uint8Array&&Be.push(ne.buffer),Ze.postMessage(ke,Be)})}else return Sr(ne,pe)},wu=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("release",[pe,xe]);let De={type:"release",in:ne};Ze.postMessage(De)});ro(ne)},Po=async(ne,pe,xe,De,ke,Be)=>{if(Ie()){if(xe.some(Ne=>Ne[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ke.some(Ne=>Ne))throw new Error("pre-allocated output tensor is not supported for proxy.");return fn(),new Promise((Ne,$e)=>{Bi("run",[Ne,$e]);let Fe=xe,tt={type:"run",in:{sessionId:ne,inputIndices:pe,inputs:Fe,outputIndices:De,options:Be}};Ze.postMessage(tt,gt(Fe))})}else return Xe(ne,pe,xe,De,ke,Be)},Ro=async ne=>{if(Ie())return fn(),new Promise((pe,xe)=>{Bi("end-profiling",[pe,xe]);let De={type:"end-profiling",in:ne};Ze.postMessage(De)});ir(ne)}}),Hl,Io,el,Wl=d(()=>{fi(),Zc(),Ft(),Bn(),Ls(),Hl=(ne,pe)=>{switch(ne.location){case"cpu":return[ne.type,ne.dims,ne.data,"cpu"];case"gpu-buffer":return[ne.type,ne.dims,{gpuBuffer:ne.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[ne.type,ne.dims,{mlTensor:ne.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${ne.location} for ${pe()}`)}},Io=ne=>{switch(ne[3]){case"cpu":return new _e(ne[0],ne[2],ne[1]);case"gpu-buffer":{let pe=ne[0];if(!Os(pe))throw new Error(`not supported data type: ${pe} for deserializing GPU tensor`);let{gpuBuffer:xe,download:De,dispose:ke}=ne[2];return _e.fromGpuBuffer(xe,{dataType:pe,dims:ne[1],download:De,dispose:ke})}case"ml-tensor":{let pe=ne[0];if(!_r(pe))throw new Error(`not supported data type: ${pe} for deserializing MLTensor tensor`);let{mlTensor:xe,download:De,dispose:ke}=ne[2];return _e.fromMLTensor(xe,{dataType:pe,dims:ne[1],download:De,dispose:ke})}default:throw new Error(`invalid data location: ${ne[3]}`)}},el=class{async fetchModelAndCopyToWasmMemory(ne){return $o(await Xi(ne))}async loadModel(ne,pe){qt();let xe;typeof ne=="string"?xe=await this.fetchModelAndCopyToWasmMemory(ne):xe=ne,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await gs(xe,pe),ut()}async dispose(){return wu(this.sessionId)}async run(ne,pe,xe){qt();let De=[],ke=[];Object.entries(ne).forEach(it=>{let Je=it[0],$t=it[1],ze=this.inputNames.indexOf(Je);if(ze===-1)throw new Error(`invalid input '${Je}'`);De.push($t),ke.push(ze)});let Be=[],Ne=[];Object.entries(pe).forEach(it=>{let Je=it[0],$t=it[1],ze=this.outputNames.indexOf(Je);if(ze===-1)throw new Error(`invalid output '${Je}'`);Be.push($t),Ne.push(ze)});let $e=De.map((it,Je)=>Hl(it,()=>`input "${this.inputNames[ke[Je]]}"`)),Fe=Be.map((it,Je)=>it?Hl(it,()=>`output "${this.outputNames[Ne[Je]]}"`):null),tt=await Po(this.sessionId,ke,$e,Ne,Fe,xe),ot={};for(let it=0;it<tt.length;it++)ot[this.outputNames[Ne[it]]]=Be[it]??Io(tt[it]);return ut(),ot}startProfiling(){}endProfiling(){Ro(this.sessionId)}}}),Fs={};p(Fs,{OnnxruntimeWebAssemblyBackend:()=>Gs,initializeFlags:()=>oo,wasmBackend:()=>Mo});var oo,Gs,Mo,Qc=d(()=>{fi(),Zc(),Wl(),oo=()=>{(typeof P.wasm.initTimeout!="number"||P.wasm.initTimeout<0)&&(P.wasm.initTimeout=0);let ne=P.wasm.simd;if(typeof ne!="boolean"&&ne!==void 0&&ne!=="fixed"&&ne!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${ne}". Reset it to \`false\` and ignore SIMD feature checking.`),P.wasm.simd=!1),typeof P.wasm.proxy!="boolean"&&(P.wasm.proxy=!1),typeof P.wasm.trace!="boolean"&&(P.wasm.trace=!1),typeof P.wasm.numThreads!="number"||!Number.isInteger(P.wasm.numThreads)||P.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)P.wasm.numThreads=1;else{let pe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;P.wasm.numThreads=Math.min(4,Math.ceil((pe||1)/2))}},Gs=class{async init(ne){oo(),await Yr(),await so(ne)}async createInferenceSessionHandler(ne,pe){let xe=new el;return await xe.loadModel(ne,pe),xe}},Mo=new Gs}),ed={};p(ed,{InferenceSession:()=>Ue,TRACE:()=>st,TRACE_EVENT_BEGIN:()=>nt,TRACE_EVENT_END:()=>Le,TRACE_FUNC_BEGIN:()=>qt,TRACE_FUNC_END:()=>ut,Tensor:()=>_e,default:()=>ql,env:()=>P,registerBackend:()=>w}),fi(),fi(),fi();var Vl="1.26.0",ql=xr;{let ne=(Qc(),f(Fs)).wasmBackend;w("cpu",ne,10),w("wasm",ne,10)}return Object.defineProperty(P.versions,"web",{value:Vl,enumerable:!0}),f(ed)})();i.exports=n})(Sy)),Sy.exports}var U1;function mN(){return U1||(U1=1,(function(i){var e=kl&&kl.__createBinding||(Object.create?(function(E,j,D,$){$===void 0&&($=D);var I=Object.getOwnPropertyDescriptor(j,D);(!I||("get"in I?!j.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return j[D]}}),Object.defineProperty(E,$,I)}):(function(E,j,D,$){$===void 0&&($=D),E[$]=j[D]})),n=kl&&kl.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=kl&&kl.__importStar||function(E){if(E&&E.__esModule)return E;var j={};if(E!=null)for(var D in E)D!=="default"&&Object.prototype.hasOwnProperty.call(E,D)&&e(j,E,D);return n(j,E),j};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const s=r(fN()),a=qw(),u=Kw(),l=Ag(),d=Bb(),p=rE(),m=sE();i.DEFAULT_MODEL="legacy",i.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",w=E=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:E,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async j=>{j.getTracks().forEach(D=>{D.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:j=>{j.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=w;const C=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,D,$,I){await D.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:$};const P=new AudioWorkletNode(D,"vad-helper-worklet",j);return P.port.onmessage=async L=>{const B=L.data;if(!(typeof B=="object"&&B&&"message"in B)){console.error("Invalid message event",B);return}switch(B.message){case d.Message.AudioFrame:{if(!("data"in B&&B.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const U=new Float32Array(B.data);await I(U);break}}},P}async function y(E,j,D){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const P=E.createScriptProcessor(4096,1,1);let L=!1;return P.onaudioprocess=async B=>{if(!L){L=!0;try{const U=B.inputBuffer.getChannelData(0);B.outputBuffer.getChannelData(0).fill(0);const X=$.process(U);for(const W of X)await D(W)}catch(U){console.error("Error processing audio:",U)}finally{L=!1}}},P.connect(E.destination),P}class _{constructor(j,D,$,I,P=!1,L=null,B=null,U=null,Z=null,X=null,W=null,J="uninitialized",te=!1){this.options=j,this.frameProcessor=D,this.model=$,this.frameSamples=I,this.listening=P,this.errored=L,this._stream=B,this._audioContext=U,this._vadNode=Z,this._mediaStreamAudioSourceNode=X,this._audioProcessorAdapterType=W,this.initializationState=J,this.ownsAudioContext=te,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=le=>{this.initializationState="errored",this.errored=le},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(le){throw le instanceof Error?this.setErrored(le.message):this.setErrored(String(le)),le}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?C(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await y(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:le,audioContext:ue,vadNode:V}=this.getAudioInstances();this._stream=await this.options.resumeStream(le);const ie=new MediaStreamAudioSourceNode(ue,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ie,ie.connect(V);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:le,mediaStreamAudioSourceNode:ue}=this.getAudioInstances();await this.options.pauseStream(le),ue.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ue;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:le}=this.getAudioInstances();le instanceof AudioWorkletNode&&le.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ue=this._audioContext)==null?void 0:ue.close())},this.setOptions=le=>{this.frameProcessor.setOptions(le)},this.processFrame=async le=>{await this.frameProcessor.process(le,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=le=>{switch(le.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(le.probs,le.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(le.audio);break}}}static async new(j={}){const D={...(0,i.getDefaultRealTimeVADOptions)(j.model??i.DEFAULT_MODEL),...j};(0,u.validateOptions)(D),i.ort.env.wasm.wasmPaths=D.onnxWASMBasePath,D.ortConfig!==void 0&&D.ortConfig(i.ort);const $=D.model==="v5"?b:S,I=D.baseAssetPath+$,P=D.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let L;try{L=await P(i.ort,()=>(0,a.defaultModelFetcher)(I))}catch(W){throw console.error(`Encountered an error while loading model file ${I}`),W}const B=D.model==="v5"?512:1536,U=B/16,Z=new u.FrameProcessor(L.process,L.reset_state,{positiveSpeechThreshold:D.positiveSpeechThreshold,negativeSpeechThreshold:D.negativeSpeechThreshold,redemptionMs:D.redemptionMs,preSpeechPadMs:D.preSpeechPadMs,minSpeechMs:D.minSpeechMs,submitUserSpeechOnPause:D.submitUserSpeechOnPause},U),X=new _(D,Z,L,B);if(D.startOnLoad)try{await X.start()}catch(W){throw console.error("Error starting micVad",W),W}return X}}i.MicVAD=_})(kl)),kl}var H1;function gN(){return H1||(H1=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=tE();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var n=qw();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return n.defaultModelFetcher}});var r=Kw();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=Bb();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return s.Message}});var a=hN();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const u=pN();i.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var l=mN();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(yy)),yy}var vN=gN();function Gv(i,e,n,r){var a,u;try{(u=(a=window.api)==null?void 0:a.logs)==null||u.write(i,e,n,r)}catch{}const s=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?s(`[${i}]`,n,r):s(`[${i}]`,n)}const pt={debug:(i,e,n)=>Gv(i,"debug",e,n),info:(i,e,n)=>Gv(i,"info",e,n),warn:(i,e,n)=>Gv(i,"warn",e,n),error:(i,e,n)=>Gv(i,"error",e,n)},aE=16e3,xN=6,tp=aE*xN,bN=400,yN=aE*bN/1e3,W1=300,V1=2e3,q1=1500,K1=3e3,_N=600,lE=.5,cE=.35,Y1=.85,X1=.7;let Ds=null,Ua=!1,ls=!1;const N_=new Set;function Uv(i){for(const e of Array.from(N_))try{e(i)}catch(n){pt.warn("speech","workerDeath listener threw",{error:n instanceof Error?n.message:String(n)})}}let ky=0;const J1=2;let gp=!1,dE=!1;function uE(i){i.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const n=e.data.level||"info";pt[n]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),wN(`error:${e.message||"unknown"}`)})}function ib(){return Ds||(Ds=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),uE(Ds),pt.info("speech","worker spawned"),Ds)}let Hv=!1;function wN(i){if(!gp){if(Hv){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(Hv=!0,ky+=1,dE=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:ky}),Uv({reason:i,respawned:!1,finalOnly:!0}),ky>J1){if(gp=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:J1}),Ds)try{Ds.terminate()}catch{}Ds=null,Ua=!1,ls=!1,Uv({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Hv=!1;return}if(Ds)try{Ds.terminate()}catch{}Ds=null,Ua=!1,ls=!1;try{Ds=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),uE(Ds),ls=!0,Ds.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),Uv({reason:i,respawned:!0,finalOnly:!0})}catch(e){gp=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Uv({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Hv=!1}}}function SN(i,e){if(Ua||ls)return;ls=!0;const n=ib();pt.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(i==null||i(s.data.status,s.data.message),s.data.status==="ready"&&(Ua=!0,ls=!1,pt.info("speech","preloadModel: ready"),n.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(ls=!1,pt.error("speech","preloadModel: worker reported error",{error:s.data.error}),i==null||i("error",s.data.error),n.removeEventListener("message",r))};n.addEventListener("message",r),n.postMessage({type:"load"})}function kN(){pt.info("speech","resetModel: clearing load flags"),Ua=!1,ls=!1}function Fb(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function CN(i){const e=ib();return!Ua&&!ls&&(ls=!0,e.postMessage({type:"load"})),new Promise((n,r)=>{const s=a=>{var u,l,d;((u=a.data)==null?void 0:u.type)==="result"?(e.removeEventListener("message",s),n((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((d=a.data)==null?void 0:d.type)==="status"&&a.data.status==="ready"&&(Ua=!0,ls=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function hE(i){let e=ib(),n=!1,r=null,s=null,a=null,u=null,l=null;const d=[],p=new Set;let m=null,f=0,b=!1,S=0,w=!1,C=!1,x=0,y=0,_=0,E=-1,j=W1,D=0,$=null,I="",P="",L=!1,B=0;function U(oe,be){const je=Math.min(oe.length,be.length);let Te=0;for(;Te<je&&oe.charCodeAt(Te)===be.charCodeAt(Te);)Te++;return Te}function Z(oe){const be=U(I,oe);return I=oe,be>P.length&&(P=oe.slice(0,be)),P.length>oe.length&&(P=oe),P}const X=()=>(m||(m=new Float32Array(tp)),m),W=()=>{f=0},J=oe=>{const be=X(),je=oe.length;if(je>=tp){be.set(oe.subarray(je-tp)),f=tp;return}if(f+je<=tp){be.set(oe,f),f+=je;return}const Te=f+je-tp;be.copyWithin(0,Te,f),f-=Te,be.set(oe,f),f+=je},te=()=>{$&&(clearTimeout($),$=null)},le=()=>{te(),b=!1,w=!1,C=!1,j=W1,I="",P="",L=!1,B=0,W()},ue=()=>{if(n||!b||C||w||$)return;if(f<yN){$=setTimeout(()=>{$=null,ue()},j);return}const oe=performance.now()-x;if(oe<j&&x!==0){$=setTimeout(()=>{$=null,ue()},j-oe);return}if(dE||gp||i.partialsEnabled&&!i.partialsEnabled())return;const be=X(),je=new Float32Array(f);je.set(be.subarray(0,f)),y+=1,_=y,w=!0,D=performance.now(),x=D,e.postMessage({type:"transcribe-partial",audio:je,seq:y},[je.buffer])},V=oe=>oe.length===0?Promise.resolve():gp?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),n||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(be=>{d.push(be),y+=1;const je=y;E=je,e.postMessage({type:"transcribe",audio:oe,seq:je},[oe.buffer])}),ie=oe=>{const be=V(oe);return p.add(be),be.finally(()=>{p.delete(be)}),be},K=oe=>{var be,je,Te,ve,re;if(oe.data.type==="result"){const Pe=oe.data.text,_e=oe.data.seq??0;_e&&_e<E&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:_e,latestFinalSeq:E}),!n&&Pe&&i.onFinal(Pe),(be=d.shift())==null||be()}else if(oe.data.type==="partial"){const Pe=oe.data.seq??0,_e=oe.data.text??"",Qe=performance.now()-D;w=!1,Qe>=K1?(C=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Qe),seq:Pe})):Qe>=q1&&(j=Math.min(j*2,V1),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Qe),newIntervalMs:j,seq:Pe})),L||(L=!0,Qe>_N&&j<500&&(j=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Qe),newIntervalMs:500})));const st=Pe!==_||Pe<=E;if(!n&&!st&&_e){const yt=Z(_e);yt&&((je=i.onPartial)==null||je.call(i,yt),B===0&&(B=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(B-S)})))}ue()}else if(oe.data.type==="partial-error"){const Pe=performance.now()-D;w=!1,Pe>=K1?(C=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Pe),seq:oe.data.seq})):Pe>=q1&&(j=Math.min(j*2,V1),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Pe),newIntervalMs:j,seq:oe.data.seq})),pt.warn("speech","partial encode failed",{error:oe.data.error,seq:oe.data.seq}),ue()}else oe.data.type==="error"?(n||i.onError(oe.data.error),(Te=d.shift())==null||Te()):oe.data.type==="status"?(n||(ve=i.onModelStatus)==null||ve.call(i,oe.data.status,oe.data.message),oe.data.status==="ready"&&(Ua=!0,ls=!1)):oe.data.type==="progress"&&(n||(re=i.onProgress)==null||re.call(i,oe.data.pct))};e.addEventListener("message",K);const se=oe=>{var be,je;if(!n){for(pt.warn("speech","createRecognition: worker death event",oe),(be=i.onStatusChange)==null||be.call(i,"restarting");d.length;)(je=d.shift())==null||je();if(p.clear(),te(),w=!1,oe.respawned){try{e.removeEventListener("message",K)}catch{}e=ib(),e.addEventListener("message",K)}}};return N_.add(se),{start:async()=>{if(!n){if(gp){i.onError("Speech recognition disabled — please reload the app.");return}!Ua&&!ls&&(ls=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:Ua,modelLoading:ls});try{const oe=new URL("vad/",document.baseURI).href,be=i.inputDeviceId||null,je={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};be&&(je.deviceId={exact:be}),pt.info("speech","getUserMedia",{hasDeviceId:!!be,deviceIdPrefix:be?be.slice(0,8):null});const Te=await navigator.mediaDevices.getUserMedia({audio:je});s=Te,a=new AudioContext;for(const ve of Te.getAudioTracks())ve.addEventListener("ended",()=>{n||(pt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),u=a.createAnalyser(),u.fftSize=2048,u.smoothingTimeConstant=.3,l.connect(u)}catch(ve){pt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),l=null,u=null}r=await vN.MicVAD.new({audioContext:a,getStream:async()=>Te,resumeStream:async()=>Te,pauseStream:async()=>{},baseAssetPath:oe,onnxWASMBasePath:oe,model:"v5",positiveSpeechThreshold:lE,negativeSpeechThreshold:cE,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,re)=>{var Pe;n||((Pe=i.onFrame)==null||Pe.call(i,ve),b&&(J(re),ue()))},onSpeechStart:()=>{var ve;n||(le(),b=!0,S=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var re;n||((re=i.onStatusChange)==null||re.call(i,"transcribing"),le(),ie(ve))},onVADMisfire:()=>{var ve,re;n||((ve=i.onStatusChange)==null||ve.call(i,"idle"),le(),(re=i.onMisfire)==null||re.call(i))}}),r.start()}catch(oe){const be=oe instanceof Error?oe.message:"Microphone access denied",je=oe instanceof Error?oe.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:be,stack:je}),u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Te=>Te.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}i.onError(be)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(le();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(oe,be)=>{if(r)try{r.setOptions({positiveSpeechThreshold:oe,negativeSpeechThreshold:be})}catch(je){pt.warn("speech","setVadThresholds failed",{error:je instanceof Error?je.message:String(je)})}},getAnalyser:()=>u,destroy:()=>{if(n=!0,le(),r){try{r.destroy()}catch{}r=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}N_.delete(se),e.removeEventListener("message",K)}}}let ig=null;const $_=new Set,P_=new Set;function EN(){for(const i of $_)try{i()}catch{}}function R_(){for(const i of P_)try{i()}catch{}}function TN(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function jN(i){if(!window.speechSynthesis)return;const e=TN(i);if(!e)return;const n=new SpeechSynthesisUtterance(e);n.rate=1,n.pitch=1,n.onstart=()=>{ig=performance.now(),EN()},n.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(ig=null,R_())},n.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(ig=null,R_())},window.speechSynthesis.speak(n)}function pE(){window.speechSynthesis&&(window.speechSynthesis.cancel(),ig=null,R_())}function fE(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function DN(){return ig}function AN(i){return $_.add(i),()=>{$_.delete(i)}}function NN(i){return P_.add(i),()=>{P_.delete(i)}}function $N(i){fE()&&(i.setVadThresholds(Y1,X1),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=AN(()=>{i.setVadThresholds(Y1,X1),pt.info("voice","tts.duck.on")}),n=NN(()=>{i.setVadThresholds(lE,cE),pt.info("voice","tts.duck.off")});return()=>{e(),n()}}const PN=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function RN(i){const e=i.trim();return PN.find(n=>n.match.test(e))??null}const IN=4e4;let ru=null;function vp(){ru&&clearTimeout(ru),ru=setTimeout(()=>{ru=null,At.getState().stopRecording()},IN)}function Wv(){ru&&(clearTimeout(ru),ru=null)}let Fc=null,Lc=null;const MN=.04,ON=.3;let nb=0,I_=0;function LN(i){Lc!==null&&cancelAnimationFrame(Lc);const e=()=>{if(Fc===null||At.getState().submitCountdownStartAt===null){Lc=null;return}const n=performance.now();if(n-I_<200&&nb>ON){const s=n-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:nb.toFixed(2),msIntoCountdown:Math.round(s)}),Pc(),vp();return}const r=mE();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const d=(s[l]-128)/128;a+=d*d}const u=Math.sqrt(a/s.length);if(u>MN){const l=n-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:u.toFixed(3),msIntoCountdown:Math.round(l)}),Pc(),vp();return}}Lc=requestAnimationFrame(e)};Lc=requestAnimationFrame(e)}function Z1(i){Fc&&clearTimeout(Fc);const e=At.getState().submitDelayMs,n=performance.now();At.setState({submitCountdownStartAt:n}),Fc=setTimeout(()=>{var s;Fc=null,At.setState({submitCountdownStartAt:null});const r=Ct.getState().tabs.find(a=>a.id===i);if((r==null?void 0:r.status)==="dormant"){const a=(s=dn.getState().chats[i])==null?void 0:s.pendingVoiceText;a&&(dn.getState().send({tabId:i,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),dn.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(a){pt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}vp()},e),LN(n)}function Pc(){Lc!==null&&(cancelAnimationFrame(Lc),Lc=null),Fc&&(clearTimeout(Fc),Fc=null),At.getState().submitCountdownStartAt!==null&&At.setState({submitCountdownStartAt:null})}let mr=null,Hr=null;function mE(){var i;return((i=mr==null?void 0:mr.getAnalyser)==null?void 0:i.call(mr))??null}const Vv=1e4;let ng=null;function qv(){ng&&(clearTimeout(ng),ng=null)}let Mx=null,Ox=null;function Kv(){Mx=null,Ox&&(Ox(),Ox=null)}const zN=1500,BN=9e4;let Yv=0,Lx=null,M_=-1;function Xv(){Lx&&(clearTimeout(Lx),Lx=null,M_=-1)}const FN=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),At=Xn((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const n=++Yv,r=()=>{n===Yv&&(Xv(),M_=n,Lx=setTimeout(()=>{M_===n&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},BN))};r(),SN((s,a)=>{n===Yv&&(s==="ready"?(Xv(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Xv(),pt.error("voice","modelStatus -> error",{msg:a}),i({modelStatus:"error",error:a,errorKind:"load"})):(r(),i({modelStatus:"loading"})))},s=>{n===Yv&&(r(),i({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),Xv(),kN(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:n=>{if(e().isRecording)return;if(mr){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Fb()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=s=>{try{const a=hE({inputDeviceId:s,onStatusChange:u=>{i(u==="transcribing"?{statusPill:"transcribing"}:u==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:u=>{e().partialsEnabled&&i({lastPartial:u})},partialsEnabled:()=>e().partialsEnabled,onFrame:u=>{nb=u.isSpeech,I_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),Wv(),Pc(),fE()){const l=DN(),d=l!==null?performance.now()-l:null;pE(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:n,utteranceOffsetMs:d})}else pt.debug("voice","barge-in.no-op",{tabId:n})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),vp();const u=e().lastBargeInAt;u!==null&&performance.now()-u<600&&pt.warn("voice","barge-in.misfire",{tabId:n,sinceBargeInMs:Math.round(performance.now()-u)})},onFinal:u=>{var f;vp();const l=u.trim();if(!l||FN.has(l)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((f=Ct.getState().tabs.find(b=>b.id===n))==null?void 0:f.status)==="dormant"){dn.getState().setPendingVoiceText(n,l),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Z1(n);const b=window;b.__transcripts&&(b.__transcripts.push({tabId:n,text:l}),b.__transcripts.length>500&&b.__transcripts.shift());return}const p=RN(l);if(p){pt.info("voice","voice-command",{tabId:n,label:p.label,transcript:l}),window.api.pty.write({tabId:n,data:p.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Pc();const b=window;b.__transcripts&&(b.__transcripts.push({tabId:n,text:l}),b.__transcripts.length>500&&b.__transcripts.shift());return}window.api.pty.write({tabId:n,data:l}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Z1(n);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:n,text:l}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:u=>{pt.error("voice","recognition error",{err:u}),Pc(),i({error:u,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Hr==null||Hr(),Hr=null,Wv(),mr==null||mr.destroy(),mr=null,Ve.error(`Microphone error: ${u}`)},onModelStatus:u=>{u==="ready"?i({modelStatus:"ready",loadingProgress:100}):u==="loading"&&i({modelStatus:"loading"})},onProgress:u=>i({loadingProgress:Math.round(u)})});mr=a,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),vp(),a.start().then(()=>{mr===a&&(Hr==null||Hr(),Hr=$N(a))}).catch(u=>{const l=u instanceof Error?u.message:String(u);pt.error("voice","handle.start() failed",{error:l}),Ve.error(`Could not start mic: ${l}`)})}catch(a){i({error:a instanceof Error?a.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var s,a,u;return((u=(a=(s=window.api)==null?void 0:s.voice)==null?void 0:a.getDevicePref)==null?void 0:u.call(a))??Promise.resolve(null)}).then(s=>r((s==null?void 0:s.selectedDeviceId)??null)).catch(s=>{pt.warn("voice","getDevicePref failed; using default device",{error:s instanceof Error?s.message:String(s)}),r(null)})},stopRecording:()=>{const n=mr;n&&(Wv(),Pc(),nb=0,I_=0,Hr==null||Hr(),Hr=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),n.stop().finally(()=>{n.destroy(),mr===n&&(mr=null),e().hotkeyState==="stopping"&&(qv(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const n=mr;if(!n)return;Wv(),Hr==null||Hr(),Hr=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await n.stop()}catch(a){pt.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}n.destroy(),mr===n&&(mr=null);const{useSessions:r}=await Dg(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>YA);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:n=>i({externalRecording:n}),toggleTTS:()=>i(n=>({ttsEnabled:!n.ttsEnabled})),setAutoSubmit:n=>i({autoSubmit:n}),setSubmitDelayMs:n=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(n)))}),cancelSubmit:()=>Pc(),setPartialsEnabled:n=>{e().partialsEnabled!==n&&(i({partialsEnabled:n}),n||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:n=>{e().permissionState!==n&&(pt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:n}),i({permissionState:n}))},setLevelMeterEnabled:n=>{e().levelMeterEnabled!==n&&i({levelMeterEnabled:n})},setTurnDetectorRuntimeState:n=>{e().turnDetectorState!==n&&(i({turnDetectorState:n}),n==="load_failed"?pt.warn("voice-turn","voice-turn.load_failed"):n==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):n==="disabled"&&pt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:n=>{e().wizardArmed!==n&&i({wizardArmed:n})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:n,source:r,mode:s,tabId:a})=>{const u=e(),{canRecord:l,reason:d}=O_(u);if(n==="down"){if(d==="error"||d==="load-timeout"){u.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:r,reason:d});return}if(!l&&d!=="loading"){pt.warn("voice-hotkey","miss-model-loading",{modelStatus:u.modelStatus,reason:d});return}if(u.hotkeyState==="recording"||u.isRecording){(s==="toggle"||r==="global")&&(i({hotkeyState:"stopping"}),qv(),ng=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Vv}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Vv),u.stopRecording());return}if(d==="loading"){u.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:r,modelStatus:u.modelStatus})),Kv(),Mx={tabId:a,source:r,mode:s},Ox=At.subscribe((p,m)=>{if(Mx&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=Mx;if(Kv(),!f.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",f),i({hotkeyState:"recording"}),At.getState().startRecording(f.tabId)}});return}if(!a){pt.warn("voice-hotkey","no-active-tab",{source:r});return}pt.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),u.startRecording(a),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(u.hotkeyState==="armed"){Kv(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}u.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),qv(),ng=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Vv}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Vv),u.stopRecording())}},destroyHotkey:()=>{const n=e();if(Kv(),Pc(),n.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{n.stopRecording()}catch{}}else(n.hotkeyState==="armed"||n.hotkeyState==="stopping")&&(qv(),i({hotkeyState:"destroyed"}))}})),GN=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),O_=i=>Fb()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=At,i.__transcripts=[]}function Yw(i,e,n){return new Promise((r,s)=>{const a=setTimeout(()=>s(new Error(`${n} timed out after ${e}ms`)),e);i.then(u=>{clearTimeout(a),r(u)},u=>{clearTimeout(a),s(u)})})}const UN=5e3,zl=Xn(()=>({snapshot:null,loaded:!1}));let Q1=!1,eS=!1,_m;async function HN(){var i;if(!Q1){Q1=!0;try{const e=await Yw(window.api.schedule.state(),UN,"schedule.state");zl.setState({snapshot:e,loaded:!0}),_m=((i=e.paused)==null?void 0:i.reason)??null}catch(e){if(!eS){eS=!0;const n=e instanceof Error?e.message:String(e);Ve.error(`Scheduler state hydrate failed: ${n}`)}_m=null}window.api.schedule.onState(e=>{var r;const n=((r=e.paused)==null?void 0:r.reason)??null;_m!==void 0&&n!==_m&&(n==="auth"?Ve.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):n==="network"&&Ve.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),_m=n,zl.setState({snapshot:e,loaded:!0})})}}const WN=6e4,VN=5e3,rg=Xn(()=>({data:null,refreshing:!1}));let tS=!1,zx=null,iS=null,nS=!1;async function Xw(){rg.setState({refreshing:!0});let i=WN;try{const e=await Yw(window.api.billing.fetch(),VN,"billing.fetch");rg.setState({data:e,refreshing:!1}),e.kind==="transient"?i=iS==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),iS=e.kind}catch(e){if(rg.setState({refreshing:!1}),!nS){nS=!0;const n=e instanceof Error?e.message:String(e);Ve.warn(`Billing usage fetch failed: ${n}`)}}zx=setTimeout(Xw,i)}function qN(){tS||(tS=!0,Xw())}function gE(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function KN(){zx!==null&&(clearTimeout(zx),zx=null),Xw()}function pi({name:i,size:e=17,stroke:n=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:n,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(i){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});default:return null}}function Ng(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),n=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!n)return i;const r=n[1].charAt(0).toUpperCase()+n[1].slice(1).toLowerCase(),s=n[3]?`${n[2]}.${n[3]}`:n[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const Jv=new Map,YN=3e4;function vE(i){const[e,n]=z.useState(()=>{var r;return i?((r=Jv.get(i))==null?void 0:r.value)??null:null});return z.useEffect(()=>{if(!i){n(null);return}let r=!1;return(async()=>{const a=Jv.get(i);if(a&&Date.now()-a.ts<YN){r||n(a.value);return}try{const u=await window.api.app.gitBranch(i);if(r)return;Jv.set(i,{value:u,ts:Date.now()}),n(u)}catch{if(r)return;Jv.set(i,{value:null,ts:Date.now()}),n(null)}})(),()=>{r=!0}},[i]),e}const $g=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Projects",icon:"terminal",hint:"Independent goal-scoped sessions, grouped by project"},{key:"system-prompt",group:"Workspace",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],XN=Object.fromEntries($g.map(i=>[i.key,i.group])),Cy={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},rS=$g.filter(i=>i.group==="Workspace"),sS=$g.filter(i=>i.group==="Configure"),oS=$g.filter(i=>i.group==="Tools").map(({key:i,label:e,icon:n,hint:r})=>({key:i,label:e,icon:n,hint:r})),L_="sm.almanac.sidebarWidth",xE=180,bE=480,z_=252;function JN(){try{const i=parseInt(localStorage.getItem(L_)??"",10);if(Number.isFinite(i))return Math.min(bE,Math.max(xE,i))}catch{}return z_}const ZN=52,yE="sm.almanac.sidebarCollapsed";function QN(){try{return localStorage.getItem(yE)==="1"}catch{}return!1}const _E="sm.almanac.collapsedGroups";function e$(){try{const i=localStorage.getItem(_E);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(n=>n==="Workspace"||n==="Configure"||n==="Tools")):new Set}catch{return new Set}}function t$(){return{scheduler:zl(e=>{var n;return(((n=e.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running")})}}function i$({active:i,onNavigate:e,onNewSession:n}){const[r,s]=z.useState(()=>e$()),a=z.useCallback(_=>{s(E=>{const j=new Set(E);j.has(_)?j.delete(_):j.add(_);try{localStorage.setItem(_E,JSON.stringify(Array.from(j)))}catch{}return j})},[]),[u,l]=z.useState(()=>QN()),d=z.useCallback(()=>{l(_=>{const E=!_;try{localStorage.setItem(yE,E?"1":"0")}catch{}return E})},[]),p=Ct(_=>_.tabs),m=Ct(_=>_.activeTabId),f=p.find(_=>_.id===m)??null,b=t$(),[S,w]=z.useState(()=>JN()),C=z.useRef(S);C.current=S;const x=z.useCallback(_=>{_.preventDefault();const E=_.clientX,j=C.current;let D=j;const $=P=>{D=Math.min(bE,Math.max(xE,j+(P.clientX-E))),w(D)},I=()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",I),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(L_,String(D))}catch{}};window.addEventListener("pointermove",$),window.addEventListener("pointerup",I),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),y=z.useCallback(()=>{w(z_);try{localStorage.setItem(L_,String(z_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:u?ZN:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(n$,{tab:f,onNewSession:n,rail:u,onToggleRail:d}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:u?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!u&&o.jsx(Ey,{label:"Workspace",desc:Cy.Workspace,collapsed:r.has("Workspace"),count:rS.length,onToggle:()=>a("Workspace")}),(u||!r.has("Workspace"))&&rS.map(_=>o.jsx(aS,{item:_,active:i===_.key,live:_.liveKind?b[_.liveKind]:!1,onClick:()=>e(_.key),rail:u},_.key)),!u&&o.jsx(Ey,{label:"Configure",desc:Cy.Configure,collapsed:r.has("Configure"),count:sS.length,onToggle:()=>a("Configure")}),(u||!r.has("Configure"))&&sS.map(_=>o.jsx(aS,{item:_,active:i===_.key,live:!1,onClick:()=>e(_.key),rail:u},_.key)),!u&&o.jsx(Ey,{label:"Tools",desc:Cy.Tools,collapsed:r.has("Tools"),count:oS.length,onToggle:()=>a("Tools")}),(u||!r.has("Tools"))&&oS.map(_=>o.jsx(r$,{tool:_,active:i===_.key,onClick:()=>e(_.key),rail:u},_.key))]})}),o.jsx(s$,{rail:u}),!u&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:x,onDoubleClick:y,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function n$({tab:i,onNewSession:e,rail:n,onToggleRail:r}){const s=(i==null?void 0:i.label)??"no session",a=vE((i==null?void 0:i.cwd)??null);return n?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:e,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:o.jsx(pi,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(pi,{name:"chevron",size:15,stroke:1.8})})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(pi,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:s})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:a?`⌥${a}`:i?i.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:e,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[o.jsx(pi,{name:"plus",size:13,stroke:1.8}),"New session"]})})]})}function Ey({label:i,desc:e,collapsed:n,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!n,title:n?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:n?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:i}),n&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!n&&o.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:e})]})}function aS({item:i,active:e,live:n,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(pi,{name:i.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:i.label}),i.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!s&&n&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&n&&o.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function r$({tool:i,active:e,onClick:n,rail:r}){return o.jsxs("button",{onClick:n,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(pi,{name:i.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:i.label}),i.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function s$({rail:i}){const e=At(l=>l.isRecording),n=Ct(l=>l.tabs),r=Ct(l=>l.activeTabId),s=n.find(l=>l.id===r)??null,[a,u]=z.useState(null);return z.useEffect(()=>{let l=!1;if(!(s!=null&&s.presetId)){u(null);return}return V2(s.presetId).then(d=>{l||u((d==null?void 0:d.model)??null)}).catch(()=>{l||u(null)}),()=>{l=!0}},[s==null?void 0:s.presetId]),i?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?"bg-red-500 animate-pulse":"bg-sage"}`,title:e?"recording":"idle"})}):o.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${e?"bg-red-500 animate-pulse":"bg-sage"}`,title:e?"recording":"idle"}),o.jsx("span",{className:"truncate",title:a??"",children:e?"recording…":a?`Claude · ${Ng(a)}`:"Claude Code"})]})}function o$(i,e,n){return e?i.map(r=>r.id===e?{...r,lastActivityAt:n}:r):i}function a$(i,e,n){return{tabId:i,sessionUuid:n,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const Bx=Xn((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(n,r,s)=>{const a={...e().refs};if(a[n]=(a[n]??0)+1,i({refs:a}),a[n]>1)return;i({tabs:{...e().tabs,[n]:a$(n,r,s)}});const u=window.api.transcripts.onEvent(n,l=>e().ingest(n,l));i({unsubs:{...e().unsubs,[n]:u}}),window.api.transcripts.subscribe({tabId:n,cwd:r,sessionUuid:s}).then(async l=>{const d=e().tabs[n];if(!d)return;if(!l.ok){const{toast:m}=await Dg(async()=>{const{toast:f}=await Promise.resolve().then(()=>J2);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),i({tabs:{...e().tabs,[n]:{...d,path:null}}});return}i({tabs:{...e().tabs,[n]:{...d,path:l.path}}});const p=await window.api.transcripts.buffer(n);for(const m of p)e().ingest(n,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",n,l))},unsubscribe:n=>{const r={...e().refs};if(!r[n])return;if(r[n]--,r[n]>0){i({refs:r});return}delete r[n];const s=e().unsubs[n];s==null||s();const a={...e().unsubs};delete a[n];const u={...e().tabs};delete u[n],window.api.transcripts.unsubscribe(n),i({refs:r,unsubs:a,tabs:u})},ingest:(n,r,s)=>{const a=e().tabs[n];if(!a)return;const u=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:u},d=[],p=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||d.push({id:0,kind:"todo-update",at:u,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])f&&S in f&&(b[S]=f[S]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:u},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const S=m.input,w=["Edit","Write","NotebookEdit"].includes(m.name),C=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,x=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,y=C?C.split("/").pop()??C:x?p(x,28):"";d.push({id:0,kind:"tool-use",at:u,label:y?`${m.name} · ${y}`:m.name,target:C??x,toolName:m.name}),w&&C&&d.push({id:0,kind:"file-edit",at:u,label:`${m.name} · ${p(C.split("/").pop()??C,34)}`,target:C,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:u,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"plan-revision",at:u,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:u,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:u},...a.agents].slice(0,50),s!=null&&s.replay||d.push({id:0,kind:"agent-spawn",at:u,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,S=m.output_tokens??m.outputTokens??0,w=f+b+S;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+S,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(w/1e3)>Math.floor(f/1e3)&&d.push({id:0,kind:"usage-tick",at:u,label:`${Math.floor(w/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=o$(a.agents,m==null?void 0:m.toolUseId,u);break}}if(d.length>0){let m=a.activitySeq;const f=d.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}i({tabs:{...e().tabs,[n]:l}})}}));function l$(i){const e=Bx(s=>s.subscribe),n=Bx(s=>s.unsubscribe),r=Bx(s=>i?s.tabs[i.id]:void 0);return z.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>n(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,n]),r}function c$({onNavigate:i}){const e=Ct(E=>E.tabs),n=Ct(E=>E.activeTabId),r=e.find(E=>E.id===n)??null,s=l$(r),a=(s==null?void 0:s.lastEventAt)??0,u=rg(E=>E.data),l=zl(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),d=vE((r==null?void 0:r.cwd)??null),[,p]=z.useState(0);z.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=z.useState(!1),S=z.useRef(null);z.useEffect(()=>{if(!f)return;const E=j=>{S.current&&!S.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),z.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const w=gE(u),C=(w==null?void 0:w.usage.five_hour)??null,x=C?Math.round(C.utilization):null,y=(u==null?void 0:u.kind)==="ok"||(u==null?void 0:u.kind)==="ok-stale",_=a>0?h$(Date.now()-a):"—";return o.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[o.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:y?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${y?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:y?"connected":"offline"})]}),o.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,d&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:_})]}),m.length>0&&o.jsx(d$,{ref:S,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.39.1"]})]})}const d$=z.forwardRef(function({todos:e,open:n,onToggle:r},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",n?"▾":"▴"]})]}),n&&o.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:o.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(u$,{status:u.status}),o.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function u$({status:i}){return i==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function h$(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const n=Math.floor(e/60);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function p$({onClose:i,onSent:e}){const n=Ct(I=>I.tabs),[r,s]=z.useState(""),[a,u]=z.useState(()=>Object.fromEntries(n.map(I=>[I.id,!0]))),[l,d]=z.useState(!1),[p,m]=z.useState({}),f=z.useRef(null),b=z.useRef(e);z.useEffect(()=>{b.current=e},[e]),z.useEffect(()=>{u(I=>{const P={};for(const L of n)P[L.id]=I[L.id]??!0;return P})},[n]),z.useEffect(()=>{var I;(I=f.current)==null||I.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(P=>{m(L=>P.tabId in L?{...L,[P.tabId]:"skipped"}:L)}),[]),z.useEffect(()=>{if(Object.keys(p).length===0)return;const I=Object.values(p).filter(L=>L==="sent").length,P=window.setTimeout(()=>b.current(I),1500);return()=>window.clearTimeout(P)},[p]);const S=n.filter(I=>a[I.id]).map(I=>I.id),w=S.length,C=Object.keys(p).length>0,x=r.length>0&&w>0&&!l&&!C,y=()=>{if(!x)return;d(!0);const I=Ct.getState().tabs,P=new Set(I.map(B=>B.id)),L={};for(const B of S)P.has(B)?(window.api.pty.write({tabId:B,data:r+"\r"}),L[B]="sent"):L[B]="skipped";m(L),d(!1)},_=I=>{if(I.key==="Escape"){I.preventDefault(),I.stopPropagation(),i();return}I.key==="Enter"&&(I.metaKey||I.ctrlKey)&&(I.preventDefault(),y())},E=n.length>0&&n.every(I=>a[I.id]),j=()=>{const I=!E;u(Object.fromEntries(n.map(P=>[P.id,I])))},D=Object.values(p).some(I=>I==="skipped"),$=C?D?"Sent (some skipped)":"Sent":`Send to ${w} tab${w===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:_,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:I=>s(I.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:E,onChange:j,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",w,"/",n.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:n.map(I=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[I.id],onChange:P=>u(L=>({...L,[I.id]:P.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:I.label}),p[I.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[I.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},I.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:y,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:$})]})]})}function f$({tabId:i,cwd:e,onClose:n}){const r=tg(w=>w.watchersForTab(i)),s=tg(w=>w.add),a=tg(w=>w.remove),u=z.useRef(null),[l,d]=z.useState(""),[p,m]=z.useState(""),[f,b]=z.useState(!1);z.useEffect(()=>{const w=C=>{C.key==="Escape"&&n()};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n]),z.useEffect(()=>{const w=C=>{u.current&&!u.current.contains(C.target)&&n()};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[n]);const S=async()=>{const w=p.trim();if(!w||f)return;b(!0);const C=await s({tabId:i,label:l.trim(),command:w,cwd:e});b(!1),C&&(d(""),m(""))};return o.jsxs("div",{ref:u,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:n,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:w=>d(w.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:p,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key==="Enter"&&S()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),o.jsx("button",{onClick:S,disabled:!p.trim()||f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(w=>{const C=w.lines[w.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:w.label}),o.jsxs("span",{className:"text-fg-faint",children:[w.lineCount," line",w.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(w.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${w.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:w.command,children:w.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},w.watcherId)})})]})}/**
|
|
2898
2898
|
* dockview-core
|
|
2899
2899
|
* @version 6.6.1
|
|
2900
2900
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3050,7 +3050,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3050
3050
|
|
|
3051
3051
|
${n}`}const Ym={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},DL=["popover","review","diff"],qT=["popover","review"];function AL(i,e){switch(e.type){case"SELECT":return{...Ym,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Ym,editCount:i.editCount};case"LISTEN":return qT.includes(i.phase)?{...i,phase:"listening",transcript:"",modelStatus:null}:i;case"HEARD":return i.phase!=="listening"?i:{...i,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return DL.includes(i.phase)?{...i,phase:"thinking",instruction:e.recordInstruction?e.instruction:i.instruction}:i;case"RUN_OK":return i.phase!=="thinking"?i:{...i,phase:"diff",diff:e.diff};case"RUN_ERR":return i.phase!=="thinking"?i:{...i,phase:"popover",transcript:"",diff:null};case"ACCEPT":return i.phase!=="diff"?i:{...Ym,editCount:i.editCount+1};case"RESET_FILE":return{...Ym,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function NL(i,e){let n=null;for(const r of e){const s=r.cwd;!s||!(i===s||i.startsWith(s.endsWith("/")?s:`${s}/`))||(n===null||s.length>n.length)&&(n=s)}return n}function $L(i,e,n){var a;let r=null,s=-1/0;for(const u of e){if(u.cwd!==i||u.status!=="dormant")continue;const l=((a=n[u.id])==null?void 0:a.lastEventAt)??0;(r===null||l>s)&&(r=u,s=l)}return r}const PL="sonnet";function RL(i,e){const[n,r]=z.useReducer(AL,Ym),s=z.useRef(0),a=z.useRef(null),u=z.useRef(i),l=z.useRef(new Map);z.useEffect(()=>window.api.docEdit.onSessionResult(E=>{const j=l.current.get(E.requestId);j&&(l.current.delete(E.requestId),j(E))}),[]),z.useEffect(()=>{u.current!==i&&(u.current=i,s.current+=1,d(),r({type:"RESET_FILE"}))},[i]);function d(){const E=a.current;E&&(a.current=null,E.stop().catch(()=>{}),E.destroy(),At.setState({externalRecording:!1}))}const p=z.useCallback(E=>{s.current+=1,d(),r({type:"SELECT",selection:E})},[]),m=z.useCallback(()=>{s.current+=1,d(),r({type:"CANCEL"})},[]),f=z.useCallback(()=>{if(!qT.includes(n.phase))return;if(At.getState().isRecording){Ve.error("Microphone is already in use");return}if(!Fb()){Ve.error("Microphone or Web Worker not available");return}const E=++s.current;r({type:"LISTEN"}),At.setState({externalRecording:!0});const j=()=>{a.current===D&&(a.current=null),At.setState({externalRecording:!1})},D=hE({onFinal:$=>{if(s.current!==E)return;D.stop().catch(()=>{}),D.destroy(),j();const I=$.trim();if(!I){r({type:"CANCEL"});return}r({type:"HEARD",transcript:I})},onError:$=>{s.current===E&&(D.destroy(),j(),Ve.error(`Microphone error: ${$}`),r({type:"CANCEL"}))},onModelStatus:($,I)=>{s.current===E&&r({type:"MODEL_STATUS",status:$,message:I})},onProgress:$=>{s.current===E&&r({type:"MODEL_STATUS",status:"loading",message:`${$}%`})}});a.current=D,D.start().catch($=>{s.current===E&&(D.destroy(),j(),Ve.error(`Could not start mic: ${$ instanceof Error?$.message:String($)}`),r({type:"CANCEL"}))})},[n.phase]),b=z.useCallback(()=>{const E=NL(i,Ct.getState().tabs);if(!E)return null;const j=$L(E,Ct.getState().tabs,Bx.getState().tabs);return!j||dn.getState().get(j.id).running?null:j},[i]),S=z.useCallback((E,j,D,$,I,P)=>{const L=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(B=>{l.current.set(L,B),window.api.docEdit.runInSession({tabId:E,sessionId:j,cwd:D,before:$,instruction:I,documentText:P,requestId:L})})},[]),w=z.useCallback(async(E,j)=>{const D=n.selection;if(!D)return;const $=++s.current;r({type:"RUN",instruction:E,recordInstruction:j});const I=jL(e);try{const P=b(),L=P?await S(P.id,P.sessionId,P.cwd,D.text,E,I):await window.api.docEdit.run({path:i,before:D.text,instruction:E,documentText:I});if(s.current!==$)return;if(!L.ok){Ve.error(L.error||"Edit failed"),r({type:"RUN_ERR"});return}r({type:"RUN_OK",diff:{before:D.text,after:L.after??""}})}catch(P){if(s.current!==$)return;Ve.error(P instanceof Error?P.message:"Edit failed"),r({type:"RUN_ERR"})}},[i,n.selection,e,b,S]),C=z.useCallback(E=>{w(E,!0)},[w]),x=z.useCallback(()=>{n.phase==="review"&&w(n.transcript,!0)},[w,n.phase,n.transcript]),y=z.useCallback(()=>{const E=n.instruction;E&&w(`${E}
|
|
3052
3052
|
|
|
3053
|
-
(Give a different rewrite than the last one.)`,!1)},[w,n.instruction]),_=z.useCallback(E=>{const j=n.diff;if(!j)return{ok:!1,reason:"not-found"};const D=EL(E,j.before,j.after);return D.ok?(s.current+=1,r({type:"ACCEPT"})):Ve.error(D.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),D},[n.diff]);return{state:n,select:p,cancel:m,listen:f,sendHeard:x,run:C,retry:y,accept:_}}const IL=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Dk=320,$m=8;function ML(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function OL(i){const e=typeof window<"u"?window.innerWidth:1024,n=Math.min(Math.max(i.left,$m),Math.max($m,e-Dk-$m)),r=Math.max(i.top-$m,$m);return{position:"fixed",left:n,top:r,width:Dk,transform:"translateY(-100%)",zIndex:50}}function LL({phase:i,rect:e,diff:n,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:u,onListen:l,onSendHeard:d,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[S,w]=z.useState(""),C=()=>{const x=S.trim();x&&(u(x),w(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:OL(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),IL.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:S,onChange:x=>w(x.target.value),onKeyDown:x=>{x.key==="Enter"?C():x.key==="Escape"&&p()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(ML,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function zL(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function Ak({phase:i,transcript:e,diff:n,editCount:r,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:d,onReject:p,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Ng(PL)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),i==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(zL,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&n&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function Nk(i){return i.split("/").filter(Boolean).pop()||i}function BL({path:i,onRenamed:e,onDeleted:n}){const[r,s]=z.useState(!1),[a,u]=z.useState(!1),[l,d]=z.useState(""),[p,m]=z.useState(!1),f=Di(B=>B.buffers[i]),b=Di(B=>B.openFile),S=Di(B=>B.renameOpenFile),w=Di(B=>B.closeFile),C=Jc(),x=Nk(i),y=()=>s(!1),_=()=>{d(x),u(!0),y()},E=async()=>{const B=l.trim();if(!B||B===x){u(!1);return}try{const U=await window.api.files.rename(i,B);if(U.ok){const Z=i.slice(0,i.lastIndexOf("/")),X=U.newPath??`${Z}/${B}`;S(i,X),e==null||e(i,X),Ve.info(`Renamed to ${B}`)}else Ve.error(U.error??`Couldn't rename ${x}`)}catch(U){Ve.error(U instanceof Error?U.message:`Couldn't rename ${x}`)}u(!1)},j=async()=>{y();try{const B=await window.api.files.duplicate(i);B.ok&&B.path?(b(B.path),Ve.info(`Duplicated as ${Nk(B.path)}`)):Ve.error(B.error??`Couldn't duplicate ${x}`)}catch(B){Ve.error(B instanceof Error?B.message:`Couldn't duplicate ${x}`)}},D=async()=>{try{const B=await window.api.files.delete(i);B.ok?(w(i),n==null||n(i),Ve.info(`Deleted ${x}`)):Ve.error(B.error??`Couldn't delete ${x}`)}catch(B){Ve.error(B instanceof Error?B.message:`Couldn't delete ${x}`)}m(!1)},$=async()=>{y();const B=f??"";try{await navigator.clipboard.writeText(B),Ve.info(`Copied ${B.length} chars`)}catch(U){Ve.error(U instanceof Error?U.message:`Couldn't copy ${x}`)}},I=()=>{if(y(),!C){Ve.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Ve.info(`Added ${x} to Claude context`)},P=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(B=>{B.ok||Ve.error(B.error??`Couldn't open ${x}`)}).catch(B=>Ve.error(B instanceof Error?B.message:`Couldn't open ${x}`))},L=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(B=>{B.ok||Ve.error(B.error??`Couldn't reveal ${x}`)}).catch(B=>Ve.error(B instanceof Error?B.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(B=>!B),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:y}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[o.jsx(qy,{children:"Edit"}),o.jsx(Xd,{label:"Rename",onClick:_}),o.jsx(Xd,{label:"Duplicate",onClick:j}),o.jsx(Xd,{label:"Delete document",danger:!0,onClick:()=>{y(),m(!0)}}),o.jsx($k,{}),o.jsx(qy,{children:"Open"}),o.jsx(Xd,{label:"Open in default app",onClick:P}),o.jsx(Xd,{label:"Reveal in OS",onClick:L}),o.jsx($k,{}),o.jsx(qy,{children:"Export"}),o.jsx(Xd,{label:"Copy as Markdown",onClick:$}),o.jsx(Xd,{label:"Add to Claude context",onClick:I,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(FL,{value:l,onChange:d,onCancel:()=>u(!1),onConfirm:()=>void E()}),p&&o.jsx(GL,{name:x,onCancel:()=>m(!1),onConfirm:()=>void D()})]})}function qy({children:i}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function Xd({label:i,onClick:e,danger:n,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function $k(){return o.jsx("div",{className:"my-1 border-t border-line"})}function FL({value:i,onChange:e,onCancel:n,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&n()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&n()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function GL({name:i,onCancel:e,onConfirm:n}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function UL(){const[i,e]=z.useState(!1),n=fp();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[o.jsx(op,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>n.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:n.fontSize}),o.jsx("button",{onClick:()=>n.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(op,{label:"Word wrap",children:o.jsx(px,{on:n.wordWrap,onClick:n.toggleWordWrap})}),o.jsx(op,{label:"Minimap",children:o.jsx(px,{on:n.minimap,onClick:n.toggleMinimap})}),o.jsx(op,{label:"Theme",children:o.jsx("button",{onClick:()=>n.setTheme(n.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:n.theme==="dark"?"Dark":"Paper"})}),o.jsx(op,{label:"Autosave",children:o.jsx(px,{on:n.autosave,onClick:n.toggleAutosave})}),o.jsx(op,{label:"Wide measure",children:o.jsx(px,{on:n.wideMeasure,onClick:n.toggleWideMeasure})})]})]})]})}function op({label:i,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:i}),e]})}function px({on:i,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const HL=z.lazy(()=>Dg(()=>import("./TiptapBody-DrqOSx6h.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function fx(i){return i.split("/").filter(Boolean).pop()||i}function mx(i,e){if(!e.length)return i;const n=new Set(e),r={};for(const[s,a]of Object.entries(i))n.has(s)||(r[s]=a);return r}function gx(i){return CT(i)||ET(i)}function xb(){const i=Og(),e=Di(Ue=>Ue.openFiles),n=Di(Ue=>Ue.activeFilePath),r=Di(Ue=>Ue.dirty),s=Di(Ue=>Ue.viewMode),a=Di(Ue=>Ue.buffers),u=Di(Ue=>Ue.setActive),l=Di(Ue=>Ue.closeFile),d=Di(Ue=>Ue.closeOthers),p=Di(Ue=>Ue.closeToTheRight),m=Di(Ue=>Ue.closeAll),f=Di(Ue=>Ue.loadBuffer),b=Di(Ue=>Ue.setBuffer),S=Di(Ue=>Ue.markSaved),w=Di(Ue=>Ue.setViewMode),C=fp(),[x,y]=z.useState({}),[_,E]=z.useState({}),[j,D]=z.useState(null),[$,I]=z.useState(null),[P,L]=z.useState(!1),[B,U]=z.useState(!1),[Z,X]=z.useState(!0),W=z.useRef(null),J=z.useRef(null),te=z.useRef(void 0),le=z.useRef(null),ue=z.useRef(null),V=RL(n??"",a[n??""]??""),ie=z.useCallback(Ue=>{W.current=Ue},[]),K=z.useCallback(()=>W.current,[]);z.useEffect(()=>{const Ue=n;if(!Ue||gx(Ue))return;if(Di.getState().hasBuffer(Ue)){y(ft=>ft[Ue]==="ready"?ft:{...ft,[Ue]:"ready"});return}let _t=!1;return y(ft=>({...ft,[Ue]:"loading"})),window.api.files.read(Ue).then(ft=>{_t||(ft.binary?y(ui=>({...ui,[Ue]:{binary:!0,size:ft.size??0,mime:ft.mime??"application/octet-stream",reason:ft.error??"Binary file"}})):ft.ok?(f(Ue,ft.text),y(ui=>({...ui,[Ue]:"ready"}))):y(ui=>({...ui,[Ue]:{error:ft.error??"failed to read"}})))}),()=>{_t=!0}},[n,f]),z.useEffect(()=>{I(null)},[n]);const se=z.useCallback(async(Ue,_t=!1)=>{const ft=Di.getState().buffers[Ue];if(ft==null)return;_t&&L(!0);const ui=await window.api.files.write(Ue,ft);ui.ok?(S(Ue),E(ji=>({...ji,[Ue]:(ji[Ue]??0)+1})),_t||Ve.info(`Saved ${fx(Ue)}`)):Ve.error(ui.error??`Couldn't save ${fx(Ue)}`),_t&&L(!1)},[S]);z.useEffect(()=>{if(!C.autosave)return;const Ue=n;if(!(!Ue||gx(Ue)||!r[Ue]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{se(Ue,!0)},1200),()=>window.clearTimeout(te.current)},[C.autosave,n,r,a,se]);const oe=z.useCallback(Ue=>{Ue.length&&(y(_t=>mx(_t,Ue)),E(_t=>mx(_t,Ue)))},[]),be=z.useCallback((Ue,_t)=>{y(ft=>Ue in ft?{...mx(ft,[Ue]),[_t]:ft[Ue]}:ft),E(ft=>Ue in ft?{...mx(ft,[Ue]),[_t]:ft[Ue]}:ft)},[]),je=z.useCallback(Ue=>{r[Ue]?D({kind:"one",path:Ue}):(l(Ue),oe([Ue]))},[r,l,oe]),Te=z.useCallback(Ue=>{e.some(ft=>ft.path!==Ue&&r[ft.path])?D({kind:"others",path:Ue}):(d(Ue),oe(e.filter(ft=>ft.path!==Ue).map(ft=>ft.path)))},[e,r,d,oe]),ve=z.useCallback(Ue=>{const _t=e.findIndex(ui=>ui.path===Ue);_t!==-1&&e.slice(_t+1).some(ui=>r[ui.path])?D({kind:"right",path:Ue}):(p(Ue),oe(_t!==-1?e.slice(_t+1).map(ui=>ui.path):[]))},[e,r,p,oe]);z.useEffect(()=>{const Ue=_t=>{if(i.current)if((_t.metaKey||_t.ctrlKey)&&(_t.key==="s"||_t.key==="S")){const ft=Di.getState().activeFilePath;ft&&!gx(ft)&&(_t.preventDefault(),se(ft))}else if((_t.metaKey||_t.ctrlKey)&&_t.shiftKey&&(_t.key==="f"||_t.key==="F"))_t.preventDefault(),U(ft=>!ft);else if((_t.metaKey||_t.ctrlKey)&&_t.shiftKey&&(_t.key==="w"||_t.key==="W")){const ft=Di.getState().activeFilePath;ft&&Di.getState().openFiles.length>1&&(_t.preventDefault(),Te(ft))}else _t.key==="Escape"&&V.state.phase!=="idle"?V.cancel():_t.key==="Escape"&&B&&U(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[se,B,Te,V.state.phase,V.cancel]),z.useEffect(()=>{if(V.state.phase==="idle")return;const Ue=_t=>{var ui,ji;const ft=_t.target;(ui=ue.current)!=null&&ui.contains(ft)||(ji=le.current)!=null&&ji.contains(ft)||V.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[V.state.phase,V.cancel]),z.useEffect(()=>{V.cancel()},[n,V.cancel]);const re=z.useCallback(()=>{e.some(_t=>r[_t.path])?D({kind:"all",path:""}):(m(),y({}),E({}))},[e,r,m]),Pe=()=>{if(j){if(j.kind==="one")l(j.path),oe([j.path]);else if(j.kind==="others"){const Ue=e.filter(_t=>_t.path!==j.path).map(_t=>_t.path);d(j.path),oe(Ue)}else if(j.kind==="right"){const Ue=e.findIndex(ft=>ft.path===j.path),_t=Ue!==-1?e.slice(Ue+1).map(ft=>ft.path):[];p(j.path),oe(_t)}else m(),y({}),E({});D(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const _e=n,Qe=_e?fx(_e):"",st=_e?x[_e]:void 0,yt=_e?DT(_e):!1,qt=_e?zM(_e):!1,ut=_e&&yt?s[_e]??BM(_e):"edit",nt=!!_e&&!gx(_e)&&st==="ready",Le=nt,ht=qt?["edit","wysiwyg","preview","split"]:yt?["edit","preview"]:[],Gt=_e&&o.jsx(KM,{path:_e,name:Qe,value:a[_e]??"",onChange:Ue=>b(_e,Ue),onSave:()=>void se(_e),onReady:ie,onCursor:I}),di=P?"Saving…":_e&&r[_e]?C.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!B&&o.jsx(HM,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:u,onCloseFile:je,onCloseOthers:Te,onCloseToTheRight:ve,onCloseAll:re}),_e&&!B&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Qe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:_e}),nt&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",di]}),Al(_e)&&(ut==="preview"||ut==="split")&&o.jsx("button",{onClick:()=>X(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Al(_e)&&(ut==="preview"||ut==="split")&&o.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),ht.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:ht.map(Ue=>o.jsx("button",{onClick:()=>w(_e,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ut===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),o.jsx("div",{className:"flex-1"}),o.jsx(BL,{path:_e,onRenamed:be,onDeleted:Ue=>oe([Ue])}),nt&&o.jsx(UL,{}),o.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),B&&o.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),o.jsx("div",{className:"flex-1 min-h-0",children:_e?CT(_e)?o.jsx(vL,{path:_e,name:Qe}):ET(_e)?o.jsx(xL,{path:_e}):st&&typeof st=="object"&&"binary"in st?o.jsx(CL,{path:_e,name:Qe,size:st.size,mime:st.mime,reason:st.reason}):st&&typeof st=="object"&&"error"in st?o.jsx("div",{className:"p-6 text-xs text-red-400",children:st.error}):st!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ut==="wysiwyg"&&Al(_e)?o.jsx(z.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(HL,{value:a[_e]??"",onChange:Ue=>b(_e,Ue)},_e)}):ut==="split"&&Al(_e)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(Ek,{text:a[_e]??"",scrollRef:J}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(Ck,{getEditor:K}),o.jsx("div",{className:"flex-1 min-h-0",children:Gt})]}),o.jsx("div",{ref:le,className:"flex-1 min-w-0",children:o.jsx(iw,{ref:J,text:a[_e]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!B&&C.assistantRail&&o.jsx(Ak,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)},onReject:V.cancel,onRetry:V.retry})]}):ut==="preview"&&Al(_e)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(Ek,{text:a[_e]??"",scrollRef:J}),o.jsx("div",{ref:le,className:"flex-1 min-w-0",children:o.jsx(iw,{ref:J,text:a[_e]??"",wideMeasure:C.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!B&&C.assistantRail&&o.jsx(Ak,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)},onReject:V.cancel,onRetry:V.retry})]}):ut==="preview"&&kT(_e)?o.jsx(mL,{path:_e,dirty:!!r[_e],reloadToken:_[_e]??0}):ut==="preview"&&TT(_e)?o.jsx(yL,{path:_e,text:a[_e]??""}):ut==="preview"&&jT(_e)?o.jsx(SL,{path:_e,text:a[_e]??""}):Al(_e)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(Ck,{getEditor:K}),o.jsx("div",{className:"flex-1 min-h-0",children:Gt})]}):Gt:null}),Le&&o.jsx(fL,{text:a[_e]??"",cursor:$,language:Qs(_e)||void 0}),_e&&Al(_e)&&(ut==="preview"||ut==="split")&&V.state.phase!=="idle"&&V.state.selection&&o.jsx("div",{ref:ue,children:o.jsx(LL,{phase:V.state.phase,rect:V.state.selection.rect,diff:V.state.diff,transcript:V.state.transcript,modelStatus:V.state.modelStatus,onQuickAction:V.run,onRunCustom:V.run,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onReject:V.cancel,onRetry:V.retry,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)}})}),j&&o.jsx(WL,{message:j.kind==="one"?`Discard unsaved changes to ${fx(j.path)}?`:j.kind==="others"?"Discard unsaved changes in the other open files?":j.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>D(null),onConfirm:Pe})]})}function WL({message:i,onCancel:e,onConfirm:n}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Pk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},VL={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function Ky(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":String(i)}function qL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(D=>D.tabs.find($=>$.id===D.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,u]=z.useState(null),[l,d]=z.useState(!1),[p,m]=z.useState(null),f=z.useRef(null),b=z.useCallback(async D=>{d(!0),m(null);try{const $=await window.api.repo.analyze(D);$.ok?u($):(m($.error||"Analysis failed"),u(null))}catch($){m($ instanceof Error?$.message:String($)),u(null)}finally{d(!1)}},[]);z.useEffect(()=>{if(i){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[i,s,b]),z.useEffect(()=>{var $;if(!i)return;const D=I=>{I.key==="Escape"&&(I.stopPropagation(),e())};return window.addEventListener("keydown",D),($=f.current)==null||$.focus(),()=>window.removeEventListener("keydown",D)},[i,e]);const S=z.useCallback(()=>{s&&b(s)},[s,b]),w=z.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([$,I])=>[$,I.files,I.lines]).sort(($,I)=>I[1]-$[1]).slice(0,12):[],[a]),C=z.useMemo(()=>w.length===0?1:w[0][1],[w]),x=z.useMemo(()=>{if(!a)return[];const D=a.topDirectories;if(D.length===0)return[];const $=D.map(P=>Math.sqrt(Math.max(1,P.fileCount))),I=$.reduce((P,L)=>P+L,0)||1;return D.map((P,L)=>({path:P.path,fileCount:P.fileCount,totalLines:P.totalLines,basis:$[L]/I*100}))},[a]);if(!i)return null;const y=D=>{D.target===D.currentTarget&&e()},_=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=n==="page",j=o.jsx("div",{className:E?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:E?void 0:y,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,role:E?void 0:"dialog","aria-modal":E?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:E?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[_,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:S,disabled:l||!s,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):p?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:p})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Yy,{label:"Files",value:Ky(a.totalFiles)}),o.jsx(Yy,{label:"Lines of code",value:Ky(a.totalLines)}),o.jsx(Yy,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),w.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:w.map(([D,$,I])=>{const P=Pk[D]??Pk.other,L=VL[D]??D,B=$/C*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:L,children:L}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${B}%`,backgroundColor:P}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[$," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[Ky(I)," L"]})]},D)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(D=>o.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max(D.basis,6)}%`,flexGrow:D.basis>15?1:0},title:`${D.path} — ${D.fileCount} files, ${D.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:D.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[D.fileCount," files"]})]},D.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!E&&typeof document<"u"&&document.body?vu.createPortal(j,document.body):j}function Yy({label:i,value:e,tone:n="neutral"}){const r=n==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:i})]})}function _u({options:i,active:e,onChange:n}){return o.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:i.map(({key:r,label:s})=>o.jsx("button",{onClick:()=>n(r),className:`px-2 py-0.5 text-xs ${e===r?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:s},r))})}const Rk=i=>/[/\\\-_.\s]/.test(i),Ik=i=>i>="A"&&i<="Z";function KL(i,e,n){if(!i)return{match:!0,score:0,matched:[]};const r=i.toLowerCase(),s=e.toLowerCase(),a=(n||e).toLowerCase(),u=e.split("/").pop()||e,l=u.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:u.length},(y,_)=>_)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:i.length},(y,_)=>_)};let d=0;for(const y of a.split("/")){if(y===r)return{match:!0,score:800,matched:[]};y.startsWith(r)&&(d=Math.max(d,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||Rk(l[p-1])||Ik(u[p])?650:600,matched:Array.from({length:i.length},(_,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,d),matched:[]};let m=0,f=0,b=0,S=-1,w=0;const C=[];for(let y=0;y<s.length&&m<r.length;y++)s[y]===r[m]&&(C.push(y),f+=10,S===y-1?(b++,f+=b*8):b=0,(y===0||Rk(s[y-1])||Ik(e[y]))&&(w++,f+=15,y===0&&(f+=10)),S=y,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,w>=r.length*.5&&(f+=30),C.length>1){const y=C[C.length-1]-C[0];y>r.length*3&&(f-=Math.min(50,(y-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:C}}function Xy(i,e){return i.startsWith(e+"/")?i.slice(e.length+1):i===e?"":i}function Mk(i){const e=i.lastIndexOf("/");return e<0?"":i.slice(0,e)}const Ok="session-manager.quickopen.recent",YL=8;function XL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(L=>L.tabs.find(B=>B.id===L.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,u]=z.useState(""),[l,d]=z.useState([]),[p,m]=z.useState(!1),[f,b]=z.useState(0),[S,w]=z.useState([]),C=z.useRef(null),x=z.useRef(null);z.useEffect(()=>{if(i)try{const L=localStorage.getItem(Ok);L&&w(JSON.parse(L))}catch{}},[i]),z.useEffect(()=>{if(!i){u(""),b(0);return}const L=setTimeout(()=>{var B;return(B=C.current)==null?void 0:B.focus()},0);return()=>clearTimeout(L)},[i]),z.useEffect(()=>{if(!i||!s)return;let L=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(B=>{if(!L){if(!B.ok){Ve.error(`File search failed: ${B.error??"unknown error"}`),d([]);return}d(B.files)}}).catch(B=>{const U=B instanceof Error?B.message:String(B);pt.error("quick-open","search.files threw",{error:U}),Ve.error(`File search failed: ${U}`),d([])}).finally(()=>{L||m(!1)}),()=>{L=!0}},[i,s]);const y=z.useMemo(()=>{if(!a.trim())return[...l].sort((Z,X)=>Z.name.localeCompare(X.name)).slice(0,100).map(Z=>({file:Z,score:0,matched:[]}));const L=a.trim(),B=[];for(const U of l){const Z=KL(L,U.name,U.path);Z.match&&B.push({file:U,score:Z.score,matched:Z.matched})}return B.sort((U,Z)=>Z.score-U.score),B.slice(0,100)},[l,a]),_=z.useMemo(()=>a.trim()?[]:S.map(L=>l.find(B=>B.path===L)||null).filter(L=>L!==null).slice(0,5),[S,l,a]);z.useEffect(()=>{const L=_.length+y.length;f>=L&&b(Math.max(0,L-1))},[_.length,y.length,f]),z.useEffect(()=>{if(!x.current)return;const L=x.current.querySelector(`[data-row="${f}"]`);L&&L.scrollIntoView({block:"nearest"})},[f]);const E=z.useCallback(L=>{try{const X=[L,...S.filter(W=>W!==L)].slice(0,YL);w(X),localStorage.setItem(Ok,JSON.stringify(X))}catch{}const B=r==null?void 0:r.id;if(!B){Ve.error("No active tab to receive file path");return}const Z=(s?Xy(L,s):L)||L;try{window.api.pty.write({tabId:B,data:Z})}catch(X){const W=X instanceof Error?X.message:String(X);pt.error("quick-open","pty.write failed",{error:W}),Ve.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,S,e]),j=z.useCallback(L=>{const B=_.length+y.length;if(L.key==="Escape"){L.preventDefault(),e();return}if(L.key==="ArrowDown"){if(L.preventDefault(),B===0)return;b(U=>Math.min(B-1,U+1));return}if(L.key==="ArrowUp"){if(L.preventDefault(),B===0)return;b(U=>Math.max(0,U-1));return}if(L.key==="Enter"){if(L.preventDefault(),f<_.length){const X=_[f];X&&E(X.path);return}const U=f-_.length,Z=y[U];Z&&E(Z.file.path)}},[f,y,_,E,e]);if(!i)return null;const D=(L,B)=>{if(B.length===0)return L;const U=new Set(B);return L.split("").map((Z,X)=>o.jsx("span",{className:U.has(X)?"text-accent font-semibold":"",children:Z},X))};let $=-1;const I=n==="page",P=o.jsx("div",{className:I?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:I?void 0:L=>{L.target===L.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:I?void 0:"dialog","aria-modal":I?void 0:"true","aria-label":"Quick Open",className:I?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:j,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:C,type:"text",value:a,onChange:L=>{u(L.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:p?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?_.length===0&&y.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[_.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(L=>{$++;const B=$,U=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":U,onClick:()=>E(L.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${U?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:L.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Xy(Mk(L.path),s)})]},`r:${L.path}`)})]}),y.length>0&&o.jsxs("div",{children:[_.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),y.map(({file:L,matched:B})=>{$++;const U=$,Z=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":Z,onClick:()=>E(L.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Z?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:D(L.name,B)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Xy(Mk(L.path),s)})]},L.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[y.length+_.length," ",y.length+_.length===1?"file":"files"]})]})]})});return!I&&typeof document<"u"&&document.body?vu.createPortal(P,document.body):P}function Lk(i,e){return i.startsWith(e+"/")?i.slice(e.length+1):i===e?"":i}function JL(i,e,n){if(!e)return i;const r=n?i:i.toLowerCase(),s=n?e:e.toLowerCase(),a=r.indexOf(s);return a<0?i:o.jsxs(o.Fragment,{children:[i.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:i.slice(a,a+e.length)}),i.slice(a+e.length)]})}function ZL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(X=>X.tabs.find(W=>W.id===X.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,u]=z.useState(""),[l,d]=z.useState(!1),[p,m]=z.useState([]),[f,b]=z.useState(!1),[S,w]=z.useState(null),[C,x]=z.useState(0),[y,_]=z.useState(null),E=z.useRef(null),j=z.useRef(null),D=z.useRef(0);z.useEffect(()=>{if(!i){u(""),m([]),w(null),x(0);return}const X=setTimeout(()=>{var W;return(W=E.current)==null?void 0:W.focus()},0);return()=>clearTimeout(X)},[i]),z.useEffect(()=>{if(!i||!s)return;const X=a.trim();if(!X){m([]),w(null),b(!1);return}const W=++D.current;b(!0);const J=setTimeout(()=>{window.api.search.text(s,X,{caseSensitive:l,limit:500}).then(te=>{W===D.current&&(te.ok?(m(te.matches),w(null)):(w(te.error??"unknown error"),m([])),_(te.usedRipgrep))}).catch(te=>{if(W!==D.current)return;const le=te instanceof Error?te.message:String(te);pt.error("global-search","search.text threw",{error:le}),w(le),m([])}).finally(()=>{W===D.current&&b(!1)})},250);return()=>clearTimeout(J)},[i,s,a,l]);const $=z.useMemo(()=>{const X=new Map;for(const J of p){const te=X.get(J.path);te?te.push(J):X.set(J.path,[J])}const W=[];for(const[J,te]of X)W.push({path:J,matches:te});return W.sort((J,te)=>te.matches.length-J.matches.length||J.path.localeCompare(te.path)),W},[p]),I=z.useMemo(()=>p,[p]);z.useEffect(()=>{C>=I.length&&x(Math.max(0,I.length-1))},[I.length,C]),z.useEffect(()=>{if(!j.current)return;const X=j.current.querySelector(`[data-match="${C}"]`);X&&X.scrollIntoView({block:"nearest"})},[C]);const P=z.useCallback(X=>{const W=r==null?void 0:r.id;if(!W){Ve.error("No active tab to receive path");return}const te=`${(s?Lk(X.path,s):X.path)||X.path}:${X.line}`;try{window.api.pty.write({tabId:W,data:te})}catch(le){const ue=le instanceof Error?le.message:String(le);pt.error("global-search","pty.write failed",{error:ue}),Ve.error(`Failed to write to terminal: ${ue}`);return}e()},[r==null?void 0:r.id,s,e]),L=z.useCallback(X=>{if(X.key==="Escape"){X.preventDefault(),e();return}if(X.key==="ArrowDown"){if(X.preventDefault(),I.length===0)return;x(W=>Math.min(I.length-1,W+1));return}if(X.key==="ArrowUp"){if(X.preventDefault(),I.length===0)return;x(W=>Math.max(0,W-1));return}if(X.key==="Enter"){X.preventDefault();const W=I[C];W&&P(W)}},[I,C,P,e]);if(!i)return null;const B=n==="page";let U=-1;const Z=o.jsx("div",{className:B?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:B?void 0:X=>{X.target===X.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:B?void 0:"dialog","aria-modal":B?void 0:"true","aria-label":"Search in project",className:B?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:L,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:E,type:"text",value:a,onChange:X=>{u(X.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),o.jsx("button",{type:"button",onClick:()=>d(X=>!X),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:j,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):I.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:$.map(X=>o.jsxs("div",{children:[o.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Lk(X.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",X.matches.length,")"]})]}),X.matches.map(W=>{U++;const J=U,te=J===C;return o.jsxs("button",{"data-match":J,role:"option","aria-selected":te,onClick:()=>P(W),onMouseEnter:()=>x(J),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${te?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:JL(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${J}`)})]},X.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[I.length," ",I.length===1?"match":"matches",y===!1&&" · fs walk (rg missing)"]})]})]})});return!B&&typeof document<"u"&&document.body?vu.createPortal(Z,document.body):Z}const QL=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function ez({open:i,onClose:e,variant:n="page",initialMode:r="files"}){const[s,a]=z.useState(r);return z.useEffect(()=>{a(r)},[r]),i?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(_u,{options:QL,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(XL,{open:!0,onClose:e,variant:"page"}):o.jsx(ZL,{open:!0,onClose:e,variant:"page"})})]}):null}const tz={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},zk='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function $p({open:i,onClose:e,children:n,title:r,size:s="sm",fillHeight:a=!1,noPadding:u=!1,variant:l="overlay"}){if(l==="page")return i?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${u?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${u?"":"p-6 pt-0"}`,children:n})]}):null;const d=z.useRef(null),p=z.useRef(null),m=z.useRef(e);if(m.current=e,z.useEffect(()=>{if(!i)return;p.current=typeof document<"u"?document.activeElement:null;const w=setTimeout(()=>{const x=d.current;if(!x)return;const y=x.querySelector(zk);y?y.focus():x.focus()},0),C=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const y=d.current;if(!y)return;const _=Array.from(y.querySelectorAll(zk)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(_.length===0){x.preventDefault(),y.focus();return}const E=_[0],j=_[_.length-1],D=document.activeElement;x.shiftKey?(D===E||!y.contains(D))&&(x.preventDefault(),j.focus()):(D===j||!y.contains(D))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",C),()=>{clearTimeout(w),document.removeEventListener("keydown",C);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[i]),!i)return null;const f=S=>{S.target===S.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":r??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${tz[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${u?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${u?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:n}):n]})});return typeof document<"u"&&document.body?vu.createPortal(b,document.body):b}class KT extends z.Component{constructor(){super(...arguments);Ui(this,"state",{error:null});Ui(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[ErrorBoundary]",n,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function iz({open:i,onClose:e,title:n,children:r,variant:s="overlay"}){return o.jsxs($p,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:n}),o.jsx("button",{type:"button",onClick:e,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(KT,{children:r})})]})}function nz(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const Bk=i=>Symbol.iterator in i,Fk=i=>"entries"in i,Gk=(i,e)=>{const n=i instanceof Map?i:new Map(i.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,a]of n)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},rz=(i,e)=>{const n=i[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=n.next(),a=r.next()}return!!s.done&&!!a.done};function sz(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:Bk(i)&&Bk(e)?Fk(i)&&Fk(e)?Gk(i,e):rz(i,e):Gk({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function YT(i){const e=Rt.useRef(void 0);return n=>{const r=i(n);return sz(e.current,r)?e.current:e.current=r}}let Uk=0;const oz=1e3;function az(i){const e=performance.now();e-Uk<oz||(Uk=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function w0(){const i=At(p=>p.isRecording),e=At(p=>p.error),n=At(p=>p.loadingProgress),r=At(YT(O_)),s=()=>{const p=At.getState(),{canRecord:m,reason:f}=O_(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return az(f);const b=Ct.getState().activeTabId;b&&p.startRecording(b)},a=nz(r.reason,{loadingPct:n,errorMessage:e,isRecording:i}),u=r.reason==="unsupported",l=!r.canRecord,d=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:u,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${d}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function lz(){const i=At(n=>n.ttsEnabled),e=At(n=>n.toggleTTS);return o.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function cz(i){return/^monitor of /i.test(i.trim())}function Hk(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Wk(i,e,n){if(i){const u=n.find(l=>l.deviceId===i);if(u)return u}if(!e)return null;const r=n.filter(u=>u.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=Hk(e),a=n.filter(u=>u.label&&Hk(u.label)===s);return a.length===1?a[0]:null}async function Vk(i){var n;return(n=navigator.mediaDevices)!=null&&n.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&cz(r.label))):[]}const qk=!1;function XT(){const i=At(p=>p.isRecording);At(p=>p.startRecording),At(p=>p.stopRecording);const[e,n]=z.useState([]),[r,s]=z.useState(null),[a,u]=z.useState(null);z.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await Vk(qk);if(p)return;n(f),u(m.selectedLabel);const b=Wk(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){pt.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=z.useCallback(async()=>{try{const p=await Vk(qk);if(n(p),r&&!p.some(m=>m.deviceId===r)){const m=Wk(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){pt.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);z.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const d=async p=>{var S;const m=p.target.value,f=m===""?null:m,b=f?((S=e.find(w=>w.deviceId===f))==null?void 0:S.label)??null:null;s(f),u(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),pt.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(w){pt.warn("voice","setDevicePref failed",{error:w instanceof Error?w.message:String(w)})}if(i)try{await At.getState().restartWithDevice()}catch(w){pt.warn("voice","device-picker restart failed",{error:w instanceof Error?w.message:String(w)})}};return o.jsxs("select",{value:r??"",onChange:d,onFocus:()=>{l()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[o.jsx("option",{value:"",children:"Default"}),e.map(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function dz(){const i=At(S=>S.isRecording),e=At(S=>S.levelMeterEnabled),[n,r]=z.useState(0),[s,a]=z.useState(0),u=z.useRef(0);u.current=s;const[l,d]=z.useState(0),[p,m]=z.useState(!1),f=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){r(0),a(0);return}let S=0,w=!1,C=null,x=null;const y=()=>{if(w)return;const E=x??mE();if(!E){S=requestAnimationFrame(y);return}x!==E&&(x=E,C=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=C;E.getByteTimeDomainData(j);let D=0;for(let L=0;L<j.length;L++){const B=j[L]-128;D+=B*B}const $=Math.sqrt(D/j.length)/128,I=$>0?20*Math.log10($):-60,P=Math.max(0,Math.min(1,(I+60)/60));a($),r(P),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),S=requestAnimationFrame(y)};S=requestAnimationFrame(y);const _=setInterval(()=>{w||d(Math.round(u.current*100))},250);return()=>{w=!0,cancelAnimationFrame(S),clearInterval(_),f.current&&(clearTimeout(f.current),f.current=null)}},[i,e]),!i||!e)return null;const b=p?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${n*100}%`}})})}function JT(){const i=At(p=>p.submitCountdownStartAt),e=At(p=>p.submitDelayMs),[n,r]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[i]),i===null)return null;const s=n-i,a=Math.max(0,e-s),u=Math.max(0,Math.min(100,a/e*100)),l=a<500,d=At.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${u}%`}})})})}function uz({open:i,onClose:e,variant:n="overlay"}){return o.jsx(iz,{open:i,onClose:e,title:"Voice / Microphone",variant:n,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(mz,{}),o.jsx(JT,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(w0,{}),o.jsx(XT,{}),o.jsx(lz,{})]}),o.jsx(hz,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>At.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(fz,{})]}),o.jsx(dz,{})]})})}function hz(){const i=At(a=>a.isRecording),[e,n]=z.useState(null);if(z.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||n(l)}).catch(()=>{});const u=window.api.voice.onHotkeyConfigChanged(l=>n(l));return()=>{a=!0,u()}},[]),i||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=pz(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function pz(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function fz(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!i)return null;const n=async r=>{if(i.mode===r)return;const s={...i,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>n("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>n("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function mz(){const i=At(a=>a.isRecording),e=At(a=>a.lastTranscript),n=At(a=>a.error),r=At(a=>a.modelStatus),s=At(a=>a.loadingProgress);return n?o.jsxs("div",{className:"text-[11px] text-red-400",title:n,children:["⚠ ",n]}):i?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Jy=null;function gz(){return Jy||(Jy=Dg(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(a0.config({monaco:i}),i))),Jy}function ZT({value:i,onChange:e,path:n,readOnly:r}){const s=z.useRef(null),a=u=>{s.current=u};return o.jsx(l0,{path:`file://${n}`,defaultLanguage:"json",value:i,onChange:u=>e(u??""),onMount:a,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let Kk=!1;async function vz(i){if(Kk)return;const e=await gz(),n=await Promise.all(i.map(async s=>{let a=s.schema;if(!a){const u=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!u.includes(l))throw new Error("untrusted origin");const d=await fetch(s.uri);d.ok&&(a=await d.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:n.filter(s=>s.schema),enableSchemaRequest:!0}),Kk=!0}function S0({node:i,targetScope:e,onOverride:n,schema:r,rootLabel:s}){const[a,u]=z.useState(""),[l,d]=z.useState(!0),p=[],m=i.kind==="object"&&Object.keys(i.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:vr[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:S=>d(S.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:S=>u(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(QT,{node:i,path:p,label:s??"(root)",targetScope:e,onOverride:n,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function QT(i){return i.node.kind==="object"?o.jsx(xz,{...i,node:i.node}):i.node.kind==="array"?o.jsx(bz,{...i,node:i.node}):o.jsx(yz,{...i,node:i.node})}function Yk(i,e){return e.trim()?i.toLowerCase().includes(e.toLowerCase()):!0}function Ep(i,e,n){return!!(!n.trim()||i.some(r=>Yk(r,n))||e!=null&&e.description&&Yk(e.description,n))}function xz({node:i,path:e,label:n,targetScope:r,onOverride:s,filter:a,depth:u,schema:l,showGhosts:d,defaultOpen:p}){const[m,f]=z.useState(p??u<2),b=(l==null?void 0:l.at(e))??null,S=new Set(Object.keys(i.children)),w=d?(b==null?void 0:b.knownChildren)??[]:[],C=Array.from(new Set([...S,...w])).sort(),x=z.useMemo(()=>a.trim()?C.filter(_=>{const E=(l==null?void 0:l.at([...e,_]))??null;return Ep([...e,_],E,a)?!0:S.has(_)?ej(i.children[_],[...e,_],a,l):!1}):C,[C.join(","),a,i,e.join("."),l]);if(a.trim()&&x.length===0&&!Ep(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(_=>y(_))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:u*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:n}),o.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,w.length>S.size?`/${new Set([...S,...w]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(_=>y(_))]});function y(_){if(S.has(_))return o.jsx(QT,{node:i.children[_],path:[...e,_],label:_,targetScope:r,onOverride:s,filter:a,depth:u+1,schema:l,showGhosts:d},_);const E=(l==null?void 0:l.at([...e,_]))??null;return E?o.jsx(_z,{path:[...e,_],label:_,info:E,targetScope:r,onSet:s,depth:u+1,filter:a},_):null}}function ej(i,e,n,r){const s=(r==null?void 0:r.at(e))??null;if(Ep(e,s,n))return!0;if(i.kind!=="object")return!1;for(const a of Object.keys(i.children))if(ej(i.children[a],[...e,a],n,r))return!0;return!1}function bz({node:i,path:e,label:n,filter:r,depth:s,schema:a}){const[u,l]=z.useState(!0),d=(a==null?void 0:a.at(e))??null;return Ep(e,d,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!u),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:u?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:n}),o.jsxs("span",{className:"text-fg-faint",children:[" [",i.items.length,"]"]}),o.jsx(_g,{tone:"warn",children:"accumulated"}),(d==null?void 0:d.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:d.description,children:["— ",d.description]})]}),u&&i.items.map((p,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:bb(p.value)}),o.jsx(sw,{scope:p.fromScope})]},m))]}):null}function yz({node:i,path:e,label:n,targetScope:r,onOverride:s,filter:a,depth:u,schema:l}){const[d,p]=z.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Ep(e,m,a))return null;const f=i.winner!==r,b=i.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:u*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!d),children:b?d?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[n,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:bb(i.value)}),o.jsx(sw,{scope:i.winner}),(m==null?void 0:m.deprecated)&&o.jsx(_g,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&wz(i.value,m.default)&&o.jsx(_g,{tone:"dim",children:"= default"}),i.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(tj,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,i.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${vr[r].label} draft`:`already winning in ${vr[r].label}`,children:"override"})]}),d&&i.shadowed.map((S,w)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(u+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:bb(S.value)}),o.jsx(sw,{scope:S.scope,dim:!0})]},w))]})}function _z({path:i,label:e,info:n,targetScope:r,onSet:s,depth:a,filter:u}){if(!Ep(i,n,u))return null;const l=n.default!==void 0?n.default:Sz(n.type),d=Array.isArray(n.type)?n.type.join("|"):n.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(_g,{tone:"dim",children:d}),n.required&&o.jsx(_g,{tone:"warn",children:"required"}),n.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",bb(n.default)]}),n.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:n.description,children:["— ",n.description]}),o.jsx("div",{className:"flex-1"}),n.enum&&o.jsx(tj,{values:n.enum}),o.jsx("button",{onClick:()=>s(i,l),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${vr[r].label} draft`,children:"set"})]})}function wz(i,e){return i===e?!0:typeof i!=typeof e?!1:i&&e&&typeof i=="object"?JSON.stringify(i)===JSON.stringify(e):!1}function Sz(i){switch(Array.isArray(i)?i[0]:i){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function bb(i){if(typeof i=="string")return JSON.stringify(i);if(i===null)return"null";if(typeof i=="object"){const e=JSON.stringify(i);return e.length>100?e.slice(0,100)+"…":e}return String(i)}function sw({scope:i,dim:e}){const n=i==="user"?"bg-bg-hi text-fg-dim border-line":i==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${n} ${e?"opacity-60":""}`,children:vr[i].label})}function _g({children:i,tone:e="default"}){const n={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${n}`,children:i})}function tj({values:i}){const e=i.map(n=>String(n)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const kz=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],Cz={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function ij(i){return i.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((r,s)=>{const a=Cz[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function nj(i){const e=new Set,n=[];for(const s of kz){const a=s.keys.filter(u=>i.has(u));a.forEach(u=>e.add(u)),a.length!==0&&n.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(i).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&n.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),n}function Ez(i,e){return nj(i).map(n=>({id:n.id,title:n.title,advanced:n.advanced,total:n.keys.length,setCount:n.keys.filter(r=>e.has(r)).length}))}const Tz={};function rj(i,e){if(e)return{text:e,authored:!1};const n=Tz[i];return n?{text:n,authored:!0}:null}const jz={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},Dz=["user","project","local","default"],Az={user:"user",project:"project",local:"local",default:"default"};function Nz({node:i,targetScope:e,onOverride:n,schema:r}){const[s,a]=z.useState(""),[u,l]=z.useState(!1),[d,p]=z.useState(!0),m=i.kind==="object"?i:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),S=new Set([...f,...b]),w=z.useMemo(()=>nj(S),[Array.from(S).sort().join(",")]),C=z.useMemo(()=>Ez(S,new Set(f)),[Array.from(S).sort().join(","),f.join(",")]),[x,y]=z.useState(null),_=j=>{const D=w.find($=>$.id===j);D!=null&&D.advanced&&!u&&l(!0),y(j)};z.useEffect(()=>{if(!x)return;const j=document.getElementById(`settings-group-${x}`);j&&(j.scrollIntoView({behavior:"smooth",block:"start"}),y(null))});const E=z.useMemo(()=>w.filter(j=>u||!j.advanced).map(j=>({...j,keys:j.keys.filter(D=>{const $=(m==null?void 0:m.children[D])!==void 0;if(!d&&!$)return!1;if(!s.trim())return!0;const I=r.at([D]);return[D,ij(D),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(j=>j.keys.length>0),[w,s,u,d,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:vr[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:j=>p(j.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:u,onChange:j=>l(j.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:j=>a(j.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx($z,{groups:C,onJump:_}),o.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[E.map(j=>o.jsx(Pz,{id:j.id,title:j.title,summary:j.summary,advanced:j.advanced,children:j.keys.map(D=>{const $=m==null?void 0:m.children[D],I=r.at([D]);return o.jsx(Rz,{keyName:D,node:$,info:I,targetScope:e,onOverride:(P,L)=>n([D],P,L)},D)})},j.id)),E.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function $z({groups:i,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:i.map(n=>o.jsxs("button",{onClick:()=>e(n.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${n.title}`,children:[o.jsx(pi,{name:jz[n.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:n.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[n.setCount,"/",n.total]})]},n.id))})}function Pz({id:i,title:e,summary:n,advanced:r,children:s}){const[a,u]=z.useState(!0);return o.jsxs("section",{id:`settings-group-${i}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>u(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:n})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function Rz({keyName:i,node:e,info:n,targetScope:r,onOverride:s}){const[a,u]=z.useState(!1),[l,d]=z.useState(!1),p=ij(i),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,S=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",w=n==null?void 0:n.default,C=b&&w!==void 0&&oj(b.value,w),x=Gz({isSet:m,leafNode:b,defaultVal:w,isDefault:!!C,node:e}),y=Iz(b,w),_=y.length>=2,E=!!b&&!C,j=rj(i,n==null?void 0:n.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>u(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:p}),o.jsx(Uz,{kind:x.kind,label:x.label}),_&&o.jsxs("button",{onClick:D=>{D.stopPropagation(),a||u(!0),d($=>!$)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",y.map(D=>Az[D]).join(" · ")]}),E&&b&&o.jsx("button",{onClick:D=>{D.stopPropagation(),s(void 0,b.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${vr[b.winner].label}`,children:"↺ reset"}),(n==null?void 0:n.deprecated)&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(n==null?void 0:n.required)&&!m&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),j&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${j.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:j.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:Hz(j.text)}),a&&l&&b&&o.jsx(Mz,{leaf:b,defaultVal:w,onReset:D=>s(void 0,D)}),a&&o.jsx(Oz,{keyName:i,node:e,info:n,targetScope:r,onOverride:D=>s(D)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(Fz,{node:e,info:n,onSet:D=>{s(D)},disabled:S&&m})})]})})}function Iz(i,e){if(!i)return[];const n=new Set;n.add(i.winner);for(const r of i.shadowed)n.add(r.scope);return e!==void 0&&n.add("default"),Dz.filter(r=>n.has(r))}function Mz({leaf:i,defaultVal:e,onReset:n}){const r={};r[i.winner]={value:i.value,winner:!0};for(const s of i.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],u=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:vr[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:u?yp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),u?o.jsx("button",{onClick:()=>n(s),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${vr[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?yp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function Oz({keyName:i,node:e,info:n,targetScope:r,onOverride:s}){const u=(e==null?void 0:e.kind)==="leaf"?e:null,l=rj(i,n==null?void 0:n.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(n==null?void 0:n.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(n.type)?n.type.join(" | "):n.type})]}),(n==null?void 0:n.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:yp(n.default)})]}),(n==null?void 0:n.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:n.enum.map(d=>String(d)).join(" | ")})]}),u&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:yp(u.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",vr[u.winner].label]})]})]}),u&&u.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:u.shadowed.map((d,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[yp(d.value)," —"," ",o.jsx("span",{className:"no-underline",children:vr[d.scope].label})]},p))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(Lz,{keyName:i,node:e,info:n,onChange:s,targetScope:r})})]})}function Lz({node:i,info:e,onChange:n,targetScope:r}){const a=(i==null?void 0:i.kind)==="leaf"?i.value:e==null?void 0:e.default,u=sj(e==null?void 0:e.type);if(u==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:d,label:p})=>o.jsx("button",{onClick:()=>n(d),className:`px-3 py-0.5 text-xs transition-colors ${l===d?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",vr[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const d=oj(a,l);return o.jsx("button",{onClick:()=>n(l),className:`px-2 py-0.5 text-xs rounded border ${d?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",vr[r].label]})]}):u==="integer"||u==="number"?o.jsx(zz,{value:typeof a=="number"?a:void 0,integer:u==="integer",onCommit:n,target:vr[r].label}):u==="string"?o.jsx(Bz,{value:typeof a=="string"?a:"",onCommit:n,target:vr[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",u??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function zz({value:i,integer:e,onCommit:n,target:r}){const[s,a]=z.useState(i!==void 0?String(i):""),u=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||n(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:u,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:u,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function Bz({value:i,onCommit:e,target:n}){const[r,s]=z.useState(i);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",n]})]})}function Fz({node:i,info:e,onSet:n,disabled:r}){const s=(i==null?void 0:i.kind)==="leaf",a=sj(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const u=s&&i.value===!0;return o.jsx("button",{onClick:()=>n(!u),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${u?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:u?"on":"off"})}return null}function Gz({isSet:i,leafNode:e,defaultVal:n,isDefault:r,node:s}){return i?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${vr[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${vr[e.winner].label}`}:{kind:"set",label:"configured"}:n!==void 0?{kind:"default",label:`using default: ${yp(n)}`}:{kind:"unset",label:"not configured"}}function Uz({kind:i,label:e}){const n={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[i];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${n}`,children:e})}function sj(i){if(i)return Array.isArray(i)?i.find(n=>n!=="null")??i[0]:i}function oj(i,e){return i===e?!0:typeof i!=typeof e?!1:i&&e&&typeof i=="object"?JSON.stringify(i)===JSON.stringify(e):!1}function Hz(i){const e=i.trim().split(`
|
|
3053
|
+
(Give a different rewrite than the last one.)`,!1)},[w,n.instruction]),_=z.useCallback(E=>{const j=n.diff;if(!j)return{ok:!1,reason:"not-found"};const D=EL(E,j.before,j.after);return D.ok?(s.current+=1,r({type:"ACCEPT"})):Ve.error(D.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),D},[n.diff]);return{state:n,select:p,cancel:m,listen:f,sendHeard:x,run:C,retry:y,accept:_}}const IL=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Dk=320,$m=8;function ML(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function OL(i){const e=typeof window<"u"?window.innerWidth:1024,n=Math.min(Math.max(i.left,$m),Math.max($m,e-Dk-$m)),r=Math.max(i.top-$m,$m);return{position:"fixed",left:n,top:r,width:Dk,transform:"translateY(-100%)",zIndex:50}}function LL({phase:i,rect:e,diff:n,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:u,onListen:l,onSendHeard:d,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[S,w]=z.useState(""),C=()=>{const x=S.trim();x&&(u(x),w(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:OL(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),IL.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:S,onChange:x=>w(x.target.value),onKeyDown:x=>{x.key==="Enter"?C():x.key==="Escape"&&p()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(ML,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function zL(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function Ak({phase:i,transcript:e,diff:n,editCount:r,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:d,onReject:p,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Ng(PL)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),i==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(zL,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&n&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function Nk(i){return i.split("/").filter(Boolean).pop()||i}function BL({path:i,onRenamed:e,onDeleted:n}){const[r,s]=z.useState(!1),[a,u]=z.useState(!1),[l,d]=z.useState(""),[p,m]=z.useState(!1),f=Di(B=>B.buffers[i]),b=Di(B=>B.openFile),S=Di(B=>B.renameOpenFile),w=Di(B=>B.closeFile),C=Jc(),x=Nk(i),y=()=>s(!1),_=()=>{d(x),u(!0),y()},E=async()=>{const B=l.trim();if(!B||B===x){u(!1);return}try{const U=await window.api.files.rename(i,B);if(U.ok){const Z=i.slice(0,i.lastIndexOf("/")),X=U.newPath??`${Z}/${B}`;S(i,X),e==null||e(i,X),Ve.info(`Renamed to ${B}`)}else Ve.error(U.error??`Couldn't rename ${x}`)}catch(U){Ve.error(U instanceof Error?U.message:`Couldn't rename ${x}`)}u(!1)},j=async()=>{y();try{const B=await window.api.files.duplicate(i);B.ok&&B.path?(b(B.path),Ve.info(`Duplicated as ${Nk(B.path)}`)):Ve.error(B.error??`Couldn't duplicate ${x}`)}catch(B){Ve.error(B instanceof Error?B.message:`Couldn't duplicate ${x}`)}},D=async()=>{try{const B=await window.api.files.delete(i);B.ok?(w(i),n==null||n(i),Ve.info(`Deleted ${x}`)):Ve.error(B.error??`Couldn't delete ${x}`)}catch(B){Ve.error(B instanceof Error?B.message:`Couldn't delete ${x}`)}m(!1)},$=async()=>{y();const B=f??"";try{await navigator.clipboard.writeText(B),Ve.info(`Copied ${B.length} chars`)}catch(U){Ve.error(U instanceof Error?U.message:`Couldn't copy ${x}`)}},I=()=>{if(y(),!C){Ve.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Ve.info(`Added ${x} to Claude context`)},P=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(B=>{B.ok||Ve.error(B.error??`Couldn't open ${x}`)}).catch(B=>Ve.error(B instanceof Error?B.message:`Couldn't open ${x}`))},L=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(B=>{B.ok||Ve.error(B.error??`Couldn't reveal ${x}`)}).catch(B=>Ve.error(B instanceof Error?B.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(B=>!B),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:y}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[o.jsx(qy,{children:"Edit"}),o.jsx(Xd,{label:"Rename",onClick:_}),o.jsx(Xd,{label:"Duplicate",onClick:j}),o.jsx(Xd,{label:"Delete document",danger:!0,onClick:()=>{y(),m(!0)}}),o.jsx($k,{}),o.jsx(qy,{children:"Open"}),o.jsx(Xd,{label:"Open in default app",onClick:P}),o.jsx(Xd,{label:"Reveal in OS",onClick:L}),o.jsx($k,{}),o.jsx(qy,{children:"Export"}),o.jsx(Xd,{label:"Copy as Markdown",onClick:$}),o.jsx(Xd,{label:"Add to Claude context",onClick:I,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(FL,{value:l,onChange:d,onCancel:()=>u(!1),onConfirm:()=>void E()}),p&&o.jsx(GL,{name:x,onCancel:()=>m(!1),onConfirm:()=>void D()})]})}function qy({children:i}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function Xd({label:i,onClick:e,danger:n,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function $k(){return o.jsx("div",{className:"my-1 border-t border-line"})}function FL({value:i,onChange:e,onCancel:n,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&n()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&n()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function GL({name:i,onCancel:e,onConfirm:n}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function UL(){const[i,e]=z.useState(!1),n=fp();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[o.jsx(op,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>n.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:n.fontSize}),o.jsx("button",{onClick:()=>n.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(op,{label:"Word wrap",children:o.jsx(px,{on:n.wordWrap,onClick:n.toggleWordWrap})}),o.jsx(op,{label:"Minimap",children:o.jsx(px,{on:n.minimap,onClick:n.toggleMinimap})}),o.jsx(op,{label:"Theme",children:o.jsx("button",{onClick:()=>n.setTheme(n.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:n.theme==="dark"?"Dark":"Paper"})}),o.jsx(op,{label:"Autosave",children:o.jsx(px,{on:n.autosave,onClick:n.toggleAutosave})}),o.jsx(op,{label:"Wide measure",children:o.jsx(px,{on:n.wideMeasure,onClick:n.toggleWideMeasure})})]})]})]})}function op({label:i,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:i}),e]})}function px({on:i,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const HL=z.lazy(()=>Dg(()=>import("./TiptapBody-CtuLATFR.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function fx(i){return i.split("/").filter(Boolean).pop()||i}function mx(i,e){if(!e.length)return i;const n=new Set(e),r={};for(const[s,a]of Object.entries(i))n.has(s)||(r[s]=a);return r}function gx(i){return CT(i)||ET(i)}function xb(){const i=Og(),e=Di(Ue=>Ue.openFiles),n=Di(Ue=>Ue.activeFilePath),r=Di(Ue=>Ue.dirty),s=Di(Ue=>Ue.viewMode),a=Di(Ue=>Ue.buffers),u=Di(Ue=>Ue.setActive),l=Di(Ue=>Ue.closeFile),d=Di(Ue=>Ue.closeOthers),p=Di(Ue=>Ue.closeToTheRight),m=Di(Ue=>Ue.closeAll),f=Di(Ue=>Ue.loadBuffer),b=Di(Ue=>Ue.setBuffer),S=Di(Ue=>Ue.markSaved),w=Di(Ue=>Ue.setViewMode),C=fp(),[x,y]=z.useState({}),[_,E]=z.useState({}),[j,D]=z.useState(null),[$,I]=z.useState(null),[P,L]=z.useState(!1),[B,U]=z.useState(!1),[Z,X]=z.useState(!0),W=z.useRef(null),J=z.useRef(null),te=z.useRef(void 0),le=z.useRef(null),ue=z.useRef(null),V=RL(n??"",a[n??""]??""),ie=z.useCallback(Ue=>{W.current=Ue},[]),K=z.useCallback(()=>W.current,[]);z.useEffect(()=>{const Ue=n;if(!Ue||gx(Ue))return;if(Di.getState().hasBuffer(Ue)){y(ft=>ft[Ue]==="ready"?ft:{...ft,[Ue]:"ready"});return}let _t=!1;return y(ft=>({...ft,[Ue]:"loading"})),window.api.files.read(Ue).then(ft=>{_t||(ft.binary?y(ui=>({...ui,[Ue]:{binary:!0,size:ft.size??0,mime:ft.mime??"application/octet-stream",reason:ft.error??"Binary file"}})):ft.ok?(f(Ue,ft.text),y(ui=>({...ui,[Ue]:"ready"}))):y(ui=>({...ui,[Ue]:{error:ft.error??"failed to read"}})))}),()=>{_t=!0}},[n,f]),z.useEffect(()=>{I(null)},[n]);const se=z.useCallback(async(Ue,_t=!1)=>{const ft=Di.getState().buffers[Ue];if(ft==null)return;_t&&L(!0);const ui=await window.api.files.write(Ue,ft);ui.ok?(S(Ue),E(ji=>({...ji,[Ue]:(ji[Ue]??0)+1})),_t||Ve.info(`Saved ${fx(Ue)}`)):Ve.error(ui.error??`Couldn't save ${fx(Ue)}`),_t&&L(!1)},[S]);z.useEffect(()=>{if(!C.autosave)return;const Ue=n;if(!(!Ue||gx(Ue)||!r[Ue]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{se(Ue,!0)},1200),()=>window.clearTimeout(te.current)},[C.autosave,n,r,a,se]);const oe=z.useCallback(Ue=>{Ue.length&&(y(_t=>mx(_t,Ue)),E(_t=>mx(_t,Ue)))},[]),be=z.useCallback((Ue,_t)=>{y(ft=>Ue in ft?{...mx(ft,[Ue]),[_t]:ft[Ue]}:ft),E(ft=>Ue in ft?{...mx(ft,[Ue]),[_t]:ft[Ue]}:ft)},[]),je=z.useCallback(Ue=>{r[Ue]?D({kind:"one",path:Ue}):(l(Ue),oe([Ue]))},[r,l,oe]),Te=z.useCallback(Ue=>{e.some(ft=>ft.path!==Ue&&r[ft.path])?D({kind:"others",path:Ue}):(d(Ue),oe(e.filter(ft=>ft.path!==Ue).map(ft=>ft.path)))},[e,r,d,oe]),ve=z.useCallback(Ue=>{const _t=e.findIndex(ui=>ui.path===Ue);_t!==-1&&e.slice(_t+1).some(ui=>r[ui.path])?D({kind:"right",path:Ue}):(p(Ue),oe(_t!==-1?e.slice(_t+1).map(ui=>ui.path):[]))},[e,r,p,oe]);z.useEffect(()=>{const Ue=_t=>{if(i.current)if((_t.metaKey||_t.ctrlKey)&&(_t.key==="s"||_t.key==="S")){const ft=Di.getState().activeFilePath;ft&&!gx(ft)&&(_t.preventDefault(),se(ft))}else if((_t.metaKey||_t.ctrlKey)&&_t.shiftKey&&(_t.key==="f"||_t.key==="F"))_t.preventDefault(),U(ft=>!ft);else if((_t.metaKey||_t.ctrlKey)&&_t.shiftKey&&(_t.key==="w"||_t.key==="W")){const ft=Di.getState().activeFilePath;ft&&Di.getState().openFiles.length>1&&(_t.preventDefault(),Te(ft))}else _t.key==="Escape"&&V.state.phase!=="idle"?V.cancel():_t.key==="Escape"&&B&&U(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[se,B,Te,V.state.phase,V.cancel]),z.useEffect(()=>{if(V.state.phase==="idle")return;const Ue=_t=>{var ui,ji;const ft=_t.target;(ui=ue.current)!=null&&ui.contains(ft)||(ji=le.current)!=null&&ji.contains(ft)||V.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[V.state.phase,V.cancel]),z.useEffect(()=>{V.cancel()},[n,V.cancel]);const re=z.useCallback(()=>{e.some(_t=>r[_t.path])?D({kind:"all",path:""}):(m(),y({}),E({}))},[e,r,m]),Pe=()=>{if(j){if(j.kind==="one")l(j.path),oe([j.path]);else if(j.kind==="others"){const Ue=e.filter(_t=>_t.path!==j.path).map(_t=>_t.path);d(j.path),oe(Ue)}else if(j.kind==="right"){const Ue=e.findIndex(ft=>ft.path===j.path),_t=Ue!==-1?e.slice(Ue+1).map(ft=>ft.path):[];p(j.path),oe(_t)}else m(),y({}),E({});D(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const _e=n,Qe=_e?fx(_e):"",st=_e?x[_e]:void 0,yt=_e?DT(_e):!1,qt=_e?zM(_e):!1,ut=_e&&yt?s[_e]??BM(_e):"edit",nt=!!_e&&!gx(_e)&&st==="ready",Le=nt,ht=qt?["edit","wysiwyg","preview","split"]:yt?["edit","preview"]:[],Gt=_e&&o.jsx(KM,{path:_e,name:Qe,value:a[_e]??"",onChange:Ue=>b(_e,Ue),onSave:()=>void se(_e),onReady:ie,onCursor:I}),di=P?"Saving…":_e&&r[_e]?C.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!B&&o.jsx(HM,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:u,onCloseFile:je,onCloseOthers:Te,onCloseToTheRight:ve,onCloseAll:re}),_e&&!B&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Qe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:_e}),nt&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",di]}),Al(_e)&&(ut==="preview"||ut==="split")&&o.jsx("button",{onClick:()=>X(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Al(_e)&&(ut==="preview"||ut==="split")&&o.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),ht.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:ht.map(Ue=>o.jsx("button",{onClick:()=>w(_e,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ut===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),o.jsx("div",{className:"flex-1"}),o.jsx(BL,{path:_e,onRenamed:be,onDeleted:Ue=>oe([Ue])}),nt&&o.jsx(UL,{}),o.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),B&&o.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),o.jsx("div",{className:"flex-1 min-h-0",children:_e?CT(_e)?o.jsx(vL,{path:_e,name:Qe}):ET(_e)?o.jsx(xL,{path:_e}):st&&typeof st=="object"&&"binary"in st?o.jsx(CL,{path:_e,name:Qe,size:st.size,mime:st.mime,reason:st.reason}):st&&typeof st=="object"&&"error"in st?o.jsx("div",{className:"p-6 text-xs text-red-400",children:st.error}):st!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ut==="wysiwyg"&&Al(_e)?o.jsx(z.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(HL,{value:a[_e]??"",onChange:Ue=>b(_e,Ue)},_e)}):ut==="split"&&Al(_e)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(Ek,{text:a[_e]??"",scrollRef:J}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(Ck,{getEditor:K}),o.jsx("div",{className:"flex-1 min-h-0",children:Gt})]}),o.jsx("div",{ref:le,className:"flex-1 min-w-0",children:o.jsx(iw,{ref:J,text:a[_e]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!B&&C.assistantRail&&o.jsx(Ak,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)},onReject:V.cancel,onRetry:V.retry})]}):ut==="preview"&&Al(_e)?o.jsxs("div",{className:"flex h-full",children:[Z&&o.jsx(Ek,{text:a[_e]??"",scrollRef:J}),o.jsx("div",{ref:le,className:"flex-1 min-w-0",children:o.jsx(iw,{ref:J,text:a[_e]??"",wideMeasure:C.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!B&&C.assistantRail&&o.jsx(Ak,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)},onReject:V.cancel,onRetry:V.retry})]}):ut==="preview"&&kT(_e)?o.jsx(mL,{path:_e,dirty:!!r[_e],reloadToken:_[_e]??0}):ut==="preview"&&TT(_e)?o.jsx(yL,{path:_e,text:a[_e]??""}):ut==="preview"&&jT(_e)?o.jsx(SL,{path:_e,text:a[_e]??""}):Al(_e)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(Ck,{getEditor:K}),o.jsx("div",{className:"flex-1 min-h-0",children:Gt})]}):Gt:null}),Le&&o.jsx(fL,{text:a[_e]??"",cursor:$,language:Qs(_e)||void 0}),_e&&Al(_e)&&(ut==="preview"||ut==="split")&&V.state.phase!=="idle"&&V.state.selection&&o.jsx("div",{ref:ue,children:o.jsx(LL,{phase:V.state.phase,rect:V.state.selection.rect,diff:V.state.diff,transcript:V.state.transcript,modelStatus:V.state.modelStatus,onQuickAction:V.run,onRunCustom:V.run,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onReject:V.cancel,onRetry:V.retry,onAccept:()=>{const Ue=V.accept(a[_e]??"");Ue.ok&&b(_e,Ue.next)}})}),j&&o.jsx(WL,{message:j.kind==="one"?`Discard unsaved changes to ${fx(j.path)}?`:j.kind==="others"?"Discard unsaved changes in the other open files?":j.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>D(null),onConfirm:Pe})]})}function WL({message:i,onCancel:e,onConfirm:n}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Pk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},VL={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function Ky(i){return i>=1e6?(i/1e6).toFixed(1)+"M":i>=1e3?(i/1e3).toFixed(1)+"K":String(i)}function qL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(D=>D.tabs.find($=>$.id===D.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,u]=z.useState(null),[l,d]=z.useState(!1),[p,m]=z.useState(null),f=z.useRef(null),b=z.useCallback(async D=>{d(!0),m(null);try{const $=await window.api.repo.analyze(D);$.ok?u($):(m($.error||"Analysis failed"),u(null))}catch($){m($ instanceof Error?$.message:String($)),u(null)}finally{d(!1)}},[]);z.useEffect(()=>{if(i){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[i,s,b]),z.useEffect(()=>{var $;if(!i)return;const D=I=>{I.key==="Escape"&&(I.stopPropagation(),e())};return window.addEventListener("keydown",D),($=f.current)==null||$.focus(),()=>window.removeEventListener("keydown",D)},[i,e]);const S=z.useCallback(()=>{s&&b(s)},[s,b]),w=z.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([$,I])=>[$,I.files,I.lines]).sort(($,I)=>I[1]-$[1]).slice(0,12):[],[a]),C=z.useMemo(()=>w.length===0?1:w[0][1],[w]),x=z.useMemo(()=>{if(!a)return[];const D=a.topDirectories;if(D.length===0)return[];const $=D.map(P=>Math.sqrt(Math.max(1,P.fileCount))),I=$.reduce((P,L)=>P+L,0)||1;return D.map((P,L)=>({path:P.path,fileCount:P.fileCount,totalLines:P.totalLines,basis:$[L]/I*100}))},[a]);if(!i)return null;const y=D=>{D.target===D.currentTarget&&e()},_=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=n==="page",j=o.jsx("div",{className:E?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:E?void 0:y,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,role:E?void 0:"dialog","aria-modal":E?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:E?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[_,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:S,disabled:l||!s,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):p?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:p})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Yy,{label:"Files",value:Ky(a.totalFiles)}),o.jsx(Yy,{label:"Lines of code",value:Ky(a.totalLines)}),o.jsx(Yy,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),w.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:w.map(([D,$,I])=>{const P=Pk[D]??Pk.other,L=VL[D]??D,B=$/C*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:L,children:L}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${B}%`,backgroundColor:P}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[$," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[Ky(I)," L"]})]},D)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(D=>o.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max(D.basis,6)}%`,flexGrow:D.basis>15?1:0},title:`${D.path} — ${D.fileCount} files, ${D.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:D.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[D.fileCount," files"]})]},D.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!E&&typeof document<"u"&&document.body?vu.createPortal(j,document.body):j}function Yy({label:i,value:e,tone:n="neutral"}){const r=n==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:i})]})}function _u({options:i,active:e,onChange:n}){return o.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:i.map(({key:r,label:s})=>o.jsx("button",{onClick:()=>n(r),className:`px-2 py-0.5 text-xs ${e===r?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:s},r))})}const Rk=i=>/[/\\\-_.\s]/.test(i),Ik=i=>i>="A"&&i<="Z";function KL(i,e,n){if(!i)return{match:!0,score:0,matched:[]};const r=i.toLowerCase(),s=e.toLowerCase(),a=(n||e).toLowerCase(),u=e.split("/").pop()||e,l=u.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:u.length},(y,_)=>_)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:i.length},(y,_)=>_)};let d=0;for(const y of a.split("/")){if(y===r)return{match:!0,score:800,matched:[]};y.startsWith(r)&&(d=Math.max(d,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||Rk(l[p-1])||Ik(u[p])?650:600,matched:Array.from({length:i.length},(_,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,d),matched:[]};let m=0,f=0,b=0,S=-1,w=0;const C=[];for(let y=0;y<s.length&&m<r.length;y++)s[y]===r[m]&&(C.push(y),f+=10,S===y-1?(b++,f+=b*8):b=0,(y===0||Rk(s[y-1])||Ik(e[y]))&&(w++,f+=15,y===0&&(f+=10)),S=y,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,w>=r.length*.5&&(f+=30),C.length>1){const y=C[C.length-1]-C[0];y>r.length*3&&(f-=Math.min(50,(y-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:C}}function Xy(i,e){return i.startsWith(e+"/")?i.slice(e.length+1):i===e?"":i}function Mk(i){const e=i.lastIndexOf("/");return e<0?"":i.slice(0,e)}const Ok="session-manager.quickopen.recent",YL=8;function XL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(L=>L.tabs.find(B=>B.id===L.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,u]=z.useState(""),[l,d]=z.useState([]),[p,m]=z.useState(!1),[f,b]=z.useState(0),[S,w]=z.useState([]),C=z.useRef(null),x=z.useRef(null);z.useEffect(()=>{if(i)try{const L=localStorage.getItem(Ok);L&&w(JSON.parse(L))}catch{}},[i]),z.useEffect(()=>{if(!i){u(""),b(0);return}const L=setTimeout(()=>{var B;return(B=C.current)==null?void 0:B.focus()},0);return()=>clearTimeout(L)},[i]),z.useEffect(()=>{if(!i||!s)return;let L=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(B=>{if(!L){if(!B.ok){Ve.error(`File search failed: ${B.error??"unknown error"}`),d([]);return}d(B.files)}}).catch(B=>{const U=B instanceof Error?B.message:String(B);pt.error("quick-open","search.files threw",{error:U}),Ve.error(`File search failed: ${U}`),d([])}).finally(()=>{L||m(!1)}),()=>{L=!0}},[i,s]);const y=z.useMemo(()=>{if(!a.trim())return[...l].sort((Z,X)=>Z.name.localeCompare(X.name)).slice(0,100).map(Z=>({file:Z,score:0,matched:[]}));const L=a.trim(),B=[];for(const U of l){const Z=KL(L,U.name,U.path);Z.match&&B.push({file:U,score:Z.score,matched:Z.matched})}return B.sort((U,Z)=>Z.score-U.score),B.slice(0,100)},[l,a]),_=z.useMemo(()=>a.trim()?[]:S.map(L=>l.find(B=>B.path===L)||null).filter(L=>L!==null).slice(0,5),[S,l,a]);z.useEffect(()=>{const L=_.length+y.length;f>=L&&b(Math.max(0,L-1))},[_.length,y.length,f]),z.useEffect(()=>{if(!x.current)return;const L=x.current.querySelector(`[data-row="${f}"]`);L&&L.scrollIntoView({block:"nearest"})},[f]);const E=z.useCallback(L=>{try{const X=[L,...S.filter(W=>W!==L)].slice(0,YL);w(X),localStorage.setItem(Ok,JSON.stringify(X))}catch{}const B=r==null?void 0:r.id;if(!B){Ve.error("No active tab to receive file path");return}const Z=(s?Xy(L,s):L)||L;try{window.api.pty.write({tabId:B,data:Z})}catch(X){const W=X instanceof Error?X.message:String(X);pt.error("quick-open","pty.write failed",{error:W}),Ve.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,S,e]),j=z.useCallback(L=>{const B=_.length+y.length;if(L.key==="Escape"){L.preventDefault(),e();return}if(L.key==="ArrowDown"){if(L.preventDefault(),B===0)return;b(U=>Math.min(B-1,U+1));return}if(L.key==="ArrowUp"){if(L.preventDefault(),B===0)return;b(U=>Math.max(0,U-1));return}if(L.key==="Enter"){if(L.preventDefault(),f<_.length){const X=_[f];X&&E(X.path);return}const U=f-_.length,Z=y[U];Z&&E(Z.file.path)}},[f,y,_,E,e]);if(!i)return null;const D=(L,B)=>{if(B.length===0)return L;const U=new Set(B);return L.split("").map((Z,X)=>o.jsx("span",{className:U.has(X)?"text-accent font-semibold":"",children:Z},X))};let $=-1;const I=n==="page",P=o.jsx("div",{className:I?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:I?void 0:L=>{L.target===L.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:I?void 0:"dialog","aria-modal":I?void 0:"true","aria-label":"Quick Open",className:I?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:j,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:C,type:"text",value:a,onChange:L=>{u(L.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:p?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?_.length===0&&y.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[_.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(L=>{$++;const B=$,U=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":U,onClick:()=>E(L.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${U?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:L.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Xy(Mk(L.path),s)})]},`r:${L.path}`)})]}),y.length>0&&o.jsxs("div",{children:[_.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),y.map(({file:L,matched:B})=>{$++;const U=$,Z=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":Z,onClick:()=>E(L.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Z?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:D(L.name,B)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Xy(Mk(L.path),s)})]},L.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[y.length+_.length," ",y.length+_.length===1?"file":"files"]})]})]})});return!I&&typeof document<"u"&&document.body?vu.createPortal(P,document.body):P}function Lk(i,e){return i.startsWith(e+"/")?i.slice(e.length+1):i===e?"":i}function JL(i,e,n){if(!e)return i;const r=n?i:i.toLowerCase(),s=n?e:e.toLowerCase(),a=r.indexOf(s);return a<0?i:o.jsxs(o.Fragment,{children:[i.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:i.slice(a,a+e.length)}),i.slice(a+e.length)]})}function ZL({open:i,onClose:e,variant:n="overlay"}){const r=Ct(X=>X.tabs.find(W=>W.id===X.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,u]=z.useState(""),[l,d]=z.useState(!1),[p,m]=z.useState([]),[f,b]=z.useState(!1),[S,w]=z.useState(null),[C,x]=z.useState(0),[y,_]=z.useState(null),E=z.useRef(null),j=z.useRef(null),D=z.useRef(0);z.useEffect(()=>{if(!i){u(""),m([]),w(null),x(0);return}const X=setTimeout(()=>{var W;return(W=E.current)==null?void 0:W.focus()},0);return()=>clearTimeout(X)},[i]),z.useEffect(()=>{if(!i||!s)return;const X=a.trim();if(!X){m([]),w(null),b(!1);return}const W=++D.current;b(!0);const J=setTimeout(()=>{window.api.search.text(s,X,{caseSensitive:l,limit:500}).then(te=>{W===D.current&&(te.ok?(m(te.matches),w(null)):(w(te.error??"unknown error"),m([])),_(te.usedRipgrep))}).catch(te=>{if(W!==D.current)return;const le=te instanceof Error?te.message:String(te);pt.error("global-search","search.text threw",{error:le}),w(le),m([])}).finally(()=>{W===D.current&&b(!1)})},250);return()=>clearTimeout(J)},[i,s,a,l]);const $=z.useMemo(()=>{const X=new Map;for(const J of p){const te=X.get(J.path);te?te.push(J):X.set(J.path,[J])}const W=[];for(const[J,te]of X)W.push({path:J,matches:te});return W.sort((J,te)=>te.matches.length-J.matches.length||J.path.localeCompare(te.path)),W},[p]),I=z.useMemo(()=>p,[p]);z.useEffect(()=>{C>=I.length&&x(Math.max(0,I.length-1))},[I.length,C]),z.useEffect(()=>{if(!j.current)return;const X=j.current.querySelector(`[data-match="${C}"]`);X&&X.scrollIntoView({block:"nearest"})},[C]);const P=z.useCallback(X=>{const W=r==null?void 0:r.id;if(!W){Ve.error("No active tab to receive path");return}const te=`${(s?Lk(X.path,s):X.path)||X.path}:${X.line}`;try{window.api.pty.write({tabId:W,data:te})}catch(le){const ue=le instanceof Error?le.message:String(le);pt.error("global-search","pty.write failed",{error:ue}),Ve.error(`Failed to write to terminal: ${ue}`);return}e()},[r==null?void 0:r.id,s,e]),L=z.useCallback(X=>{if(X.key==="Escape"){X.preventDefault(),e();return}if(X.key==="ArrowDown"){if(X.preventDefault(),I.length===0)return;x(W=>Math.min(I.length-1,W+1));return}if(X.key==="ArrowUp"){if(X.preventDefault(),I.length===0)return;x(W=>Math.max(0,W-1));return}if(X.key==="Enter"){X.preventDefault();const W=I[C];W&&P(W)}},[I,C,P,e]);if(!i)return null;const B=n==="page";let U=-1;const Z=o.jsx("div",{className:B?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:B?void 0:X=>{X.target===X.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:B?void 0:"dialog","aria-modal":B?void 0:"true","aria-label":"Search in project",className:B?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:L,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:E,type:"text",value:a,onChange:X=>{u(X.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),o.jsx("button",{type:"button",onClick:()=>d(X=>!X),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:j,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):I.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:$.map(X=>o.jsxs("div",{children:[o.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Lk(X.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",X.matches.length,")"]})]}),X.matches.map(W=>{U++;const J=U,te=J===C;return o.jsxs("button",{"data-match":J,role:"option","aria-selected":te,onClick:()=>P(W),onMouseEnter:()=>x(J),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${te?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:JL(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${J}`)})]},X.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[I.length," ",I.length===1?"match":"matches",y===!1&&" · fs walk (rg missing)"]})]})]})});return!B&&typeof document<"u"&&document.body?vu.createPortal(Z,document.body):Z}const QL=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function ez({open:i,onClose:e,variant:n="page",initialMode:r="files"}){const[s,a]=z.useState(r);return z.useEffect(()=>{a(r)},[r]),i?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(_u,{options:QL,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(XL,{open:!0,onClose:e,variant:"page"}):o.jsx(ZL,{open:!0,onClose:e,variant:"page"})})]}):null}const tz={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},zk='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function $p({open:i,onClose:e,children:n,title:r,size:s="sm",fillHeight:a=!1,noPadding:u=!1,variant:l="overlay"}){if(l==="page")return i?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${u?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${u?"":"p-6 pt-0"}`,children:n})]}):null;const d=z.useRef(null),p=z.useRef(null),m=z.useRef(e);if(m.current=e,z.useEffect(()=>{if(!i)return;p.current=typeof document<"u"?document.activeElement:null;const w=setTimeout(()=>{const x=d.current;if(!x)return;const y=x.querySelector(zk);y?y.focus():x.focus()},0),C=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const y=d.current;if(!y)return;const _=Array.from(y.querySelectorAll(zk)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(_.length===0){x.preventDefault(),y.focus();return}const E=_[0],j=_[_.length-1],D=document.activeElement;x.shiftKey?(D===E||!y.contains(D))&&(x.preventDefault(),j.focus()):(D===j||!y.contains(D))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",C),()=>{clearTimeout(w),document.removeEventListener("keydown",C);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[i]),!i)return null;const f=S=>{S.target===S.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":r??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${tz[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${u?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${u?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:n}):n]})});return typeof document<"u"&&document.body?vu.createPortal(b,document.body):b}class KT extends z.Component{constructor(){super(...arguments);Ui(this,"state",{error:null});Ui(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[ErrorBoundary]",n,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function iz({open:i,onClose:e,title:n,children:r,variant:s="overlay"}){return o.jsxs($p,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:n}),o.jsx("button",{type:"button",onClick:e,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(KT,{children:r})})]})}function nz(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const Bk=i=>Symbol.iterator in i,Fk=i=>"entries"in i,Gk=(i,e)=>{const n=i instanceof Map?i:new Map(i.entries()),r=e instanceof Map?e:new Map(e.entries());if(n.size!==r.size)return!1;for(const[s,a]of n)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},rz=(i,e)=>{const n=i[Symbol.iterator](),r=e[Symbol.iterator]();let s=n.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=n.next(),a=r.next()}return!!s.done&&!!a.done};function sz(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:Bk(i)&&Bk(e)?Fk(i)&&Fk(e)?Gk(i,e):rz(i,e):Gk({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function YT(i){const e=Rt.useRef(void 0);return n=>{const r=i(n);return sz(e.current,r)?e.current:e.current=r}}let Uk=0;const oz=1e3;function az(i){const e=performance.now();e-Uk<oz||(Uk=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function w0(){const i=At(p=>p.isRecording),e=At(p=>p.error),n=At(p=>p.loadingProgress),r=At(YT(O_)),s=()=>{const p=At.getState(),{canRecord:m,reason:f}=O_(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return az(f);const b=Ct.getState().activeTabId;b&&p.startRecording(b)},a=nz(r.reason,{loadingPct:n,errorMessage:e,isRecording:i}),u=r.reason==="unsupported",l=!r.canRecord,d=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:u,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${d}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function lz(){const i=At(n=>n.ttsEnabled),e=At(n=>n.toggleTTS);return o.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function cz(i){return/^monitor of /i.test(i.trim())}function Hk(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Wk(i,e,n){if(i){const u=n.find(l=>l.deviceId===i);if(u)return u}if(!e)return null;const r=n.filter(u=>u.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=Hk(e),a=n.filter(u=>u.label&&Hk(u.label)===s);return a.length===1?a[0]:null}async function Vk(i){var n;return(n=navigator.mediaDevices)!=null&&n.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&cz(r.label))):[]}const qk=!1;function XT(){const i=At(p=>p.isRecording);At(p=>p.startRecording),At(p=>p.stopRecording);const[e,n]=z.useState([]),[r,s]=z.useState(null),[a,u]=z.useState(null);z.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await Vk(qk);if(p)return;n(f),u(m.selectedLabel);const b=Wk(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){pt.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=z.useCallback(async()=>{try{const p=await Vk(qk);if(n(p),r&&!p.some(m=>m.deviceId===r)){const m=Wk(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){pt.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);z.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const d=async p=>{var S;const m=p.target.value,f=m===""?null:m,b=f?((S=e.find(w=>w.deviceId===f))==null?void 0:S.label)??null:null;s(f),u(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),pt.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(w){pt.warn("voice","setDevicePref failed",{error:w instanceof Error?w.message:String(w)})}if(i)try{await At.getState().restartWithDevice()}catch(w){pt.warn("voice","device-picker restart failed",{error:w instanceof Error?w.message:String(w)})}};return o.jsxs("select",{value:r??"",onChange:d,onFocus:()=>{l()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[o.jsx("option",{value:"",children:"Default"}),e.map(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function dz(){const i=At(S=>S.isRecording),e=At(S=>S.levelMeterEnabled),[n,r]=z.useState(0),[s,a]=z.useState(0),u=z.useRef(0);u.current=s;const[l,d]=z.useState(0),[p,m]=z.useState(!1),f=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){r(0),a(0);return}let S=0,w=!1,C=null,x=null;const y=()=>{if(w)return;const E=x??mE();if(!E){S=requestAnimationFrame(y);return}x!==E&&(x=E,C=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=C;E.getByteTimeDomainData(j);let D=0;for(let L=0;L<j.length;L++){const B=j[L]-128;D+=B*B}const $=Math.sqrt(D/j.length)/128,I=$>0?20*Math.log10($):-60,P=Math.max(0,Math.min(1,(I+60)/60));a($),r(P),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),S=requestAnimationFrame(y)};S=requestAnimationFrame(y);const _=setInterval(()=>{w||d(Math.round(u.current*100))},250);return()=>{w=!0,cancelAnimationFrame(S),clearInterval(_),f.current&&(clearTimeout(f.current),f.current=null)}},[i,e]),!i||!e)return null;const b=p?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${n*100}%`}})})}function JT(){const i=At(p=>p.submitCountdownStartAt),e=At(p=>p.submitDelayMs),[n,r]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[i]),i===null)return null;const s=n-i,a=Math.max(0,e-s),u=Math.max(0,Math.min(100,a/e*100)),l=a<500,d=At.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${u}%`}})})})}function uz({open:i,onClose:e,variant:n="overlay"}){return o.jsx(iz,{open:i,onClose:e,title:"Voice / Microphone",variant:n,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(mz,{}),o.jsx(JT,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(w0,{}),o.jsx(XT,{}),o.jsx(lz,{})]}),o.jsx(hz,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>At.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(fz,{})]}),o.jsx(dz,{})]})})}function hz(){const i=At(a=>a.isRecording),[e,n]=z.useState(null);if(z.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||n(l)}).catch(()=>{});const u=window.api.voice.onHotkeyConfigChanged(l=>n(l));return()=>{a=!0,u()}},[]),i||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=pz(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function pz(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function fz(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!i)return null;const n=async r=>{if(i.mode===r)return;const s={...i,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>n("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>n("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function mz(){const i=At(a=>a.isRecording),e=At(a=>a.lastTranscript),n=At(a=>a.error),r=At(a=>a.modelStatus),s=At(a=>a.loadingProgress);return n?o.jsxs("div",{className:"text-[11px] text-red-400",title:n,children:["⚠ ",n]}):i?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Jy=null;function gz(){return Jy||(Jy=Dg(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(a0.config({monaco:i}),i))),Jy}function ZT({value:i,onChange:e,path:n,readOnly:r}){const s=z.useRef(null),a=u=>{s.current=u};return o.jsx(l0,{path:`file://${n}`,defaultLanguage:"json",value:i,onChange:u=>e(u??""),onMount:a,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let Kk=!1;async function vz(i){if(Kk)return;const e=await gz(),n=await Promise.all(i.map(async s=>{let a=s.schema;if(!a){const u=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!u.includes(l))throw new Error("untrusted origin");const d=await fetch(s.uri);d.ok&&(a=await d.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:n.filter(s=>s.schema),enableSchemaRequest:!0}),Kk=!0}function S0({node:i,targetScope:e,onOverride:n,schema:r,rootLabel:s}){const[a,u]=z.useState(""),[l,d]=z.useState(!0),p=[],m=i.kind==="object"&&Object.keys(i.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:vr[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:S=>d(S.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:S=>u(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(QT,{node:i,path:p,label:s??"(root)",targetScope:e,onOverride:n,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function QT(i){return i.node.kind==="object"?o.jsx(xz,{...i,node:i.node}):i.node.kind==="array"?o.jsx(bz,{...i,node:i.node}):o.jsx(yz,{...i,node:i.node})}function Yk(i,e){return e.trim()?i.toLowerCase().includes(e.toLowerCase()):!0}function Ep(i,e,n){return!!(!n.trim()||i.some(r=>Yk(r,n))||e!=null&&e.description&&Yk(e.description,n))}function xz({node:i,path:e,label:n,targetScope:r,onOverride:s,filter:a,depth:u,schema:l,showGhosts:d,defaultOpen:p}){const[m,f]=z.useState(p??u<2),b=(l==null?void 0:l.at(e))??null,S=new Set(Object.keys(i.children)),w=d?(b==null?void 0:b.knownChildren)??[]:[],C=Array.from(new Set([...S,...w])).sort(),x=z.useMemo(()=>a.trim()?C.filter(_=>{const E=(l==null?void 0:l.at([...e,_]))??null;return Ep([...e,_],E,a)?!0:S.has(_)?ej(i.children[_],[...e,_],a,l):!1}):C,[C.join(","),a,i,e.join("."),l]);if(a.trim()&&x.length===0&&!Ep(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(_=>y(_))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:u*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:n}),o.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,w.length>S.size?`/${new Set([...S,...w]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(_=>y(_))]});function y(_){if(S.has(_))return o.jsx(QT,{node:i.children[_],path:[...e,_],label:_,targetScope:r,onOverride:s,filter:a,depth:u+1,schema:l,showGhosts:d},_);const E=(l==null?void 0:l.at([...e,_]))??null;return E?o.jsx(_z,{path:[...e,_],label:_,info:E,targetScope:r,onSet:s,depth:u+1,filter:a},_):null}}function ej(i,e,n,r){const s=(r==null?void 0:r.at(e))??null;if(Ep(e,s,n))return!0;if(i.kind!=="object")return!1;for(const a of Object.keys(i.children))if(ej(i.children[a],[...e,a],n,r))return!0;return!1}function bz({node:i,path:e,label:n,filter:r,depth:s,schema:a}){const[u,l]=z.useState(!0),d=(a==null?void 0:a.at(e))??null;return Ep(e,d,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!u),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:u?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:n}),o.jsxs("span",{className:"text-fg-faint",children:[" [",i.items.length,"]"]}),o.jsx(_g,{tone:"warn",children:"accumulated"}),(d==null?void 0:d.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:d.description,children:["— ",d.description]})]}),u&&i.items.map((p,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:bb(p.value)}),o.jsx(sw,{scope:p.fromScope})]},m))]}):null}function yz({node:i,path:e,label:n,targetScope:r,onOverride:s,filter:a,depth:u,schema:l}){const[d,p]=z.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Ep(e,m,a))return null;const f=i.winner!==r,b=i.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:u*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!d),children:b?d?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[n,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:bb(i.value)}),o.jsx(sw,{scope:i.winner}),(m==null?void 0:m.deprecated)&&o.jsx(_g,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&wz(i.value,m.default)&&o.jsx(_g,{tone:"dim",children:"= default"}),i.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(tj,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,i.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${vr[r].label} draft`:`already winning in ${vr[r].label}`,children:"override"})]}),d&&i.shadowed.map((S,w)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(u+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:bb(S.value)}),o.jsx(sw,{scope:S.scope,dim:!0})]},w))]})}function _z({path:i,label:e,info:n,targetScope:r,onSet:s,depth:a,filter:u}){if(!Ep(i,n,u))return null;const l=n.default!==void 0?n.default:Sz(n.type),d=Array.isArray(n.type)?n.type.join("|"):n.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(_g,{tone:"dim",children:d}),n.required&&o.jsx(_g,{tone:"warn",children:"required"}),n.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",bb(n.default)]}),n.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:n.description,children:["— ",n.description]}),o.jsx("div",{className:"flex-1"}),n.enum&&o.jsx(tj,{values:n.enum}),o.jsx("button",{onClick:()=>s(i,l),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${vr[r].label} draft`,children:"set"})]})}function wz(i,e){return i===e?!0:typeof i!=typeof e?!1:i&&e&&typeof i=="object"?JSON.stringify(i)===JSON.stringify(e):!1}function Sz(i){switch(Array.isArray(i)?i[0]:i){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function bb(i){if(typeof i=="string")return JSON.stringify(i);if(i===null)return"null";if(typeof i=="object"){const e=JSON.stringify(i);return e.length>100?e.slice(0,100)+"…":e}return String(i)}function sw({scope:i,dim:e}){const n=i==="user"?"bg-bg-hi text-fg-dim border-line":i==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${n} ${e?"opacity-60":""}`,children:vr[i].label})}function _g({children:i,tone:e="default"}){const n={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${n}`,children:i})}function tj({values:i}){const e=i.map(n=>String(n)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const kz=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],Cz={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function ij(i){return i.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((r,s)=>{const a=Cz[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function nj(i){const e=new Set,n=[];for(const s of kz){const a=s.keys.filter(u=>i.has(u));a.forEach(u=>e.add(u)),a.length!==0&&n.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(i).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&n.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),n}function Ez(i,e){return nj(i).map(n=>({id:n.id,title:n.title,advanced:n.advanced,total:n.keys.length,setCount:n.keys.filter(r=>e.has(r)).length}))}const Tz={};function rj(i,e){if(e)return{text:e,authored:!1};const n=Tz[i];return n?{text:n,authored:!0}:null}const jz={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},Dz=["user","project","local","default"],Az={user:"user",project:"project",local:"local",default:"default"};function Nz({node:i,targetScope:e,onOverride:n,schema:r}){const[s,a]=z.useState(""),[u,l]=z.useState(!1),[d,p]=z.useState(!0),m=i.kind==="object"?i:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),S=new Set([...f,...b]),w=z.useMemo(()=>nj(S),[Array.from(S).sort().join(",")]),C=z.useMemo(()=>Ez(S,new Set(f)),[Array.from(S).sort().join(","),f.join(",")]),[x,y]=z.useState(null),_=j=>{const D=w.find($=>$.id===j);D!=null&&D.advanced&&!u&&l(!0),y(j)};z.useEffect(()=>{if(!x)return;const j=document.getElementById(`settings-group-${x}`);j&&(j.scrollIntoView({behavior:"smooth",block:"start"}),y(null))});const E=z.useMemo(()=>w.filter(j=>u||!j.advanced).map(j=>({...j,keys:j.keys.filter(D=>{const $=(m==null?void 0:m.children[D])!==void 0;if(!d&&!$)return!1;if(!s.trim())return!0;const I=r.at([D]);return[D,ij(D),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(j=>j.keys.length>0),[w,s,u,d,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:vr[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:j=>p(j.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:u,onChange:j=>l(j.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:j=>a(j.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx($z,{groups:C,onJump:_}),o.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[E.map(j=>o.jsx(Pz,{id:j.id,title:j.title,summary:j.summary,advanced:j.advanced,children:j.keys.map(D=>{const $=m==null?void 0:m.children[D],I=r.at([D]);return o.jsx(Rz,{keyName:D,node:$,info:I,targetScope:e,onOverride:(P,L)=>n([D],P,L)},D)})},j.id)),E.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function $z({groups:i,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:i.map(n=>o.jsxs("button",{onClick:()=>e(n.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${n.title}`,children:[o.jsx(pi,{name:jz[n.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:n.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[n.setCount,"/",n.total]})]},n.id))})}function Pz({id:i,title:e,summary:n,advanced:r,children:s}){const[a,u]=z.useState(!0);return o.jsxs("section",{id:`settings-group-${i}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>u(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:n})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function Rz({keyName:i,node:e,info:n,targetScope:r,onOverride:s}){const[a,u]=z.useState(!1),[l,d]=z.useState(!1),p=ij(i),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,S=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",w=n==null?void 0:n.default,C=b&&w!==void 0&&oj(b.value,w),x=Gz({isSet:m,leafNode:b,defaultVal:w,isDefault:!!C,node:e}),y=Iz(b,w),_=y.length>=2,E=!!b&&!C,j=rj(i,n==null?void 0:n.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>u(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:p}),o.jsx(Uz,{kind:x.kind,label:x.label}),_&&o.jsxs("button",{onClick:D=>{D.stopPropagation(),a||u(!0),d($=>!$)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",y.map(D=>Az[D]).join(" · ")]}),E&&b&&o.jsx("button",{onClick:D=>{D.stopPropagation(),s(void 0,b.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${vr[b.winner].label}`,children:"↺ reset"}),(n==null?void 0:n.deprecated)&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(n==null?void 0:n.required)&&!m&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),j&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${j.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:j.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:Hz(j.text)}),a&&l&&b&&o.jsx(Mz,{leaf:b,defaultVal:w,onReset:D=>s(void 0,D)}),a&&o.jsx(Oz,{keyName:i,node:e,info:n,targetScope:r,onOverride:D=>s(D)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(Fz,{node:e,info:n,onSet:D=>{s(D)},disabled:S&&m})})]})})}function Iz(i,e){if(!i)return[];const n=new Set;n.add(i.winner);for(const r of i.shadowed)n.add(r.scope);return e!==void 0&&n.add("default"),Dz.filter(r=>n.has(r))}function Mz({leaf:i,defaultVal:e,onReset:n}){const r={};r[i.winner]={value:i.value,winner:!0};for(const s of i.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],u=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:vr[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:u?yp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),u?o.jsx("button",{onClick:()=>n(s),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${vr[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?yp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function Oz({keyName:i,node:e,info:n,targetScope:r,onOverride:s}){const u=(e==null?void 0:e.kind)==="leaf"?e:null,l=rj(i,n==null?void 0:n.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(n==null?void 0:n.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(n.type)?n.type.join(" | "):n.type})]}),(n==null?void 0:n.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:yp(n.default)})]}),(n==null?void 0:n.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:n.enum.map(d=>String(d)).join(" | ")})]}),u&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:yp(u.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",vr[u.winner].label]})]})]}),u&&u.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:u.shadowed.map((d,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[yp(d.value)," —"," ",o.jsx("span",{className:"no-underline",children:vr[d.scope].label})]},p))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(Lz,{keyName:i,node:e,info:n,onChange:s,targetScope:r})})]})}function Lz({node:i,info:e,onChange:n,targetScope:r}){const a=(i==null?void 0:i.kind)==="leaf"?i.value:e==null?void 0:e.default,u=sj(e==null?void 0:e.type);if(u==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:d,label:p})=>o.jsx("button",{onClick:()=>n(d),className:`px-3 py-0.5 text-xs transition-colors ${l===d?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",vr[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const d=oj(a,l);return o.jsx("button",{onClick:()=>n(l),className:`px-2 py-0.5 text-xs rounded border ${d?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",vr[r].label]})]}):u==="integer"||u==="number"?o.jsx(zz,{value:typeof a=="number"?a:void 0,integer:u==="integer",onCommit:n,target:vr[r].label}):u==="string"?o.jsx(Bz,{value:typeof a=="string"?a:"",onCommit:n,target:vr[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",u??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function zz({value:i,integer:e,onCommit:n,target:r}){const[s,a]=z.useState(i!==void 0?String(i):""),u=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||n(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:u,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:u,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function Bz({value:i,onCommit:e,target:n}){const[r,s]=z.useState(i);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",n]})]})}function Fz({node:i,info:e,onSet:n,disabled:r}){const s=(i==null?void 0:i.kind)==="leaf",a=sj(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const u=s&&i.value===!0;return o.jsx("button",{onClick:()=>n(!u),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${u?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:u?"on":"off"})}return null}function Gz({isSet:i,leafNode:e,defaultVal:n,isDefault:r,node:s}){return i?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${vr[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${vr[e.winner].label}`}:{kind:"set",label:"configured"}:n!==void 0?{kind:"default",label:`using default: ${yp(n)}`}:{kind:"unset",label:"not configured"}}function Uz({kind:i,label:e}){const n={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[i];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${n}`,children:e})}function sj(i){if(i)return Array.isArray(i)?i.find(n=>n!=="null")??i[0]:i}function oj(i,e){return i===e?!0:typeof i!=typeof e?!1:i&&e&&typeof i=="object"?JSON.stringify(i)===JSON.stringify(e):!1}function Hz(i){const e=i.trim().split(`
|
|
3054
3054
|
`)[0],n=e.match(/^([^.!?]+[.!?])/);return n?n[1]:e.length>120?e.slice(0,120)+"…":e}function yp(i){if(typeof i=="string")return i===""?'""':JSON.stringify(i);if(i===null)return"null";if(i===void 0)return"—";if(typeof i=="object"){const e=JSON.stringify(i);return e.length>60?e.slice(0,60)+"…":e}return String(i)}function k0(i,e,n){const r=li(d=>d.files),s=li(d=>d.loadJson),a=li(d=>d.watchFile),u=li(d=>d.unwatchFile),l=z.useMemo(()=>{const d={};for(const p of i.scopes){const m=i.resolve(p,e??"",n);m&&(d[p]=m)}return d},[i,e,n]);return z.useEffect(()=>{const d=Object.values(l).filter(Boolean);return d.forEach(p=>{r[p]||s(p),a(p)}),()=>{d.forEach(p=>u(p))}},[JSON.stringify(l)]),l}const Wz=[];function vx(i){return Array.isArray(i)?"array":i!==null&&typeof i=="object"?"object":"scalar"}function C0(i){const e=i.filter(n=>n.data!==void 0);return e.length===0?{kind:"object",children:{}}:aj(e,[])}function aj(i,e){const n=Wz.includes(e.join(".")),r=i.every(m=>vx(m.data)==="object"),s=i.every(m=>vx(m.data)==="array");if(r){const m=new Set;for(const b of i)for(const S of Object.keys(b.data))m.add(S);const f={};for(const b of m){const S=i.filter(w=>b in w.data).map(w=>({scope:w.scope,data:w.data[b]}));f[b]=aj(S,[...e,b])}return{kind:"object",children:f}}if(s&&!n){const m=[];for(const f of[...i].reverse())for(const b of f.data)m.push({value:b,fromScope:f.scope,index:m.length});return{kind:"array",items:m}}const a=[...i].reverse(),u=a[0],l=a.slice(1).map(m=>({scope:m.scope,value:m.data})),d=vx(u.data),p=l.some(m=>vx(m.value)!==d);return{kind:"leaf",value:u.data,winner:u.scope,shadowed:l,...p?{typeMismatch:!0}:{}}}function E0(i,e){if(e.length===0)return i;if(i.kind!=="object")return null;const[n,...r]=e,s=i.children[n];return s?E0(s,r):null}function Yb(i,e,n){if(e.length===0)return n;const[r,...s]=e,a=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};return a[r]=Yb(a[r],s,n),a}const Vz=["user","project","local"];function T0(i,e){const n=[];for(const r of Vz){const s=e[r];if(!s)continue;const a=i[s];if(!a||!a.exists)continue;const u=a.draftRaw??"";if(u.trim())try{n.push({scope:r,data:JSON.parse(u)})}catch{}}return n}const qz="http://json-schema.org/draft-07/schema#",Kz="https://json.schemastore.org/claude-code-settings.json",Yz={permissionRule:{type:"string",description:`Tool permission rule.
|
|
3055
3055
|
See https://code.claude.com/docs/en/settings#permission-rule-syntax
|
|
3056
3056
|
See https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.`,pattern:"^((Agent|Bash|Edit|ExitPlanMode|Glob|Grep|KillShell|LSP|NotebookEdit|Read|Skill|TaskCreate|TaskGet|TaskList|TaskOutput|TaskStop|TaskUpdate|TodoWrite|ToolSearch|WebFetch|WebSearch|Write)(\\((?=.*[^)*?])[^)]+\\))?|mcp__.*)$",examples:["Bash","Bash(npm run build)","Bash(git commit *)","Bash(npm run *)","Bash(ls*)","Bash(git * main)","Edit","Edit(/src/**/*.ts)","Read(./.env)","Read(./secrets/**)","Read(//Users/alice/secrets/**)","Read(~/Documents/*.pdf)","Agent(Explore)","WebFetch","WebFetch(domain:example.com)","mcp__puppeteer","mcp__github__search_repositories"]},hookCommand:{anyOf:[{type:"object",description:"Bash command hook",additionalProperties:!1,required:["type","command"],properties:{type:{type:"string",description:"Hook type",const:"command"},command:{type:"string",description:"Shell command to execute",minLength:1},timeout:{type:"number",description:"Optional timeout in seconds",exclusiveMinimum:0},async:{type:"boolean",description:"Run this hook asynchronously without blocking Claude Code"},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"LLM prompt hook. See https://code.claude.com/docs/en/hooks#prompt-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"prompt"},prompt:{type:"string",description:"Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"Agent hook with multi-turn tool access for verification. See https://code.claude.com/docs/en/hooks#agent-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"agent"},prompt:{type:"string",description:"Prompt describing what to verify. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 60)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"HTTP webhook hook. POST JSON to a URL and receive JSON response. See https://code.claude.com/docs/en/hooks#http-hooks",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",description:"Hook type",const:"http"},url:{type:"string",description:"URL to POST hook input JSON to. Endpoint must accept POST requests and return JSON.",minLength:1},headers:{type:"object",additionalProperties:{type:"string"},description:"Custom HTTP headers (e.g., Authorization: Bearer token). Values support $VAR_NAME or ${VAR_NAME} interpolation."},allowedEnvVars:{type:"array",items:{type:"string",minLength:1},description:"List of environment variable names permitted for interpolation in headers. If not set, no env var interpolation is allowed."},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}}]},hookMatcher:{type:"object",description:"Hook matcher configuration with multiple hooks",additionalProperties:!1,required:["hooks"],properties:{matcher:{type:"string",description:"Optional pattern to match event contexts, case-sensitive. Behavior depends on event type. See https://code.claude.com/docs/en/hooks#matcher-patterns for event-specific details and examples"},hooks:{type:"array",description:"Array of hooks to execute",items:{$ref:"#/$defs/hookCommand"}}}}},Xz="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",Jz=!0,Zz=!0,Qz="object",e5=JSON.parse(`{"$schema":{"type":"string","description":"JSON Schema reference for Claude Code settings"},"apiKeyHelper":{"type":"string","description":"Path to a script that outputs authentication values","examples":["/bin/generate_temp_api_key.sh"],"minLength":1},"autoMemoryEnabled":{"type":"boolean","description":"Enable automatic memory saves that capture useful context to .claude/memory/. Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#auto-memory","default":true},"autoUpdatesChannel":{"type":"string","enum":["stable","latest"],"description":"Release channel to follow for updates. Use \\"stable\\" for a version that is typically about one week old and skips versions with major regressions, or \\"latest\\" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable updates entirely.","default":"latest"},"awsCredentialExport":{"type":"string","description":"Path to a script that exports AWS credentials","examples":["/bin/generate_aws_grant.sh"],"minLength":1},"awsAuthRefresh":{"type":"string","description":"Path to a script that refreshes AWS authentication","examples":["aws sso login --profile myprofile"],"minLength":1},"claudeMdExcludes":{"type":"array","items":{"type":"string","minLength":1},"description":"Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claudemd-files","examples":[["**/monorepo/CLAUDE.md","/home/user/monorepo/other-team/.claude/rules/**"]]},"cleanupPeriodDays":{"type":"integer","minimum":0,"description":"Number of days to retain chat transcripts (0 to disable cleanup)","examples":[20,30,60],"default":30},"env":{"type":"object","additionalProperties":false,"description":"Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.\\nUNDOCUMENTED: CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS (plugin marketplace git timeout in ms, default 120000, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2151).\\nUNDOCUMENTED: ENABLE_CLAUDEAI_MCP_SERVERS (set to false to opt out of claude.ai MCP servers, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2163).","examples":[{"ANTHROPIC_MODEL":"claude-opus-4-1","ANTHROPIC_SMALL_FAST_MODEL":"claude-3-5-haiku-latest"}],"default":{},"patternProperties":{"^[A-Z_][A-Z0-9_]*$":{"type":"string","description":"Environment variable value"}}},"attribution":{"type":"object","description":"Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings","additionalProperties":false,"properties":{"commit":{"type":"string","description":"Attribution for git commits, including any trailers. Empty string hides commit attribution"},"pr":{"type":"string","description":"Attribution for pull request descriptions. Empty string hides pull request attribution"}}},"includeGitInstructions":{"type":"boolean","description":"Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings","default":true},"includeCoAuthoredBy":{"type":"boolean","description":"DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)","default":true},"plansDirectory":{"type":"string","description":"Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)","default":"~/.claude/plans","examples":["./plans"]},"respectGitignore":{"type":"boolean","description":"Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions","default":true},"permissions":{"type":"object","properties":{"allow":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for allowed operations","uniqueItems":true},"deny":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for denied operations","uniqueItems":true},"ask":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules that should always prompt for confirmation","uniqueItems":true},"defaultMode":{"type":"string","enum":["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"],"description":"Default permission mode.\\n\\"default\\": prompts on first use.\\n\\"acceptEdits\\": auto-accepts file edits.\\n\\"plan\\": read-only, no modifications.\\nUNDOCUMENTED. \\"delegate\\": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).\\n\\"dontAsk\\": auto-denies unless pre-approved via permissions.\\n\\"bypassPermissions\\": skips all prompts (use only in isolated environments).\\nSee https://code.claude.com/docs/en/permissions"},"disableBypassPermissionsMode":{"type":"string","enum":["disable"],"description":"Disable the ability to bypass permission prompts"},"additionalDirectories":{"type":"array","items":{"type":"string","minLength":1},"description":"Additional directories to include in the permission scope","examples":[["//Users/alice/Documents","~/projects"]],"uniqueItems":true}},"additionalProperties":false,"description":"Tool usage permissions configuration.\\nSee https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings\\nSee https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.","examples":[{"allow":["Bash(git add:*)"],"ask":["Bash(gh pr create:*)","Bash(git commit:*)"],"deny":["Read(*.env)","Bash(rm:*)","Bash(curl:*)"],"defaultMode":"default"}]},"language":{"type":"string","description":"Preferred language for Claude's responses","examples":["japanese","spanish","french"]},"model":{"type":"string","enum":["opus","sonnet","haiku","default"],"description":"Override the default model used by Claude Code. Accepts a short alias (opus|sonnet|haiku) or a full model ID. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config"},"availableModels":{"type":"array","items":{"type":"string"},"description":"Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection","examples":[["sonnet","haiku"]]},"modelOverrides":{"type":"object","additionalProperties":{"type":"string"},"description":"Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version","examples":[{"claude-opus-4-6":"arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"}]},"effortLevel":{"type":"string","enum":["low","medium","high"],"description":"Control Opus 4.6 adaptive reasoning effort. Lower effort is faster and cheaper for straightforward tasks, higher effort provides deeper reasoning. Defaults vary by model and plan (Opus 4.6 defaults to medium for Max and Team subscribers). Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level"},"fastMode":{"type":"boolean","description":"Enable fast mode for Opus 4.6 (research preview). Fast mode uses the same model with 2.5x faster output at higher per-token cost. Requires extra usage enabled. Alternatively, toggle with /fast command. See https://code.claude.com/docs/en/fast-mode","default":false},"fastModePerSessionOptIn":{"type":"boolean","description":"Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode","default":false},"feedbackSurveyRate":{"type":"number","minimum":0,"maximum":1,"description":"Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings","examples":[0.05]},"editorMode":{"type":"string","enum":["normal","vim"],"default":"normal","description":"Editor input mode for the Claude Code terminal prompt. 'vim' enables modal editing (Esc for normal mode, i for insert). See https://code.claude.com/docs/en/settings"},"skillOverrides":{"type":"object","additionalProperties":{"type":"string","enum":["on","name-only","user-invocable-only","off"]},"description":"Per-skill availability override map. Keys are skill names; values are one of 'on' (default), 'name-only' (skill name listed but not auto-loaded), 'user-invocable-only' (load only when user explicitly invokes), or 'off' (hidden). Requires Claude Code v2.1.129+. See https://code.claude.com/docs/en/settings","examples":[{"playwright-debug":"user-invocable-only","init":"off"}]},"disableAgentView":{"type":"boolean","default":false,"description":"Disable the Agent View feature (read-only inspection of sub-agent activity). Useful when administering managed deployments. Requires Claude Code v2.1.139+. See https://code.claude.com/docs/en/settings"},"disableRemoteControl":{"type":"boolean","default":false,"description":"Block the \`claude remote-control\` channel that allows external clients to drive this Claude Code instance. Recommended default for shared/CI environments. Requires Claude Code v2.1.128+. See https://code.claude.com/docs/en/settings"},"enableAllProjectMcpServers":{"type":"boolean","description":"Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp","examples":[true]},"enabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["memory","github"]]},"disabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["filesystem"]]},"allowedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that users are allowed to configure"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"deniedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that is explicitly blocked"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"httpHookAllowedEnvVars":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["MY_TOKEN","HOOK_SECRET"]]},"hooks":{"type":"object","additionalProperties":false,"description":"Custom commands to run before/after tool executions. See https://code.claude.com/docs/en/hooks","examples":[{"PostToolUse":[{"matcher":"Edit|Write","hooks":[{"type":"command","command":"prettier --write","timeout":5}]}]}],"properties":{"PreToolUse":{"type":"array","description":"Hooks that run before tool calls","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUse":{"type":"array","description":"Hooks that run after tool completion","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUseFailure":{"type":"array","description":"Hooks that run after a tool fails","items":{"$ref":"#/$defs/hookMatcher"}},"PermissionRequest":{"type":"array","description":"Hooks that run when a permission dialog appears","items":{"$ref":"#/$defs/hookMatcher"}},"Notification":{"type":"array","description":"Hooks that trigger on notifications","items":{"$ref":"#/$defs/hookMatcher"}},"UserPromptSubmit":{"type":"array","description":"Hooks that run when a user submits a prompt","items":{"$ref":"#/$defs/hookMatcher"}},"Stop":{"type":"array","description":"Hooks that run when agents finish responding. Does not run on user interrupt","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStart":{"type":"array","description":"Hooks that run when a subagent is spawned","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStop":{"type":"array","description":"Hooks that run when subagents finish responding","items":{"$ref":"#/$defs/hookMatcher"}},"PreCompact":{"type":"array","description":"Hooks that run before the context is compacted","items":{"$ref":"#/$defs/hookMatcher"}},"PostCompact":{"type":"array","description":"Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"Elicitation":{"type":"array","description":"Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"ElicitationResult":{"type":"array","description":"Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"TeammateIdle":{"type":"array","description":"Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle","items":{"$ref":"#/$defs/hookMatcher"}},"TaskCompleted":{"type":"array","description":"Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted","items":{"$ref":"#/$defs/hookMatcher"}},"Setup":{"type":"array","description":"UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)","items":{"$ref":"#/$defs/hookMatcher"}},"InstructionsLoaded":{"type":"array","description":"Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded","items":{"$ref":"#/$defs/hookMatcher"}},"ConfigChange":{"type":"array","description":"Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeCreate":{"type":"array","description":"Hooks that run when a worktree is created via --worktree or isolation: \\"worktree\\" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeRemove":{"type":"array","description":"Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove","items":{"$ref":"#/$defs/hookMatcher"}},"SessionStart":{"type":"array","description":"Hooks that run when a new session starts","items":{"$ref":"#/$defs/hookMatcher"}},"SessionEnd":{"type":"array","description":"Hooks that run when a session ends","items":{"$ref":"#/$defs/hookMatcher"}}}},"disableAllHooks":{"type":"boolean","description":"Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks"},"allowedHttpHookUrls":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["https://hooks.example.com/*","http://localhost:*"]]},"allowManagedHooksOnly":{"type":"boolean","description":"(Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration"},"allowManagedPermissionRulesOnly":{"type":"boolean","description":"(Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings"},"statusLine":{"type":"object","properties":{"type":{"type":"string","description":"The type of status line handler; must be set to \\"command\\" to run a custom shell script that receives JSON session data via stdin.","const":"command"},"command":{"type":"string","description":"A shell command or path to a script that displays session information (context usage, costs, git status, etc.) by reading JSON data from stdin and writing output to stdout. See https://code.claude.com/docs/en/statusline"},"padding":{"type":"number","description":"Optional number of extra horizontal spacing characters added to the status line content; defaults to 0."}},"required":["type","command"],"additionalProperties":false,"description":"Custom status line display configuration. See https://code.claude.com/docs/en/statusline","examples":[{"type":"command","command":"~/.claude/statusline.sh"}]},"fileSuggestion":{"type":"object","properties":{"type":{"type":"string","description":"The type of file suggestion handler; must be set to \\"command\\" to execute a custom shell script that generates file suggestions for the @ file picker.","const":"command"},"command":{"type":"string","description":"Shell command to execute for file suggestions"}},"required":["type","command"],"additionalProperties":false,"description":"Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings","examples":[{"type":"command","command":"~/.claude/file-suggestion.sh"}]},"enabledPlugins":{"type":"object","additionalProperties":{"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"boolean"},{"not":{}}]},"description":"Enabled plugins using plugin-id@marketplace-id format. Example: { \\"formatter@anthropic-tools\\": true }. See https://code.claude.com/docs/en/plugins"},"extraKnownMarketplaces":{"type":"object","additionalProperties":{"type":"object","properties":{"source":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","pattern":"\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false}],"description":"Where to fetch the marketplace from"},"installLocation":{"type":"string","description":"Local cache path where marketplace manifest is stored (auto-generated if not provided)"}},"required":["source"],"additionalProperties":false},"description":"Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces"},"strictKnownMarketplaces":{"type":"array","description":"(Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/settings#strictknownmarketplaces","items":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"HTTP headers for authenticated access"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package name (supports scoped packages)"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Absolute path to marketplace.json file"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Absolute path to directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"pathPattern"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"],"additionalProperties":false}]},"examples":[[{"source":"github","repo":"acme-corp/approved-plugins"},{"source":"npm","package":"@acme-corp/compliance-plugins"}]]},"skippedMarketplaces":{"type":"array","items":{"type":"string","minLength":1},"description":"List of marketplace names the user has chosen not to install when prompted"},"skippedPlugins":{"type":"array","items":{"type":"string","minLength":1},"description":"List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted"},"forceLoginMethod":{"type":"string","enum":["claudeai","console"],"description":"Force a specific login method: \\"claudeai\\" for Claude Pro/Max, \\"console\\" for Console billing","examples":["claudeai"]},"forceLoginOrgUUID":{"type":"string","description":"Organization UUID to use for OAuth login","examples":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"],"minLength":1},"otelHeadersHelper":{"type":"string","description":"Path to a script that outputs OpenTelemetry headers","minLength":1},"outputStyle":{"type":"string","description":"Controls the output style for assistant responses. Built-in styles: default, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles","examples":["default","Explanatory","Learning"],"minLength":1},"skipWebFetchPreflight":{"type":"boolean","description":"Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"},"sandbox":{"type":"object","description":"Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing","properties":{"network":{"type":"object","description":"Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.","properties":{"allowUnixSockets":{"type":"array","items":{"type":"string"},"description":"Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified"},"allowLocalBinding":{"type":"boolean","description":"Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified"},"httpProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"socksProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"allowAllUnixSockets":{"type":"boolean","description":"Allow all Unix domain socket connections. If true, this overrides allowUnixSockets"},"allowedDomains":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com"},"allowManagedDomainsOnly":{"type":"boolean","description":"(Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts."}},"additionalProperties":false},"ignoreViolations":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"},"description":"List of filesystem paths to ignore sandbox violations for when this command pattern matches"},"description":"Map of command patterns to filesystem paths to ignore violations for. Use \\"*\\" to match all commands"},"excludedCommands":{"type":"array","items":{"type":"string"},"description":"Commands that should never run in the sandbox (e.g., [\\"git\\", \\"docker\\"])"},"autoAllowBashIfSandboxed":{"type":"boolean","description":"Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed.","default":true},"enableWeakerNetworkIsolation":{"type":"boolean","description":"macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/settings#sandbox-settings","default":false},"enableWeakerNestedSandbox":{"type":"boolean","description":"Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable.Default: false (secure)."},"allowUnsandboxedCommands":{"type":"boolean","description":"Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."},"enabled":{"type":"boolean","description":"Enable sandboxed bash"},"filesystem":{"type":"object","description":"Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation","properties":{"allowWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path)"},"denyWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite"},"denyRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied read access"},"allowRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths"},"allowManagedReadPathsOnly":{"type":"boolean","description":"When true (managed settings only), only allowRead paths from managed settings are used"}},"additionalProperties":false}},"additionalProperties":false},"spinnerVerbs":{"type":"object","description":"Customize the verbs shown in spinner progress messages","properties":{"mode":{"type":"string","enum":["append","replace"],"description":"How to combine custom verbs with default spinner verbs: 'append' adds custom verbs to the default list, 'replace' uses only custom verbs"},"verbs":{"type":"array","items":{"type":"string","minLength":1},"minItems":1,"description":"Custom verbs used in spinner progress text"}},"required":["verbs"],"additionalProperties":false},"spinnerTipsEnabled":{"type":"boolean","description":"Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)","default":true},"spinnerTipsOverride":{"type":"object","description":"Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings","properties":{"excludeDefault":{"type":"boolean","description":"If true, only show custom tips. If false or absent, custom tips merge with built-in tips","default":false},"tips":{"type":"array","items":{"type":"string","minLength":1},"description":"Custom tip strings to display in the spinner","minItems":1}},"required":["tips"],"additionalProperties":false},"terminalProgressBarEnabled":{"type":"boolean","description":"Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)","default":true},"showTurnDuration":{"type":"boolean","description":"Show turn duration messages after responses (e.g., \\"Cooked for 1m 6s\\"). Set to false to hide these messages (default: true)","default":true},"prefersReducedMotion":{"type":"boolean","description":"Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility","default":false},"alwaysThinkingEnabled":{"type":"boolean","description":"Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode"},"companyAnnouncements":{"type":"array","items":{"type":"string","minLength":1},"description":"Company announcements to display at startup (one will be randomly selected if multiple are provided)"},"teammateMode":{"type":"string","enum":["auto","in-process","tmux"],"description":"How agent team teammates display: \\"auto\\" picks split panes in tmux or iTerm2, in-process otherwise. Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams","default":"auto"},"worktree":{"type":"object","additionalProperties":false,"description":"Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings","properties":{"sparsePaths":{"type":"array","items":{"type":"string","minLength":1},"description":"Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos.","examples":[["packages/my-app","shared/utils"]]}}},"pluginTrustMessage":{"type":"string","description":"(Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings","minLength":1},"pluginConfigs":{"type":"object","additionalProperties":{"type":"object","properties":{"mcpServers":{"type":"object","additionalProperties":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"array","items":{"type":"string"}}]}},"description":"User configuration values for MCP servers keyed by server name"}},"additionalProperties":false},"description":"Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins"},"allowManagedMcpServersOnly":{"type":"boolean","description":"(Managed settings only) Only allowedMcpServers from managed settings are respected. deniedMcpServers still merges from all sources. Users can still add their own MCP servers, but only the admin-defined allowlist applies."},"blockedMarketplaces":{"type":"array","description":"(Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"url","description":"Block marketplace fetched from direct URL"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Custom HTTP headers (e.g., for authentication)"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"github","description":"Block marketplace from GitHub repository"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","repo"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"git","description":"Block marketplace from git repository URL"},"url":{"type":"string","pattern":".*\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"npm","description":"Block marketplace from NPM package"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"file","description":"Block marketplace from local file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"directory","description":"Block marketplace from local directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"hostPattern","description":"Block marketplace by host pattern matching"},"hostPattern":{"type":"string","description":"Regex pattern to match the host/domain extracted from any marketplace source type"}},"required":["source","hostPattern"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"pathPattern","description":"Block marketplace by file/directory path pattern matching"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"]}]}}}`),t5="Claude Code Settings",i5={$schema:qz,$id:Kz,$defs:Yz,description:Xz,allowTrailingCommas:Jz,additionalProperties:Zz,type:Qz,properties:e5,title:t5};function n5(i){const e=i??{},n={...e.$defs??{},...e.definitions??{}},r=S=>{if(!S)return{};if(!S.$ref)return u(S);const w=/^#\/(\$defs|definitions)\/(.+)$/.exec(S.$ref);if(!w)return u(S);const C=n[w[2]];return C?r({...C,...l(S)}):u(S)},s=new Set(["__proto__","constructor","prototype"]),a=S=>{if(!S)return{};const w={};for(const[C,x]of Object.entries(S))s.has(C)||(w[C]=x);return w},u=S=>{if(!S.allOf||S.allOf.length===0)return S;const w={...S};delete w.allOf;for(const C of S.allOf){const x=r(C);Object.assign(w,{properties:{...a(w.properties),...a(x.properties)},required:r5([...w.required??[],...x.required??[]])}),!w.description&&x.description&&(w.description=x.description),w.default===void 0&&x.default!==void 0&&(w.default=x.default),!w.type&&x.type&&(w.type=x.type)}return w},l=S=>{const{$ref:w,...C}=S;return C},d=(S,w)=>{let C=r(S);for(const x of w){if(!C)return null;if(/^\d+$/.test(x)){const E=Array.isArray(C.items)?C.items[Number(x)]:C.items;C=E?r(E):null;continue}const y=C.properties;if(y&&!s.has(x)&&x in y){C=r(y[x]);continue}const _=C.additionalProperties;if(_&&typeof _=="object"){C=r(_);continue}return null}return C},p=(S,w,C)=>{if(!S)return null;const x={};if(S.description&&(x.description=S.description),S.type&&(x.type=S.type),S.default!==void 0&&(x.default=S.default),S.enum&&(x.enum=S.enum),S.const!==void 0&&(x.const=S.const),S.deprecated&&(x.deprecated=!0),S.examples&&(x.examples=S.examples),S.properties&&(x.knownChildren=Object.keys(S.properties)),C&&(w!=null&&w.includes(C))&&(x.required=!0),S.items&&!Array.isArray(S.items)){const y=r(S.items),_=p(y,void 0,null);_&&(x.itemsInfo=_)}return(S.additionalProperties===!0||typeof S.additionalProperties=="object")&&(x.open=!0),x},m=S=>w=>{if(w.length===0)return p(r(S),void 0,null);const C=d(S,w.slice(0,-1));if(!C)return null;const x=w[w.length-1],y=d(C,[x]);return p(y,C.required,x)},f=S=>{const w=r(S);return Object.keys(w.properties??{})},b=S=>({at:m(S),rootKeys:()=>f(S),rootedAt:w=>{const C=d(S,w);return b(C??{})}});return b(e)}function r5(i){return Array.from(new Set(i))}let Zy=null;function yb(){return Zy||(Zy=n5(i5)),Zy}function s5(){const[i,e]=z.useState(null),[n,r]=z.useState(null),[s,a]=z.useState(null),[u,l]=z.useState(null),[d,p]=z.useState(!1),[m,f]=z.useState(null),[b,S]=z.useState(null);if(z.useEffect(()=>{let _=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([E,j,D])=>{_||(e(E),a(E),r(j),l(D))}).catch(E=>{console.warn("[telemetry] load failed:",E==null?void 0:E.message)}),()=>{_=!0}},[]),!s||!i)return o.jsx(Kt,{title:"loading…"});const w=JSON.stringify(s)!==JSON.stringify(i),C=(_,E)=>{f(null),a({...s,[_]:E})},x=async()=>{p(!0),f(null);try{const _=await window.api.otel.setConfig(s);!_.ok&&_.error&&f(_.error),e(_.config),a(_.config),r(_.status),S(Date.now())}catch(_){f(_ instanceof Error?_.message:String(_))}finally{p(!1)}},y=()=>{f(null),a(i)};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Telemetry — OpenTelemetry export"}),o.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"When enabled, every classified transcript event (tool_use, todo_write, plan, usage, agent_spawn) is mirrored as a 0-duration OTLP/HTTP span. Point this at a local collector (Jaeger, Grafana Tempo, SigNoz, Honeycomb) for cross-session analysis."}),u&&o.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",o.jsx("span",{className:"font-mono",children:u})]})]}),o.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),o.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),o.jsx(cb,{checked:s.enabled,onChange:_=>C("enabled",_),label:s.enabled?"on":"off"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),o.jsx("input",{type:"text",value:s.endpoint,onChange:_=>C("endpoint",_.target.value),placeholder:"http://localhost:4318/v1/traces",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",o.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),o.jsx("textarea",{value:s.headers,onChange:_=>C("headers",_.target.value),placeholder:"x-honeycomb-team: YOUR_API_KEY",rows:3,className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),o.jsx("input",{type:"text",value:s.serviceName,onChange:_=>C("serviceName",_.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Include content (PII)"}),o.jsxs("div",{className:"text-fg-faint text-xs leading-relaxed",children:["Adds tool inputs, plan text, and agent prompts to span attributes. Off by default — matches upstream Claude Code's ",o.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),o.jsx(cb,{checked:s.includeContent,onChange:_=>C("includeContent",_),label:s.includeContent?"on":"off"})]})]}),n&&o.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[o.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),o.jsxs("div",{children:[o.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",o.jsx("span",{className:n.enabled?"text-accent":"text-fg-dim",children:String(n.enabled)})]}),n.error&&o.jsxs("div",{className:"text-red-400 break-words",children:[o.jsx("span",{className:"text-fg-faint",children:"error:"})," ",n.error]}),!n.error&&n.enabled&&o.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),o.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[o.jsx("button",{onClick:x,disabled:!w||d,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:d?"saving…":"Save"}),o.jsx("button",{onClick:y,disabled:!w||d,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert"}),m&&o.jsx("span",{className:"text-red-400 text-xs",children:m}),!m&&b&&!w&&o.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function o5(){const{model:i,setModel:e}=zA();return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Session Manager preferences"}),o.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"Native app preferences, stored locally — not part of Claude Code's own settings."})]}),o.jsx("section",{className:"border border-line rounded p-3 space-y-3",children:o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Default model for raw sessions"}),o.jsx("select",{value:i,onChange:n=>e(n.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:Vw.map(n=>o.jsx("option",{value:n,children:n.charAt(0).toUpperCase()+n.slice(1)},n))}),o.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function a5(){const i=zn(),e=Ct(D=>D.tabs),n=Ct(D=>D.activeTabId),r=e.find(D=>D.id===n)??null,s=(r==null?void 0:r.cwd)??null,[a,u]=z.useState("user"),[l,d]=z.useState("effective"),p=k0(lb,i,s),m=p[a]??null,f=li(D=>D.files),b=li(D=>D.setDraft),S=li(D=>D.saveJson),w=li(D=>D.revert),[C,x]=z.useState(null),y=z.useMemo(()=>C0(T0(f,p)),[f,p]),_=(D,$,I)=>{var X;const L=p[I??a];if(!L)return;x(null);const B=((X=f[L])==null?void 0:X.draftRaw)??"";let U={};if(B.trim())try{U=JSON.parse(B)}catch{U={}}const Z=Yb(U,D,$);b(L,JSON.stringify(Z,null,2)+`
|
|
@@ -3166,13 +3166,13 @@ WARNING: This link could potentially be dangerous`)){const y=window.open();if(y)
|
|
|
3166
3166
|
`:`
|
|
3167
3167
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(P){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),y.isLinux&&P&&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(P){const L=this._getMouseBufferCoords(P),B=this._model.finalSelectionStart,U=this._model.finalSelectionEnd;return!!(B&&U&&L)&&this._areCoordsInSelection(L,B,U)}isCellInSelection(P,L){const B=this._model.finalSelectionStart,U=this._model.finalSelectionEnd;return!(!B||!U)&&this._areCoordsInSelection([P,L],B,U)}_areCoordsInSelection(P,L,B){return P[1]>L[1]&&P[1]<B[1]||L[1]===B[1]&&P[1]===L[1]&&P[0]>=L[0]&&P[0]<B[0]||L[1]<B[1]&&P[1]===B[1]&&P[0]<B[0]||L[1]<B[1]&&P[1]===L[1]&&P[0]>=L[0]}_selectWordAtCursor(P,L){var Z,X;const B=(X=(Z=this._linkifier.currentLink)==null?void 0:Z.link)==null?void 0:X.range;if(B)return this._model.selectionStart=[B.start.x-1,B.start.y-1],this._model.selectionStartLength=(0,_.getRangeLength)(B,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const U=this._getMouseBufferCoords(P);return!!U&&(this._selectWordAt(U,L),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(P,L){this._model.clearSelection(),P=Math.max(P,0),L=Math.min(L,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,P],this._model.selectionEnd=[this._bufferService.cols,L],this.refresh(),this._onSelectionChange.fire()}_handleTrim(P){this._model.handleTrim(P)&&this.refresh()}_getMouseBufferCoords(P){const L=this._mouseService.getCoords(P,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(L)return L[0]--,L[1]--,L[1]+=this._bufferService.buffer.ydisp,L}_getMouseEventScrollAmount(P){let L=(0,f.getCoordsRelativeToElement)(this._coreBrowserService.window,P,this._screenElement)[1];const B=this._renderService.dimensions.css.canvas.height;return L>=0&&L<=B?0:(L>B&&(L-=B),L=Math.min(Math.max(L,-50),50),L/=50,L/Math.abs(L)+Math.round(14*L))}shouldForceSelection(P){return y.isMac?P.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:P.shiftKey}handleMouseDown(P){if(this._mouseDownTimeStamp=P.timeStamp,(P.button!==2||!this.hasSelection)&&P.button===0){if(!this._enabled){if(!this.shouldForceSelection(P))return;P.stopPropagation()}P.preventDefault(),this._dragScrollAmount=0,this._enabled&&P.shiftKey?this._handleIncrementalClick(P):P.detail===1?this._handleSingleClick(P):P.detail===2?this._handleDoubleClick(P):P.detail===3&&this._handleTripleClick(P),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(P){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(P))}_handleSingleClick(P){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(P)?3:0,this._model.selectionStart=this._getMouseBufferCoords(P),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const L=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);L&&L.length!==this._model.selectionStart[0]&&L.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(P){this._selectWordAtCursor(P,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(P){const L=this._getMouseBufferCoords(P);L&&(this._activeSelectionMode=2,this._selectLineAt(L[1]))}shouldColumnSelect(P){return P.altKey&&!(y.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(P){if(P.stopImmediatePropagation(),!this._model.selectionStart)return;const L=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(P),!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(P),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const B=this._bufferService.buffer;if(this._model.selectionEnd[1]<B.lines.length){const U=B.lines.get(this._model.selectionEnd[1]);U&&U.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}L&&L[0]===this._model.selectionEnd[0]&&L[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 P=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(P.ydisp+this._bufferService.rows,P.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=P.ydisp),this.refresh()}}_handleMouseUp(P){const L=P.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&L<500&&P.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const B=this._mouseService.getCoords(P,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(B&&B[0]!==void 0&&B[1]!==void 0){const U=(0,b.moveToCellSequence)(B[0]-1,B[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(U,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const P=this._model.finalSelectionStart,L=this._model.finalSelectionEnd,B=!(!P||!L||P[0]===L[0]&&P[1]===L[1]);B?P&&L&&(this._oldSelectionStart&&this._oldSelectionEnd&&P[0]===this._oldSelectionStart[0]&&P[1]===this._oldSelectionStart[1]&&L[0]===this._oldSelectionEnd[0]&&L[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(P,L,B)):this._oldHasSelection&&this._fireOnSelectionChange(P,L,B)}_fireOnSelectionChange(P,L,B){this._oldSelectionStart=P,this._oldSelectionEnd=L,this._oldHasSelection=B,this._onSelectionChange.fire()}_handleBufferActivate(P){this.clearSelection(),this._trimListener.dispose(),this._trimListener=P.activeBuffer.lines.onTrim((L=>this._handleTrim(L)))}_convertViewportColToCharacterIndex(P,L){let B=L;for(let U=0;L>=U;U++){const Z=P.loadCell(U,this._workCell).getChars().length;this._workCell.getWidth()===0?B--:Z>1&&L!==U&&(B+=Z-1)}return B}setSelection(P,L,B){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[P,L],this._model.selectionStartLength=B,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(P){this._isClickInSelection(P)||(this._selectWordAtCursor(P,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(P,L,B=!0,U=!0){if(P[0]>=this._bufferService.cols)return;const Z=this._bufferService.buffer,X=Z.lines.get(P[1]);if(!X)return;const W=Z.translateBufferLineToString(P[1],!1);let J=this._convertViewportColToCharacterIndex(X,P[0]),te=J;const le=P[0]-J;let ue=0,V=0,ie=0,K=0;if(W.charAt(J)===" "){for(;J>0&&W.charAt(J-1)===" ";)J--;for(;te<W.length&&W.charAt(te+1)===" ";)te++}else{let be=P[0],je=P[0];X.getWidth(be)===0&&(ue++,be--),X.getWidth(je)===2&&(V++,je++);const Te=X.getString(je).length;for(Te>1&&(K+=Te-1,te+=Te-1);be>0&&J>0&&!this._isCharWordSeparator(X.loadCell(be-1,this._workCell));){X.loadCell(be-1,this._workCell);const ve=this._workCell.getChars().length;this._workCell.getWidth()===0?(ue++,be--):ve>1&&(ie+=ve-1,J-=ve-1),J--,be--}for(;je<X.length&&te+1<W.length&&!this._isCharWordSeparator(X.loadCell(je+1,this._workCell));){X.loadCell(je+1,this._workCell);const ve=this._workCell.getChars().length;this._workCell.getWidth()===2?(V++,je++):ve>1&&(K+=ve-1,te+=ve-1),te++,je++}}te++;let se=J+le-ue+ie,oe=Math.min(this._bufferService.cols,te-J+ue+V-ie-K);if(L||W.slice(J,te).trim()!==""){if(B&&se===0&&X.getCodePoint(0)!==32){const be=Z.lines.get(P[1]-1);if(be&&X.isWrapped&&be.getCodePoint(this._bufferService.cols-1)!==32){const je=this._getWordAt([this._bufferService.cols-1,P[1]-1],!1,!0,!1);if(je){const Te=this._bufferService.cols-je.start;se-=Te,oe+=Te}}}if(U&&se+oe===this._bufferService.cols&&X.getCodePoint(this._bufferService.cols-1)!==32){const be=Z.lines.get(P[1]+1);if(be!=null&&be.isWrapped&&be.getCodePoint(0)!==32){const je=this._getWordAt([0,P[1]+1],!1,!1,!0);je&&(oe+=je.length)}}return{start:se,length:oe}}}_selectWordAt(P,L){const B=this._getWordAt(P,L);if(B){for(;B.start<0;)B.start+=this._bufferService.cols,P[1]--;this._model.selectionStart=[B.start,P[1]],this._model.selectionStartLength=B.length}}_selectToWordAt(P){const L=this._getWordAt(P,!0);if(L){let B=P[1];for(;L.start<0;)L.start+=this._bufferService.cols,B--;if(!this._model.areSelectionValuesReversed())for(;L.start+L.length>this._bufferService.cols;)L.length-=this._bufferService.cols,B++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?L.start:L.start+L.length,B]}}_isCharWordSeparator(P){return P.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(P.getChars())>=0}_selectLineAt(P){const L=this._bufferService.buffer.getWrappedRangeForLine(P),B={start:{x:0,y:L.first},end:{x:this._bufferService.cols-1,y:L.last}};this._model.selectionStart=[0,L.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,_.getRangeLength)(B,this._bufferService.cols)}};l.SelectionService=I=p([m(3,j.IBufferService),m(4,j.ICoreService),m(5,w.IMouseService),m(6,j.IOptionsService),m(7,w.IRenderService),m(8,w.ICoreBrowserService)],I)},4725:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ILinkProviderService=l.IThemeService=l.ICharacterJoinerService=l.ISelectionService=l.IRenderService=l.IMouseService=l.ICoreBrowserService=l.ICharSizeService=void 0;const p=d(8343);l.ICharSizeService=(0,p.createDecorator)("CharSizeService"),l.ICoreBrowserService=(0,p.createDecorator)("CoreBrowserService"),l.IMouseService=(0,p.createDecorator)("MouseService"),l.IRenderService=(0,p.createDecorator)("RenderService"),l.ISelectionService=(0,p.createDecorator)("SelectionService"),l.ICharacterJoinerService=(0,p.createDecorator)("CharacterJoinerService"),l.IThemeService=(0,p.createDecorator)("ThemeService"),l.ILinkProviderService=(0,p.createDecorator)("LinkProviderService")},6731:function(u,l,d){var p=this&&this.__decorate||function(I,P,L,B){var U,Z=arguments.length,X=Z<3?P:B===null?B=Object.getOwnPropertyDescriptor(P,L):B;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")X=Reflect.decorate(I,P,L,B);else for(var W=I.length-1;W>=0;W--)(U=I[W])&&(X=(Z<3?U(X):Z>3?U(P,L,X):U(P,L))||X);return Z>3&&X&&Object.defineProperty(P,L,X),X},m=this&&this.__param||function(I,P){return function(L,B){P(L,B,I)}};Object.defineProperty(l,"__esModule",{value:!0}),l.ThemeService=l.DEFAULT_ANSI_COLORS=void 0;const f=d(7239),b=d(8055),S=d(8460),w=d(844),C=d(2585),x=b.css.toColor("#ffffff"),y=b.css.toColor("#000000"),_=b.css.toColor("#ffffff"),E=b.css.toColor("#000000"),j={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};l.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const I=[b.css.toColor("#2e3436"),b.css.toColor("#cc0000"),b.css.toColor("#4e9a06"),b.css.toColor("#c4a000"),b.css.toColor("#3465a4"),b.css.toColor("#75507b"),b.css.toColor("#06989a"),b.css.toColor("#d3d7cf"),b.css.toColor("#555753"),b.css.toColor("#ef2929"),b.css.toColor("#8ae234"),b.css.toColor("#fce94f"),b.css.toColor("#729fcf"),b.css.toColor("#ad7fa8"),b.css.toColor("#34e2e2"),b.css.toColor("#eeeeec")],P=[0,95,135,175,215,255];for(let L=0;L<216;L++){const B=P[L/36%6|0],U=P[L/6%6|0],Z=P[L%6];I.push({css:b.channels.toCss(B,U,Z),rgba:b.channels.toRgba(B,U,Z)})}for(let L=0;L<24;L++){const B=8+10*L;I.push({css:b.channels.toCss(B,B,B),rgba:b.channels.toRgba(B,B,B)})}return I})());let D=l.ThemeService=class extends w.Disposable{get colors(){return this._colors}constructor(I){super(),this._optionsService=I,this._contrastCache=new f.ColorContrastCache,this._halfContrastCache=new f.ColorContrastCache,this._onChangeColors=this.register(new S.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:x,background:y,cursor:_,cursorAccent:E,selectionForeground:void 0,selectionBackgroundTransparent:j,selectionBackgroundOpaque:b.color.blend(y,j),selectionInactiveBackgroundTransparent:j,selectionInactiveBackgroundOpaque:b.color.blend(y,j),ansi:l.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(I={}){const P=this._colors;if(P.foreground=$(I.foreground,x),P.background=$(I.background,y),P.cursor=$(I.cursor,_),P.cursorAccent=$(I.cursorAccent,E),P.selectionBackgroundTransparent=$(I.selectionBackground,j),P.selectionBackgroundOpaque=b.color.blend(P.background,P.selectionBackgroundTransparent),P.selectionInactiveBackgroundTransparent=$(I.selectionInactiveBackground,P.selectionBackgroundTransparent),P.selectionInactiveBackgroundOpaque=b.color.blend(P.background,P.selectionInactiveBackgroundTransparent),P.selectionForeground=I.selectionForeground?$(I.selectionForeground,b.NULL_COLOR):void 0,P.selectionForeground===b.NULL_COLOR&&(P.selectionForeground=void 0),b.color.isOpaque(P.selectionBackgroundTransparent)&&(P.selectionBackgroundTransparent=b.color.opacity(P.selectionBackgroundTransparent,.3)),b.color.isOpaque(P.selectionInactiveBackgroundTransparent)&&(P.selectionInactiveBackgroundTransparent=b.color.opacity(P.selectionInactiveBackgroundTransparent,.3)),P.ansi=l.DEFAULT_ANSI_COLORS.slice(),P.ansi[0]=$(I.black,l.DEFAULT_ANSI_COLORS[0]),P.ansi[1]=$(I.red,l.DEFAULT_ANSI_COLORS[1]),P.ansi[2]=$(I.green,l.DEFAULT_ANSI_COLORS[2]),P.ansi[3]=$(I.yellow,l.DEFAULT_ANSI_COLORS[3]),P.ansi[4]=$(I.blue,l.DEFAULT_ANSI_COLORS[4]),P.ansi[5]=$(I.magenta,l.DEFAULT_ANSI_COLORS[5]),P.ansi[6]=$(I.cyan,l.DEFAULT_ANSI_COLORS[6]),P.ansi[7]=$(I.white,l.DEFAULT_ANSI_COLORS[7]),P.ansi[8]=$(I.brightBlack,l.DEFAULT_ANSI_COLORS[8]),P.ansi[9]=$(I.brightRed,l.DEFAULT_ANSI_COLORS[9]),P.ansi[10]=$(I.brightGreen,l.DEFAULT_ANSI_COLORS[10]),P.ansi[11]=$(I.brightYellow,l.DEFAULT_ANSI_COLORS[11]),P.ansi[12]=$(I.brightBlue,l.DEFAULT_ANSI_COLORS[12]),P.ansi[13]=$(I.brightMagenta,l.DEFAULT_ANSI_COLORS[13]),P.ansi[14]=$(I.brightCyan,l.DEFAULT_ANSI_COLORS[14]),P.ansi[15]=$(I.brightWhite,l.DEFAULT_ANSI_COLORS[15]),I.extendedAnsi){const L=Math.min(P.ansi.length-16,I.extendedAnsi.length);for(let B=0;B<L;B++)P.ansi[B+16]=$(I.extendedAnsi[B],l.DEFAULT_ANSI_COLORS[B+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(I){this._restoreColor(I),this._onChangeColors.fire(this.colors)}_restoreColor(I){if(I!==void 0)switch(I){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[I]=this._restoreColors.ansi[I]}else for(let P=0;P<this._restoreColors.ansi.length;++P)this._colors.ansi[P]=this._restoreColors.ansi[P]}modifyColors(I){I(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 $(I,P){if(I!==void 0)try{return b.css.toColor(I)}catch{}return P}l.ThemeService=D=p([m(0,C.IOptionsService)],D)},6349:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CircularList=void 0;const p=d(8460),m=d(844);class f extends m.Disposable{constructor(S){super(),this._maxLength=S,this.onDeleteEmitter=this.register(new p.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new p.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new p.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(S){if(this._maxLength===S)return;const w=new Array(S);for(let C=0;C<Math.min(S,this.length);C++)w[C]=this._array[this._getCyclicIndex(C)];this._array=w,this._maxLength=S,this._startIndex=0}get length(){return this._length}set length(S){if(S>this._length)for(let w=this._length;w<S;w++)this._array[w]=void 0;this._length=S}get(S){return this._array[this._getCyclicIndex(S)]}set(S,w){this._array[this._getCyclicIndex(S)]=w}push(S){this._array[this._getCyclicIndex(this._length)]=S,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(S,w,...C){if(w){for(let x=S;x<this._length-w;x++)this._array[this._getCyclicIndex(x)]=this._array[this._getCyclicIndex(x+w)];this._length-=w,this.onDeleteEmitter.fire({index:S,amount:w})}for(let x=this._length-1;x>=S;x--)this._array[this._getCyclicIndex(x+C.length)]=this._array[this._getCyclicIndex(x)];for(let x=0;x<C.length;x++)this._array[this._getCyclicIndex(S+x)]=C[x];if(C.length&&this.onInsertEmitter.fire({index:S,amount:C.length}),this._length+C.length>this._maxLength){const x=this._length+C.length-this._maxLength;this._startIndex+=x,this._length=this._maxLength,this.onTrimEmitter.fire(x)}else this._length+=C.length}trimStart(S){S>this._length&&(S=this._length),this._startIndex+=S,this._length-=S,this.onTrimEmitter.fire(S)}shiftElements(S,w,C){if(!(w<=0)){if(S<0||S>=this._length)throw new Error("start argument out of range");if(S+C<0)throw new Error("Cannot shift elements in list beyond index 0");if(C>0){for(let y=w-1;y>=0;y--)this.set(S+y+C,this.get(S+y));const x=S+w+C-this._length;if(x>0)for(this._length+=x;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let x=0;x<w;x++)this.set(S+x+C,this.get(S+x))}}_getCyclicIndex(S){return(this._startIndex+S)%this._maxLength}}l.CircularList=f},1439:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.clone=void 0,l.clone=function d(p,m=5){if(typeof p!="object")return p;const f=Array.isArray(p)?[]:{};for(const b in p)f[b]=m<=1?p[b]:p[b]&&d(p[b],m-1);return f}},8055:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.contrastRatio=l.toPaddedHex=l.rgba=l.rgb=l.css=l.color=l.channels=l.NULL_COLOR=void 0;let d=0,p=0,m=0,f=0;var b,S,w,C,x;function y(E){const j=E.toString(16);return j.length<2?"0"+j:j}function _(E,j){return E<j?(j+.05)/(E+.05):(E+.05)/(j+.05)}l.NULL_COLOR={css:"#00000000",rgba:0},(function(E){E.toCss=function(j,D,$,I){return I!==void 0?`#${y(j)}${y(D)}${y($)}${y(I)}`:`#${y(j)}${y(D)}${y($)}`},E.toRgba=function(j,D,$,I=255){return(j<<24|D<<16|$<<8|I)>>>0},E.toColor=function(j,D,$,I){return{css:E.toCss(j,D,$,I),rgba:E.toRgba(j,D,$,I)}}})(b||(l.channels=b={})),(function(E){function j(D,$){return f=Math.round(255*$),[d,p,m]=x.toChannels(D.rgba),{css:b.toCss(d,p,m,f),rgba:b.toRgba(d,p,m,f)}}E.blend=function(D,$){if(f=(255&$.rgba)/255,f===1)return{css:$.css,rgba:$.rgba};const I=$.rgba>>24&255,P=$.rgba>>16&255,L=$.rgba>>8&255,B=D.rgba>>24&255,U=D.rgba>>16&255,Z=D.rgba>>8&255;return d=B+Math.round((I-B)*f),p=U+Math.round((P-U)*f),m=Z+Math.round((L-Z)*f),{css:b.toCss(d,p,m),rgba:b.toRgba(d,p,m)}},E.isOpaque=function(D){return(255&D.rgba)==255},E.ensureContrastRatio=function(D,$,I){const P=x.ensureContrastRatio(D.rgba,$.rgba,I);if(P)return b.toColor(P>>24&255,P>>16&255,P>>8&255)},E.opaque=function(D){const $=(255|D.rgba)>>>0;return[d,p,m]=x.toChannels($),{css:b.toCss(d,p,m),rgba:$}},E.opacity=j,E.multiplyOpacity=function(D,$){return f=255&D.rgba,j(D,f*$/255)},E.toColorRGB=function(D){return[D.rgba>>24&255,D.rgba>>16&255,D.rgba>>8&255]}})(S||(l.color=S={})),(function(E){let j,D;try{const $=document.createElement("canvas");$.width=1,$.height=1;const I=$.getContext("2d",{willReadFrequently:!0});I&&(j=I,j.globalCompositeOperation="copy",D=j.createLinearGradient(0,0,1,1))}catch{}E.toColor=function($){if($.match(/#[\da-f]{3,8}/i))switch($.length){case 4:return d=parseInt($.slice(1,2).repeat(2),16),p=parseInt($.slice(2,3).repeat(2),16),m=parseInt($.slice(3,4).repeat(2),16),b.toColor(d,p,m);case 5:return d=parseInt($.slice(1,2).repeat(2),16),p=parseInt($.slice(2,3).repeat(2),16),m=parseInt($.slice(3,4).repeat(2),16),f=parseInt($.slice(4,5).repeat(2),16),b.toColor(d,p,m,f);case 7:return{css:$,rgba:(parseInt($.slice(1),16)<<8|255)>>>0};case 9:return{css:$,rgba:parseInt($.slice(1),16)>>>0}}const I=$.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(I)return d=parseInt(I[1]),p=parseInt(I[2]),m=parseInt(I[3]),f=Math.round(255*(I[5]===void 0?1:parseFloat(I[5]))),b.toColor(d,p,m,f);if(!j||!D)throw new Error("css.toColor: Unsupported css format");if(j.fillStyle=D,j.fillStyle=$,typeof j.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(j.fillRect(0,0,1,1),[d,p,m,f]=j.getImageData(0,0,1,1).data,f!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:b.toRgba(d,p,m,f),css:$}}})(w||(l.css=w={})),(function(E){function j(D,$,I){const P=D/255,L=$/255,B=I/255;return .2126*(P<=.03928?P/12.92:Math.pow((P+.055)/1.055,2.4))+.7152*(L<=.03928?L/12.92:Math.pow((L+.055)/1.055,2.4))+.0722*(B<=.03928?B/12.92:Math.pow((B+.055)/1.055,2.4))}E.relativeLuminance=function(D){return j(D>>16&255,D>>8&255,255&D)},E.relativeLuminance2=j})(C||(l.rgb=C={})),(function(E){function j($,I,P){const L=$>>24&255,B=$>>16&255,U=$>>8&255;let Z=I>>24&255,X=I>>16&255,W=I>>8&255,J=_(C.relativeLuminance2(Z,X,W),C.relativeLuminance2(L,B,U));for(;J<P&&(Z>0||X>0||W>0);)Z-=Math.max(0,Math.ceil(.1*Z)),X-=Math.max(0,Math.ceil(.1*X)),W-=Math.max(0,Math.ceil(.1*W)),J=_(C.relativeLuminance2(Z,X,W),C.relativeLuminance2(L,B,U));return(Z<<24|X<<16|W<<8|255)>>>0}function D($,I,P){const L=$>>24&255,B=$>>16&255,U=$>>8&255;let Z=I>>24&255,X=I>>16&255,W=I>>8&255,J=_(C.relativeLuminance2(Z,X,W),C.relativeLuminance2(L,B,U));for(;J<P&&(Z<255||X<255||W<255);)Z=Math.min(255,Z+Math.ceil(.1*(255-Z))),X=Math.min(255,X+Math.ceil(.1*(255-X))),W=Math.min(255,W+Math.ceil(.1*(255-W))),J=_(C.relativeLuminance2(Z,X,W),C.relativeLuminance2(L,B,U));return(Z<<24|X<<16|W<<8|255)>>>0}E.blend=function($,I){if(f=(255&I)/255,f===1)return I;const P=I>>24&255,L=I>>16&255,B=I>>8&255,U=$>>24&255,Z=$>>16&255,X=$>>8&255;return d=U+Math.round((P-U)*f),p=Z+Math.round((L-Z)*f),m=X+Math.round((B-X)*f),b.toRgba(d,p,m)},E.ensureContrastRatio=function($,I,P){const L=C.relativeLuminance($>>8),B=C.relativeLuminance(I>>8);if(_(L,B)<P){if(B<L){const X=j($,I,P),W=_(L,C.relativeLuminance(X>>8));if(W<P){const J=D($,I,P);return W>_(L,C.relativeLuminance(J>>8))?X:J}return X}const U=D($,I,P),Z=_(L,C.relativeLuminance(U>>8));if(Z<P){const X=j($,I,P);return Z>_(L,C.relativeLuminance(X>>8))?U:X}return U}},E.reduceLuminance=j,E.increaseLuminance=D,E.toChannels=function($){return[$>>24&255,$>>16&255,$>>8&255,255&$]}})(x||(l.rgba=x={})),l.toPaddedHex=y,l.contrastRatio=_},8969:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CoreTerminal=void 0;const p=d(844),m=d(2585),f=d(4348),b=d(7866),S=d(744),w=d(7302),C=d(6975),x=d(8460),y=d(1753),_=d(1480),E=d(7994),j=d(9282),D=d(5435),$=d(5981),I=d(2660);let P=!1;class L extends p.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new x.EventEmitter),this._onScroll.event((U=>{var Z;(Z=this._onScrollApi)==null||Z.fire(U.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(U){for(const Z in U)this.optionsService.options[Z]=U[Z]}constructor(U){super(),this._windowsWrappingHeuristics=this.register(new p.MutableDisposable),this._onBinary=this.register(new x.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new x.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new x.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new x.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new x.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new x.EventEmitter),this._instantiationService=new f.InstantiationService,this.optionsService=this.register(new w.OptionsService(U)),this._instantiationService.setService(m.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(S.BufferService)),this._instantiationService.setService(m.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(b.LogService)),this._instantiationService.setService(m.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(C.CoreService)),this._instantiationService.setService(m.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(y.CoreMouseService)),this._instantiationService.setService(m.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(_.UnicodeService)),this._instantiationService.setService(m.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(E.CharsetService),this._instantiationService.setService(m.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(I.OscLinkService),this._instantiationService.setService(m.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,x.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,x.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,x.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,x.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 $.WriteBuffer(((Z,X)=>this._inputHandler.parse(Z,X)))),this.register((0,x.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(U,Z){this._writeBuffer.write(U,Z)}writeSync(U,Z){this._logService.logLevel<=m.LogLevelEnum.WARN&&!P&&(this._logService.warn("writeSync is unreliable and will be removed soon."),P=!0),this._writeBuffer.writeSync(U,Z)}input(U,Z=!0){this.coreService.triggerDataEvent(U,Z)}resize(U,Z){isNaN(U)||isNaN(Z)||(U=Math.max(U,S.MINIMUM_COLS),Z=Math.max(Z,S.MINIMUM_ROWS),this._bufferService.resize(U,Z))}scroll(U,Z=!1){this._bufferService.scroll(U,Z)}scrollLines(U,Z,X){this._bufferService.scrollLines(U,Z,X)}scrollPages(U){this.scrollLines(U*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(U){const Z=U-this._bufferService.buffer.ydisp;Z!==0&&this.scrollLines(Z)}registerEscHandler(U,Z){return this._inputHandler.registerEscHandler(U,Z)}registerDcsHandler(U,Z){return this._inputHandler.registerDcsHandler(U,Z)}registerCsiHandler(U,Z){return this._inputHandler.registerCsiHandler(U,Z)}registerOscHandler(U,Z){return this._inputHandler.registerOscHandler(U,Z)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let U=!1;const Z=this.optionsService.rawOptions.windowsPty;Z&&Z.buildNumber!==void 0&&Z.buildNumber!==void 0?U=Z.backend==="conpty"&&Z.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(U=!0),U?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const U=[];U.push(this.onLineFeed(j.updateWindowsModeWrappedState.bind(null,this._bufferService))),U.push(this.registerCsiHandler({final:"H"},(()=>((0,j.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,p.toDisposable)((()=>{for(const Z of U)Z.dispose()}))}}}l.CoreTerminal=L},8460:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.runAndSubscribe=l.forwardEvent=l.EventEmitter=void 0,l.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=d=>(this._listeners.push(d),{dispose:()=>{if(!this._disposed){for(let p=0;p<this._listeners.length;p++)if(this._listeners[p]===d)return void this._listeners.splice(p,1)}}})),this._event}fire(d,p){const m=[];for(let f=0;f<this._listeners.length;f++)m.push(this._listeners[f]);for(let f=0;f<m.length;f++)m[f].call(void 0,d,p)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},l.forwardEvent=function(d,p){return d((m=>p.fire(m)))},l.runAndSubscribe=function(d,p){return p(void 0),d((m=>p(m)))}},5435:function(u,l,d){var p=this&&this.__decorate||function(ue,V,ie,K){var se,oe=arguments.length,be=oe<3?V:K===null?K=Object.getOwnPropertyDescriptor(V,ie):K;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")be=Reflect.decorate(ue,V,ie,K);else for(var je=ue.length-1;je>=0;je--)(se=ue[je])&&(be=(oe<3?se(be):oe>3?se(V,ie,be):se(V,ie))||be);return oe>3&&be&&Object.defineProperty(V,ie,be),be},m=this&&this.__param||function(ue,V){return function(ie,K){V(ie,K,ue)}};Object.defineProperty(l,"__esModule",{value:!0}),l.InputHandler=l.WindowsOptionsReportType=void 0;const f=d(2584),b=d(7116),S=d(2015),w=d(844),C=d(482),x=d(8437),y=d(8460),_=d(643),E=d(511),j=d(3734),D=d(2585),$=d(1480),I=d(6242),P=d(6351),L=d(5941),B={"(":0,")":1,"*":2,"+":3,"-":1,".":2},U=131072;function Z(ue,V){if(ue>24)return V.setWinLines||!1;switch(ue){case 1:return!!V.restoreWin;case 2:return!!V.minimizeWin;case 3:return!!V.setWinPosition;case 4:return!!V.setWinSizePixels;case 5:return!!V.raiseWin;case 6:return!!V.lowerWin;case 7:return!!V.refreshWin;case 8:return!!V.setWinSizeChars;case 9:return!!V.maximizeWin;case 10:return!!V.fullscreenWin;case 11:return!!V.getWinState;case 13:return!!V.getWinPosition;case 14:return!!V.getWinSizePixels;case 15:return!!V.getScreenSizePixels;case 16:return!!V.getCellSizePixels;case 18:return!!V.getWinSizeChars;case 19:return!!V.getScreenSizeChars;case 20:return!!V.getIconTitle;case 21:return!!V.getWinTitle;case 22:return!!V.pushTitle;case 23:return!!V.popTitle;case 24:return!!V.setWinLines}return!1}var X;(function(ue){ue[ue.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",ue[ue.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(X||(l.WindowsOptionsReportType=X={}));let W=0;class J extends w.Disposable{getAttrData(){return this._curAttrData}constructor(V,ie,K,se,oe,be,je,Te,ve=new S.EscapeSequenceParser){super(),this._bufferService=V,this._charsetService=ie,this._coreService=K,this._logService=se,this._optionsService=oe,this._oscLinkService=be,this._coreMouseService=je,this._unicodeService=Te,this._parser=ve,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new C.StringToUtf32,this._utf8Decoder=new C.Utf8ToUtf32,this._workCell=new E.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=x.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=x.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new y.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new y.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new y.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new y.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new y.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new y.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new y.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new y.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new y.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new y.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new y.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new y.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new y.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 te(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((re=>this._activeBuffer=re.activeBuffer))),this._parser.setCsiHandlerFallback(((re,Pe)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(re),params:Pe.toArray()})})),this._parser.setEscHandlerFallback((re=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(re)})})),this._parser.setExecuteHandlerFallback((re=>{this._logService.debug("Unknown EXECUTE code: ",{code:re})})),this._parser.setOscHandlerFallback(((re,Pe,_e)=>{this._logService.debug("Unknown OSC code: ",{identifier:re,action:Pe,data:_e})})),this._parser.setDcsHandlerFallback(((re,Pe,_e)=>{Pe==="HOOK"&&(_e=_e.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(re),action:Pe,payload:_e})})),this._parser.setPrintHandler(((re,Pe,_e)=>this.print(re,Pe,_e))),this._parser.registerCsiHandler({final:"@"},(re=>this.insertChars(re))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(re=>this.scrollLeft(re))),this._parser.registerCsiHandler({final:"A"},(re=>this.cursorUp(re))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(re=>this.scrollRight(re))),this._parser.registerCsiHandler({final:"B"},(re=>this.cursorDown(re))),this._parser.registerCsiHandler({final:"C"},(re=>this.cursorForward(re))),this._parser.registerCsiHandler({final:"D"},(re=>this.cursorBackward(re))),this._parser.registerCsiHandler({final:"E"},(re=>this.cursorNextLine(re))),this._parser.registerCsiHandler({final:"F"},(re=>this.cursorPrecedingLine(re))),this._parser.registerCsiHandler({final:"G"},(re=>this.cursorCharAbsolute(re))),this._parser.registerCsiHandler({final:"H"},(re=>this.cursorPosition(re))),this._parser.registerCsiHandler({final:"I"},(re=>this.cursorForwardTab(re))),this._parser.registerCsiHandler({final:"J"},(re=>this.eraseInDisplay(re,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(re=>this.eraseInDisplay(re,!0))),this._parser.registerCsiHandler({final:"K"},(re=>this.eraseInLine(re,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(re=>this.eraseInLine(re,!0))),this._parser.registerCsiHandler({final:"L"},(re=>this.insertLines(re))),this._parser.registerCsiHandler({final:"M"},(re=>this.deleteLines(re))),this._parser.registerCsiHandler({final:"P"},(re=>this.deleteChars(re))),this._parser.registerCsiHandler({final:"S"},(re=>this.scrollUp(re))),this._parser.registerCsiHandler({final:"T"},(re=>this.scrollDown(re))),this._parser.registerCsiHandler({final:"X"},(re=>this.eraseChars(re))),this._parser.registerCsiHandler({final:"Z"},(re=>this.cursorBackwardTab(re))),this._parser.registerCsiHandler({final:"`"},(re=>this.charPosAbsolute(re))),this._parser.registerCsiHandler({final:"a"},(re=>this.hPositionRelative(re))),this._parser.registerCsiHandler({final:"b"},(re=>this.repeatPrecedingCharacter(re))),this._parser.registerCsiHandler({final:"c"},(re=>this.sendDeviceAttributesPrimary(re))),this._parser.registerCsiHandler({prefix:">",final:"c"},(re=>this.sendDeviceAttributesSecondary(re))),this._parser.registerCsiHandler({final:"d"},(re=>this.linePosAbsolute(re))),this._parser.registerCsiHandler({final:"e"},(re=>this.vPositionRelative(re))),this._parser.registerCsiHandler({final:"f"},(re=>this.hVPosition(re))),this._parser.registerCsiHandler({final:"g"},(re=>this.tabClear(re))),this._parser.registerCsiHandler({final:"h"},(re=>this.setMode(re))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(re=>this.setModePrivate(re))),this._parser.registerCsiHandler({final:"l"},(re=>this.resetMode(re))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(re=>this.resetModePrivate(re))),this._parser.registerCsiHandler({final:"m"},(re=>this.charAttributes(re))),this._parser.registerCsiHandler({final:"n"},(re=>this.deviceStatus(re))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(re=>this.deviceStatusPrivate(re))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(re=>this.softReset(re))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(re=>this.setCursorStyle(re))),this._parser.registerCsiHandler({final:"r"},(re=>this.setScrollRegion(re))),this._parser.registerCsiHandler({final:"s"},(re=>this.saveCursor(re))),this._parser.registerCsiHandler({final:"t"},(re=>this.windowOptions(re))),this._parser.registerCsiHandler({final:"u"},(re=>this.restoreCursor(re))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(re=>this.insertColumns(re))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(re=>this.deleteColumns(re))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(re=>this.selectProtected(re))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(re=>this.requestMode(re,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(re=>this.requestMode(re,!1))),this._parser.setExecuteHandler(f.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(f.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(f.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(f.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(f.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(f.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(f.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(f.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(f.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(f.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(f.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(f.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new I.OscHandler((re=>(this.setTitle(re),this.setIconName(re),!0)))),this._parser.registerOscHandler(1,new I.OscHandler((re=>this.setIconName(re)))),this._parser.registerOscHandler(2,new I.OscHandler((re=>this.setTitle(re)))),this._parser.registerOscHandler(4,new I.OscHandler((re=>this.setOrReportIndexedColor(re)))),this._parser.registerOscHandler(8,new I.OscHandler((re=>this.setHyperlink(re)))),this._parser.registerOscHandler(10,new I.OscHandler((re=>this.setOrReportFgColor(re)))),this._parser.registerOscHandler(11,new I.OscHandler((re=>this.setOrReportBgColor(re)))),this._parser.registerOscHandler(12,new I.OscHandler((re=>this.setOrReportCursorColor(re)))),this._parser.registerOscHandler(104,new I.OscHandler((re=>this.restoreIndexedColor(re)))),this._parser.registerOscHandler(110,new I.OscHandler((re=>this.restoreFgColor(re)))),this._parser.registerOscHandler(111,new I.OscHandler((re=>this.restoreBgColor(re)))),this._parser.registerOscHandler(112,new I.OscHandler((re=>this.restoreCursorColor(re)))),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 re in b.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:re},(()=>this.selectCharset("("+re))),this._parser.registerEscHandler({intermediates:")",final:re},(()=>this.selectCharset(")"+re))),this._parser.registerEscHandler({intermediates:"*",final:re},(()=>this.selectCharset("*"+re))),this._parser.registerEscHandler({intermediates:"+",final:re},(()=>this.selectCharset("+"+re))),this._parser.registerEscHandler({intermediates:"-",final:re},(()=>this.selectCharset("-"+re))),this._parser.registerEscHandler({intermediates:".",final:re},(()=>this.selectCharset("."+re))),this._parser.registerEscHandler({intermediates:"/",final:re},(()=>this.selectCharset("/"+re)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((re=>(this._logService.error("Parsing error: ",re),re))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new P.DcsHandler(((re,Pe)=>this.requestStatusString(re,Pe))))}_preserveStack(V,ie,K,se){this._parseStack.paused=!0,this._parseStack.cursorStartX=V,this._parseStack.cursorStartY=ie,this._parseStack.decodedLength=K,this._parseStack.position=se}_logSlowResolvingAsync(V){this._logService.logLevel<=D.LogLevelEnum.WARN&&Promise.race([V,new Promise(((ie,K)=>setTimeout((()=>K("#SLOW_TIMEOUT")),5e3)))]).catch((ie=>{if(ie!=="#SLOW_TIMEOUT")throw ie;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(V,ie){let K,se=this._activeBuffer.x,oe=this._activeBuffer.y,be=0;const je=this._parseStack.paused;if(je){if(K=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,ie))return this._logSlowResolvingAsync(K),K;se=this._parseStack.cursorStartX,oe=this._parseStack.cursorStartY,this._parseStack.paused=!1,V.length>U&&(be=this._parseStack.position+U)}if(this._logService.logLevel<=D.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof V=="string"?` "${V}"`:` "${Array.prototype.map.call(V,(re=>String.fromCharCode(re))).join("")}"`),typeof V=="string"?V.split("").map((re=>re.charCodeAt(0))):V),this._parseBuffer.length<V.length&&this._parseBuffer.length<U&&(this._parseBuffer=new Uint32Array(Math.min(V.length,U))),je||this._dirtyRowTracker.clearRange(),V.length>U)for(let re=be;re<V.length;re+=U){const Pe=re+U<V.length?re+U:V.length,_e=typeof V=="string"?this._stringDecoder.decode(V.substring(re,Pe),this._parseBuffer):this._utf8Decoder.decode(V.subarray(re,Pe),this._parseBuffer);if(K=this._parser.parse(this._parseBuffer,_e))return this._preserveStack(se,oe,_e,re),this._logSlowResolvingAsync(K),K}else if(!je){const re=typeof V=="string"?this._stringDecoder.decode(V,this._parseBuffer):this._utf8Decoder.decode(V,this._parseBuffer);if(K=this._parser.parse(this._parseBuffer,re))return this._preserveStack(se,oe,re,0),this._logSlowResolvingAsync(K),K}this._activeBuffer.x===se&&this._activeBuffer.y===oe||this._onCursorMove.fire();const Te=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),ve=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);ve<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(ve,this._bufferService.rows-1),Math.min(Te,this._bufferService.rows-1))}print(V,ie,K){let se,oe;const be=this._charsetService.charset,je=this._optionsService.rawOptions.screenReaderMode,Te=this._bufferService.cols,ve=this._coreService.decPrivateModes.wraparound,re=this._coreService.modes.insertMode,Pe=this._curAttrData;let _e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&K-ie>0&&_e.getWidth(this._activeBuffer.x-1)===2&&_e.setCellFromCodepoint(this._activeBuffer.x-1,0,1,Pe);let Qe=this._parser.precedingJoinState;for(let st=ie;st<K;++st){if(se=V[st],se<127&&be){const nt=be[String.fromCharCode(se)];nt&&(se=nt.charCodeAt(0))}const yt=this._unicodeService.charProperties(se,Qe);oe=$.UnicodeService.extractWidth(yt);const qt=$.UnicodeService.extractShouldJoin(yt),ut=qt?$.UnicodeService.extractWidth(Qe):0;if(Qe=yt,je&&this._onA11yChar.fire((0,C.stringFromCodePoint)(se)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+oe-ut>Te){if(ve){const nt=_e;let Le=this._activeBuffer.x-ut;for(this._activeBuffer.x=ut,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),_e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),ut>0&&_e instanceof x.BufferLine&&_e.copyCellsFrom(nt,Le,0,ut,!1);Le<Te;)nt.setCellFromCodepoint(Le++,0,1,Pe)}else if(this._activeBuffer.x=Te-1,oe===2)continue}if(qt&&this._activeBuffer.x){const nt=_e.getWidth(this._activeBuffer.x-1)?1:2;_e.addCodepointToCell(this._activeBuffer.x-nt,se,oe);for(let Le=oe-ut;--Le>=0;)_e.setCellFromCodepoint(this._activeBuffer.x++,0,0,Pe)}else if(re&&(_e.insertCells(this._activeBuffer.x,oe-ut,this._activeBuffer.getNullCell(Pe)),_e.getWidth(Te-1)===2&&_e.setCellFromCodepoint(Te-1,_.NULL_CELL_CODE,_.NULL_CELL_WIDTH,Pe)),_e.setCellFromCodepoint(this._activeBuffer.x++,se,oe,Pe),oe>0)for(;--oe;)_e.setCellFromCodepoint(this._activeBuffer.x++,0,0,Pe)}this._parser.precedingJoinState=Qe,this._activeBuffer.x<Te&&K-ie>0&&_e.getWidth(this._activeBuffer.x)===0&&!_e.hasContent(this._activeBuffer.x)&&_e.setCellFromCodepoint(this._activeBuffer.x,0,1,Pe),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(V,ie){return V.final!=="t"||V.prefix||V.intermediates?this._parser.registerCsiHandler(V,ie):this._parser.registerCsiHandler(V,(K=>!Z(K.params[0],this._optionsService.rawOptions.windowOptions)||ie(K)))}registerDcsHandler(V,ie){return this._parser.registerDcsHandler(V,new P.DcsHandler(ie))}registerEscHandler(V,ie){return this._parser.registerEscHandler(V,ie)}registerOscHandler(V,ie){return this._parser.registerOscHandler(V,new I.OscHandler(ie))}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 V;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&&((V=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y))!=null&&V.isWrapped)){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);ie.hasWidth(this._activeBuffer.x)&&!ie.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const V=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-V),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(V=this._bufferService.cols-1){this._activeBuffer.x=Math.min(V,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(V,ie){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=V,this._activeBuffer.y=this._activeBuffer.scrollTop+ie):(this._activeBuffer.x=V,this._activeBuffer.y=ie),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(V,ie){this._restrictCursor(),this._setCursor(this._activeBuffer.x+V,this._activeBuffer.y+ie)}cursorUp(V){const ie=this._activeBuffer.y-this._activeBuffer.scrollTop;return ie>=0?this._moveCursor(0,-Math.min(ie,V.params[0]||1)):this._moveCursor(0,-(V.params[0]||1)),!0}cursorDown(V){const ie=this._activeBuffer.scrollBottom-this._activeBuffer.y;return ie>=0?this._moveCursor(0,Math.min(ie,V.params[0]||1)):this._moveCursor(0,V.params[0]||1),!0}cursorForward(V){return this._moveCursor(V.params[0]||1,0),!0}cursorBackward(V){return this._moveCursor(-(V.params[0]||1),0),!0}cursorNextLine(V){return this.cursorDown(V),this._activeBuffer.x=0,!0}cursorPrecedingLine(V){return this.cursorUp(V),this._activeBuffer.x=0,!0}cursorCharAbsolute(V){return this._setCursor((V.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(V){return this._setCursor(V.length>=2?(V.params[1]||1)-1:0,(V.params[0]||1)-1),!0}charPosAbsolute(V){return this._setCursor((V.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(V){return this._moveCursor(V.params[0]||1,0),!0}linePosAbsolute(V){return this._setCursor(this._activeBuffer.x,(V.params[0]||1)-1),!0}vPositionRelative(V){return this._moveCursor(0,V.params[0]||1),!0}hVPosition(V){return this.cursorPosition(V),!0}tabClear(V){const ie=V.params[0];return ie===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:ie===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(V){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let ie=V.params[0]||1;for(;ie--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(V){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let ie=V.params[0]||1;for(;ie--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(V){const ie=V.params[0];return ie===1&&(this._curAttrData.bg|=536870912),ie!==2&&ie!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(V,ie,K,se=!1,oe=!1){const be=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);be.replaceCells(ie,K,this._activeBuffer.getNullCell(this._eraseAttrData()),oe),se&&(be.isWrapped=!1)}_resetBufferLine(V,ie=!1){const K=this._activeBuffer.lines.get(this._activeBuffer.ybase+V);K&&(K.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),ie),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+V),K.isWrapped=!1)}eraseInDisplay(V,ie=!1){let K;switch(this._restrictCursor(this._bufferService.cols),V.params[0]){case 0:for(K=this._activeBuffer.y,this._dirtyRowTracker.markDirty(K),this._eraseInBufferLine(K++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,ie);K<this._bufferService.rows;K++)this._resetBufferLine(K,ie);this._dirtyRowTracker.markDirty(K);break;case 1:for(K=this._activeBuffer.y,this._dirtyRowTracker.markDirty(K),this._eraseInBufferLine(K,0,this._activeBuffer.x+1,!0,ie),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(K+1).isWrapped=!1);K--;)this._resetBufferLine(K,ie);this._dirtyRowTracker.markDirty(0);break;case 2:for(K=this._bufferService.rows,this._dirtyRowTracker.markDirty(K-1);K--;)this._resetBufferLine(K,ie);this._dirtyRowTracker.markDirty(0);break;case 3:const se=this._activeBuffer.lines.length-this._bufferService.rows;se>0&&(this._activeBuffer.lines.trimStart(se),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-se,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-se,0),this._onScroll.fire(0))}return!0}eraseInLine(V,ie=!1){switch(this._restrictCursor(this._bufferService.cols),V.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,ie);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,ie);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,ie)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(V){this._restrictCursor();let ie=V.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const K=this._activeBuffer.ybase+this._activeBuffer.y,se=this._bufferService.rows-1-this._activeBuffer.scrollBottom,oe=this._bufferService.rows-1+this._activeBuffer.ybase-se+1;for(;ie--;)this._activeBuffer.lines.splice(oe-1,1),this._activeBuffer.lines.splice(K,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(V){this._restrictCursor();let ie=V.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const K=this._activeBuffer.ybase+this._activeBuffer.y;let se;for(se=this._bufferService.rows-1-this._activeBuffer.scrollBottom,se=this._bufferService.rows-1+this._activeBuffer.ybase-se;ie--;)this._activeBuffer.lines.splice(K,1),this._activeBuffer.lines.splice(se,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(V){this._restrictCursor();const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return ie&&(ie.insertCells(this._activeBuffer.x,V.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(V){this._restrictCursor();const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return ie&&(ie.deleteCells(this._activeBuffer.x,V.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(V){let ie=V.params[0]||1;for(;ie--;)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(V){let ie=V.params[0]||1;for(;ie--;)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(x.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(V){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const ie=V.params[0]||1;for(let K=this._activeBuffer.scrollTop;K<=this._activeBuffer.scrollBottom;++K){const se=this._activeBuffer.lines.get(this._activeBuffer.ybase+K);se.deleteCells(0,ie,this._activeBuffer.getNullCell(this._eraseAttrData())),se.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(V){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const ie=V.params[0]||1;for(let K=this._activeBuffer.scrollTop;K<=this._activeBuffer.scrollBottom;++K){const se=this._activeBuffer.lines.get(this._activeBuffer.ybase+K);se.insertCells(0,ie,this._activeBuffer.getNullCell(this._eraseAttrData())),se.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(V){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const ie=V.params[0]||1;for(let K=this._activeBuffer.scrollTop;K<=this._activeBuffer.scrollBottom;++K){const se=this._activeBuffer.lines.get(this._activeBuffer.ybase+K);se.insertCells(this._activeBuffer.x,ie,this._activeBuffer.getNullCell(this._eraseAttrData())),se.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(V){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const ie=V.params[0]||1;for(let K=this._activeBuffer.scrollTop;K<=this._activeBuffer.scrollBottom;++K){const se=this._activeBuffer.lines.get(this._activeBuffer.ybase+K);se.deleteCells(this._activeBuffer.x,ie,this._activeBuffer.getNullCell(this._eraseAttrData())),se.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(V){this._restrictCursor();const ie=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return ie&&(ie.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(V.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(V){const ie=this._parser.precedingJoinState;if(!ie)return!0;const K=V.params[0]||1,se=$.UnicodeService.extractWidth(ie),oe=this._activeBuffer.x-se,be=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(oe),je=new Uint32Array(be.length*K);let Te=0;for(let re=0;re<be.length;){const Pe=be.codePointAt(re)||0;je[Te++]=Pe,re+=Pe>65535?2:1}let ve=Te;for(let re=1;re<K;++re)je.copyWithin(ve,0,Te),ve+=Te;return this.print(je,0,ve),!0}sendDeviceAttributesPrimary(V){return V.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(f.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(f.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(V){return V.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(f.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(f.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(V.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(f.C0.ESC+"[>83;40003;0c")),!0}_is(V){return(this._optionsService.rawOptions.termName+"").indexOf(V)===0}setMode(V){for(let ie=0;ie<V.length;ie++)switch(V.params[ie]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(V){for(let ie=0;ie<V.length;ie++)switch(V.params[ie]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,b.DEFAULT_CHARSET),this._charsetService.setgCharset(1,b.DEFAULT_CHARSET),this._charsetService.setgCharset(2,b.DEFAULT_CHARSET),this._charsetService.setgCharset(3,b.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(V){for(let ie=0;ie<V.length;ie++)switch(V.params[ie]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(V){for(let ie=0;ie<V.length;ie++)switch(V.params[ie]){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(),V.params[ie]===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(V,ie){const K=this._coreService.decPrivateModes,{activeProtocol:se,activeEncoding:oe}=this._coreMouseService,be=this._coreService,{buffers:je,cols:Te}=this._bufferService,{active:ve,alt:re}=je,Pe=this._optionsService.rawOptions,_e=qt=>qt?1:2,Qe=V.params[0];return st=Qe,yt=ie?Qe===2?4:Qe===4?_e(be.modes.insertMode):Qe===12?3:Qe===20?_e(Pe.convertEol):0:Qe===1?_e(K.applicationCursorKeys):Qe===3?Pe.windowOptions.setWinLines?Te===80?2:Te===132?1:0:0:Qe===6?_e(K.origin):Qe===7?_e(K.wraparound):Qe===8?3:Qe===9?_e(se==="X10"):Qe===12?_e(Pe.cursorBlink):Qe===25?_e(!be.isCursorHidden):Qe===45?_e(K.reverseWraparound):Qe===66?_e(K.applicationKeypad):Qe===67?4:Qe===1e3?_e(se==="VT200"):Qe===1002?_e(se==="DRAG"):Qe===1003?_e(se==="ANY"):Qe===1004?_e(K.sendFocus):Qe===1005?4:Qe===1006?_e(oe==="SGR"):Qe===1015?4:Qe===1016?_e(oe==="SGR_PIXELS"):Qe===1048?1:Qe===47||Qe===1047||Qe===1049?_e(ve===re):Qe===2004?_e(K.bracketedPasteMode):0,be.triggerDataEvent(`${f.C0.ESC}[${ie?"":"?"}${st};${yt}$y`),!0;var st,yt}_updateAttrColor(V,ie,K,se,oe){return ie===2?(V|=50331648,V&=-16777216,V|=j.AttributeData.fromColorRGB([K,se,oe])):ie===5&&(V&=-50331904,V|=33554432|255&K),V}_extractColor(V,ie,K){const se=[0,0,-1,0,0,0];let oe=0,be=0;do{if(se[be+oe]=V.params[ie+be],V.hasSubParams(ie+be)){const je=V.getSubParams(ie+be);let Te=0;do se[1]===5&&(oe=1),se[be+Te+1+oe]=je[Te];while(++Te<je.length&&Te+be+1+oe<se.length);break}if(se[1]===5&&be+oe>=2||se[1]===2&&be+oe>=5)break;se[1]&&(oe=1)}while(++be+ie<V.length&&be+oe<se.length);for(let je=2;je<se.length;++je)se[je]===-1&&(se[je]=0);switch(se[0]){case 38:K.fg=this._updateAttrColor(K.fg,se[1],se[3],se[4],se[5]);break;case 48:K.bg=this._updateAttrColor(K.bg,se[1],se[3],se[4],se[5]);break;case 58:K.extended=K.extended.clone(),K.extended.underlineColor=this._updateAttrColor(K.extended.underlineColor,se[1],se[3],se[4],se[5])}return be}_processUnderline(V,ie){ie.extended=ie.extended.clone(),(!~V||V>5)&&(V=1),ie.extended.underlineStyle=V,ie.fg|=268435456,V===0&&(ie.fg&=-268435457),ie.updateExtended()}_processSGR0(V){V.fg=x.DEFAULT_ATTR_DATA.fg,V.bg=x.DEFAULT_ATTR_DATA.bg,V.extended=V.extended.clone(),V.extended.underlineStyle=0,V.extended.underlineColor&=-67108864,V.updateExtended()}charAttributes(V){if(V.length===1&&V.params[0]===0)return this._processSGR0(this._curAttrData),!0;const ie=V.length;let K;const se=this._curAttrData;for(let oe=0;oe<ie;oe++)K=V.params[oe],K>=30&&K<=37?(se.fg&=-50331904,se.fg|=16777216|K-30):K>=40&&K<=47?(se.bg&=-50331904,se.bg|=16777216|K-40):K>=90&&K<=97?(se.fg&=-50331904,se.fg|=16777224|K-90):K>=100&&K<=107?(se.bg&=-50331904,se.bg|=16777224|K-100):K===0?this._processSGR0(se):K===1?se.fg|=134217728:K===3?se.bg|=67108864:K===4?(se.fg|=268435456,this._processUnderline(V.hasSubParams(oe)?V.getSubParams(oe)[0]:1,se)):K===5?se.fg|=536870912:K===7?se.fg|=67108864:K===8?se.fg|=1073741824:K===9?se.fg|=2147483648:K===2?se.bg|=134217728:K===21?this._processUnderline(2,se):K===22?(se.fg&=-134217729,se.bg&=-134217729):K===23?se.bg&=-67108865:K===24?(se.fg&=-268435457,this._processUnderline(0,se)):K===25?se.fg&=-536870913:K===27?se.fg&=-67108865:K===28?se.fg&=-1073741825:K===29?se.fg&=2147483647:K===39?(se.fg&=-67108864,se.fg|=16777215&x.DEFAULT_ATTR_DATA.fg):K===49?(se.bg&=-67108864,se.bg|=16777215&x.DEFAULT_ATTR_DATA.bg):K===38||K===48||K===58?oe+=this._extractColor(V,oe,se):K===53?se.bg|=1073741824:K===55?se.bg&=-1073741825:K===59?(se.extended=se.extended.clone(),se.extended.underlineColor=-1,se.updateExtended()):K===100?(se.fg&=-67108864,se.fg|=16777215&x.DEFAULT_ATTR_DATA.fg,se.bg&=-67108864,se.bg|=16777215&x.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",K);return!0}deviceStatus(V){switch(V.params[0]){case 5:this._coreService.triggerDataEvent(`${f.C0.ESC}[0n`);break;case 6:const ie=this._activeBuffer.y+1,K=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[${ie};${K}R`)}return!0}deviceStatusPrivate(V){if(V.params[0]===6){const ie=this._activeBuffer.y+1,K=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${f.C0.ESC}[?${ie};${K}R`)}return!0}softReset(V){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=x.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(V){const ie=V.params[0]||1;switch(ie){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 K=ie%2==1;return this._optionsService.options.cursorBlink=K,!0}setScrollRegion(V){const ie=V.params[0]||1;let K;return(V.length<2||(K=V.params[1])>this._bufferService.rows||K===0)&&(K=this._bufferService.rows),K>ie&&(this._activeBuffer.scrollTop=ie-1,this._activeBuffer.scrollBottom=K-1,this._setCursor(0,0)),!0}windowOptions(V){if(!Z(V.params[0],this._optionsService.rawOptions.windowOptions))return!0;const ie=V.length>1?V.params[1]:0;switch(V.params[0]){case 14:ie!==2&&this._onRequestWindowsOptionsReport.fire(X.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(X.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${f.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:ie!==0&&ie!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),ie!==0&&ie!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:ie!==0&&ie!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),ie!==0&&ie!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(V){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(V){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(V){return this._windowTitle=V,this._onTitleChange.fire(V),!0}setIconName(V){return this._iconName=V,!0}setOrReportIndexedColor(V){const ie=[],K=V.split(";");for(;K.length>1;){const se=K.shift(),oe=K.shift();if(/^\d+$/.exec(se)){const be=parseInt(se);if(le(be))if(oe==="?")ie.push({type:0,index:be});else{const je=(0,L.parseColor)(oe);je&&ie.push({type:1,index:be,color:je})}}}return ie.length&&this._onColor.fire(ie),!0}setHyperlink(V){const ie=V.split(";");return!(ie.length<2)&&(ie[1]?this._createHyperlink(ie[0],ie[1]):!ie[0]&&this._finishHyperlink())}_createHyperlink(V,ie){this._getCurrentLinkId()&&this._finishHyperlink();const K=V.split(":");let se;const oe=K.findIndex((be=>be.startsWith("id=")));return oe!==-1&&(se=K[oe].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:se,uri:ie}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(V,ie){const K=V.split(";");for(let se=0;se<K.length&&!(ie>=this._specialColors.length);++se,++ie)if(K[se]==="?")this._onColor.fire([{type:0,index:this._specialColors[ie]}]);else{const oe=(0,L.parseColor)(K[se]);oe&&this._onColor.fire([{type:1,index:this._specialColors[ie],color:oe}])}return!0}setOrReportFgColor(V){return this._setOrReportSpecialColor(V,0)}setOrReportBgColor(V){return this._setOrReportSpecialColor(V,1)}setOrReportCursorColor(V){return this._setOrReportSpecialColor(V,2)}restoreIndexedColor(V){if(!V)return this._onColor.fire([{type:2}]),!0;const ie=[],K=V.split(";");for(let se=0;se<K.length;++se)if(/^\d+$/.exec(K[se])){const oe=parseInt(K[se]);le(oe)&&ie.push({type:2,index:oe})}return ie.length&&this._onColor.fire(ie),!0}restoreFgColor(V){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(V){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(V){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,b.DEFAULT_CHARSET),!0}selectCharset(V){return V.length!==2?(this.selectDefaultCharset(),!0):(V[0]==="/"||this._charsetService.setgCharset(B[V[0]],b.CHARSETS[V[1]]||b.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 V=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,V,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=x.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=x.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(V){return this._charsetService.setgLevel(V),!0}screenAlignmentPattern(){const V=new E.CellData;V.content=4194373,V.fg=this._curAttrData.fg,V.bg=this._curAttrData.bg,this._setCursor(0,0);for(let ie=0;ie<this._bufferService.rows;++ie){const K=this._activeBuffer.ybase+this._activeBuffer.y+ie,se=this._activeBuffer.lines.get(K);se&&(se.fill(V),se.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(V,ie){const K=this._bufferService.buffer,se=this._optionsService.rawOptions;return(oe=>(this._coreService.triggerDataEvent(`${f.C0.ESC}${oe}${f.C0.ESC}\\`),!0))(V==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:V==='"p'?'P1$r61;1"p':V==="r"?`P1$r${K.scrollTop+1};${K.scrollBottom+1}r`:V==="m"?"P1$r0m":V===" q"?`P1$r${{block:2,underline:4,bar:6}[se.cursorStyle]-(se.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(V,ie){this._dirtyRowTracker.markRangeDirty(V,ie)}}l.InputHandler=J;let te=class{constructor(ue){this._bufferService=ue,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(ue){ue<this.start?this.start=ue:ue>this.end&&(this.end=ue)}markRangeDirty(ue,V){ue>V&&(W=ue,ue=V,V=W),ue<this.start&&(this.start=ue),V>this.end&&(this.end=V)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function le(ue){return 0<=ue&&ue<256}te=p([m(0,D.IBufferService)],te)},844:(u,l)=>{function d(p){for(const m of p)m.dispose();p.length=0}Object.defineProperty(l,"__esModule",{value:!0}),l.getDisposeArrayDisposable=l.disposeArray=l.toDisposable=l.MutableDisposable=l.Disposable=void 0,l.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const p of this._disposables)p.dispose();this._disposables.length=0}register(p){return this._disposables.push(p),p}unregister(p){const m=this._disposables.indexOf(p);m!==-1&&this._disposables.splice(m,1)}},l.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(p){var m;this._isDisposed||p===this._value||((m=this._value)==null||m.dispose(),this._value=p)}clear(){this.value=void 0}dispose(){var p;this._isDisposed=!0,(p=this._value)==null||p.dispose(),this._value=void 0}},l.toDisposable=function(p){return{dispose:p}},l.disposeArray=d,l.getDisposeArrayDisposable=function(p){return{dispose:()=>d(p)}}},1505:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.FourKeyMap=l.TwoKeyMap=void 0;class d{constructor(){this._data={}}set(m,f,b){this._data[m]||(this._data[m]={}),this._data[m][f]=b}get(m,f){return this._data[m]?this._data[m][f]:void 0}clear(){this._data={}}}l.TwoKeyMap=d,l.FourKeyMap=class{constructor(){this._data=new d}set(p,m,f,b,S){this._data.get(p,m)||this._data.set(p,m,new d),this._data.get(p,m).set(f,b,S)}get(p,m,f,b){var S;return(S=this._data.get(p,m))==null?void 0:S.get(f,b)}clear(){this._data.clear()}}},6114:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.isChromeOS=l.isLinux=l.isWindows=l.isIphone=l.isIpad=l.isMac=l.getSafariVersion=l.isSafari=l.isLegacyEdge=l.isFirefox=l.isNode=void 0,l.isNode=typeof process<"u"&&"title"in process;const d=l.isNode?"node":navigator.userAgent,p=l.isNode?"node":navigator.platform;l.isFirefox=d.includes("Firefox"),l.isLegacyEdge=d.includes("Edge"),l.isSafari=/^((?!chrome|android).)*safari/i.test(d),l.getSafariVersion=function(){if(!l.isSafari)return 0;const m=d.match(/Version\/(\d+)/);return m===null||m.length<2?0:parseInt(m[1])},l.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(p),l.isIpad=p==="iPad",l.isIphone=p==="iPhone",l.isWindows=["Windows","Win16","Win32","WinCE"].includes(p),l.isLinux=p.indexOf("Linux")>=0,l.isChromeOS=/\bCrOS\b/.test(d)},6106:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.SortedList=void 0;let d=0;l.SortedList=class{constructor(p){this._getKey=p,this._array=[]}clear(){this._array.length=0}insert(p){this._array.length!==0?(d=this._search(this._getKey(p)),this._array.splice(d,0,p)):this._array.push(p)}delete(p){if(this._array.length===0)return!1;const m=this._getKey(p);if(m===void 0||(d=this._search(m),d===-1)||this._getKey(this._array[d])!==m)return!1;do if(this._array[d]===p)return this._array.splice(d,1),!0;while(++d<this._array.length&&this._getKey(this._array[d])===m);return!1}*getKeyIterator(p){if(this._array.length!==0&&(d=this._search(p),!(d<0||d>=this._array.length)&&this._getKey(this._array[d])===p))do yield this._array[d];while(++d<this._array.length&&this._getKey(this._array[d])===p)}forEachByKey(p,m){if(this._array.length!==0&&(d=this._search(p),!(d<0||d>=this._array.length)&&this._getKey(this._array[d])===p))do m(this._array[d]);while(++d<this._array.length&&this._getKey(this._array[d])===p)}values(){return[...this._array].values()}_search(p){let m=0,f=this._array.length-1;for(;f>=m;){let b=m+f>>1;const S=this._getKey(this._array[b]);if(S>p)f=b-1;else{if(!(S<p)){for(;b>0&&this._getKey(this._array[b-1])===p;)b--;return b}m=b+1}}return m}}},7226:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DebouncedIdleTask=l.IdleTaskQueue=l.PriorityTaskQueue=void 0;const p=d(6114);class m{constructor(){this._tasks=[],this._i=0}enqueue(S){this._tasks.push(S),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(S){this._idleCallback=void 0;let w=0,C=0,x=S.timeRemaining(),y=0;for(;this._i<this._tasks.length;){if(w=Date.now(),this._tasks[this._i]()||this._i++,w=Math.max(1,Date.now()-w),C=Math.max(w,C),y=S.timeRemaining(),1.5*C>y)return x-w<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(x-w))}ms`),void this._start();x=y}this.clear()}}class f extends m{_requestCallback(S){return setTimeout((()=>S(this._createDeadline(16))))}_cancelCallback(S){clearTimeout(S)}_createDeadline(S){const w=Date.now()+S;return{timeRemaining:()=>Math.max(0,w-Date.now())}}}l.PriorityTaskQueue=f,l.IdleTaskQueue=!p.isNode&&"requestIdleCallback"in window?class extends m{_requestCallback(b){return requestIdleCallback(b)}_cancelCallback(b){cancelIdleCallback(b)}}:f,l.DebouncedIdleTask=class{constructor(){this._queue=new l.IdleTaskQueue}set(b){this._queue.clear(),this._queue.enqueue(b)}flush(){this._queue.flush()}}},9282:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.updateWindowsModeWrappedState=void 0;const p=d(643);l.updateWindowsModeWrappedState=function(m){const f=m.buffer.lines.get(m.buffer.ybase+m.buffer.y-1),b=f==null?void 0:f.get(m.cols-1),S=m.buffer.lines.get(m.buffer.ybase+m.buffer.y);S&&b&&(S.isWrapped=b[p.CHAR_DATA_CODE_INDEX]!==p.NULL_CELL_CODE&&b[p.CHAR_DATA_CODE_INDEX]!==p.WHITESPACE_CELL_CODE)}},3734:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ExtendedAttrs=l.AttributeData=void 0;class d{constructor(){this.fg=0,this.bg=0,this.extended=new p}static toColorRGB(f){return[f>>>16&255,f>>>8&255,255&f]}static fromColorRGB(f){return(255&f[0])<<16|(255&f[1])<<8|255&f[2]}clone(){const f=new d;return f.fg=this.fg,f.bg=this.bg,f.extended=this.extended.clone(),f}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}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}l.AttributeData=d;class p{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(f){this._ext=f}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(f){this._ext&=-469762049,this._ext|=f<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(f){this._ext&=-67108864,this._ext|=67108863&f}get urlId(){return this._urlId}set urlId(f){this._urlId=f}get underlineVariantOffset(){const f=(3758096384&this._ext)>>29;return f<0?4294967288^f:f}set underlineVariantOffset(f){this._ext&=536870911,this._ext|=f<<29&3758096384}constructor(f=0,b=0){this._ext=0,this._urlId=0,this._ext=f,this._urlId=b}clone(){return new p(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}l.ExtendedAttrs=p},9092:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Buffer=l.MAX_BUFFER_SIZE=void 0;const p=d(6349),m=d(7226),f=d(3734),b=d(8437),S=d(4634),w=d(511),C=d(643),x=d(4863),y=d(7116);l.MAX_BUFFER_SIZE=4294967295,l.Buffer=class{constructor(_,E,j){this._hasScrollback=_,this._optionsService=E,this._bufferService=j,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=b.DEFAULT_ATTR_DATA.clone(),this.savedCharset=y.DEFAULT_CHARSET,this.markers=[],this._nullCell=w.CellData.fromCharData([0,C.NULL_CELL_CHAR,C.NULL_CELL_WIDTH,C.NULL_CELL_CODE]),this._whitespaceCell=w.CellData.fromCharData([0,C.WHITESPACE_CELL_CHAR,C.WHITESPACE_CELL_WIDTH,C.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new m.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new p.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 f.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 f.ExtendedAttrs),this._whitespaceCell}getBlankLine(_,E){return new b.BufferLine(this._bufferService.cols,this.getNullCell(_),E)}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 E=_+this._optionsService.rawOptions.scrollback;return E>l.MAX_BUFFER_SIZE?l.MAX_BUFFER_SIZE:E}fillViewportRows(_){if(this.lines.length===0){_===void 0&&(_=b.DEFAULT_ATTR_DATA);let E=this._rows;for(;E--;)this.lines.push(this.getBlankLine(_))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new p.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(_,E){const j=this.getNullCell(b.DEFAULT_ATTR_DATA);let D=0;const $=this._getCorrectBufferLength(E);if($>this.lines.maxLength&&(this.lines.maxLength=$),this.lines.length>0){if(this._cols<_)for(let P=0;P<this.lines.length;P++)D+=+this.lines.get(P).resize(_,j);let I=0;if(this._rows<E)for(let P=this._rows;P<E;P++)this.lines.length<E+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new b.BufferLine(_,j)):this.ybase>0&&this.lines.length<=this.ybase+this.y+I+1?(this.ybase--,I++,this.ydisp>0&&this.ydisp--):this.lines.push(new b.BufferLine(_,j)));else for(let P=this._rows;P>E;P--)this.lines.length>E+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if($<this.lines.maxLength){const P=this.lines.length-$;P>0&&(this.lines.trimStart(P),this.ybase=Math.max(this.ybase-P,0),this.ydisp=Math.max(this.ydisp-P,0),this.savedY=Math.max(this.savedY-P,0)),this.lines.maxLength=$}this.x=Math.min(this.x,_-1),this.y=Math.min(this.y,E-1),I&&(this.y+=I),this.savedX=Math.min(this.savedX,_-1),this.scrollTop=0}if(this.scrollBottom=E-1,this._isReflowEnabled&&(this._reflow(_,E),this._cols>_))for(let I=0;I<this.lines.length;I++)D+=+this.lines.get(I).resize(_,j);this._cols=_,this._rows=E,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 E=0;for(;this._memoryCleanupPosition<this.lines.length;)if(E+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),E>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(_,E){this._cols!==_&&(_>this._cols?this._reflowLarger(_,E):this._reflowSmaller(_,E))}_reflowLarger(_,E){const j=(0,S.reflowLargerGetLinesToRemove)(this.lines,this._cols,_,this.ybase+this.y,this.getNullCell(b.DEFAULT_ATTR_DATA));if(j.length>0){const D=(0,S.reflowLargerCreateNewLayout)(this.lines,j);(0,S.reflowLargerApplyNewLayout)(this.lines,D.layout),this._reflowLargerAdjustViewport(_,E,D.countRemoved)}}_reflowLargerAdjustViewport(_,E,j){const D=this.getNullCell(b.DEFAULT_ATTR_DATA);let $=j;for(;$-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<E&&this.lines.push(new b.BufferLine(_,D))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-j,0)}_reflowSmaller(_,E){const j=this.getNullCell(b.DEFAULT_ATTR_DATA),D=[];let $=0;for(let I=this.lines.length-1;I>=0;I--){let P=this.lines.get(I);if(!P||!P.isWrapped&&P.getTrimmedLength()<=_)continue;const L=[P];for(;P.isWrapped&&I>0;)P=this.lines.get(--I),L.unshift(P);const B=this.ybase+this.y;if(B>=I&&B<I+L.length)continue;const U=L[L.length-1].getTrimmedLength(),Z=(0,S.reflowSmallerGetNewLineLengths)(L,this._cols,_),X=Z.length-L.length;let W;W=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+X):Math.max(0,this.lines.length-this.lines.maxLength+X);const J=[];for(let K=0;K<X;K++){const se=this.getBlankLine(b.DEFAULT_ATTR_DATA,!0);J.push(se)}J.length>0&&(D.push({start:I+L.length+$,newLines:J}),$+=J.length),L.push(...J);let te=Z.length-1,le=Z[te];le===0&&(te--,le=Z[te]);let ue=L.length-X-1,V=U;for(;ue>=0;){const K=Math.min(V,le);if(L[te]===void 0)break;if(L[te].copyCellsFrom(L[ue],V-K,le-K,K,!0),le-=K,le===0&&(te--,le=Z[te]),V-=K,V===0){ue--;const se=Math.max(ue,0);V=(0,S.getWrappedLineTrimmedLength)(L,se,this._cols)}}for(let K=0;K<L.length;K++)Z[K]<_&&L[K].setCell(Z[K],j);let ie=X-W;for(;ie-- >0;)this.ybase===0?this.y<E-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+$)-E&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+X,this.ybase+E-1)}if(D.length>0){const I=[],P=[];for(let te=0;te<this.lines.length;te++)P.push(this.lines.get(te));const L=this.lines.length;let B=L-1,U=0,Z=D[U];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+$);let X=0;for(let te=Math.min(this.lines.maxLength-1,L+$-1);te>=0;te--)if(Z&&Z.start>B+X){for(let le=Z.newLines.length-1;le>=0;le--)this.lines.set(te--,Z.newLines[le]);te++,I.push({index:B+1,amount:Z.newLines.length}),X+=Z.newLines.length,Z=D[++U]}else this.lines.set(te,P[B--]);let W=0;for(let te=I.length-1;te>=0;te--)I[te].index+=W,this.lines.onInsertEmitter.fire(I[te]),W+=I[te].amount;const J=Math.max(0,L+$-this.lines.maxLength);J>0&&this.lines.onTrimEmitter.fire(J)}}translateBufferLineToString(_,E,j=0,D){const $=this.lines.get(_);return $?$.translateToString(E,j,D):""}getWrappedRangeForLine(_){let E=_,j=_;for(;E>0&&this.lines.get(E).isWrapped;)E--;for(;j+1<this.lines.length&&this.lines.get(j+1).isWrapped;)j++;return{first:E,last:j}}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 E=0;E<this.markers.length;E++)this.markers[E].line===_&&(this.markers[E].dispose(),this.markers.splice(E--,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 E=new x.Marker(_);return this.markers.push(E),E.register(this.lines.onTrim((j=>{E.line-=j,E.line<0&&E.dispose()}))),E.register(this.lines.onInsert((j=>{E.line>=j.index&&(E.line+=j.amount)}))),E.register(this.lines.onDelete((j=>{E.line>=j.index&&E.line<j.index+j.amount&&E.dispose(),E.line>j.index&&(E.line-=j.amount)}))),E.register(E.onDispose((()=>this._removeMarker(E)))),E}_removeMarker(_){this._isClearing||this.markers.splice(this.markers.indexOf(_),1)}}},8437:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferLine=l.DEFAULT_ATTR_DATA=void 0;const p=d(3734),m=d(511),f=d(643),b=d(482);l.DEFAULT_ATTR_DATA=Object.freeze(new p.AttributeData);let S=0;class w{constructor(x,y,_=!1){this.isWrapped=_,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*x);const E=y||m.CellData.fromCharData([0,f.NULL_CELL_CHAR,f.NULL_CELL_WIDTH,f.NULL_CELL_CODE]);for(let j=0;j<x;++j)this.setCell(j,E);this.length=x}get(x){const y=this._data[3*x+0],_=2097151&y;return[this._data[3*x+1],2097152&y?this._combined[x]:_?(0,b.stringFromCodePoint)(_):"",y>>22,2097152&y?this._combined[x].charCodeAt(this._combined[x].length-1):_]}set(x,y){this._data[3*x+1]=y[f.CHAR_DATA_ATTR_INDEX],y[f.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[x]=y[1],this._data[3*x+0]=2097152|x|y[f.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*x+0]=y[f.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|y[f.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(x){return this._data[3*x+0]>>22}hasWidth(x){return 12582912&this._data[3*x+0]}getFg(x){return this._data[3*x+1]}getBg(x){return this._data[3*x+2]}hasContent(x){return 4194303&this._data[3*x+0]}getCodePoint(x){const y=this._data[3*x+0];return 2097152&y?this._combined[x].charCodeAt(this._combined[x].length-1):2097151&y}isCombined(x){return 2097152&this._data[3*x+0]}getString(x){const y=this._data[3*x+0];return 2097152&y?this._combined[x]:2097151&y?(0,b.stringFromCodePoint)(2097151&y):""}isProtected(x){return 536870912&this._data[3*x+2]}loadCell(x,y){return S=3*x,y.content=this._data[S+0],y.fg=this._data[S+1],y.bg=this._data[S+2],2097152&y.content&&(y.combinedData=this._combined[x]),268435456&y.bg&&(y.extended=this._extendedAttrs[x]),y}setCell(x,y){2097152&y.content&&(this._combined[x]=y.combinedData),268435456&y.bg&&(this._extendedAttrs[x]=y.extended),this._data[3*x+0]=y.content,this._data[3*x+1]=y.fg,this._data[3*x+2]=y.bg}setCellFromCodepoint(x,y,_,E){268435456&E.bg&&(this._extendedAttrs[x]=E.extended),this._data[3*x+0]=y|_<<22,this._data[3*x+1]=E.fg,this._data[3*x+2]=E.bg}addCodepointToCell(x,y,_){let E=this._data[3*x+0];2097152&E?this._combined[x]+=(0,b.stringFromCodePoint)(y):2097151&E?(this._combined[x]=(0,b.stringFromCodePoint)(2097151&E)+(0,b.stringFromCodePoint)(y),E&=-2097152,E|=2097152):E=y|4194304,_&&(E&=-12582913,E|=_<<22),this._data[3*x+0]=E}insertCells(x,y,_){if((x%=this.length)&&this.getWidth(x-1)===2&&this.setCellFromCodepoint(x-1,0,1,_),y<this.length-x){const E=new m.CellData;for(let j=this.length-x-y-1;j>=0;--j)this.setCell(x+y+j,this.loadCell(x+j,E));for(let j=0;j<y;++j)this.setCell(x+j,_)}else for(let E=x;E<this.length;++E)this.setCell(E,_);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,_)}deleteCells(x,y,_){if(x%=this.length,y<this.length-x){const E=new m.CellData;for(let j=0;j<this.length-x-y;++j)this.setCell(x+j,this.loadCell(x+y+j,E));for(let j=this.length-y;j<this.length;++j)this.setCell(j,_)}else for(let E=x;E<this.length;++E)this.setCell(E,_);x&&this.getWidth(x-1)===2&&this.setCellFromCodepoint(x-1,0,1,_),this.getWidth(x)!==0||this.hasContent(x)||this.setCellFromCodepoint(x,0,1,_)}replaceCells(x,y,_,E=!1){if(E)for(x&&this.getWidth(x-1)===2&&!this.isProtected(x-1)&&this.setCellFromCodepoint(x-1,0,1,_),y<this.length&&this.getWidth(y-1)===2&&!this.isProtected(y)&&this.setCellFromCodepoint(y,0,1,_);x<y&&x<this.length;)this.isProtected(x)||this.setCell(x,_),x++;else for(x&&this.getWidth(x-1)===2&&this.setCellFromCodepoint(x-1,0,1,_),y<this.length&&this.getWidth(y-1)===2&&this.setCellFromCodepoint(y,0,1,_);x<y&&x<this.length;)this.setCell(x++,_)}resize(x,y){if(x===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const _=3*x;if(x>this.length){if(this._data.buffer.byteLength>=4*_)this._data=new Uint32Array(this._data.buffer,0,_);else{const E=new Uint32Array(_);E.set(this._data),this._data=E}for(let E=this.length;E<x;++E)this.setCell(E,y)}else{this._data=this._data.subarray(0,_);const E=Object.keys(this._combined);for(let D=0;D<E.length;D++){const $=parseInt(E[D],10);$>=x&&delete this._combined[$]}const j=Object.keys(this._extendedAttrs);for(let D=0;D<j.length;D++){const $=parseInt(j[D],10);$>=x&&delete this._extendedAttrs[$]}}return this.length=x,4*_*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const x=new Uint32Array(this._data.length);return x.set(this._data),this._data=x,1}return 0}fill(x,y=!1){if(y)for(let _=0;_<this.length;++_)this.isProtected(_)||this.setCell(_,x);else{this._combined={},this._extendedAttrs={};for(let _=0;_<this.length;++_)this.setCell(_,x)}}copyFrom(x){this.length!==x.length?this._data=new Uint32Array(x._data):this._data.set(x._data),this.length=x.length,this._combined={};for(const y in x._combined)this._combined[y]=x._combined[y];this._extendedAttrs={};for(const y in x._extendedAttrs)this._extendedAttrs[y]=x._extendedAttrs[y];this.isWrapped=x.isWrapped}clone(){const x=new w(0);x._data=new Uint32Array(this._data),x.length=this.length;for(const y in this._combined)x._combined[y]=this._combined[y];for(const y in this._extendedAttrs)x._extendedAttrs[y]=this._extendedAttrs[y];return x.isWrapped=this.isWrapped,x}getTrimmedLength(){for(let x=this.length-1;x>=0;--x)if(4194303&this._data[3*x+0])return x+(this._data[3*x+0]>>22);return 0}getNoBgTrimmedLength(){for(let x=this.length-1;x>=0;--x)if(4194303&this._data[3*x+0]||50331648&this._data[3*x+2])return x+(this._data[3*x+0]>>22);return 0}copyCellsFrom(x,y,_,E,j){const D=x._data;if(j)for(let I=E-1;I>=0;I--){for(let P=0;P<3;P++)this._data[3*(_+I)+P]=D[3*(y+I)+P];268435456&D[3*(y+I)+2]&&(this._extendedAttrs[_+I]=x._extendedAttrs[y+I])}else for(let I=0;I<E;I++){for(let P=0;P<3;P++)this._data[3*(_+I)+P]=D[3*(y+I)+P];268435456&D[3*(y+I)+2]&&(this._extendedAttrs[_+I]=x._extendedAttrs[y+I])}const $=Object.keys(x._combined);for(let I=0;I<$.length;I++){const P=parseInt($[I],10);P>=y&&(this._combined[P-y+_]=x._combined[P])}}translateToString(x,y,_,E){y=y??0,_=_??this.length,x&&(_=Math.min(_,this.getTrimmedLength())),E&&(E.length=0);let j="";for(;y<_;){const D=this._data[3*y+0],$=2097151&D,I=2097152&D?this._combined[y]:$?(0,b.stringFromCodePoint)($):f.WHITESPACE_CELL_CHAR;if(j+=I,E)for(let P=0;P<I.length;++P)E.push(y);y+=D>>22||1}return E&&E.push(y),j}}l.BufferLine=w},4841:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.getRangeLength=void 0,l.getRangeLength=function(d,p){if(d.start.y>d.end.y)throw new Error(`Buffer range end (${d.end.x}, ${d.end.y}) cannot be before start (${d.start.x}, ${d.start.y})`);return p*(d.end.y-d.start.y)+(d.end.x-d.start.x+1)}},4634:(u,l)=>{function d(p,m,f){if(m===p.length-1)return p[m].getTrimmedLength();const b=!p[m].hasContent(f-1)&&p[m].getWidth(f-1)===1,S=p[m+1].getWidth(0)===2;return b&&S?f-1:f}Object.defineProperty(l,"__esModule",{value:!0}),l.getWrappedLineTrimmedLength=l.reflowSmallerGetNewLineLengths=l.reflowLargerApplyNewLayout=l.reflowLargerCreateNewLayout=l.reflowLargerGetLinesToRemove=void 0,l.reflowLargerGetLinesToRemove=function(p,m,f,b,S){const w=[];for(let C=0;C<p.length-1;C++){let x=C,y=p.get(++x);if(!y.isWrapped)continue;const _=[p.get(C)];for(;x<p.length&&y.isWrapped;)_.push(y),y=p.get(++x);if(b>=C&&b<x){C+=_.length-1;continue}let E=0,j=d(_,E,m),D=1,$=0;for(;D<_.length;){const P=d(_,D,m),L=P-$,B=f-j,U=Math.min(L,B);_[E].copyCellsFrom(_[D],$,j,U,!1),j+=U,j===f&&(E++,j=0),$+=U,$===P&&(D++,$=0),j===0&&E!==0&&_[E-1].getWidth(f-1)===2&&(_[E].copyCellsFrom(_[E-1],f-1,j++,1,!1),_[E-1].setCell(f-1,S))}_[E].replaceCells(j,f,S);let I=0;for(let P=_.length-1;P>0&&(P>E||_[P].getTrimmedLength()===0);P--)I++;I>0&&(w.push(C+_.length-I),w.push(I)),C+=_.length-1}return w},l.reflowLargerCreateNewLayout=function(p,m){const f=[];let b=0,S=m[b],w=0;for(let C=0;C<p.length;C++)if(S===C){const x=m[++b];p.onDeleteEmitter.fire({index:C-w,amount:x}),C+=x-1,w+=x,S=m[++b]}else f.push(C);return{layout:f,countRemoved:w}},l.reflowLargerApplyNewLayout=function(p,m){const f=[];for(let b=0;b<m.length;b++)f.push(p.get(m[b]));for(let b=0;b<f.length;b++)p.set(b,f[b]);p.length=m.length},l.reflowSmallerGetNewLineLengths=function(p,m,f){const b=[],S=p.map(((y,_)=>d(p,_,m))).reduce(((y,_)=>y+_));let w=0,C=0,x=0;for(;x<S;){if(S-x<f){b.push(S-x);break}w+=f;const y=d(p,C,m);w>y&&(w-=y,C++);const _=p[C].getWidth(w-1)===2;_&&w--;const E=_?f-1:f;b.push(E),x+=E}return b},l.getWrappedLineTrimmedLength=d},5295:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferSet=void 0;const p=d(8460),m=d(844),f=d(9092);class b extends m.Disposable{constructor(w,C){super(),this._optionsService=w,this._bufferService=C,this._onBufferActivate=this.register(new p.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 f.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new f.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(w){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(w),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(w,C){this._normal.resize(w,C),this._alt.resize(w,C),this.setupTabStops(w)}setupTabStops(w){this._normal.setupTabStops(w),this._alt.setupTabStops(w)}}l.BufferSet=b},511:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CellData=void 0;const p=d(482),m=d(643),f=d(3734);class b extends f.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new f.ExtendedAttrs,this.combinedData=""}static fromCharData(w){const C=new b;return C.setFromCharData(w),C}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,p.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(w){this.fg=w[m.CHAR_DATA_ATTR_INDEX],this.bg=0;let C=!1;if(w[m.CHAR_DATA_CHAR_INDEX].length>2)C=!0;else if(w[m.CHAR_DATA_CHAR_INDEX].length===2){const x=w[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=x&&x<=56319){const y=w[m.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=y&&y<=57343?this.content=1024*(x-55296)+y-56320+65536|w[m.CHAR_DATA_WIDTH_INDEX]<<22:C=!0}else C=!0}else this.content=w[m.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|w[m.CHAR_DATA_WIDTH_INDEX]<<22;C&&(this.combinedData=w[m.CHAR_DATA_CHAR_INDEX],this.content=2097152|w[m.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}l.CellData=b},643:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.WHITESPACE_CELL_CODE=l.WHITESPACE_CELL_WIDTH=l.WHITESPACE_CELL_CHAR=l.NULL_CELL_CODE=l.NULL_CELL_WIDTH=l.NULL_CELL_CHAR=l.CHAR_DATA_CODE_INDEX=l.CHAR_DATA_WIDTH_INDEX=l.CHAR_DATA_CHAR_INDEX=l.CHAR_DATA_ATTR_INDEX=l.DEFAULT_EXT=l.DEFAULT_ATTR=l.DEFAULT_COLOR=void 0,l.DEFAULT_COLOR=0,l.DEFAULT_ATTR=256|l.DEFAULT_COLOR<<9,l.DEFAULT_EXT=0,l.CHAR_DATA_ATTR_INDEX=0,l.CHAR_DATA_CHAR_INDEX=1,l.CHAR_DATA_WIDTH_INDEX=2,l.CHAR_DATA_CODE_INDEX=3,l.NULL_CELL_CHAR="",l.NULL_CELL_WIDTH=1,l.NULL_CELL_CODE=0,l.WHITESPACE_CELL_CHAR=" ",l.WHITESPACE_CELL_WIDTH=1,l.WHITESPACE_CELL_CODE=32},4863:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Marker=void 0;const p=d(8460),m=d(844);class f{get id(){return this._id}constructor(S){this.line=S,this.isDisposed=!1,this._disposables=[],this._id=f._nextId++,this._onDispose=this.register(new p.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,m.disposeArray)(this._disposables),this._disposables.length=0)}register(S){return this._disposables.push(S),S}}l.Marker=f,f._nextId=1},7116:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DEFAULT_CHARSET=l.CHARSETS=void 0,l.CHARSETS={},l.DEFAULT_CHARSET=l.CHARSETS.B,l.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:"≥","{":"π","|":"≠","}":"£","~":"·"},l.CHARSETS.A={"#":"£"},l.CHARSETS.B=void 0,l.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},l.CHARSETS.C=l.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},l.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},l.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},l.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},l.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},l.CHARSETS.E=l.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},l.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},l.CHARSETS.H=l.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},l.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(u,l)=>{var d,p,m;Object.defineProperty(l,"__esModule",{value:!0}),l.C1_ESCAPED=l.C1=l.C0=void 0,(function(f){f.NUL="\0",f.SOH="",f.STX="",f.ETX="",f.EOT="",f.ENQ="",f.ACK="",f.BEL="\x07",f.BS="\b",f.HT=" ",f.LF=`
|
|
3168
3168
|
`,f.VT="\v",f.FF="\f",f.CR="\r",f.SO="",f.SI="",f.DLE="",f.DC1="",f.DC2="",f.DC3="",f.DC4="",f.NAK="",f.SYN="",f.ETB="",f.CAN="",f.EM="",f.SUB="",f.ESC="\x1B",f.FS="",f.GS="",f.RS="",f.US="",f.SP=" ",f.DEL=""})(d||(l.C0=d={})),(function(f){f.PAD="",f.HOP="",f.BPH="",f.NBH="",f.IND="",f.NEL="
",f.SSA="",f.ESA="",f.HTS="",f.HTJ="",f.VTS="",f.PLD="",f.PLU="",f.RI="",f.SS2="",f.SS3="",f.DCS="",f.PU1="",f.PU2="",f.STS="",f.CCH="",f.MW="",f.SPA="",f.EPA="",f.SOS="",f.SGCI="",f.SCI="",f.CSI="",f.ST="",f.OSC="",f.PM="",f.APC=""})(p||(l.C1=p={})),(function(f){f.ST=`${d.ESC}\\`})(m||(l.C1_ESCAPED=m={}))},7399:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.evaluateKeyboardEvent=void 0;const p=d(2584),m={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:["'",'"']};l.evaluateKeyboardEvent=function(f,b,S,w){const C={type:0,cancel:!1,key:void 0},x=(f.shiftKey?1:0)|(f.altKey?2:0)|(f.ctrlKey?4:0)|(f.metaKey?8:0);switch(f.keyCode){case 0:f.key==="UIKeyInputUpArrow"?C.key=b?p.C0.ESC+"OA":p.C0.ESC+"[A":f.key==="UIKeyInputLeftArrow"?C.key=b?p.C0.ESC+"OD":p.C0.ESC+"[D":f.key==="UIKeyInputRightArrow"?C.key=b?p.C0.ESC+"OC":p.C0.ESC+"[C":f.key==="UIKeyInputDownArrow"&&(C.key=b?p.C0.ESC+"OB":p.C0.ESC+"[B");break;case 8:C.key=f.ctrlKey?"\b":p.C0.DEL,f.altKey&&(C.key=p.C0.ESC+C.key);break;case 9:if(f.shiftKey){C.key=p.C0.ESC+"[Z";break}C.key=p.C0.HT,C.cancel=!0;break;case 13:C.key=f.altKey?p.C0.ESC+p.C0.CR:p.C0.CR,C.cancel=!0;break;case 27:C.key=p.C0.ESC,f.altKey&&(C.key=p.C0.ESC+p.C0.ESC),C.cancel=!0;break;case 37:if(f.metaKey)break;x?(C.key=p.C0.ESC+"[1;"+(x+1)+"D",C.key===p.C0.ESC+"[1;3D"&&(C.key=p.C0.ESC+(S?"b":"[1;5D"))):C.key=b?p.C0.ESC+"OD":p.C0.ESC+"[D";break;case 39:if(f.metaKey)break;x?(C.key=p.C0.ESC+"[1;"+(x+1)+"C",C.key===p.C0.ESC+"[1;3C"&&(C.key=p.C0.ESC+(S?"f":"[1;5C"))):C.key=b?p.C0.ESC+"OC":p.C0.ESC+"[C";break;case 38:if(f.metaKey)break;x?(C.key=p.C0.ESC+"[1;"+(x+1)+"A",S||C.key!==p.C0.ESC+"[1;3A"||(C.key=p.C0.ESC+"[1;5A")):C.key=b?p.C0.ESC+"OA":p.C0.ESC+"[A";break;case 40:if(f.metaKey)break;x?(C.key=p.C0.ESC+"[1;"+(x+1)+"B",S||C.key!==p.C0.ESC+"[1;3B"||(C.key=p.C0.ESC+"[1;5B")):C.key=b?p.C0.ESC+"OB":p.C0.ESC+"[B";break;case 45:f.shiftKey||f.ctrlKey||(C.key=p.C0.ESC+"[2~");break;case 46:C.key=x?p.C0.ESC+"[3;"+(x+1)+"~":p.C0.ESC+"[3~";break;case 36:C.key=x?p.C0.ESC+"[1;"+(x+1)+"H":b?p.C0.ESC+"OH":p.C0.ESC+"[H";break;case 35:C.key=x?p.C0.ESC+"[1;"+(x+1)+"F":b?p.C0.ESC+"OF":p.C0.ESC+"[F";break;case 33:f.shiftKey?C.type=2:f.ctrlKey?C.key=p.C0.ESC+"[5;"+(x+1)+"~":C.key=p.C0.ESC+"[5~";break;case 34:f.shiftKey?C.type=3:f.ctrlKey?C.key=p.C0.ESC+"[6;"+(x+1)+"~":C.key=p.C0.ESC+"[6~";break;case 112:C.key=x?p.C0.ESC+"[1;"+(x+1)+"P":p.C0.ESC+"OP";break;case 113:C.key=x?p.C0.ESC+"[1;"+(x+1)+"Q":p.C0.ESC+"OQ";break;case 114:C.key=x?p.C0.ESC+"[1;"+(x+1)+"R":p.C0.ESC+"OR";break;case 115:C.key=x?p.C0.ESC+"[1;"+(x+1)+"S":p.C0.ESC+"OS";break;case 116:C.key=x?p.C0.ESC+"[15;"+(x+1)+"~":p.C0.ESC+"[15~";break;case 117:C.key=x?p.C0.ESC+"[17;"+(x+1)+"~":p.C0.ESC+"[17~";break;case 118:C.key=x?p.C0.ESC+"[18;"+(x+1)+"~":p.C0.ESC+"[18~";break;case 119:C.key=x?p.C0.ESC+"[19;"+(x+1)+"~":p.C0.ESC+"[19~";break;case 120:C.key=x?p.C0.ESC+"[20;"+(x+1)+"~":p.C0.ESC+"[20~";break;case 121:C.key=x?p.C0.ESC+"[21;"+(x+1)+"~":p.C0.ESC+"[21~";break;case 122:C.key=x?p.C0.ESC+"[23;"+(x+1)+"~":p.C0.ESC+"[23~";break;case 123:C.key=x?p.C0.ESC+"[24;"+(x+1)+"~":p.C0.ESC+"[24~";break;default:if(!f.ctrlKey||f.shiftKey||f.altKey||f.metaKey)if(S&&!w||!f.altKey||f.metaKey)!S||f.altKey||f.ctrlKey||f.shiftKey||!f.metaKey?f.key&&!f.ctrlKey&&!f.altKey&&!f.metaKey&&f.keyCode>=48&&f.key.length===1?C.key=f.key:f.key&&f.ctrlKey&&(f.key==="_"&&(C.key=p.C0.US),f.key==="@"&&(C.key=p.C0.NUL)):f.keyCode===65&&(C.type=1);else{const y=m[f.keyCode],_=y==null?void 0:y[f.shiftKey?1:0];if(_)C.key=p.C0.ESC+_;else if(f.keyCode>=65&&f.keyCode<=90){const E=f.ctrlKey?f.keyCode-64:f.keyCode+32;let j=String.fromCharCode(E);f.shiftKey&&(j=j.toUpperCase()),C.key=p.C0.ESC+j}else if(f.keyCode===32)C.key=p.C0.ESC+(f.ctrlKey?p.C0.NUL:" ");else if(f.key==="Dead"&&f.code.startsWith("Key")){let E=f.code.slice(3,4);f.shiftKey||(E=E.toLowerCase()),C.key=p.C0.ESC+E,C.cancel=!0}}else f.keyCode>=65&&f.keyCode<=90?C.key=String.fromCharCode(f.keyCode-64):f.keyCode===32?C.key=p.C0.NUL:f.keyCode>=51&&f.keyCode<=55?C.key=String.fromCharCode(f.keyCode-51+27):f.keyCode===56?C.key=p.C0.DEL:f.keyCode===219?C.key=p.C0.ESC:f.keyCode===220?C.key=p.C0.FS:f.keyCode===221&&(C.key=p.C0.GS)}return C}},482:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Utf8ToUtf32=l.StringToUtf32=l.utf32ToString=l.stringFromCodePoint=void 0,l.stringFromCodePoint=function(d){return d>65535?(d-=65536,String.fromCharCode(55296+(d>>10))+String.fromCharCode(d%1024+56320)):String.fromCharCode(d)},l.utf32ToString=function(d,p=0,m=d.length){let f="";for(let b=p;b<m;++b){let S=d[b];S>65535?(S-=65536,f+=String.fromCharCode(55296+(S>>10))+String.fromCharCode(S%1024+56320)):f+=String.fromCharCode(S)}return f},l.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(d,p){const m=d.length;if(!m)return 0;let f=0,b=0;if(this._interim){const S=d.charCodeAt(b++);56320<=S&&S<=57343?p[f++]=1024*(this._interim-55296)+S-56320+65536:(p[f++]=this._interim,p[f++]=S),this._interim=0}for(let S=b;S<m;++S){const w=d.charCodeAt(S);if(55296<=w&&w<=56319){if(++S>=m)return this._interim=w,f;const C=d.charCodeAt(S);56320<=C&&C<=57343?p[f++]=1024*(w-55296)+C-56320+65536:(p[f++]=w,p[f++]=C)}else w!==65279&&(p[f++]=w)}return f}},l.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(d,p){const m=d.length;if(!m)return 0;let f,b,S,w,C=0,x=0,y=0;if(this.interim[0]){let j=!1,D=this.interim[0];D&=(224&D)==192?31:(240&D)==224?15:7;let $,I=0;for(;($=63&this.interim[++I])&&I<4;)D<<=6,D|=$;const P=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,L=P-I;for(;y<L;){if(y>=m)return 0;if($=d[y++],(192&$)!=128){y--,j=!0;break}this.interim[I++]=$,D<<=6,D|=63&$}j||(P===2?D<128?y--:p[C++]=D:P===3?D<2048||D>=55296&&D<=57343||D===65279||(p[C++]=D):D<65536||D>1114111||(p[C++]=D)),this.interim.fill(0)}const _=m-4;let E=y;for(;E<m;){for(;!(!(E<_)||128&(f=d[E])||128&(b=d[E+1])||128&(S=d[E+2])||128&(w=d[E+3]));)p[C++]=f,p[C++]=b,p[C++]=S,p[C++]=w,E+=4;if(f=d[E++],f<128)p[C++]=f;else if((224&f)==192){if(E>=m)return this.interim[0]=f,C;if(b=d[E++],(192&b)!=128){E--;continue}if(x=(31&f)<<6|63&b,x<128){E--;continue}p[C++]=x}else if((240&f)==224){if(E>=m)return this.interim[0]=f,C;if(b=d[E++],(192&b)!=128){E--;continue}if(E>=m)return this.interim[0]=f,this.interim[1]=b,C;if(S=d[E++],(192&S)!=128){E--;continue}if(x=(15&f)<<12|(63&b)<<6|63&S,x<2048||x>=55296&&x<=57343||x===65279)continue;p[C++]=x}else if((248&f)==240){if(E>=m)return this.interim[0]=f,C;if(b=d[E++],(192&b)!=128){E--;continue}if(E>=m)return this.interim[0]=f,this.interim[1]=b,C;if(S=d[E++],(192&S)!=128){E--;continue}if(E>=m)return this.interim[0]=f,this.interim[1]=b,this.interim[2]=S,C;if(w=d[E++],(192&w)!=128){E--;continue}if(x=(7&f)<<18|(63&b)<<12|(63&S)<<6|63&w,x<65536||x>1114111)continue;p[C++]=x}}return C}}},225:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeV6=void 0;const p=d(1480),m=[[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 b;l.UnicodeV6=class{constructor(){if(this.version="6",!b){b=new Uint8Array(65536),b.fill(1),b[0]=0,b.fill(0,1,32),b.fill(0,127,160),b.fill(2,4352,4448),b[9001]=2,b[9002]=2,b.fill(2,11904,42192),b[12351]=1,b.fill(2,44032,55204),b.fill(2,63744,64256),b.fill(2,65040,65050),b.fill(2,65072,65136),b.fill(2,65280,65377),b.fill(2,65504,65511);for(let S=0;S<m.length;++S)b.fill(0,m[S][0],m[S][1]+1)}}wcwidth(S){return S<32?0:S<127?1:S<65536?b[S]:(function(w,C){let x,y=0,_=C.length-1;if(w<C[0][0]||w>C[_][1])return!1;for(;_>=y;)if(x=y+_>>1,w>C[x][1])y=x+1;else{if(!(w<C[x][0]))return!0;_=x-1}return!1})(S,f)?0:S>=131072&&S<=196605||S>=196608&&S<=262141?2:1}charProperties(S,w){let C=this.wcwidth(S),x=C===0&&w!==0;if(x){const y=p.UnicodeService.extractWidth(w);y===0?x=!1:y>C&&(C=y)}return p.UnicodeService.createPropertyValue(0,C,x)}}},5981:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.WriteBuffer=void 0;const p=d(8460),m=d(844);class f extends m.Disposable{constructor(S){super(),this._action=S,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new p.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(S,w){if(w!==void 0&&this._syncCalls>w)return void(this._syncCalls=0);if(this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let C;for(this._isSyncWriting=!0;C=this._writeBuffer.shift();){this._action(C);const x=this._callbacks.shift();x&&x()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(S,w){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+=S.length,this._writeBuffer.push(S),this._callbacks.push(w),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=S.length,this._writeBuffer.push(S),this._callbacks.push(w)}_innerWrite(S=0,w=!0){const C=S||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const x=this._writeBuffer[this._bufferOffset],y=this._action(x,w);if(y){const E=j=>Date.now()-C>=12?setTimeout((()=>this._innerWrite(0,j))):this._innerWrite(C,j);return void y.catch((j=>(queueMicrotask((()=>{throw j})),Promise.resolve(!1)))).then(E)}const _=this._callbacks[this._bufferOffset];if(_&&_(),this._bufferOffset++,this._pendingData-=x.length,Date.now()-C>=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()}}l.WriteBuffer=f},5941:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.toRgbString=l.parseColor=void 0;const d=/^([\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})$/,p=/^[\da-f]+$/;function m(f,b){const S=f.toString(16),w=S.length<2?"0"+S:S;switch(b){case 4:return S[0];case 8:return w;case 12:return(w+w).slice(0,3);default:return w+w}}l.parseColor=function(f){if(!f)return;let b=f.toLowerCase();if(b.indexOf("rgb:")===0){b=b.slice(4);const S=d.exec(b);if(S){const w=S[1]?15:S[4]?255:S[7]?4095:65535;return[Math.round(parseInt(S[1]||S[4]||S[7]||S[10],16)/w*255),Math.round(parseInt(S[2]||S[5]||S[8]||S[11],16)/w*255),Math.round(parseInt(S[3]||S[6]||S[9]||S[12],16)/w*255)]}}else if(b.indexOf("#")===0&&(b=b.slice(1),p.exec(b)&&[3,6,9,12].includes(b.length))){const S=b.length/3,w=[0,0,0];for(let C=0;C<3;++C){const x=parseInt(b.slice(S*C,S*C+S),16);w[C]=S===1?x<<4:S===2?x:S===3?x>>4:x>>8}return w}},l.toRgbString=function(f,b=16){const[S,w,C]=f;return`rgb:${m(S,b)}/${m(w,b)}/${m(C,b)}`}},5770:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.PAYLOAD_LIMIT=void 0,l.PAYLOAD_LIMIT=1e7},6351:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DcsHandler=l.DcsParser=void 0;const p=d(482),m=d(8742),f=d(5770),b=[];l.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=b,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=b}registerHandler(w,C){this._handlers[w]===void 0&&(this._handlers[w]=[]);const x=this._handlers[w];return x.push(C),{dispose:()=>{const y=x.indexOf(C);y!==-1&&x.splice(y,1)}}}clearHandler(w){this._handlers[w]&&delete this._handlers[w]}setHandlerFallback(w){this._handlerFb=w}reset(){if(this._active.length)for(let w=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;w>=0;--w)this._active[w].unhook(!1);this._stack.paused=!1,this._active=b,this._ident=0}hook(w,C){if(this.reset(),this._ident=w,this._active=this._handlers[w]||b,this._active.length)for(let x=this._active.length-1;x>=0;x--)this._active[x].hook(C);else this._handlerFb(this._ident,"HOOK",C)}put(w,C,x){if(this._active.length)for(let y=this._active.length-1;y>=0;y--)this._active[y].put(w,C,x);else this._handlerFb(this._ident,"PUT",(0,p.utf32ToString)(w,C,x))}unhook(w,C=!0){if(this._active.length){let x=!1,y=this._active.length-1,_=!1;if(this._stack.paused&&(y=this._stack.loopPosition-1,x=C,_=this._stack.fallThrough,this._stack.paused=!1),!_&&x===!1){for(;y>=0&&(x=this._active[y].unhook(w),x!==!0);y--)if(x instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!1,x;y--}for(;y>=0;y--)if(x=this._active[y].unhook(!1),x instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=y,this._stack.fallThrough=!0,x}else this._handlerFb(this._ident,"UNHOOK",w);this._active=b,this._ident=0}};const S=new m.Params;S.addParam(0),l.DcsHandler=class{constructor(w){this._handler=w,this._data="",this._params=S,this._hitLimit=!1}hook(w){this._params=w.length>1||w.params[0]?w.clone():S,this._data="",this._hitLimit=!1}put(w,C,x){this._hitLimit||(this._data+=(0,p.utf32ToString)(w,C,x),this._data.length>f.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(w){let C=!1;if(this._hitLimit)C=!1;else if(w&&(C=this._handler(this._data,this._params),C instanceof Promise))return C.then((x=>(this._params=S,this._data="",this._hitLimit=!1,x)));return this._params=S,this._data="",this._hitLimit=!1,C}}},2015:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.EscapeSequenceParser=l.VT500_TRANSITION_TABLE=l.TransitionTable=void 0;const p=d(844),m=d(8742),f=d(6242),b=d(6351);class S{constructor(y){this.table=new Uint8Array(y)}setDefault(y,_){this.table.fill(y<<4|_)}add(y,_,E,j){this.table[_<<8|y]=E<<4|j}addMany(y,_,E,j){for(let D=0;D<y.length;D++)this.table[_<<8|y[D]]=E<<4|j}}l.TransitionTable=S;const w=160;l.VT500_TRANSITION_TABLE=(function(){const x=new S(4095),y=Array.apply(null,Array(256)).map(((I,P)=>P)),_=(I,P)=>y.slice(I,P),E=_(32,127),j=_(0,24);j.push(25),j.push.apply(j,_(28,32));const D=_(0,14);let $;for($ in x.setDefault(1,0),x.addMany(E,0,2,0),D)x.addMany([24,26,153,154],$,3,0),x.addMany(_(128,144),$,3,0),x.addMany(_(144,152),$,3,0),x.add(156,$,0,0),x.add(27,$,11,1),x.add(157,$,4,8),x.addMany([152,158,159],$,0,7),x.add(155,$,11,3),x.add(144,$,11,9);return x.addMany(j,0,3,0),x.addMany(j,1,3,1),x.add(127,1,0,1),x.addMany(j,8,0,8),x.addMany(j,3,3,3),x.add(127,3,0,3),x.addMany(j,4,3,4),x.add(127,4,0,4),x.addMany(j,6,3,6),x.addMany(j,5,3,5),x.add(127,5,0,5),x.addMany(j,2,3,2),x.add(127,2,0,2),x.add(93,1,4,8),x.addMany(E,8,5,8),x.add(127,8,5,8),x.addMany([156,27,24,26,7],8,6,0),x.addMany(_(28,32),8,0,8),x.addMany([88,94,95],1,0,7),x.addMany(E,7,0,7),x.addMany(j,7,0,7),x.add(156,7,0,0),x.add(127,7,0,7),x.add(91,1,11,3),x.addMany(_(64,127),3,7,0),x.addMany(_(48,60),3,8,4),x.addMany([60,61,62,63],3,9,4),x.addMany(_(48,60),4,8,4),x.addMany(_(64,127),4,7,0),x.addMany([60,61,62,63],4,0,6),x.addMany(_(32,64),6,0,6),x.add(127,6,0,6),x.addMany(_(64,127),6,0,0),x.addMany(_(32,48),3,9,5),x.addMany(_(32,48),5,9,5),x.addMany(_(48,64),5,0,6),x.addMany(_(64,127),5,7,0),x.addMany(_(32,48),4,9,5),x.addMany(_(32,48),1,9,2),x.addMany(_(32,48),2,9,2),x.addMany(_(48,127),2,10,0),x.addMany(_(48,80),1,10,0),x.addMany(_(81,88),1,10,0),x.addMany([89,90,92],1,10,0),x.addMany(_(96,127),1,10,0),x.add(80,1,11,9),x.addMany(j,9,0,9),x.add(127,9,0,9),x.addMany(_(28,32),9,0,9),x.addMany(_(32,48),9,9,12),x.addMany(_(48,60),9,8,10),x.addMany([60,61,62,63],9,9,10),x.addMany(j,11,0,11),x.addMany(_(32,128),11,0,11),x.addMany(_(28,32),11,0,11),x.addMany(j,10,0,10),x.add(127,10,0,10),x.addMany(_(28,32),10,0,10),x.addMany(_(48,60),10,8,10),x.addMany([60,61,62,63],10,0,11),x.addMany(_(32,48),10,9,12),x.addMany(j,12,0,12),x.add(127,12,0,12),x.addMany(_(28,32),12,0,12),x.addMany(_(32,48),12,9,12),x.addMany(_(48,64),12,0,11),x.addMany(_(64,127),12,12,13),x.addMany(_(64,127),10,12,13),x.addMany(_(64,127),9,12,13),x.addMany(j,13,13,13),x.addMany(E,13,13,13),x.add(127,13,0,13),x.addMany([27,156,24,26],13,14,0),x.add(w,0,2,0),x.add(w,8,5,8),x.add(w,6,0,6),x.add(w,11,0,11),x.add(w,13,13,13),x})();class C extends p.Disposable{constructor(y=l.VT500_TRANSITION_TABLE){super(),this._transitions=y,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new m.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(_,E,j)=>{},this._executeHandlerFb=_=>{},this._csiHandlerFb=(_,E)=>{},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,p.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new f.OscParser),this._dcsParser=this.register(new b.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(y,_=[64,126]){let E=0;if(y.prefix){if(y.prefix.length>1)throw new Error("only one byte as prefix supported");if(E=y.prefix.charCodeAt(0),E&&60>E||E>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(y.intermediates){if(y.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let D=0;D<y.intermediates.length;++D){const $=y.intermediates.charCodeAt(D);if(32>$||$>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");E<<=8,E|=$}}if(y.final.length!==1)throw new Error("final must be a single byte");const j=y.final.charCodeAt(0);if(_[0]>j||j>_[1])throw new Error(`final must be in range ${_[0]} .. ${_[1]}`);return E<<=8,E|=j,E}identToString(y){const _=[];for(;y;)_.push(String.fromCharCode(255&y)),y>>=8;return _.reverse().join("")}setPrintHandler(y){this._printHandler=y}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(y,_){const E=this._identifier(y,[48,126]);this._escHandlers[E]===void 0&&(this._escHandlers[E]=[]);const j=this._escHandlers[E];return j.push(_),{dispose:()=>{const D=j.indexOf(_);D!==-1&&j.splice(D,1)}}}clearEscHandler(y){this._escHandlers[this._identifier(y,[48,126])]&&delete this._escHandlers[this._identifier(y,[48,126])]}setEscHandlerFallback(y){this._escHandlerFb=y}setExecuteHandler(y,_){this._executeHandlers[y.charCodeAt(0)]=_}clearExecuteHandler(y){this._executeHandlers[y.charCodeAt(0)]&&delete this._executeHandlers[y.charCodeAt(0)]}setExecuteHandlerFallback(y){this._executeHandlerFb=y}registerCsiHandler(y,_){const E=this._identifier(y);this._csiHandlers[E]===void 0&&(this._csiHandlers[E]=[]);const j=this._csiHandlers[E];return j.push(_),{dispose:()=>{const D=j.indexOf(_);D!==-1&&j.splice(D,1)}}}clearCsiHandler(y){this._csiHandlers[this._identifier(y)]&&delete this._csiHandlers[this._identifier(y)]}setCsiHandlerFallback(y){this._csiHandlerFb=y}registerDcsHandler(y,_){return this._dcsParser.registerHandler(this._identifier(y),_)}clearDcsHandler(y){this._dcsParser.clearHandler(this._identifier(y))}setDcsHandlerFallback(y){this._dcsParser.setHandlerFallback(y)}registerOscHandler(y,_){return this._oscParser.registerHandler(y,_)}clearOscHandler(y){this._oscParser.clearHandler(y)}setOscHandlerFallback(y){this._oscParser.setHandlerFallback(y)}setErrorHandler(y){this._errorHandler=y}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.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(y,_,E,j,D){this._parseStack.state=y,this._parseStack.handlers=_,this._parseStack.handlerPos=E,this._parseStack.transition=j,this._parseStack.chunkPos=D}parse(y,_,E){let j,D=0,$=0,I=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,I=this._parseStack.chunkPos+1;else{if(E===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const P=this._parseStack.handlers;let L=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(E===!1&&L>-1){for(;L>=0&&(j=P[L](this._params),j!==!0);L--)if(j instanceof Promise)return this._parseStack.handlerPos=L,j}this._parseStack.handlers=[];break;case 4:if(E===!1&&L>-1){for(;L>=0&&(j=P[L](),j!==!0);L--)if(j instanceof Promise)return this._parseStack.handlerPos=L,j}this._parseStack.handlers=[];break;case 6:if(D=y[this._parseStack.chunkPos],j=this._dcsParser.unhook(D!==24&&D!==26,E),j)return j;D===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(D=y[this._parseStack.chunkPos],j=this._oscParser.end(D!==24&&D!==26,E),j)return j;D===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,I=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let P=I;P<_;++P){switch(D=y[P],$=this._transitions.table[this.currentState<<8|(D<160?D:w)],$>>4){case 2:for(let X=P+1;;++X){if(X>=_||(D=y[X])<32||D>126&&D<w){this._printHandler(y,P,X),P=X-1;break}if(++X>=_||(D=y[X])<32||D>126&&D<w){this._printHandler(y,P,X),P=X-1;break}if(++X>=_||(D=y[X])<32||D>126&&D<w){this._printHandler(y,P,X),P=X-1;break}if(++X>=_||(D=y[X])<32||D>126&&D<w){this._printHandler(y,P,X),P=X-1;break}}break;case 3:this._executeHandlers[D]?this._executeHandlers[D]():this._executeHandlerFb(D),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:P,code:D,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const L=this._csiHandlers[this._collect<<8|D];let B=L?L.length-1:-1;for(;B>=0&&(j=L[B](this._params),j!==!0);B--)if(j instanceof Promise)return this._preserveStack(3,L,B,$,P),j;B<0&&this._csiHandlerFb(this._collect<<8|D,this._params),this.precedingJoinState=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(++P<_&&(D=y[P])>47&&D<60);P--;break;case 9:this._collect<<=8,this._collect|=D;break;case 10:const U=this._escHandlers[this._collect<<8|D];let Z=U?U.length-1:-1;for(;Z>=0&&(j=U[Z](),j!==!0);Z--)if(j instanceof Promise)return this._preserveStack(4,U,Z,$,P),j;Z<0&&this._escHandlerFb(this._collect<<8|D),this.precedingJoinState=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 X=P+1;;++X)if(X>=_||(D=y[X])===24||D===26||D===27||D>127&&D<w){this._dcsParser.put(y,P,X),P=X-1;break}break;case 14:if(j=this._dcsParser.unhook(D!==24&&D!==26),j)return this._preserveStack(6,[],0,$,P),j;D===27&&($|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let X=P+1;;X++)if(X>=_||(D=y[X])<32||D>127&&D<w){this._oscParser.put(y,P,X),P=X-1;break}break;case 6:if(j=this._oscParser.end(D!==24&&D!==26),j)return this._preserveStack(5,[],0,$,P),j;D===27&&($|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&$}}}l.EscapeSequenceParser=C},6242:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.OscHandler=l.OscParser=void 0;const p=d(5770),m=d(482),f=[];l.OscParser=class{constructor(){this._state=0,this._active=f,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(b,S){this._handlers[b]===void 0&&(this._handlers[b]=[]);const w=this._handlers[b];return w.push(S),{dispose:()=>{const C=w.indexOf(S);C!==-1&&w.splice(C,1)}}}clearHandler(b){this._handlers[b]&&delete this._handlers[b]}setHandlerFallback(b){this._handlerFb=b}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=f}reset(){if(this._state===2)for(let b=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;b>=0;--b)this._active[b].end(!1);this._stack.paused=!1,this._active=f,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||f,this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].start();else this._handlerFb(this._id,"START")}_put(b,S,w){if(this._active.length)for(let C=this._active.length-1;C>=0;C--)this._active[C].put(b,S,w);else this._handlerFb(this._id,"PUT",(0,m.utf32ToString)(b,S,w))}start(){this.reset(),this._state=1}put(b,S,w){if(this._state!==3){if(this._state===1)for(;S<w;){const C=b[S++];if(C===59){this._state=2,this._start();break}if(C<48||57<C)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+C-48}this._state===2&&w-S>0&&this._put(b,S,w)}}end(b,S=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let w=!1,C=this._active.length-1,x=!1;if(this._stack.paused&&(C=this._stack.loopPosition-1,w=S,x=this._stack.fallThrough,this._stack.paused=!1),!x&&w===!1){for(;C>=0&&(w=this._active[C].end(b),w!==!0);C--)if(w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=C,this._stack.fallThrough=!1,w;C--}for(;C>=0;C--)if(w=this._active[C].end(!1),w instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=C,this._stack.fallThrough=!0,w}else this._handlerFb(this._id,"END",b);this._active=f,this._id=-1,this._state=0}}},l.OscHandler=class{constructor(b){this._handler=b,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(b,S,w){this._hitLimit||(this._data+=(0,m.utf32ToString)(b,S,w),this._data.length>p.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(b){let S=!1;if(this._hitLimit)S=!1;else if(b&&(S=this._handler(this._data),S instanceof Promise))return S.then((w=>(this._data="",this._hitLimit=!1,w)));return this._data="",this._hitLimit=!1,S}}},8742:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.Params=void 0;const d=2147483647;class p{static fromArray(f){const b=new p;if(!f.length)return b;for(let S=Array.isArray(f[0])?1:0;S<f.length;++S){const w=f[S];if(Array.isArray(w))for(let C=0;C<w.length;++C)b.addSubParam(w[C]);else b.addParam(w)}return b}constructor(f=32,b=32){if(this.maxLength=f,this.maxSubParamsLength=b,b>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(f),this.length=0,this._subParams=new Int32Array(b),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(f),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const f=new p(this.maxLength,this.maxSubParamsLength);return f.params.set(this.params),f.length=this.length,f._subParams.set(this._subParams),f._subParamsLength=this._subParamsLength,f._subParamsIdx.set(this._subParamsIdx),f._rejectDigits=this._rejectDigits,f._rejectSubDigits=this._rejectSubDigits,f._digitIsSub=this._digitIsSub,f}toArray(){const f=[];for(let b=0;b<this.length;++b){f.push(this.params[b]);const S=this._subParamsIdx[b]>>8,w=255&this._subParamsIdx[b];w-S>0&&f.push(Array.prototype.slice.call(this._subParams,S,w))}return f}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(f){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=f>d?d:f}}addSubParam(f){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(f<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=f>d?d:f,this._subParamsIdx[this.length-1]++}}hasSubParams(f){return(255&this._subParamsIdx[f])-(this._subParamsIdx[f]>>8)>0}getSubParams(f){const b=this._subParamsIdx[f]>>8,S=255&this._subParamsIdx[f];return S-b>0?this._subParams.subarray(b,S):null}getSubParamsAll(){const f={};for(let b=0;b<this.length;++b){const S=this._subParamsIdx[b]>>8,w=255&this._subParamsIdx[b];w-S>0&&(f[b]=this._subParams.slice(S,w))}return f}addDigit(f){let b;if(this._rejectDigits||!(b=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const S=this._digitIsSub?this._subParams:this.params,w=S[b-1];S[b-1]=~w?Math.min(10*w+f,d):f}}l.Params=p},5741:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.AddonManager=void 0,l.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let d=this._addons.length-1;d>=0;d--)this._addons[d].instance.dispose()}loadAddon(d,p){const m={instance:p,dispose:p.dispose,isDisposed:!1};this._addons.push(m),p.dispose=()=>this._wrappedAddonDispose(m),p.activate(d)}_wrappedAddonDispose(d){if(d.isDisposed)return;let p=-1;for(let m=0;m<this._addons.length;m++)if(this._addons[m]===d){p=m;break}if(p===-1)throw new Error("Could not dispose an addon that has not been loaded");d.isDisposed=!0,d.dispose.apply(d.instance),this._addons.splice(p,1)}}},8771:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferApiView=void 0;const p=d(3785),m=d(511);l.BufferApiView=class{constructor(f,b){this._buffer=f,this.type=b}init(f){return this._buffer=f,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(f){const b=this._buffer.lines.get(f);if(b)return new p.BufferLineApiView(b)}getNullCell(){return new m.CellData}}},3785:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferLineApiView=void 0;const p=d(511);l.BufferLineApiView=class{constructor(m){this._line=m}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(m,f){if(!(m<0||m>=this._line.length))return f?(this._line.loadCell(m,f),f):this._line.loadCell(m,new p.CellData)}translateToString(m,f,b){return this._line.translateToString(m,f,b)}}},8285:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.BufferNamespaceApi=void 0;const p=d(8771),m=d(8460),f=d(844);class b extends f.Disposable{constructor(w){super(),this._core=w,this._onBufferChange=this.register(new m.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new p.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new p.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)}}l.BufferNamespaceApi=b},7975:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ParserApi=void 0,l.ParserApi=class{constructor(d){this._core=d}registerCsiHandler(d,p){return this._core.registerCsiHandler(d,(m=>p(m.toArray())))}addCsiHandler(d,p){return this.registerCsiHandler(d,p)}registerDcsHandler(d,p){return this._core.registerDcsHandler(d,((m,f)=>p(m,f.toArray())))}addDcsHandler(d,p){return this.registerDcsHandler(d,p)}registerEscHandler(d,p){return this._core.registerEscHandler(d,p)}addEscHandler(d,p){return this.registerEscHandler(d,p)}registerOscHandler(d,p){return this._core.registerOscHandler(d,p)}addOscHandler(d,p){return this.registerOscHandler(d,p)}}},7090:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeApi=void 0,l.UnicodeApi=class{constructor(d){this._core=d}register(d){this._core.unicodeService.register(d)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(d){this._core.unicodeService.activeVersion=d}}},744:function(u,l,d){var p=this&&this.__decorate||function(x,y,_,E){var j,D=arguments.length,$=D<3?y:E===null?E=Object.getOwnPropertyDescriptor(y,_):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(x,y,_,E);else for(var I=x.length-1;I>=0;I--)(j=x[I])&&($=(D<3?j($):D>3?j(y,_,$):j(y,_))||$);return D>3&&$&&Object.defineProperty(y,_,$),$},m=this&&this.__param||function(x,y){return function(_,E){y(_,E,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.BufferService=l.MINIMUM_ROWS=l.MINIMUM_COLS=void 0;const f=d(8460),b=d(844),S=d(5295),w=d(2585);l.MINIMUM_COLS=2,l.MINIMUM_ROWS=1;let C=l.BufferService=class extends b.Disposable{get buffer(){return this.buffers.active}constructor(x){super(),this.isUserScrolling=!1,this._onResize=this.register(new f.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new f.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(x.rawOptions.cols||0,l.MINIMUM_COLS),this.rows=Math.max(x.rawOptions.rows||0,l.MINIMUM_ROWS),this.buffers=this.register(new S.BufferSet(x,this))}resize(x,y){this.cols=x,this.rows=y,this.buffers.resize(x,y),this._onResize.fire({cols:x,rows:y})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(x,y=!1){const _=this.buffer;let E;E=this._cachedBlankLine,E&&E.length===this.cols&&E.getFg(0)===x.fg&&E.getBg(0)===x.bg||(E=_.getBlankLine(x,y),this._cachedBlankLine=E),E.isWrapped=y;const j=_.ybase+_.scrollTop,D=_.ybase+_.scrollBottom;if(_.scrollTop===0){const $=_.lines.isFull;D===_.lines.length-1?$?_.lines.recycle().copyFrom(E):_.lines.push(E.clone()):_.lines.splice(D+1,0,E.clone()),$?this.isUserScrolling&&(_.ydisp=Math.max(_.ydisp-1,0)):(_.ybase++,this.isUserScrolling||_.ydisp++)}else{const $=D-j+1;_.lines.shiftElements(j+1,$-1,-1),_.lines.set(D,E.clone())}this.isUserScrolling||(_.ydisp=_.ybase),this._onScroll.fire(_.ydisp)}scrollLines(x,y,_){const E=this.buffer;if(x<0){if(E.ydisp===0)return;this.isUserScrolling=!0}else x+E.ydisp>=E.ybase&&(this.isUserScrolling=!1);const j=E.ydisp;E.ydisp=Math.max(Math.min(E.ydisp+x,E.ybase),0),j!==E.ydisp&&(y||this._onScroll.fire(E.ydisp))}};l.BufferService=C=p([m(0,w.IOptionsService)],C)},7994:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.CharsetService=void 0,l.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(d){this.glevel=d,this.charset=this._charsets[d]}setgCharset(d,p){this._charsets[d]=p,this.glevel===d&&(this.charset=p)}}},1753:function(u,l,d){var p=this&&this.__decorate||function(E,j,D,$){var I,P=arguments.length,L=P<3?j:$===null?$=Object.getOwnPropertyDescriptor(j,D):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(E,j,D,$);else for(var B=E.length-1;B>=0;B--)(I=E[B])&&(L=(P<3?I(L):P>3?I(j,D,L):I(j,D))||L);return P>3&&L&&Object.defineProperty(j,D,L),L},m=this&&this.__param||function(E,j){return function(D,$){j(D,$,E)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CoreMouseService=void 0;const f=d(2585),b=d(8460),S=d(844),w={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:E=>E.button!==4&&E.action===1&&(E.ctrl=!1,E.alt=!1,E.shift=!1,!0)},VT200:{events:19,restrict:E=>E.action!==32},DRAG:{events:23,restrict:E=>E.action!==32||E.button!==3},ANY:{events:31,restrict:E=>!0}};function C(E,j){let D=(E.ctrl?16:0)|(E.shift?4:0)|(E.alt?8:0);return E.button===4?(D|=64,D|=E.action):(D|=3&E.button,4&E.button&&(D|=64),8&E.button&&(D|=128),E.action===32?D|=32:E.action!==0||j||(D|=3)),D}const x=String.fromCharCode,y={DEFAULT:E=>{const j=[C(E,!1)+32,E.col+32,E.row+32];return j[0]>255||j[1]>255||j[2]>255?"":`\x1B[M${x(j[0])}${x(j[1])}${x(j[2])}`},SGR:E=>{const j=E.action===0&&E.button!==4?"m":"M";return`\x1B[<${C(E,!0)};${E.col};${E.row}${j}`},SGR_PIXELS:E=>{const j=E.action===0&&E.button!==4?"m":"M";return`\x1B[<${C(E,!0)};${E.x};${E.y}${j}`}};let _=l.CoreMouseService=class extends S.Disposable{constructor(E,j){super(),this._bufferService=E,this._coreService=j,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new b.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const D of Object.keys(w))this.addProtocol(D,w[D]);for(const D of Object.keys(y))this.addEncoding(D,y[D]);this.reset()}addProtocol(E,j){this._protocols[E]=j}addEncoding(E,j){this._encodings[E]=j}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(E){if(!this._protocols[E])throw new Error(`unknown protocol "${E}"`);this._activeProtocol=E,this._onProtocolChange.fire(this._protocols[E].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(E){if(!this._encodings[E])throw new Error(`unknown encoding "${E}"`);this._activeEncoding=E}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(E){if(E.col<0||E.col>=this._bufferService.cols||E.row<0||E.row>=this._bufferService.rows||E.button===4&&E.action===32||E.button===3&&E.action!==32||E.button!==4&&(E.action===2||E.action===3)||(E.col++,E.row++,E.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,E,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(E))return!1;const j=this._encodings[this._activeEncoding](E);return j&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(j):this._coreService.triggerDataEvent(j,!0)),this._lastEvent=E,!0}explainEvents(E){return{down:!!(1&E),up:!!(2&E),drag:!!(4&E),move:!!(8&E),wheel:!!(16&E)}}_equalEvents(E,j,D){if(D){if(E.x!==j.x||E.y!==j.y)return!1}else if(E.col!==j.col||E.row!==j.row)return!1;return E.button===j.button&&E.action===j.action&&E.ctrl===j.ctrl&&E.alt===j.alt&&E.shift===j.shift}};l.CoreMouseService=_=p([m(0,f.IBufferService),m(1,f.ICoreService)],_)},6975:function(u,l,d){var p=this&&this.__decorate||function(_,E,j,D){var $,I=arguments.length,P=I<3?E:D===null?D=Object.getOwnPropertyDescriptor(E,j):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(_,E,j,D);else for(var L=_.length-1;L>=0;L--)($=_[L])&&(P=(I<3?$(P):I>3?$(E,j,P):$(E,j))||P);return I>3&&P&&Object.defineProperty(E,j,P),P},m=this&&this.__param||function(_,E){return function(j,D){E(j,D,_)}};Object.defineProperty(l,"__esModule",{value:!0}),l.CoreService=void 0;const f=d(1439),b=d(8460),S=d(844),w=d(2585),C=Object.freeze({insertMode:!1}),x=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let y=l.CoreService=class extends S.Disposable{constructor(_,E,j){super(),this._bufferService=_,this._logService=E,this._optionsService=j,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new b.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new b.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new b.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new b.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,f.clone)(C),this.decPrivateModes=(0,f.clone)(x)}reset(){this.modes=(0,f.clone)(C),this.decPrivateModes=(0,f.clone)(x)}triggerDataEvent(_,E=!1){if(this._optionsService.rawOptions.disableStdin)return;const j=this._bufferService.buffer;E&&this._optionsService.rawOptions.scrollOnUserInput&&j.ybase!==j.ydisp&&this._onRequestScrollToBottom.fire(),E&&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((E=>E.charCodeAt(0))))),this._onBinary.fire(_))}};l.CoreService=y=p([m(0,w.IBufferService),m(1,w.ILogService),m(2,w.IOptionsService)],y)},9074:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.DecorationService=void 0;const p=d(8055),m=d(8460),f=d(844),b=d(6106);let S=0,w=0;class C extends f.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new b.SortedList((_=>_==null?void 0:_.marker.line)),this._onDecorationRegistered=this.register(new m.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new m.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,f.toDisposable)((()=>this.reset())))}registerDecoration(_){if(_.marker.isDisposed)return;const E=new x(_);if(E){const j=E.marker.onDispose((()=>E.dispose()));E.onDispose((()=>{E&&(this._decorations.delete(E)&&this._onDecorationRemoved.fire(E),j.dispose())})),this._decorations.insert(E),this._onDecorationRegistered.fire(E)}return E}reset(){for(const _ of this._decorations.values())_.dispose();this._decorations.clear()}*getDecorationsAtCell(_,E,j){let D=0,$=0;for(const I of this._decorations.getKeyIterator(E))D=I.options.x??0,$=D+(I.options.width??1),_>=D&&_<$&&(!j||(I.options.layer??"bottom")===j)&&(yield I)}forEachDecorationAtCell(_,E,j,D){this._decorations.forEachByKey(E,($=>{S=$.options.x??0,w=S+($.options.width??1),_>=S&&_<w&&(!j||($.options.layer??"bottom")===j)&&D($)}))}}l.DecorationService=C;class x extends f.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=p.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=p.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(_){super(),this.options=_,this.onRenderEmitter=this.register(new m.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new m.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:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.InstantiationService=l.ServiceCollection=void 0;const p=d(2585),m=d(8343);class f{constructor(...S){this._entries=new Map;for(const[w,C]of S)this.set(w,C)}set(S,w){const C=this._entries.get(S);return this._entries.set(S,w),C}forEach(S){for(const[w,C]of this._entries.entries())S(w,C)}has(S){return this._entries.has(S)}get(S){return this._entries.get(S)}}l.ServiceCollection=f,l.InstantiationService=class{constructor(){this._services=new f,this._services.set(p.IInstantiationService,this)}setService(b,S){this._services.set(b,S)}getService(b){return this._services.get(b)}createInstance(b,...S){const w=(0,m.getServiceDependencies)(b).sort(((y,_)=>y.index-_.index)),C=[];for(const y of w){const _=this._services.get(y.id);if(!_)throw new Error(`[createInstance] ${b.name} depends on UNKNOWN service ${y.id}.`);C.push(_)}const x=w.length>0?w[0].index:S.length;if(S.length!==x)throw new Error(`[createInstance] First service dependency of ${b.name} at position ${x+1} conflicts with ${S.length} static arguments`);return new b(...S,...C)}}},7866:function(u,l,d){var p=this&&this.__decorate||function(x,y,_,E){var j,D=arguments.length,$=D<3?y:E===null?E=Object.getOwnPropertyDescriptor(y,_):E;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(x,y,_,E);else for(var I=x.length-1;I>=0;I--)(j=x[I])&&($=(D<3?j($):D>3?j(y,_,$):j(y,_))||$);return D>3&&$&&Object.defineProperty(y,_,$),$},m=this&&this.__param||function(x,y){return function(_,E){y(_,E,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.traceCall=l.setTraceLogger=l.LogService=void 0;const f=d(844),b=d(2585),S={trace:b.LogLevelEnum.TRACE,debug:b.LogLevelEnum.DEBUG,info:b.LogLevelEnum.INFO,warn:b.LogLevelEnum.WARN,error:b.LogLevelEnum.ERROR,off:b.LogLevelEnum.OFF};let w,C=l.LogService=class extends f.Disposable{get logLevel(){return this._logLevel}constructor(x){super(),this._optionsService=x,this._logLevel=b.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),w=this}_updateLogLevel(){this._logLevel=S[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(x){for(let y=0;y<x.length;y++)typeof x[y]=="function"&&(x[y]=x[y]())}_log(x,y,_){this._evalLazyOptionalParams(_),x.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+y,..._)}trace(x,...y){var _;this._logLevel<=b.LogLevelEnum.TRACE&&this._log(((_=this._optionsService.options.logger)==null?void 0:_.trace.bind(this._optionsService.options.logger))??console.log,x,y)}debug(x,...y){var _;this._logLevel<=b.LogLevelEnum.DEBUG&&this._log(((_=this._optionsService.options.logger)==null?void 0:_.debug.bind(this._optionsService.options.logger))??console.log,x,y)}info(x,...y){var _;this._logLevel<=b.LogLevelEnum.INFO&&this._log(((_=this._optionsService.options.logger)==null?void 0:_.info.bind(this._optionsService.options.logger))??console.info,x,y)}warn(x,...y){var _;this._logLevel<=b.LogLevelEnum.WARN&&this._log(((_=this._optionsService.options.logger)==null?void 0:_.warn.bind(this._optionsService.options.logger))??console.warn,x,y)}error(x,...y){var _;this._logLevel<=b.LogLevelEnum.ERROR&&this._log(((_=this._optionsService.options.logger)==null?void 0:_.error.bind(this._optionsService.options.logger))??console.error,x,y)}};l.LogService=C=p([m(0,b.IOptionsService)],C),l.setTraceLogger=function(x){w=x},l.traceCall=function(x,y,_){if(typeof _.value!="function")throw new Error("not supported");const E=_.value;_.value=function(...j){if(w.logLevel!==b.LogLevelEnum.TRACE)return E.apply(this,j);w.trace(`GlyphRenderer#${E.name}(${j.map(($=>JSON.stringify($))).join(", ")})`);const D=E.apply(this,j);return w.trace(`GlyphRenderer#${E.name} return`,D),D}}},7302:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.OptionsService=l.DEFAULT_OPTIONS=void 0;const p=d(8460),m=d(844),f=d(6114);l.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,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:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:f.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const b=["normal","bold","100","200","300","400","500","600","700","800","900"];class S extends m.Disposable{constructor(C){super(),this._onOptionChange=this.register(new p.EventEmitter),this.onOptionChange=this._onOptionChange.event;const x={...l.DEFAULT_OPTIONS};for(const y in C)if(y in x)try{const _=C[y];x[y]=this._sanitizeAndValidateOption(y,_)}catch(_){console.error(_)}this.rawOptions=x,this.options={...x},this._setupOptions(),this.register((0,m.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(C,x){return this.onOptionChange((y=>{y===C&&x(this.rawOptions[C])}))}onMultipleOptionChange(C,x){return this.onOptionChange((y=>{C.indexOf(y)!==-1&&x()}))}_setupOptions(){const C=y=>{if(!(y in l.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);return this.rawOptions[y]},x=(y,_)=>{if(!(y in l.DEFAULT_OPTIONS))throw new Error(`No option with key "${y}"`);_=this._sanitizeAndValidateOption(y,_),this.rawOptions[y]!==_&&(this.rawOptions[y]=_,this._onOptionChange.fire(y))};for(const y in this.rawOptions){const _={get:C.bind(this,y),set:x.bind(this,y)};Object.defineProperty(this.options,y,_)}}_sanitizeAndValidateOption(C,x){switch(C){case"cursorStyle":if(x||(x=l.DEFAULT_OPTIONS[C]),!(function(y){return y==="block"||y==="underline"||y==="bar"})(x))throw new Error(`"${x}" is not a valid value for ${C}`);break;case"wordSeparator":x||(x=l.DEFAULT_OPTIONS[C]);break;case"fontWeight":case"fontWeightBold":if(typeof x=="number"&&1<=x&&x<=1e3)break;x=b.includes(x)?x:l.DEFAULT_OPTIONS[C];break;case"cursorWidth":x=Math.floor(x);case"lineHeight":case"tabStopWidth":if(x<1)throw new Error(`${C} cannot be less than 1, value: ${x}`);break;case"minimumContrastRatio":x=Math.max(1,Math.min(21,Math.round(10*x)/10));break;case"scrollback":if((x=Math.min(x,4294967295))<0)throw new Error(`${C} cannot be less than 0, value: ${x}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(x<=0)throw new Error(`${C} cannot be less than or equal to 0, value: ${x}`);break;case"rows":case"cols":if(!x&&x!==0)throw new Error(`${C} must be numeric, value: ${x}`);break;case"windowsPty":x=x??{}}return x}}l.OptionsService=S},2660:function(u,l,d){var p=this&&this.__decorate||function(S,w,C,x){var y,_=arguments.length,E=_<3?w:x===null?x=Object.getOwnPropertyDescriptor(w,C):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(S,w,C,x);else for(var j=S.length-1;j>=0;j--)(y=S[j])&&(E=(_<3?y(E):_>3?y(w,C,E):y(w,C))||E);return _>3&&E&&Object.defineProperty(w,C,E),E},m=this&&this.__param||function(S,w){return function(C,x){w(C,x,S)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkService=void 0;const f=d(2585);let b=l.OscLinkService=class{constructor(S){this._bufferService=S,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(S){const w=this._bufferService.buffer;if(S.id===void 0){const j=w.addMarker(w.ybase+w.y),D={data:S,id:this._nextId++,lines:[j]};return j.onDispose((()=>this._removeMarkerFromLink(D,j))),this._dataByLinkId.set(D.id,D),D.id}const C=S,x=this._getEntryIdKey(C),y=this._entriesWithId.get(x);if(y)return this.addLineToLink(y.id,w.ybase+w.y),y.id;const _=w.addMarker(w.ybase+w.y),E={id:this._nextId++,key:this._getEntryIdKey(C),data:C,lines:[_]};return _.onDispose((()=>this._removeMarkerFromLink(E,_))),this._entriesWithId.set(E.key,E),this._dataByLinkId.set(E.id,E),E.id}addLineToLink(S,w){const C=this._dataByLinkId.get(S);if(C&&C.lines.every((x=>x.line!==w))){const x=this._bufferService.buffer.addMarker(w);C.lines.push(x),x.onDispose((()=>this._removeMarkerFromLink(C,x)))}}getLinkData(S){var w;return(w=this._dataByLinkId.get(S))==null?void 0:w.data}_getEntryIdKey(S){return`${S.id};;${S.uri}`}_removeMarkerFromLink(S,w){const C=S.lines.indexOf(w);C!==-1&&(S.lines.splice(C,1),S.lines.length===0&&(S.data.id!==void 0&&this._entriesWithId.delete(S.key),this._dataByLinkId.delete(S.id)))}};l.OscLinkService=b=p([m(0,f.IBufferService)],b)},8343:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.createDecorator=l.getServiceDependencies=l.serviceRegistry=void 0;const d="di$target",p="di$dependencies";l.serviceRegistry=new Map,l.getServiceDependencies=function(m){return m[p]||[]},l.createDecorator=function(m){if(l.serviceRegistry.has(m))return l.serviceRegistry.get(m);const f=function(b,S,w){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(C,x,y){x[d]===x?x[p].push({id:C,index:y}):(x[p]=[{id:C,index:y}],x[d]=x)})(f,b,w)};return f.toString=()=>m,l.serviceRegistry.set(m,f),f}},2585:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.IDecorationService=l.IUnicodeService=l.IOscLinkService=l.IOptionsService=l.ILogService=l.LogLevelEnum=l.IInstantiationService=l.ICharsetService=l.ICoreService=l.ICoreMouseService=l.IBufferService=void 0;const p=d(8343);var m;l.IBufferService=(0,p.createDecorator)("BufferService"),l.ICoreMouseService=(0,p.createDecorator)("CoreMouseService"),l.ICoreService=(0,p.createDecorator)("CoreService"),l.ICharsetService=(0,p.createDecorator)("CharsetService"),l.IInstantiationService=(0,p.createDecorator)("InstantiationService"),(function(f){f[f.TRACE=0]="TRACE",f[f.DEBUG=1]="DEBUG",f[f.INFO=2]="INFO",f[f.WARN=3]="WARN",f[f.ERROR=4]="ERROR",f[f.OFF=5]="OFF"})(m||(l.LogLevelEnum=m={})),l.ILogService=(0,p.createDecorator)("LogService"),l.IOptionsService=(0,p.createDecorator)("OptionsService"),l.IOscLinkService=(0,p.createDecorator)("OscLinkService"),l.IUnicodeService=(0,p.createDecorator)("UnicodeService"),l.IDecorationService=(0,p.createDecorator)("DecorationService")},1480:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.UnicodeService=void 0;const p=d(8460),m=d(225);class f{static extractShouldJoin(S){return(1&S)!=0}static extractWidth(S){return S>>1&3}static extractCharKind(S){return S>>3}static createPropertyValue(S,w,C=!1){return(16777215&S)<<3|(3&w)<<1|(C?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new p.EventEmitter,this.onChange=this._onChange.event;const S=new m.UnicodeV6;this.register(S),this._active=S.version,this._activeProvider=S}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(S){if(!this._providers[S])throw new Error(`unknown Unicode version "${S}"`);this._active=S,this._activeProvider=this._providers[S],this._onChange.fire(S)}register(S){this._providers[S.version]=S}wcwidth(S){return this._activeProvider.wcwidth(S)}getStringCellWidth(S){let w=0,C=0;const x=S.length;for(let y=0;y<x;++y){let _=S.charCodeAt(y);if(55296<=_&&_<=56319){if(++y>=x)return w+this.wcwidth(_);const D=S.charCodeAt(y);56320<=D&&D<=57343?_=1024*(_-55296)+D-56320+65536:w+=this.wcwidth(D)}const E=this.charProperties(_,C);let j=f.extractWidth(E);f.extractShouldJoin(E)&&(j-=f.extractWidth(C)),w+=j,C=E}return w}charProperties(S,w){return this._activeProvider.charProperties(S,w)}}l.UnicodeService=f}},r={};function s(u){var l=r[u];if(l!==void 0)return l.exports;var d=r[u]={exports:{}};return n[u].call(d.exports,d,d.exports,s),d.exports}var a={};return(()=>{var u=a;Object.defineProperty(u,"__esModule",{value:!0}),u.Terminal=void 0;const l=s(9042),d=s(3236),p=s(844),m=s(5741),f=s(8285),b=s(7975),S=s(7090),w=["cols","rows"];class C extends p.Disposable{constructor(y){super(),this._core=this.register(new d.Terminal(y)),this._addonManager=this.register(new m.AddonManager),this._publicOptions={...this._core.options};const _=j=>this._core.options[j],E=(j,D)=>{this._checkReadonlyOptions(j),this._core.options[j]=D};for(const j in this._core.options){const D={get:_.bind(this,j),set:E.bind(this,j)};Object.defineProperty(this._publicOptions,j,D)}}_checkReadonlyOptions(y){if(w.includes(y))throw new Error(`Option "${y}" 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 b.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new S.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 f.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const y=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:y.applicationCursorKeys,applicationKeypadMode:y.applicationKeypad,bracketedPasteMode:y.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:_,originMode:y.origin,reverseWraparoundMode:y.reverseWraparound,sendFocusMode:y.sendFocus,wraparoundMode:y.wraparound}}get options(){return this._publicOptions}set options(y){for(const _ in y)this._publicOptions[_]=y[_]}blur(){this._core.blur()}focus(){this._core.focus()}input(y,_=!0){this._core.input(y,_)}resize(y,_){this._verifyIntegers(y,_),this._core.resize(y,_)}open(y){this._core.open(y)}attachCustomKeyEventHandler(y){this._core.attachCustomKeyEventHandler(y)}attachCustomWheelEventHandler(y){this._core.attachCustomWheelEventHandler(y)}registerLinkProvider(y){return this._core.registerLinkProvider(y)}registerCharacterJoiner(y){return this._checkProposedApi(),this._core.registerCharacterJoiner(y)}deregisterCharacterJoiner(y){this._checkProposedApi(),this._core.deregisterCharacterJoiner(y)}registerMarker(y=0){return this._verifyIntegers(y),this._core.registerMarker(y)}registerDecoration(y){return this._checkProposedApi(),this._verifyPositiveIntegers(y.x??0,y.width??0,y.height??0),this._core.registerDecoration(y)}hasSelection(){return this._core.hasSelection()}select(y,_,E){this._verifyIntegers(y,_,E),this._core.select(y,_,E)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(y,_){this._verifyIntegers(y,_),this._core.selectLines(y,_)}dispose(){super.dispose()}scrollLines(y){this._verifyIntegers(y),this._core.scrollLines(y)}scrollPages(y){this._verifyIntegers(y),this._core.scrollPages(y)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(y){this._verifyIntegers(y),this._core.scrollToLine(y)}clear(){this._core.clear()}write(y,_){this._core.write(y,_)}writeln(y,_){this._core.write(y),this._core.write(`\r
|
|
3169
|
-
`,_)}paste(y){this._core.paste(y)}refresh(y,_){this._verifyIntegers(y,_),this._core.refresh(y,_)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return l}_verifyIntegers(...y){for(const _ of y)if(_===1/0||isNaN(_)||_%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const _ of y)if(_&&(_===1/0||isNaN(_)||_%1!=0||_<0))throw new Error("This API only accepts positive integers")}}u.Terminal=C})(),a})()))})(__)),__.exports}var S9=w9(),w_={exports:{}},j2;function k9(){return j2||(j2=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(s){this._terminal=s}dispose(){}fit(){const s=this.proposeDimensions();if(!s||!this._terminal||isNaN(s.cols)||isNaN(s.rows))return;const a=this._terminal._core;this._terminal.rows===s.rows&&this._terminal.cols===s.cols||(a._renderService.clear(),this._terminal.resize(s.cols,s.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const s=this._terminal._core,a=s._renderService.dimensions;if(a.css.cell.width===0||a.css.cell.height===0)return;const u=this._terminal.options.scrollback===0?0:s.viewport.scrollBarWidth,l=window.getComputedStyle(this._terminal.element.parentElement),d=parseInt(l.getPropertyValue("height")),p=Math.max(0,parseInt(l.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),f=d-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),b=p-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-u;return{cols:Math.max(2,Math.floor(b/a.css.cell.width)),rows:Math.max(1,Math.floor(f/a.css.cell.height))}}}})(),n})()))})(w_)),w_.exports}var C9=k9(),S_={exports:{}},D2;function E9(){return D2||(D2=1,(function(i,e){(function(n,r){i.exports=r()})(self,(()=>(()=>{var n={6:(u,l)=>{function d(m){try{const f=new URL(m),b=f.password&&f.username?`${f.protocol}//${f.username}:${f.password}@${f.host}`:f.username?`${f.protocol}//${f.username}@${f.host}`:`${f.protocol}//${f.host}`;return m.toLocaleLowerCase().startsWith(b.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(l,"__esModule",{value:!0}),l.LinkComputer=l.WebLinkProvider=void 0,l.WebLinkProvider=class{constructor(m,f,b,S={}){this._terminal=m,this._regex=f,this._handler=b,this._options=S}provideLinks(m,f){const b=p.computeLink(m,this._regex,this._terminal,this._handler);f(this._addCallbacks(b))}_addCallbacks(m){return m.map((f=>(f.leave=this._options.leave,f.hover=(b,S)=>{if(this._options.hover){const{range:w}=f;this._options.hover(b,S,w)}},f)))}};class p{static computeLink(f,b,S,w){const C=new RegExp(b.source,(b.flags||"")+"g"),[x,y]=p._getWindowedLineStrings(f-1,S),_=x.join("");let E;const j=[];for(;E=C.exec(_);){const D=E[0];if(!d(D))continue;const[$,I]=p._mapStrIdx(S,y,0,E.index),[P,L]=p._mapStrIdx(S,$,I,D.length);if($===-1||I===-1||P===-1||L===-1)continue;const B={start:{x:I+1,y:$+1},end:{x:L,y:P+1}};j.push({range:B,text:D,activate:w})}return j}static _getWindowedLineStrings(f,b){let S,w=f,C=f,x=0,y="";const _=[];if(S=b.buffer.active.getLine(f)){const E=S.translateToString(!0);if(S.isWrapped&&E[0]!==" "){for(x=0;(S=b.buffer.active.getLine(--w))&&x<2048&&(y=S.translateToString(!0),x+=y.length,_.push(y),S.isWrapped&&y.indexOf(" ")===-1););_.reverse()}for(_.push(E),x=0;(S=b.buffer.active.getLine(++C))&&S.isWrapped&&x<2048&&(y=S.translateToString(!0),x+=y.length,_.push(y),y.indexOf(" ")===-1););}return[_,w]}static _mapStrIdx(f,b,S,w){const C=f.buffer.active,x=C.getNullCell();let y=S;for(;w;){const _=C.getLine(b);if(!_)return[-1,-1];for(let E=y;E<_.length;++E){_.getCell(E,x);const j=x.getChars();if(x.getWidth()&&(w-=j.length||1,E===_.length-1&&j==="")){const D=C.getLine(b+1);D&&D.isWrapped&&(D.getCell(0,x),x.getWidth()===2&&(w+=1))}if(w<0)return[b,E]}b++,y=0}return[b,y]}}l.LinkComputer=p}},r={};function s(u){var l=r[u];if(l!==void 0)return l.exports;var d=r[u]={exports:{}};return n[u](d,d.exports,s),d.exports}var a={};return(()=>{var u=a;Object.defineProperty(u,"__esModule",{value:!0}),u.WebLinksAddon=void 0;const l=s(6),d=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function p(m,f){const b=window.open();if(b){try{b.opener=null}catch{}b.location.href=f}else console.warn("Opening link blocked as opener could not be cleared")}u.WebLinksAddon=class{constructor(m=p,f={}){this._handler=m,this._options=f}activate(m){this._terminal=m;const f=this._options,b=f.urlRegex||d;this._linkProvider=this._terminal.registerLinkProvider(new l.WebLinkProvider(this._terminal,b,this._handler,f))}dispose(){var m;(m=this._linkProvider)==null||m.dispose()}}})(),a})()))})(S_)),S_.exports}var T9=E9();const FD="sm.terminal.settings",Pw="sm:terminal:settings",Rw=10,Iw=22,GD=13,Ax={theme:"dark",fontSize:GD};function UD(){try{const i=localStorage.getItem(FD);if(!i)return Ax;const e=JSON.parse(i);return{theme:e.theme==="light"||e.theme==="paper"||e.theme==="dark"?e.theme:Ax.theme,fontSize:typeof e.fontSize=="number"&&e.fontSize>=Rw&&e.fontSize<=Iw?e.fontSize:Ax.fontSize}}catch{return Ax}}function j9(i){try{localStorage.setItem(FD,JSON.stringify(i))}catch{}window.dispatchEvent(new CustomEvent(Pw,{detail:i}))}function D9(i){const e=n=>{i(n.detail)};return window.addEventListener(Pw,e),()=>window.removeEventListener(Pw,e)}const Mw={dark:{background:"#0b0d10",foreground:"#e6e8ec",cursor:"#d97757",selectionBackground:"#3a4250",black:"#1a1f27",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#e6e8ec",brightBlack:"#545c68",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff"},light:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"#cce5ff",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#a45a16",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#9a6700",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#1f2328"},paper:{background:"#f6efe1",foreground:"#2a221a",cursor:"#a7532f",selectionBackground:"#e0d3b8",black:"#2a221a",red:"#b8443c",green:"#5c6f3a",yellow:"#8e641a",blue:"#3a6ea5",magenta:"#8a4a8c",cyan:"#38767e",white:"#5b4a36",brightBlack:"#796b54",brightRed:"#b8493f",brightGreen:"#65714a",brightYellow:"#8c641e",brightBlue:"#416ea1",brightMagenta:"#925494",brightCyan:"#3e757d",brightWhite:"#2a221a"}};function A9(){const[i,e]=z.useState(!1),[n,r]=z.useState(()=>UD()),s=z.useRef(null);z.useEffect(()=>{if(!i)return;const l=d=>{s.current&&!s.current.contains(d.target)&&e(!1)};return window.addEventListener("mousedown",l),()=>window.removeEventListener("mousedown",l)},[i]);const a=l=>{r(d=>{const p={...d,...l};return j9(p),p})},u=l=>{const d=Math.min(Iw,Math.max(Rw,n.fontSize+l));a({fontSize:d})};return o.jsxs("div",{className:"absolute top-2 right-2 z-20",children:[o.jsx("button",{type:"button",onClick:()=>e(l=>!l),"aria-expanded":i,"aria-label":"Terminal settings",title:"Terminal settings",className:"w-7 h-7 grid place-items-center rounded-md border border-line bg-bg-elev/80 text-fg-dim hover:text-fg hover:bg-bg-hi backdrop-blur-sm transition-colors",children:o.jsx(N9,{})}),i&&o.jsxs("div",{ref:s,role:"dialog","aria-label":"Terminal settings",className:"absolute top-9 right-0 w-[240px] bg-bg-elev border border-line rounded-lg shadow-xl p-3 text-fg",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-1.5",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-3 gap-1 mb-3",children:["dark","light","paper"].map(l=>o.jsxs("button",{onClick:()=>a({theme:l}),"aria-pressed":n.theme===l,className:`px-2 py-1.5 rounded text-[11px] font-medium border transition-colors ${n.theme===l?"bg-bg-hi border-accent text-fg":"bg-bg border-line text-fg-dim hover:text-fg hover:border-fg-faint"}`,children:[o.jsx($9,{theme:l}),o.jsx("div",{className:"mt-1 capitalize",children:l})]},l))}),o.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-fg-faint",children:"Font size"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-dim",children:[n.fontSize,"px"]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:()=>u(-1),disabled:n.fontSize<=Rw,"aria-label":"Decrease font size",className:"flex-1 py-1 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"−"}),o.jsx("button",{onClick:()=>a({fontSize:GD}),className:"flex-1 py-1 rounded border border-line bg-bg text-[11px] text-fg-dim hover:text-fg hover:border-fg-faint",children:"reset"}),o.jsx("button",{onClick:()=>u(1),disabled:n.fontSize>=Iw,"aria-label":"Increase font size",className:"flex-1 py-1 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"+"})]})]})]})}function N9(){return o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]})}function $9({theme:i}){const e=Mw[i];return o.jsxs("div",{"aria-hidden":!0,className:"w-full h-3.5 rounded border",style:{background:e.background,borderColor:"rgba(0,0,0,0.15)",position:"relative",overflow:"hidden"},children:[o.jsx("div",{style:{position:"absolute",top:2,left:3,width:"40%",height:1.5,background:e.foreground}}),o.jsx("div",{style:{position:"absolute",top:6,left:3,width:"25%",height:1.5,background:e.green??e.foreground}}),o.jsx("div",{style:{position:"absolute",top:10,left:3,width:"55%",height:1.5,background:e.cyan??e.foreground}})]})}const P9={mcp:"mcp",permissions:"permissions",hooks:"hooks",memory:"memory",skills:"skills",plugins:"plugins",usage:"overview",cost:"overview",config:"settings",model:"settings",settings:"settings",history:"history",resume:"history",keybindings:"keybindings",scheduler:"scheduler",remote:"remote",projects:"projects",voice:"voice",repoviz:"repoviz",repo:"repoviz",search:"search",system:"system-prompt"};function HD(i){var r;const e=i.trim();if(!e.startsWith("/"))return null;const n=(r=e.slice(1).split(/\s+/)[0])==null?void 0:r.toLowerCase();return n?P9[n]??null:null}function R9(i){var r;const e=i.trim();return!e.startsWith("/")||!((r=e.slice(1).split(/\s+/)[0])==null?void 0:r.toLowerCase())?!1:HD(i)===null}function I9(i){const e=HD(i);return e?{type:"nav",key:e}:R9(i)?{type:"warn-unrouted"}:{type:"send"}}function A2(i,e,n,r){return{value:i.slice(0,e)+r+i.slice(n),caret:e+r.length}}async function M9(i,e,n,r){let s=null;try{s=await i.pasteImage()}catch{s=null}if(s&&s.ok){const d=s.path+" ",{value:p,caret:m}=A2(e,n,r,d);return{value:p,caret:m,toast:`Pasted image: ${s.path.split("/").pop()}`,imagePath:s.path}}const a=await i.readText(),{value:u,caret:l}=A2(e,n,r,a);return{value:u,caret:l,toast:null}}function O9(i){switch(i){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed";case"needs-input":return"needs_input"}}const L9={feature:{bg:"bg-sage/20",text:"text-sage",border:!0,label:"Feature"},bug:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"Bug"}};function z9(i){return L9[i]}function B9(i,e,n){const r=[...i,...e?[e]:[],...n],s=r.filter(u=>u.status==="needs-input"),a=r.filter(u=>u.status!=="needs-input");return[...s,...a]}function F9(i,e){return e.find(n=>n.slug===i)}function G9({slugs:i,jobs:e}){return i.length===0?o.jsx("div",{className:"text-xs italic text-fg-faint",children:"No PRDs linked yet."}):o.jsx("ul",{className:"space-y-1.5","data-testid":"ticket-detail-prd-list",children:i.map(n=>{const r=F9(n,e);return o.jsxs("li",{className:"flex items-center gap-2","data-testid":"ticket-detail-prd",children:[o.jsxs("button",{onClick:()=>iA(n),title:`Open PRD "${n}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[11px] text-accent hover:bg-hi",children:["#",n]}),r&&o.jsx(h0,{status:r.status})]},n)})})}function N2({ticket:i,jobs:e}){return o.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5","data-testid":"ticket-detail-entry",children:[i.tag&&o.jsx("div",{className:"mb-1.5",children:o.jsx(nA,{tag:i.tag})}),o.jsx("div",{className:"whitespace-pre-wrap text-sm text-fg",children:i.text}),o.jsx("div",{className:"mt-2",children:o.jsx(G9,{slugs:i.prdSlugs??[],jobs:e})})]})}function U9({ticket:i,allTickets:e,jobs:n,onClose:r}){const s=e.filter(a=>a.chainRootId===i.id);return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-4","data-testid":"ticket-detail-view",children:[o.jsx("div",{className:"mb-3",children:o.jsx("button",{onClick:r,"data-testid":"ticket-detail-back",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to queue"})}),o.jsx(N2,{ticket:i,jobs:n}),s.length>0&&o.jsxs("div",{className:"mt-3 space-y-2 border-l-2 border-line pl-3",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Follow-ups"}),s.map(a=>o.jsx(N2,{ticket:a,jobs:n},a.id))]})]})}function WD({path:i,onDismiss:e}){const[n,r]=z.useState(!1);return n?null:o.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[o.jsx("img",{src:qb(i),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>r(!0)}),o.jsx("button",{type:"button",onClick:e,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}const Mb=/(?:^|[\s(])((?:\.{1,2}\/)?[\w./-]+\.[A-Za-z]\w*(?::(\d+))?(?::(\d+))?)/g,Ow="data-file-link-text",H9=10,W9=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;function VD(i){const e=i.replace(/(?::\d+)+$/,"");if(e.includes("/"))return!0;const n=e.lastIndexOf("."),r=n===-1?"":e.slice(n+1);return!(!r||r.length>H9||W9.test(r))}function V9(i){var s;const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(a){const u=a.parentElement;return!u||u.closest("a, code, pre")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n=[];let r;for(;r=e.nextNode();)n.push(r);for(const a of n){const u=a.textContent??"";Mb.lastIndex=0;const l=[...u.matchAll(Mb)].filter(m=>VD(m[1]));if(l.length===0)continue;const d=document.createDocumentFragment();let p=0;for(const m of l){const f=m[0],b=m[1],w=(m.index??0)+(f.length-b.length);if(w<p)continue;w>p&&d.appendChild(document.createTextNode(u.slice(p,w)));const C=document.createElement("span");C.className="chat-file-link",C.setAttribute(Ow,b),C.textContent=b,d.appendChild(C),p=w+b.length}p<u.length&&d.appendChild(document.createTextNode(u.slice(p))),(s=a.parentNode)==null||s.replaceChild(d,a)}}const q9=3;function K9(i){Mb.lastIndex=0;const e=new Set,n=[];for(const r of i.matchAll(Mb)){const s=r[1];if(VD(s)&&!e.has(s)&&(e.add(s),n.push(s),n.length>=q9))break}return n}function $2(i,e){const n=i.match(/(?::(\d+))?(?::(\d+))?$/),r=i.replace(/(?::\d+)+$/,""),s=n!=null&&n[1]?parseInt(n[1],10):void 0,a=n!=null&&n[2]?parseInt(n[2],10):void 0;return{absPath:r.startsWith("/")?r:`${e}/${r}`,line:s,col:a}}const Y9=3;function X9(i){const e=new Set,n=[],r=/\[[^\]]*\]\((https?:\/\/[^\s)]+)\)|https?:\/\/[^\s)"'<>]+/g;let s;for(;s=r.exec(i);){const a=s[1]??s[0];if(!e.has(a)&&(e.add(a),n.push(a),n.length>=Y9))break}return n}const Ob=new ki.Renderer,J9=Ob.table.bind(Ob);Ob.table=i=>`<div class="prose-chat-table-wrap">${J9(i)}</div>`;function Z9(i){return _0.sanitize(ki.parse(i,{async:!1,breaks:!0,renderer:Ob}))}async function qD(i,e){const n=i.replace(/(?::\d+)+$/,""),r=$2(i,e),s=await window.api.files.read(r.absPath);if(!s.ok&&s.error==="path outside home")return Ve.error("That path is outside the project and can't be opened."),null;if(s.ok)return{target:r,text:s.text};let a=0;if(!n.startsWith("/")){const l=Array.from(new Set(Ct.getState().tabs.map(d=>d.cwd).filter(d=>d&&d!==e)));for(const d of l){const p=$2(i,d),m=await window.api.files.read(p.absPath);if(a++,m.ok)return{target:p,text:m.text}}}const u=a===1?"tab":"tabs";return Ve.error(`${s.error||"Not found"} under ${e} (tried ${a} other open ${u})`),null}async function KD(i,e=""){if(!i)return;const n=await qD(i,e);n&&(Di.getState().openFile(n.target.absPath,{line:n.target.line,col:n.target.col}),window.dispatchEvent(new CustomEvent("sm:open-editor")))}async function Q9(i,e=""){if(!i)return null;const n=await qD(i,e);return(n==null?void 0:n.text)??null}function e7(i){Pt.getState().openTab({url:i}),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"browser"}))}async function t7(i,e="",n="external"){const r=i.target,s=r.closest("a");if(s){const l=s.getAttribute("href")||"";/^https?:\/\//i.test(l)&&(i.preventDefault(),n==="browser"?e7(l):window.api.shell.open({as:"external",url:l}).catch(()=>{}));return}const a=r.closest(`[${Ow}]`);if(!a)return;const u=a.getAttribute(Ow)??"";await KD(u,e)}function i7(i,e){var n;return i.text.trim().length>0?"text":e?"working":(n=i.toolUses)!=null&&n.length?"placeholder":"suppress"}const n7=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function r7(i){return n7.test(i)}function YD(i,e){window.api.clipboard.writeText(i).then(n=>e(!!(n!=null&&n.ok))).catch(()=>e(!1))}function s7({url:i}){const[e,n]=z.useState(!1),r=()=>{YD(i,s=>{s?(n(!0),setTimeout(()=>n(!1),1100)):Ve.error("Copy failed")})};return o.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[o.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:i}),o.jsx("button",{onClick:r,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:e?"Copied":"Copy"})]})}const o7=/\.(?:md|markdown)(?::\d+)*$/i;function a7({path:i,cwd:e,inlinePreview:n=!1}){const[r,s]=z.useState(!1),[a,u]=z.useState(!1),[l,d]=z.useState(null),[p,m]=z.useState(!1),f=()=>{YD(i,C=>{C?(s(!0),setTimeout(()=>s(!1),1100)):Ve.error("Copy failed")})},b=()=>{KD(i,e)},S=n&&o7.test(i),w=async()=>{if(a){u(!1);return}if(u(!0),l===null&&!p){m(!0);const C=await Q9(i,e);m(!1),d(C??"")}};return o.jsxs("div",{className:"mt-1.5",children:[o.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[o.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),o.jsx("button",{onClick:b,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:i}),S&&o.jsx("button",{onClick:()=>{w()},className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:a?"Hide preview":"Preview"}),o.jsx("button",{onClick:f,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]}),S&&a&&o.jsx("div",{className:"mt-1 max-h-80 overflow-hidden rounded-lg border border-line","data-testid":"file-inline-preview",children:p?o.jsx("div",{className:"px-3 py-2 text-xs text-fg-dim",children:"Loading preview…"}):o.jsx(iw,{text:l??"",flush:!0})})]})}const XD={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},JD={skill:"🧩",mcp:"🔌",tool:"⚙"};function ZD(i){const e=[];for(const n of i){const r=e[e.length-1];r&&r.kind===n.kind&&r.label===n.label?(r.count+=1,r.id=n.id):e.push({id:n.id,kind:n.kind,label:n.label,count:1})}return e}function QD(i){return i.count>1?`${i.label} ×${i.count}`:i.label}function Lw({items:i,running:e=!1}){if(!(i!=null&&i.length))return null;const n=ZD(i),r=n.length-1;return o.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[n.map((s,a)=>{const u=e&&a===r;return o.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${u?"border-accent/40 bg-accent/10 text-accent":XD[s.kind]}`,children:[JD[s.kind]," ",QD(s)]},s.id)}),o.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",i.length," steps"]})]})}const eA="text-[#8a2f28]",l7="border-[#b8443c]/40 bg-[#b8443c]/10",Um="text-[#7a5416]",Nx="border-[#8e641a]/40 bg-[#8e641a]/10",c7="needs interactive consent for an MCP server";function tA({turn:i,cwd:e,tabId:n,runActive:r=!1,consentActionDisabled:s=!1,enableRawSessionActions:a=!0,linkTarget:u="external",inlineFilePreview:l=!1}){const d=z.useRef(null),p=i.role==="assistant"?i7(i,r):null;if(z.useEffect(()=>{i.role==="assistant"&&p==="text"&&d.current&&V9(d.current)},[i.role,p,i.text]),i.role==="user")return o.jsx("div",{className:"flex justify-end",children:o.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:i.text})});if(i.role==="error")return o.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${l7} ${eA}`,children:i.text});if(i.role==="question")return o.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${Nx} ${Um}`,children:[o.jsx(Lw,{items:i.toolUses}),o.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${Um}`,children:[o.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),o.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(i.questions??[i.text]).map((S,w)=>o.jsx("li",{children:S},w))}),o.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${Nx}`,children:"Reply in the composer below to answer."})]});if(i.role==="notice"){const S=i.text.includes(c7),w=()=>{Ct.getState().queueRawCommand(n,"/design consent"),Ct.getState().wakeTab(n)};return o.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${Nx} ${Um}`,children:[o.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${Um}`,children:[o.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),i.text,S&&a&&o.jsx("div",{className:`mt-2 border-t pt-2 ${Nx}`,children:o.jsx("button",{onClick:w,disabled:s,title:s?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${Um} border-current`,children:"Grant consent →"})})]})}if(p==="suppress")return null;const m=X9(i.text),f=K9(i.text),b=r7(i.text);return o.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[o.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(Lw,{items:i.toolUses,running:p==="working"}),p==="working"?o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):p==="placeholder"?o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:d,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${b?"prose-chat--plan":""}`,onClick:S=>{t7(S,e,u)},dangerouslySetInnerHTML:{__html:Z9(i.text)}}),m.map(S=>o.jsx(s7,{url:S},S)),f.map(S=>o.jsx(a7,{path:S,cwd:e,inlinePreview:l},S))]})]})]})}const d7=1180,P2={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function u7(){const[i,e]=z.useState(()=>window.innerWidth);return z.useEffect(()=>{const n=()=>e(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),i}function h7({cwd:i,label:e,running:n,queuedPosition:r,stream:s,liveToolUses:a}){const u=ZD(a),l=n&&!s?u.length-1:-1;return o.jsxs("div",{className:"min-h-0 max-h-[45%] shrink-0 overflow-y-auto border-b border-rule px-3 py-4",children:[o.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[o.jsx("div",{className:"text-xs font-semibold text-fg",children:e}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:i,children:i}),o.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:n?r>0?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",r]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),o.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),u.length===0?o.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):o.jsx("ul",{className:"mt-1.5 space-y-1",children:u.map((d,p)=>o.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${p===l?"border-accent/40 bg-accent/10 text-accent":XD[d.kind]}`,children:[p===l?o.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):o.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:JD[d.kind]}),o.jsx("span",{className:"truncate",children:QD(d)})]},d.id))})]})}function iA(i){i9(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function nA({tag:i}){const e=z9(i);return o.jsx("span",{className:`inline-block text-[10.5px] font-semibold px-[7px] py-0.5 rounded-full ${e.bg} ${e.text}${e.border?" ring-1 ring-inset ring-line":""}`,children:e.label})}function p7({tickets:i,onSelectNeedsInput:e,onSelectTicket:n}){const r=z.useRef(null),s=z.useRef(!0),a=()=>{const l=r.current;l&&(s.current=l.scrollHeight-l.scrollTop-l.clientHeight<8)},u=i.map(l=>`${l.id}:${l.status}`).join(",");return z.useEffect(()=>{const l=r.current;l&&s.current&&(l.scrollTop=l.scrollHeight)},[u]),o.jsxs("div",{ref:r,onScroll:a,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4","data-testid":"chat-queue-panel",children:[o.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),i.length===0?o.jsx(Kt,{title:"No prompts queued",hint:"Prompts sent while a turn is running will show up here."}):o.jsx("ul",{className:"space-y-2",children:i.map(l=>{var m;const d=l.status==="needs-input",p=d||!!n;return o.jsxs("li",{className:`rounded-lg border px-2.5 py-2 ${d?"cursor-pointer border-[#8e641a]/40 bg-[#8e641a]/10 hover:bg-[#8e641a]/20":p?"cursor-pointer border-line bg-elev hover:bg-hi":"border-line bg-elev"}`,"data-testid":"chat-queue-ticket",onClick:p?()=>d?e==null?void 0:e(l):n==null?void 0:n(l):void 0,role:p?"button":void 0,tabIndex:p?0:void 0,children:[o.jsx(J_,{status:O9(l.status)}),l.tag&&o.jsx("span",{className:"ml-1.5",children:o.jsx(nA,{tag:l.tag})}),o.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:l.text,children:l.text}),l.status==="dispatched-to-prd"&&!!((m=l.prdSlugs)!=null&&m.length)&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:l.prdSlugs.map(f=>o.jsxs("button",{onClick:()=>iA(f),title:`Open PRD "${f}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",f]},f))})]},l.id)})})]})}function f7({tabId:i,cwd:e}){const n=Ct(Le=>Le.tabs.find(ht=>ht.id===i)),r=(n==null?void 0:n.sessionId)??i,s=dn(Le=>Le.chats[i]),a=dn(Le=>Le.send),u=dn(Le=>Le.hydrate),l=dn(Le=>Le.resetThread),d=dn(Le=>Le.pushNotice),p=dn(Le=>{var ht;return(ht=Le.chats[i])==null?void 0:ht.pendingVoiceText}),m=dn(Le=>Le.clearPendingVoiceText),[f,b]=z.useState(""),[S,w]=z.useState("feature"),[C,x]=z.useState("new"),[y,_]=z.useState(!1),[E,j]=z.useState(null),[D,$]=z.useState(null),[I,P]=z.useState(null),[L,B]=z.useState("queue"),U=z.useRef(null),Z=z.useRef(null),X=z.useRef(null),J=u7()>d7,te=J||L==="queue",le=J||L==="transcript",ue=(s==null?void 0:s.turns)??[],V=(s==null?void 0:s.running)??!1,ie=(s==null?void 0:s.stream)??"",K=(s==null?void 0:s.queuedPosition)??0,se=(s==null?void 0:s.liveToolUses)??[],oe=B9((s==null?void 0:s.ticketHistory)??[],s==null?void 0:s.activeTicket,(s==null?void 0:s.queue)??[]),be=oe.find(Le=>Le.status==="needs-input")??null,je=zl(Le=>{var ht;return((ht=Le.snapshot)==null?void 0:ht.jobs)??[]}),Te=((s==null?void 0:s.ticketHistory)??[]).filter(Le=>Le.status==="dispatched-to-prd"&&!Le.chainRootId&&!HA(Le,je)),ve=Te.map(Le=>Le.id).join(",");z.useEffect(()=>{C!=="new"&&!Te.some(Le=>Le.id===C)&&x("new")},[ve,C]);const re=Le=>{const ht=Le.questionTurnId,Gt=()=>{var di,Ue;if(ht){const _t=document.getElementById(`chat-turn-${ht}`);(di=_t==null?void 0:_t.scrollIntoView)==null||di.call(_t,{behavior:"smooth",block:"center"}),$(ht),window.setTimeout(()=>{$(ft=>ft===ht?null:ft)},1500)}(Ue=X.current)==null||Ue.focus()};J?Gt():(B("transcript"),requestAnimationFrame(Gt))};z.useEffect(()=>{u({tabId:i,cwd:e,sessionId:r})},[i]),z.useEffect(()=>{p&&(b(Le=>Le.trim()?`${Le} ${p}`:p),m(i))},[p,i,m]),z.useEffect(()=>{var Le;(Le=U.current)==null||Le.scrollTo({top:U.current.scrollHeight})},[ue.length,ie,V,le]);const Pe=()=>{if(!f.trim())return;const Le=I9(f.trim());if(Le.type==="nav"){b(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:Le.key}));const Gt=`→ opened ${P2[Le.key]} — showing the live list`;d(i,Gt),Ve.info(`Opened ${P2[Le.key]} — showing the live list`);return}Le.type==="warn-unrouted"&&Ve.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),a({tabId:i,sessionId:r,cwd:e,prompt:f,tag:S,chainRootId:C!=="new"?C:void 0}),b(""),j(null),x("new")},_e=Le=>{Le.key==="Enter"&&!Le.shiftKey&&(Le.preventDefault(),Pe())},Qe=Le=>{const ht=Le.currentTarget,Gt=ht.selectionStart??f.length,di=ht.selectionEnd??Gt;Le.preventDefault(),(async()=>{try{const Ue=await M9({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(_t=>_t.ok?_t.text:"")},f,Gt,di);b(Ue.value),Ue.toast&&Ve.info(Ue.toast),Ue.imagePath&&j(Ue.imagePath),requestAnimationFrame(()=>{try{ht.setSelectionRange(Ue.caret,Ue.caret)}catch{}})}catch(Ue){Ve.error(Ue instanceof Error?Ue.message:"Paste failed — clipboard unavailable")}})()};z.useEffect(()=>{if(!y)return;const Le=ht=>{var Gt;(Gt=Z.current)!=null&&Gt.contains(ht.target)||_(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[y]);const st=()=>{Ct.getState().wakeTab(i)},yt=Le=>{Ct.getState().wakeTab(i,Le),_(!1)},[qt,ut]=z.useState(!1),nt=()=>{if(!V){if(!qt){ut(!0);return}Ct.getState().newSession(i),l(i),ut(!1)}};return o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),o.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),o.jsx(X0,{active:"terminal"})]}),o.jsxs("div",{className:"flex items-stretch gap-2",children:[o.jsx("button",{onClick:nt,onBlur:()=>ut(!1),disabled:V,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${qt?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:qt?"Confirm new session?":"New session"}),o.jsxs("div",{ref:Z,className:"relative flex items-stretch",children:[o.jsx("button",{onClick:st,disabled:V,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:V?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),o.jsx("button",{onClick:()=>_(Le=>!Le),disabled:V,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),y&&o.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Vw.map(Le=>o.jsx("button",{onClick:()=>yt(Le),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:Le.charAt(0).toUpperCase()+Le.slice(1)},Le))})]})]})]}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[te&&o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[!J&&o.jsx("div",{className:"flex items-center justify-end border-b border-rule px-3 py-1.5",children:o.jsx("button",{onClick:()=>B("transcript"),"data-testid":"show-transcript-btn",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"View transcript →"})}),o.jsx("div",{className:I?"hidden":"flex min-h-0 flex-1 flex-col",children:o.jsx(p7,{tickets:oe,onSelectNeedsInput:re,onSelectTicket:Le=>P(Le.id)})}),I&&(()=>{const Le=oe.find(ht=>ht.id===I);return Le?o.jsx(U9,{ticket:Le,allTickets:oe,jobs:je,onClose:()=>P(null)}):null})()]}),le&&o.jsxs("div",{className:J?"flex h-full w-[280px] shrink-0 flex-col border-l border-rule":"flex min-w-0 flex-1 flex-col",children:[!J&&o.jsx("div",{className:"flex items-center justify-start border-b border-rule px-3 py-1.5",children:o.jsx("button",{onClick:()=>B("queue"),"data-testid":"show-queue-btn",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to queue"})}),J&&o.jsx(h7,{cwd:e,label:(n==null?void 0:n.label)??e,running:V,queuedPosition:K,stream:ie,liveToolUses:se}),o.jsxs("div",{ref:U,className:J?"min-h-0 flex-1 space-y-3 overflow-y-auto px-3 py-4":"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[ue.length===0&&!V&&o.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),ue.map((Le,ht)=>o.jsx("div",{id:`chat-turn-${Le.id}`,className:D===Le.id?"rounded-[14px] ring-2 ring-accent/60 transition-shadow":"rounded-[14px]",children:o.jsx(tA,{turn:Le,cwd:e,tabId:i,runActive:V&&Le.role==="assistant"&&ht===ue.length-1,consentActionDisabled:V})},Le.id)),V&&o.jsxs("div",{className:"max-w-[90%]",children:[o.jsx(Lw,{items:se,running:V&&!ie}),o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:K>0?o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",K," — waiting for a free run slot"]}):ie?o.jsx("span",{className:"whitespace-pre-wrap",children:ie}):o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]})]})]}),o.jsxs("div",{className:"border-t border-rule p-3",children:[E&&o.jsx(WD,{path:E,onDismiss:()=>j(null)},E),Te.length>0&&o.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-dim",role:"radiogroup","aria-label":"New item or continue an existing PRD chain","data-testid":"chain-picker",children:[o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"radio",name:"chain-choice",checked:C==="new",onChange:()=>x("new")}),"New item"]}),Te.map(Le=>o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"radio",name:"chain-choice",checked:C===Le.id,onChange:()=>x(Le.id)}),"Continue: ",Le.text.length>40?`${Le.text.slice(0,40)}…`:Le.text]},Le.id))]}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx(w0,{}),o.jsx("textarea",{ref:X,value:f,onChange:Le=>b(Le.target.value),onKeyDown:_e,onPaste:Qe,rows:2,placeholder:be?"Reply to answer the pending question…":V?"Running… send to queue a follow-up prompt":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),o.jsxs("div",{className:"flex items-center gap-0.5 rounded-md border border-line p-0.5",role:"group","aria-label":"Feature or bug tag",children:[o.jsx("button",{type:"button",onClick:()=>w("feature"),"aria-pressed":S==="feature",className:`rounded px-2 py-1.5 text-xs font-medium ${S==="feature"?"bg-sage/25 text-sage":"text-fg-faint hover:text-fg-dim"}`,children:"Feature"}),o.jsx("button",{type:"button",onClick:()=>w("bug"),"aria-pressed":S==="bug",className:`rounded px-2 py-1.5 text-xs font-medium ${S==="bug"?"bg-accent/15 text-accent":"text-fg-faint hover:text-fg-dim"}`,children:"Bug"})]}),V&&o.jsx("button",{onClick:()=>window.api.chat.cancel(i),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${eA} border-[#b8443c]/40`,children:"Cancel"}),o.jsx("button",{onClick:Pe,disabled:!f.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const zw="\x1B[38;5;240m",Bw="\x1B[0m",m7=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function g7(i){return i.replace(m7,"")}function v7(i){var a;if(!i||typeof i!="object")return null;const e=i,n=e.type==="user"?"You":e.type==="assistant"?"Claude":null;if(!n)return null;const r=(a=e.message)==null?void 0:a.content;if(!Array.isArray(r))return null;const s=r.filter(u=>(u==null?void 0:u.type)==="text"&&typeof u.text=="string").map(u=>g7(u.text).trim()).filter(Boolean).join(`
|
|
3169
|
+
`,_)}paste(y){this._core.paste(y)}refresh(y,_){this._verifyIntegers(y,_),this._core.refresh(y,_)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(y){this._addonManager.loadAddon(this,y)}static get strings(){return l}_verifyIntegers(...y){for(const _ of y)if(_===1/0||isNaN(_)||_%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...y){for(const _ of y)if(_&&(_===1/0||isNaN(_)||_%1!=0||_<0))throw new Error("This API only accepts positive integers")}}u.Terminal=C})(),a})()))})(__)),__.exports}var S9=w9(),w_={exports:{}},j2;function k9(){return j2||(j2=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(s){this._terminal=s}dispose(){}fit(){const s=this.proposeDimensions();if(!s||!this._terminal||isNaN(s.cols)||isNaN(s.rows))return;const a=this._terminal._core;this._terminal.rows===s.rows&&this._terminal.cols===s.cols||(a._renderService.clear(),this._terminal.resize(s.cols,s.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const s=this._terminal._core,a=s._renderService.dimensions;if(a.css.cell.width===0||a.css.cell.height===0)return;const u=this._terminal.options.scrollback===0?0:s.viewport.scrollBarWidth,l=window.getComputedStyle(this._terminal.element.parentElement),d=parseInt(l.getPropertyValue("height")),p=Math.max(0,parseInt(l.getPropertyValue("width"))),m=window.getComputedStyle(this._terminal.element),f=d-(parseInt(m.getPropertyValue("padding-top"))+parseInt(m.getPropertyValue("padding-bottom"))),b=p-(parseInt(m.getPropertyValue("padding-right"))+parseInt(m.getPropertyValue("padding-left")))-u;return{cols:Math.max(2,Math.floor(b/a.css.cell.width)),rows:Math.max(1,Math.floor(f/a.css.cell.height))}}}})(),n})()))})(w_)),w_.exports}var C9=k9(),S_={exports:{}},D2;function E9(){return D2||(D2=1,(function(i,e){(function(n,r){i.exports=r()})(self,(()=>(()=>{var n={6:(u,l)=>{function d(m){try{const f=new URL(m),b=f.password&&f.username?`${f.protocol}//${f.username}:${f.password}@${f.host}`:f.username?`${f.protocol}//${f.username}@${f.host}`:`${f.protocol}//${f.host}`;return m.toLocaleLowerCase().startsWith(b.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(l,"__esModule",{value:!0}),l.LinkComputer=l.WebLinkProvider=void 0,l.WebLinkProvider=class{constructor(m,f,b,S={}){this._terminal=m,this._regex=f,this._handler=b,this._options=S}provideLinks(m,f){const b=p.computeLink(m,this._regex,this._terminal,this._handler);f(this._addCallbacks(b))}_addCallbacks(m){return m.map((f=>(f.leave=this._options.leave,f.hover=(b,S)=>{if(this._options.hover){const{range:w}=f;this._options.hover(b,S,w)}},f)))}};class p{static computeLink(f,b,S,w){const C=new RegExp(b.source,(b.flags||"")+"g"),[x,y]=p._getWindowedLineStrings(f-1,S),_=x.join("");let E;const j=[];for(;E=C.exec(_);){const D=E[0];if(!d(D))continue;const[$,I]=p._mapStrIdx(S,y,0,E.index),[P,L]=p._mapStrIdx(S,$,I,D.length);if($===-1||I===-1||P===-1||L===-1)continue;const B={start:{x:I+1,y:$+1},end:{x:L,y:P+1}};j.push({range:B,text:D,activate:w})}return j}static _getWindowedLineStrings(f,b){let S,w=f,C=f,x=0,y="";const _=[];if(S=b.buffer.active.getLine(f)){const E=S.translateToString(!0);if(S.isWrapped&&E[0]!==" "){for(x=0;(S=b.buffer.active.getLine(--w))&&x<2048&&(y=S.translateToString(!0),x+=y.length,_.push(y),S.isWrapped&&y.indexOf(" ")===-1););_.reverse()}for(_.push(E),x=0;(S=b.buffer.active.getLine(++C))&&S.isWrapped&&x<2048&&(y=S.translateToString(!0),x+=y.length,_.push(y),y.indexOf(" ")===-1););}return[_,w]}static _mapStrIdx(f,b,S,w){const C=f.buffer.active,x=C.getNullCell();let y=S;for(;w;){const _=C.getLine(b);if(!_)return[-1,-1];for(let E=y;E<_.length;++E){_.getCell(E,x);const j=x.getChars();if(x.getWidth()&&(w-=j.length||1,E===_.length-1&&j==="")){const D=C.getLine(b+1);D&&D.isWrapped&&(D.getCell(0,x),x.getWidth()===2&&(w+=1))}if(w<0)return[b,E]}b++,y=0}return[b,y]}}l.LinkComputer=p}},r={};function s(u){var l=r[u];if(l!==void 0)return l.exports;var d=r[u]={exports:{}};return n[u](d,d.exports,s),d.exports}var a={};return(()=>{var u=a;Object.defineProperty(u,"__esModule",{value:!0}),u.WebLinksAddon=void 0;const l=s(6),d=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function p(m,f){const b=window.open();if(b){try{b.opener=null}catch{}b.location.href=f}else console.warn("Opening link blocked as opener could not be cleared")}u.WebLinksAddon=class{constructor(m=p,f={}){this._handler=m,this._options=f}activate(m){this._terminal=m;const f=this._options,b=f.urlRegex||d;this._linkProvider=this._terminal.registerLinkProvider(new l.WebLinkProvider(this._terminal,b,this._handler,f))}dispose(){var m;(m=this._linkProvider)==null||m.dispose()}}})(),a})()))})(S_)),S_.exports}var T9=E9();const FD="sm.terminal.settings",Pw="sm:terminal:settings",Rw=10,Iw=22,GD=13,Ax={theme:"dark",fontSize:GD};function UD(){try{const i=localStorage.getItem(FD);if(!i)return Ax;const e=JSON.parse(i);return{theme:e.theme==="light"||e.theme==="paper"||e.theme==="dark"?e.theme:Ax.theme,fontSize:typeof e.fontSize=="number"&&e.fontSize>=Rw&&e.fontSize<=Iw?e.fontSize:Ax.fontSize}}catch{return Ax}}function j9(i){try{localStorage.setItem(FD,JSON.stringify(i))}catch{}window.dispatchEvent(new CustomEvent(Pw,{detail:i}))}function D9(i){const e=n=>{i(n.detail)};return window.addEventListener(Pw,e),()=>window.removeEventListener(Pw,e)}const Mw={dark:{background:"#0b0d10",foreground:"#e6e8ec",cursor:"#d97757",selectionBackground:"#3a4250",black:"#1a1f27",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#e6e8ec",brightBlack:"#545c68",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff"},light:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"#cce5ff",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#a45a16",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#9a6700",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#1f2328"},paper:{background:"#f6efe1",foreground:"#2a221a",cursor:"#a7532f",selectionBackground:"#e0d3b8",black:"#2a221a",red:"#b8443c",green:"#5c6f3a",yellow:"#8e641a",blue:"#3a6ea5",magenta:"#8a4a8c",cyan:"#38767e",white:"#5b4a36",brightBlack:"#796b54",brightRed:"#b8493f",brightGreen:"#65714a",brightYellow:"#8c641e",brightBlue:"#416ea1",brightMagenta:"#925494",brightCyan:"#3e757d",brightWhite:"#2a221a"}};function A9(){const[i,e]=z.useState(!1),[n,r]=z.useState(()=>UD()),s=z.useRef(null);z.useEffect(()=>{if(!i)return;const l=d=>{s.current&&!s.current.contains(d.target)&&e(!1)};return window.addEventListener("mousedown",l),()=>window.removeEventListener("mousedown",l)},[i]);const a=l=>{r(d=>{const p={...d,...l};return j9(p),p})},u=l=>{const d=Math.min(Iw,Math.max(Rw,n.fontSize+l));a({fontSize:d})};return o.jsxs("div",{className:"absolute top-2 right-2 z-20",children:[o.jsx("button",{type:"button",onClick:()=>e(l=>!l),"aria-expanded":i,"aria-label":"Terminal settings",title:"Terminal settings",className:"w-7 h-7 grid place-items-center rounded-md border border-line bg-bg-elev/80 text-fg-dim hover:text-fg hover:bg-bg-hi backdrop-blur-sm transition-colors",children:o.jsx(N9,{})}),i&&o.jsxs("div",{ref:s,role:"dialog","aria-label":"Terminal settings",className:"absolute top-9 right-0 w-[240px] bg-bg-elev border border-line rounded-lg shadow-xl p-3 text-fg",children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-1.5",children:"Theme"}),o.jsx("div",{className:"grid grid-cols-3 gap-1 mb-3",children:["dark","light","paper"].map(l=>o.jsxs("button",{onClick:()=>a({theme:l}),"aria-pressed":n.theme===l,className:`px-2 py-1.5 rounded text-[11px] font-medium border transition-colors ${n.theme===l?"bg-bg-hi border-accent text-fg":"bg-bg border-line text-fg-dim hover:text-fg hover:border-fg-faint"}`,children:[o.jsx($9,{theme:l}),o.jsx("div",{className:"mt-1 capitalize",children:l})]},l))}),o.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[o.jsx("span",{className:"text-[10px] uppercase tracking-wider text-fg-faint",children:"Font size"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-dim",children:[n.fontSize,"px"]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx("button",{onClick:()=>u(-1),disabled:n.fontSize<=Rw,"aria-label":"Decrease font size",className:"flex-1 py-1 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"−"}),o.jsx("button",{onClick:()=>a({fontSize:GD}),className:"flex-1 py-1 rounded border border-line bg-bg text-[11px] text-fg-dim hover:text-fg hover:border-fg-faint",children:"reset"}),o.jsx("button",{onClick:()=>u(1),disabled:n.fontSize>=Iw,"aria-label":"Increase font size",className:"flex-1 py-1 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"+"})]})]})]})}function N9(){return o.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]})}function $9({theme:i}){const e=Mw[i];return o.jsxs("div",{"aria-hidden":!0,className:"w-full h-3.5 rounded border",style:{background:e.background,borderColor:"rgba(0,0,0,0.15)",position:"relative",overflow:"hidden"},children:[o.jsx("div",{style:{position:"absolute",top:2,left:3,width:"40%",height:1.5,background:e.foreground}}),o.jsx("div",{style:{position:"absolute",top:6,left:3,width:"25%",height:1.5,background:e.green??e.foreground}}),o.jsx("div",{style:{position:"absolute",top:10,left:3,width:"55%",height:1.5,background:e.cyan??e.foreground}})]})}const P9={mcp:"mcp",permissions:"permissions",hooks:"hooks",memory:"memory",skills:"skills",plugins:"plugins",usage:"overview",cost:"overview",config:"settings",model:"settings",settings:"settings",history:"history",resume:"history",keybindings:"keybindings",scheduler:"scheduler",remote:"remote",projects:"projects",voice:"voice",repoviz:"repoviz",repo:"repoviz",search:"search",system:"system-prompt"};function HD(i){var r;const e=i.trim();if(!e.startsWith("/"))return null;const n=(r=e.slice(1).split(/\s+/)[0])==null?void 0:r.toLowerCase();return n?P9[n]??null:null}function R9(i){var r;const e=i.trim();return!e.startsWith("/")||!((r=e.slice(1).split(/\s+/)[0])==null?void 0:r.toLowerCase())?!1:HD(i)===null}function I9(i){const e=HD(i);return e?{type:"nav",key:e}:R9(i)?{type:"warn-unrouted"}:{type:"send"}}function A2(i,e,n,r){return{value:i.slice(0,e)+r+i.slice(n),caret:e+r.length}}async function M9(i,e,n,r){let s=null;try{s=await i.pasteImage()}catch{s=null}if(s&&s.ok){const d=s.path+" ",{value:p,caret:m}=A2(e,n,r,d);return{value:p,caret:m,toast:`Pasted image: ${s.path.split("/").pop()}`,imagePath:s.path}}const a=await i.readText(),{value:u,caret:l}=A2(e,n,r,a);return{value:u,caret:l,toast:null}}function O9(i){switch(i){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed";case"needs-input":return"needs_input"}}const L9={feature:{bg:"bg-sage/20",text:"text-sage",border:!0,label:"Feature"},bug:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"Bug"}};function z9(i){return L9[i]}function B9(i,e,n){const r=[...i,...e?[e]:[],...n],s=r.filter(u=>u.status==="needs-input"),a=r.filter(u=>u.status!=="needs-input");return[...s,...a]}function F9(i,e){return e.find(n=>n.slug===i)}function G9({slugs:i,jobs:e}){return i.length===0?o.jsx("div",{className:"text-xs italic text-fg-faint",children:"No PRDs linked yet."}):o.jsx("ul",{className:"space-y-1.5","data-testid":"ticket-detail-prd-list",children:i.map(n=>{const r=F9(n,e);return o.jsxs("li",{className:"flex items-center gap-2","data-testid":"ticket-detail-prd",children:[o.jsxs("button",{onClick:()=>iA(n),title:`Open PRD "${n}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[11px] text-accent hover:bg-hi",children:["#",n]}),r&&o.jsx(h0,{status:r.status})]},n)})})}function N2({ticket:i,jobs:e}){return o.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5","data-testid":"ticket-detail-entry",children:[i.tag&&o.jsx("div",{className:"mb-1.5",children:o.jsx(nA,{tag:i.tag})}),o.jsx("div",{className:"whitespace-pre-wrap text-sm text-fg",children:i.text}),o.jsx("div",{className:"mt-2",children:o.jsx(G9,{slugs:i.prdSlugs??[],jobs:e})})]})}function U9({ticket:i,allTickets:e,jobs:n,onClose:r}){const s=e.filter(a=>a.chainRootId===i.id);return o.jsxs("div",{className:"flex min-h-0 flex-1 flex-col overflow-y-auto px-3 py-4","data-testid":"ticket-detail-view",children:[o.jsx("div",{className:"mb-3",children:o.jsx("button",{onClick:r,"data-testid":"ticket-detail-back",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to queue"})}),o.jsx(N2,{ticket:i,jobs:n}),s.length>0&&o.jsxs("div",{className:"mt-3 space-y-2 border-l-2 border-line pl-3",children:[o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Follow-ups"}),s.map(a=>o.jsx(N2,{ticket:a,jobs:n},a.id))]})]})}function WD({path:i,onDismiss:e}){const[n,r]=z.useState(!1);return n?null:o.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[o.jsx("img",{src:qb(i),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>r(!0)}),o.jsx("button",{type:"button",onClick:e,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}const Mb=/(?:^|[\s(])((?:\.{1,2}\/)?[\w./-]+\.[A-Za-z]\w*(?::(\d+))?(?::(\d+))?)/g,Ow="data-file-link-text",H9=10,W9=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;function VD(i){const e=i.replace(/(?::\d+)+$/,"");if(e.includes("/"))return!0;const n=e.lastIndexOf("."),r=n===-1?"":e.slice(n+1);return!(!r||r.length>H9||W9.test(r))}function V9(i){var s;const e=document.createTreeWalker(i,NodeFilter.SHOW_TEXT,{acceptNode(a){const u=a.parentElement;return!u||u.closest("a, code, pre")?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_ACCEPT}}),n=[];let r;for(;r=e.nextNode();)n.push(r);for(const a of n){const u=a.textContent??"";Mb.lastIndex=0;const l=[...u.matchAll(Mb)].filter(m=>VD(m[1]));if(l.length===0)continue;const d=document.createDocumentFragment();let p=0;for(const m of l){const f=m[0],b=m[1],w=(m.index??0)+(f.length-b.length);if(w<p)continue;w>p&&d.appendChild(document.createTextNode(u.slice(p,w)));const C=document.createElement("span");C.className="chat-file-link",C.setAttribute(Ow,b),C.textContent=b,d.appendChild(C),p=w+b.length}p<u.length&&d.appendChild(document.createTextNode(u.slice(p))),(s=a.parentNode)==null||s.replaceChild(d,a)}}const q9=3;function K9(i){Mb.lastIndex=0;const e=new Set,n=[];for(const r of i.matchAll(Mb)){const s=r[1];if(VD(s)&&!e.has(s)&&(e.add(s),n.push(s),n.length>=q9))break}return n}function $2(i,e){const n=i.match(/(?::(\d+))?(?::(\d+))?$/),r=i.replace(/(?::\d+)+$/,""),s=n!=null&&n[1]?parseInt(n[1],10):void 0,a=n!=null&&n[2]?parseInt(n[2],10):void 0;return{absPath:r.startsWith("/")?r:`${e}/${r}`,line:s,col:a}}const Y9=3;function X9(i){const e=new Set,n=[],r=/\[[^\]]*\]\((https?:\/\/[^\s)]+)\)|https?:\/\/[^\s)"'<>]+/g;let s;for(;s=r.exec(i);){const a=s[1]??s[0];if(!e.has(a)&&(e.add(a),n.push(a),n.length>=Y9))break}return n}const Ob=new ki.Renderer,J9=Ob.table.bind(Ob);Ob.table=i=>`<div class="prose-chat-table-wrap">${J9(i)}</div>`;function Z9(i){return _0.sanitize(ki.parse(i,{async:!1,breaks:!0,renderer:Ob}))}async function qD(i,e){const n=i.replace(/(?::\d+)+$/,""),r=$2(i,e),s=await window.api.files.read(r.absPath);if(!s.ok&&s.error==="path outside home")return Ve.error("That path is outside the project and can't be opened."),null;if(s.ok)return{target:r,text:s.text};let a=0;if(!n.startsWith("/")){const l=Array.from(new Set(Ct.getState().tabs.map(d=>d.cwd).filter(d=>d&&d!==e)));for(const d of l){const p=$2(i,d),m=await window.api.files.read(p.absPath);if(a++,m.ok)return{target:p,text:m.text}}}const u=a===1?"tab":"tabs";return Ve.error(`${s.error||"Not found"} under ${e} (tried ${a} other open ${u})`),null}async function KD(i,e=""){if(!i)return;const n=await qD(i,e);n&&(Di.getState().openFile(n.target.absPath,{line:n.target.line,col:n.target.col}),window.dispatchEvent(new CustomEvent("sm:open-editor")))}async function Q9(i,e=""){if(!i)return null;const n=await qD(i,e);return(n==null?void 0:n.text)??null}function e7(i){Pt.getState().openTab({url:i}),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"browser"}))}async function t7(i,e="",n="external"){const r=i.target,s=r.closest("a");if(s){const l=s.getAttribute("href")||"";/^https?:\/\//i.test(l)&&(i.preventDefault(),n==="browser"?e7(l):window.api.shell.open({as:"external",url:l}).catch(()=>{}));return}const a=r.closest(`[${Ow}]`);if(!a)return;const u=a.getAttribute(Ow)??"";await KD(u,e)}function i7(i,e){var n;return i.text.trim().length>0?"text":e?"working":(n=i.toolUses)!=null&&n.length?"placeholder":"suppress"}const n7=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function r7(i){return n7.test(i)}function YD(i,e){window.api.clipboard.writeText(i).then(n=>e(!!(n!=null&&n.ok))).catch(()=>e(!1))}function s7({url:i}){const[e,n]=z.useState(!1),r=()=>{YD(i,s=>{s?(n(!0),setTimeout(()=>n(!1),1100)):Ve.error("Copy failed")})};return o.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[o.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),o.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:i}),o.jsx("button",{onClick:r,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:e?"Copied":"Copy"})]})}const o7=/\.(?:md|markdown)(?::\d+)*$/i;function a7({path:i,cwd:e,inlinePreview:n=!1}){const[r,s]=z.useState(!1),[a,u]=z.useState(!1),[l,d]=z.useState(null),[p,m]=z.useState(!1),f=()=>{YD(i,C=>{C?(s(!0),setTimeout(()=>s(!1),1100)):Ve.error("Copy failed")})},b=()=>{KD(i,e)},S=n&&o7.test(i),w=async()=>{if(a){u(!1);return}if(u(!0),l===null&&!p){m(!0);const C=await Q9(i,e);m(!1),d(C??"")}};return o.jsxs("div",{className:"mt-1.5",children:[o.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[o.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),o.jsx("button",{onClick:b,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:i}),S&&o.jsx("button",{onClick:()=>{w()},className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:a?"Hide preview":"Preview"}),o.jsx("button",{onClick:f,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]}),S&&a&&o.jsx("div",{className:"mt-1 max-h-80 overflow-hidden rounded-lg border border-line","data-testid":"file-inline-preview",children:p?o.jsx("div",{className:"px-3 py-2 text-xs text-fg-dim",children:"Loading preview…"}):o.jsx(iw,{text:l??"",flush:!0})})]})}const XD={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},JD={skill:"🧩",mcp:"🔌",tool:"⚙"};function ZD(i){const e=[];for(const n of i){const r=e[e.length-1];r&&r.kind===n.kind&&r.label===n.label?(r.count+=1,r.id=n.id):e.push({id:n.id,kind:n.kind,label:n.label,count:1})}return e}function QD(i){return i.count>1?`${i.label} ×${i.count}`:i.label}function Lw({items:i,running:e=!1}){if(!(i!=null&&i.length))return null;const n=ZD(i),r=n.length-1;return o.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[n.map((s,a)=>{const u=e&&a===r;return o.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${u?"border-accent/40 bg-accent/10 text-accent":XD[s.kind]}`,children:[JD[s.kind]," ",QD(s)]},s.id)}),o.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",i.length," steps"]})]})}const eA="text-[#8a2f28]",l7="border-[#b8443c]/40 bg-[#b8443c]/10",Um="text-[#7a5416]",Nx="border-[#8e641a]/40 bg-[#8e641a]/10",c7="needs interactive consent for an MCP server";function tA({turn:i,cwd:e,tabId:n,runActive:r=!1,consentActionDisabled:s=!1,enableRawSessionActions:a=!0,linkTarget:u="external",inlineFilePreview:l=!1}){const d=z.useRef(null),p=i.role==="assistant"?i7(i,r):null;if(z.useEffect(()=>{i.role==="assistant"&&p==="text"&&d.current&&V9(d.current)},[i.role,p,i.text]),i.role==="user")return o.jsx("div",{className:"flex justify-end",children:o.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:i.text})});if(i.role==="error")return o.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${l7} ${eA}`,children:i.text});if(i.role==="question")return o.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${Nx} ${Um}`,children:[o.jsx(Lw,{items:i.toolUses}),o.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${Um}`,children:[o.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),o.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(i.questions??[i.text]).map((S,w)=>o.jsx("li",{children:S},w))}),o.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${Nx}`,children:"Reply in the composer below to answer."})]});if(i.role==="notice"){const S=i.text.includes(c7),w=()=>{Ct.getState().queueRawCommand(n,"/design consent"),Ct.getState().wakeTab(n)};return o.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${Nx} ${Um}`,children:[o.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${Um}`,children:[o.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),i.text,S&&a&&o.jsx("div",{className:`mt-2 border-t pt-2 ${Nx}`,children:o.jsx("button",{onClick:w,disabled:s,title:s?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${Um} border-current`,children:"Grant consent →"})})]})}if(p==="suppress")return null;const m=X9(i.text),f=K9(i.text),b=r7(i.text);return o.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[o.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(Lw,{items:i.toolUses,running:p==="working"}),p==="working"?o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):p==="placeholder"?o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:d,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${b?"prose-chat--plan":""}`,onClick:S=>{t7(S,e,u)},dangerouslySetInnerHTML:{__html:Z9(i.text)}}),m.map(S=>o.jsx(s7,{url:S},S)),f.map(S=>o.jsx(a7,{path:S,cwd:e,inlinePreview:l},S))]})]})]})}const d7=1180,P2={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function u7(){const[i,e]=z.useState(()=>window.innerWidth);return z.useEffect(()=>{const n=()=>e(window.innerWidth);return window.addEventListener("resize",n),()=>window.removeEventListener("resize",n)},[]),i}function h7({cwd:i,label:e,running:n,queuedPosition:r,stream:s,liveToolUses:a}){const u=ZD(a),l=n&&!s?u.length-1:-1;return o.jsxs("div",{className:"min-h-0 max-h-[45%] shrink-0 overflow-y-auto border-b border-rule px-3 py-4",children:[o.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[o.jsx("div",{className:"text-xs font-semibold text-fg",children:e}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:i,children:i}),o.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:n?r>0?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",r]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),o.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),u.length===0?o.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):o.jsx("ul",{className:"mt-1.5 space-y-1",children:u.map((d,p)=>o.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${p===l?"border-accent/40 bg-accent/10 text-accent":XD[d.kind]}`,children:[p===l?o.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):o.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:JD[d.kind]}),o.jsx("span",{className:"truncate",children:QD(d)})]},d.id))})]})}function iA(i){i9(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function nA({tag:i}){const e=z9(i);return o.jsx("span",{className:`inline-block text-[10.5px] font-semibold px-[7px] py-0.5 rounded-full ${e.bg} ${e.text}${e.border?" ring-1 ring-inset ring-line":""}`,children:e.label})}function p7({tickets:i,onSelectNeedsInput:e,onSelectTicket:n}){const r=z.useRef(null),s=z.useRef(!0),a=()=>{const l=r.current;l&&(s.current=l.scrollHeight-l.scrollTop-l.clientHeight<8)},u=i.map(l=>`${l.id}:${l.status}`).join(",");return z.useEffect(()=>{const l=r.current;l&&s.current&&(l.scrollTop=l.scrollHeight)},[u]),o.jsxs("div",{ref:r,onScroll:a,className:"min-h-0 flex-1 overflow-y-auto px-3 py-4","data-testid":"chat-queue-panel",children:[o.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),i.length===0?o.jsx(Kt,{title:"No prompts queued",hint:"Prompts sent while a turn is running will show up here."}):o.jsx("ul",{className:"space-y-2",children:i.map(l=>{var m;const d=l.status==="needs-input",p=d||!!n;return o.jsxs("li",{className:`rounded-lg border px-2.5 py-2 ${d?"cursor-pointer border-[#8e641a]/40 bg-[#8e641a]/10 hover:bg-[#8e641a]/20":p?"cursor-pointer border-line bg-elev hover:bg-hi":"border-line bg-elev"}`,"data-testid":"chat-queue-ticket",onClick:p?()=>d?e==null?void 0:e(l):n==null?void 0:n(l):void 0,role:p?"button":void 0,tabIndex:p?0:void 0,children:[o.jsx(J_,{status:O9(l.status)}),l.tag&&o.jsx("span",{className:"ml-1.5",children:o.jsx(nA,{tag:l.tag})}),o.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:l.text,children:l.text}),l.status==="dispatched-to-prd"&&!!((m=l.prdSlugs)!=null&&m.length)&&o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:l.prdSlugs.map(f=>o.jsxs("button",{onClick:()=>iA(f),title:`Open PRD "${f}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",f]},f))})]},l.id)})})]})}const f7=[];function m7({tabId:i,cwd:e}){const n=Ct(Le=>Le.tabs.find(ht=>ht.id===i)),r=(n==null?void 0:n.sessionId)??i,s=dn(Le=>Le.chats[i]),a=dn(Le=>Le.send),u=dn(Le=>Le.hydrate),l=dn(Le=>Le.resetThread),d=dn(Le=>Le.pushNotice),p=dn(Le=>{var ht;return(ht=Le.chats[i])==null?void 0:ht.pendingVoiceText}),m=dn(Le=>Le.clearPendingVoiceText),[f,b]=z.useState(""),[S,w]=z.useState("feature"),[C,x]=z.useState("new"),[y,_]=z.useState(!1),[E,j]=z.useState(null),[D,$]=z.useState(null),[I,P]=z.useState(null),[L,B]=z.useState("queue"),U=z.useRef(null),Z=z.useRef(null),X=z.useRef(null),J=u7()>d7,te=J||L==="queue",le=J||L==="transcript",ue=(s==null?void 0:s.turns)??[],V=(s==null?void 0:s.running)??!1,ie=(s==null?void 0:s.stream)??"",K=(s==null?void 0:s.queuedPosition)??0,se=(s==null?void 0:s.liveToolUses)??[],oe=B9((s==null?void 0:s.ticketHistory)??[],s==null?void 0:s.activeTicket,(s==null?void 0:s.queue)??[]),be=oe.find(Le=>Le.status==="needs-input")??null,je=zl(Le=>{var ht;return((ht=Le.snapshot)==null?void 0:ht.jobs)??f7}),Te=((s==null?void 0:s.ticketHistory)??[]).filter(Le=>Le.status==="dispatched-to-prd"&&!Le.chainRootId&&!HA(Le,je)),ve=Te.map(Le=>Le.id).join(",");z.useEffect(()=>{C!=="new"&&!Te.some(Le=>Le.id===C)&&x("new")},[ve,C]);const re=Le=>{const ht=Le.questionTurnId,Gt=()=>{var di,Ue;if(ht){const _t=document.getElementById(`chat-turn-${ht}`);(di=_t==null?void 0:_t.scrollIntoView)==null||di.call(_t,{behavior:"smooth",block:"center"}),$(ht),window.setTimeout(()=>{$(ft=>ft===ht?null:ft)},1500)}(Ue=X.current)==null||Ue.focus()};J?Gt():(B("transcript"),requestAnimationFrame(Gt))};z.useEffect(()=>{u({tabId:i,cwd:e,sessionId:r})},[i]),z.useEffect(()=>{p&&(b(Le=>Le.trim()?`${Le} ${p}`:p),m(i))},[p,i,m]),z.useEffect(()=>{var Le;(Le=U.current)==null||Le.scrollTo({top:U.current.scrollHeight})},[ue.length,ie,V,le]);const Pe=()=>{if(!f.trim())return;const Le=I9(f.trim());if(Le.type==="nav"){b(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:Le.key}));const Gt=`→ opened ${P2[Le.key]} — showing the live list`;d(i,Gt),Ve.info(`Opened ${P2[Le.key]} — showing the live list`);return}Le.type==="warn-unrouted"&&Ve.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),a({tabId:i,sessionId:r,cwd:e,prompt:f,tag:S,chainRootId:C!=="new"?C:void 0}),b(""),j(null),x("new")},_e=Le=>{Le.key==="Enter"&&!Le.shiftKey&&(Le.preventDefault(),Pe())},Qe=Le=>{const ht=Le.currentTarget,Gt=ht.selectionStart??f.length,di=ht.selectionEnd??Gt;Le.preventDefault(),(async()=>{try{const Ue=await M9({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(_t=>_t.ok?_t.text:"")},f,Gt,di);b(Ue.value),Ue.toast&&Ve.info(Ue.toast),Ue.imagePath&&j(Ue.imagePath),requestAnimationFrame(()=>{try{ht.setSelectionRange(Ue.caret,Ue.caret)}catch{}})}catch(Ue){Ve.error(Ue instanceof Error?Ue.message:"Paste failed — clipboard unavailable")}})()};z.useEffect(()=>{if(!y)return;const Le=ht=>{var Gt;(Gt=Z.current)!=null&&Gt.contains(ht.target)||_(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[y]);const st=()=>{Ct.getState().wakeTab(i)},yt=Le=>{Ct.getState().wakeTab(i,Le),_(!1)},[qt,ut]=z.useState(!1),nt=()=>{if(!V){if(!qt){ut(!0);return}Ct.getState().newSession(i),l(i),ut(!1)}};return o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),o.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),o.jsx(X0,{active:"terminal"})]}),o.jsxs("div",{className:"flex items-stretch gap-2",children:[o.jsx("button",{onClick:nt,onBlur:()=>ut(!1),disabled:V,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${qt?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:qt?"Confirm new session?":"New session"}),o.jsxs("div",{ref:Z,className:"relative flex items-stretch",children:[o.jsx("button",{onClick:st,disabled:V,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:V?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),o.jsx("button",{onClick:()=>_(Le=>!Le),disabled:V,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),y&&o.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Vw.map(Le=>o.jsx("button",{onClick:()=>yt(Le),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:Le.charAt(0).toUpperCase()+Le.slice(1)},Le))})]})]})]}),o.jsxs("div",{className:"flex min-h-0 flex-1",children:[te&&o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[!J&&o.jsx("div",{className:"flex items-center justify-end border-b border-rule px-3 py-1.5",children:o.jsx("button",{onClick:()=>B("transcript"),"data-testid":"show-transcript-btn",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"View transcript →"})}),o.jsx("div",{className:I?"hidden":"flex min-h-0 flex-1 flex-col",children:o.jsx(p7,{tickets:oe,onSelectNeedsInput:re,onSelectTicket:Le=>P(Le.id)})}),I&&(()=>{const Le=oe.find(ht=>ht.id===I);return Le?o.jsx(U9,{ticket:Le,allTickets:oe,jobs:je,onClose:()=>P(null)}):null})()]}),le&&o.jsxs("div",{className:J?"flex h-full w-[280px] shrink-0 flex-col border-l border-rule":"flex min-w-0 flex-1 flex-col",children:[!J&&o.jsx("div",{className:"flex items-center justify-start border-b border-rule px-3 py-1.5",children:o.jsx("button",{onClick:()=>B("queue"),"data-testid":"show-queue-btn",className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to queue"})}),J&&o.jsx(h7,{cwd:e,label:(n==null?void 0:n.label)??e,running:V,queuedPosition:K,stream:ie,liveToolUses:se}),o.jsxs("div",{ref:U,className:J?"min-h-0 flex-1 space-y-3 overflow-y-auto px-3 py-4":"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[ue.length===0&&!V&&o.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),ue.map((Le,ht)=>o.jsx("div",{id:`chat-turn-${Le.id}`,className:D===Le.id?"rounded-[14px] ring-2 ring-accent/60 transition-shadow":"rounded-[14px]",children:o.jsx(tA,{turn:Le,cwd:e,tabId:i,runActive:V&&Le.role==="assistant"&&ht===ue.length-1,consentActionDisabled:V})},Le.id)),V&&o.jsxs("div",{className:"max-w-[90%]",children:[o.jsx(Lw,{items:se,running:V&&!ie}),o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:K>0?o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",K," — waiting for a free run slot"]}):ie?o.jsx("span",{className:"whitespace-pre-wrap",children:ie}):o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]})]})]}),o.jsxs("div",{className:"border-t border-rule p-3",children:[E&&o.jsx(WD,{path:E,onDismiss:()=>j(null)},E),Te.length>0&&o.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-fg-dim",role:"radiogroup","aria-label":"New item or continue an existing PRD chain","data-testid":"chain-picker",children:[o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"radio",name:"chain-choice",checked:C==="new",onChange:()=>x("new")}),"New item"]}),Te.map(Le=>o.jsxs("label",{className:"flex items-center gap-1",children:[o.jsx("input",{type:"radio",name:"chain-choice",checked:C===Le.id,onChange:()=>x(Le.id)}),"Continue: ",Le.text.length>40?`${Le.text.slice(0,40)}…`:Le.text]},Le.id))]}),o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx(w0,{}),o.jsx("textarea",{ref:X,value:f,onChange:Le=>b(Le.target.value),onKeyDown:_e,onPaste:Qe,rows:2,placeholder:be?"Reply to answer the pending question…":V?"Running… send to queue a follow-up prompt":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),o.jsxs("div",{className:"flex items-center gap-0.5 rounded-md border border-line p-0.5",role:"group","aria-label":"Feature or bug tag",children:[o.jsx("button",{type:"button",onClick:()=>w("feature"),"aria-pressed":S==="feature",className:`rounded px-2 py-1.5 text-xs font-medium ${S==="feature"?"bg-sage/25 text-sage":"text-fg-faint hover:text-fg-dim"}`,children:"Feature"}),o.jsx("button",{type:"button",onClick:()=>w("bug"),"aria-pressed":S==="bug",className:`rounded px-2 py-1.5 text-xs font-medium ${S==="bug"?"bg-accent/15 text-accent":"text-fg-faint hover:text-fg-dim"}`,children:"Bug"})]}),V&&o.jsx("button",{onClick:()=>window.api.chat.cancel(i),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${eA} border-[#b8443c]/40`,children:"Cancel"}),o.jsx("button",{onClick:Pe,disabled:!f.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const zw="\x1B[38;5;240m",Bw="\x1B[0m",g7=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function v7(i){return i.replace(g7,"")}function x7(i){var a;if(!i||typeof i!="object")return null;const e=i,n=e.type==="user"?"You":e.type==="assistant"?"Claude":null;if(!n)return null;const r=(a=e.message)==null?void 0:a.content;if(!Array.isArray(r))return null;const s=r.filter(u=>(u==null?void 0:u.type)==="text"&&typeof u.text=="string").map(u=>v7(u.text).trim()).filter(Boolean).join(`
|
|
3170
3170
|
`);return s?`${zw}[${n}] ${s}${Bw}\r
|
|
3171
|
-
`:null}function
|
|
3171
|
+
`:null}function b7(i){const e=i.filter(n=>n.kind==="message").map(n=>x7(n.data)).filter(n=>n!==null);return e.length===0?null:`${zw}── prior conversation (from transcript) ──${Bw}\r
|
|
3172
3172
|
`+e.join("")+`${zw}── end prior conversation ──${Bw}\r
|
|
3173
|
-
`}async function
|
|
3173
|
+
`}async function y7({tabId:i,cwd:e}){try{if(!(await window.api.transcripts.subscribe({tabId:i,cwd:e,sessionUuid:i})).ok)return null;const r=await window.api.transcripts.buffer(i);return b7(r)}catch{return null}}function _7(i,e){return i>0&&e>0}const Lb="sm:workbench-refit",w7=/(?:^|[\s(])((?:\.{1,2}\/)?[\w./-]+\.[A-Za-z]\w*(?::(\d+))?(?::(\d+))?)/g,R2=60*1024;function Hm(i,e){for(let n=0;n<e.length;n+=R2)window.api.pty.write({tabId:i,data:e.slice(n,n+R2)})}function rA({tabId:i,cwd:e}){const n=Ct(d=>{var p;return((p=d.tabs.find(m=>m.id===i))==null?void 0:p.status)==="dormant"}),r=z.useRef(null),s=z.useRef(null),a=z.useRef(!1),[u,l]=z.useState(null);return z.useEffect(()=>{if(console.log("[Terminal] mount effect running, tabId=",i,"cwd=",e,"alreadySpawned=",a.current),!r.current||a.current)return;a.current=!0;const d=UD(),p=new S9.Terminal({fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',fontSize:d.fontSize,lineHeight:1.2,cursorBlink:!0,allowProposedApi:!0,theme:Mw[d.theme]}),m=new C9.FitAddon;p.loadAddon(m);const f=()=>{const j=r.current;if(!(!j||!_7(j.clientWidth,j.clientHeight)))try{m.fit()}catch{}},b=D9(j=>{p.options.theme=Mw[j.theme],p.options.fontSize=j.fontSize,f()});p.loadAddon(new T9.WebLinksAddon((j,D)=>{window.api.shell.open({as:"external",url:D}).catch(()=>{Ve.error(`Couldn't open URL: ${D}`)})}));const S={provideLinks(j,D){var P;const $=((P=p.buffer.active.getLine(j-1))==null?void 0:P.translateToString(!0))??"",I=[];for(const L of $.matchAll(w7)){const B=L[0],U=L[1],Z=L[2],X=L[3],W=(L.index??0)+(B.length-U.length)+1,J=W+U.length-1;I.push({range:{start:{x:W,y:j},end:{x:J,y:j}},text:U,activate:()=>{const te=U.replace(/(?::\d+)+$/,""),le=Z?parseInt(Z,10):void 0,ue=X?parseInt(X,10):void 0,V=te.startsWith("/")?te:`${e}/${te}`;Di.getState().openFile(V,{line:le,col:ue}),window.dispatchEvent(new CustomEvent("sm:open-editor"))}})}D(I)}};p.registerLinkProvider(S),p.open(r.current),f(),p.focus(),p.attachCustomKeyEventHandler(j=>{if(j.type!=="keydown")return!0;if(j.ctrlKey&&!j.shiftKey&&!j.metaKey&&(j.key==="c"||j.key==="C")){const $=p.getSelection();if($)return navigator.clipboard.writeText($).catch(()=>{}),p.clearSelection(),!1}if(j.ctrlKey&&j.shiftKey&&j.key==="C"){const $=p.getSelection();if($)return navigator.clipboard.writeText($).catch(()=>{}),!1}return j.ctrlKey&&(j.key==="v"||j.key==="V")?((async()=>{try{const $=await window.api.clipboard.pasteImage();if($.ok){Hm(i,$.path+" "),Ve.info(`Pasted image: ${$.path.split("/").pop()}`),l($.path);return}const I=await window.api.clipboard.pasteText();I.ok&&I.text&&Hm(i,I.text)}catch{}})(),!1):!0}),s.current=p;const{cols:w,rows:C}=p,x=window.api.pty.onData(i,j=>p.write(j)),y=window.api.pty.onExit(i,({exitCode:j})=>{p.write(`\r
|
|
3174
3174
|
\x1B[38;5;240m[session exited code=${j}]\x1B[0m\r
|
|
3175
|
-
`),Ct.getState().setTabExited(i,j)});p.onData(j=>Hm(i,j)),p.onResize(({cols:j,rows:D})=>window.api.pty.resize({tabId:i,cols:j,rows:D})),
|
|
3175
|
+
`),Ct.getState().setTabExited(i,j)});p.onData(j=>Hm(i,j)),p.onResize(({cols:j,rows:D})=>window.api.pty.resize({tabId:i,cols:j,rows:D})),y7({tabId:i,cwd:e}).then(j=>{j&&p.write(j)}).catch(()=>{}).finally(()=>{console.log("[Terminal] calling pty.spawn",{tabId:i,cwd:e,cols:w,rows:C}),window.api.pty.spawn({tabId:i,cwd:e,cols:w,rows:C}).then(({pid:j,reattached:D})=>{console.log("[Terminal] pty.spawn resolved, pid=",j,"tabId=",i,"reattached=",D),Ct.getState().setTabRunning(i,j);const $=Ct.getState().consumeRawCommand(i);if($&&setTimeout(()=>{Hm(i,`${$}\r`)},D?150:1500),D)return;const{startupCommand:I}=Ct.getState().tabs.find(P=>P.id===i)??{};I&&setTimeout(()=>{Hm(i,`${I}
|
|
3176
3176
|
`)},350)}).catch(j=>{console.error("[Terminal] pty.spawn rejected for tabId=",i,j),p.write(`\r
|
|
3177
3177
|
\x1B[31mfailed to spawn: ${j.message}\x1B[0m\r
|
|
3178
|
-
`),Ve.error(`Terminal failed to start: ${j.message??"spawn failed"}`),Ct.getState().setTabExited(i,-1)})});const _=()=>f();window.addEventListener("resize",_),window.addEventListener(Lb,_);const E=new ResizeObserver(()=>f());return E.observe(r.current),()=>{window.removeEventListener("resize",_),window.removeEventListener(Lb,_),E.disconnect(),x(),y(),b(),p.dispose()}},[i,e]),n?o.jsx(f7,{tabId:i,cwd:e}):o.jsxs("div",{className:"relative h-full w-full",children:[o.jsx("button",{type:"button",onClick:()=>Ct.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),u&&o.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:o.jsx(WD,{path:u,onDismiss:()=>l(null)},u)}),o.jsx("div",{ref:r,onMouseDown:()=>{var d;return(d=s.current)==null?void 0:d.focus()},className:"h-full w-full bg-bg"})]})}const w7={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},S7={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function k7(){const{isRecording:i,statusPill:e,lastPartial:n,lastTranscript:r,submitCountdownStartAt:s}=At(YT(GN)),a=i||!!n||!!r,[u,l]=z.useState(a);if(z.useEffect(()=>{if(a)l(!0);else{const p=setTimeout(()=>l(!1),300);return()=>clearTimeout(p)}},[a]),!u)return null;let d=n;return d.length>200&&(d="…"+d.slice(-200)),o.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${a?"opacity-100":"opacity-0"}`,children:o.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[o.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${w7[e]??"bg-fg-faint"}`}),o.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:S7[e]??e})]}),d&&o.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),s!==null&&o.jsx("div",{className:"shrink-0",children:o.jsx(JT,{})})]})})})}const I2=new Map;function C7({promptSession:i}){const e=i.id,{cwd:n,claudeSessionId:r}=i,s=dn(_=>_.chats[e]),a=dn(_=>_.send),u=dn(_=>_.hydrate),l=Bc(_=>_.appendPromptSessionEvent),[d,p]=z.useState(""),m=z.useRef(null),f=z.useRef(null);z.useEffect(()=>{u({tabId:e,cwd:n,sessionId:r})},[e]);const b=(s==null?void 0:s.turns)??[],S=(s==null?void 0:s.running)??!1,w=(s==null?void 0:s.stream)??"",C=(s==null?void 0:s.queuedPosition)??0;z.useEffect(()=>{var D;const _=b[b.length-1];if(!_||_.role!=="assistant"||S)return;const E=I2.get(i.id)??new Set;if(E.has(_.id))return;E.add(_.id),I2.set(i.id,E);const j=(D=Bc.getState().events[i.id])==null?void 0:D.slice(-1)[0];j&&l(i.id,{kind:"response",causedByEventId:j.id,text:_.text})},[b,S,i.id,l]),z.useEffect(()=>{const _=m.current;_&&(_.scrollTop=_.scrollHeight)},[b.length,w]);const x=()=>{d.trim()&&(a({tabId:e,sessionId:r,cwd:n,prompt:d}),p(""))},y=_=>{_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),x())};return o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg","data-testid":"prompt-session-conversation",children:[o.jsx("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-serif text-base text-fg truncate",title:i.goalText,children:i.goalText}),o.jsx("div",{className:"truncate font-mono text-[11px] text-fg-dim",title:n,children:n})]})}),o.jsxs("div",{ref:m,className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4","data-testid":"prompt-session-transcript",children:[b.length===0&&!S&&o.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Send a message to work this goal."}),b.map((_,E)=>o.jsx("div",{id:`prompt-session-turn-${_.id}`,className:"rounded-[14px]",children:o.jsx(tA,{turn:_,cwd:n,tabId:e,runActive:S&&_.role==="assistant"&&E===b.length-1,consentActionDisabled:S,enableRawSessionActions:!1,linkTarget:"browser",inlineFilePreview:!0})},_.id)),S&&o.jsx("div",{className:"max-w-[90%]",children:o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:C>0?o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",C," — waiting for a free run slot"]}):w?o.jsx("span",{className:"whitespace-pre-wrap",children:w}):o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})})]}),o.jsx("div",{className:"border-t border-rule p-3",children:o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("textarea",{ref:f,value:d,onChange:_=>p(_.target.value),onKeyDown:y,rows:2,placeholder:S?"Running… send to queue a follow-up prompt":"Type a message (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),S&&o.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:"rounded-md border border-[#b8443c]/40 px-3 py-2 text-sm text-[#8a2f28] hover:bg-[#b8443c]/10",children:"Cancel"}),o.jsx("button",{onClick:x,disabled:!d.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})})]})}function E7({cwd:i,promptSessionId:e}){const[n,r]=z.useState(null),[s,a]=z.useState(null);return z.useEffect(()=>{let u=!1;r(null),a(null);const l=ID(i,e);return window.api.config.readJson(l).then(d=>{if(!u){if(!d.exists||d.parseError||!d.data){a(d.parseError??d.error??"archive not found");return}r(d.data)}}).catch(d=>{u||a(String(d))}),()=>{u=!0}},[i,e]),s?o.jsxs("div",{"data-testid":"prompt-session-archive-view",className:"flex h-full items-center justify-center text-sm text-fg-faint",children:["Could not load archive: ",s]}):n?o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg","data-testid":"prompt-session-archive-view",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-serif text-base text-fg truncate",title:n.session.goalText,children:n.session.goalText}),o.jsxs("div",{className:"truncate font-mono text-[11px] text-fg-dim",title:n.session.cwd,children:[n.session.cwd," · archived ",n.archivedAt]})]}),o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-bg-hi text-fg-faint",children:"Completed (read-only)"})]}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4 space-y-4","data-testid":"prompt-session-archive-events",children:[o.jsx("div",{className:"flex flex-col gap-2",children:n.events.map(u=>o.jsxs("div",{"data-testid":"prompt-session-archive-event","data-kind":u.kind,className:"rounded-md border border-line bg-bg-elev px-3 py-2",children:[o.jsxs("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-fg-faint",children:[u.kind,u.prdSlug?` · ${u.prdSlug}`:""]}),u.text&&o.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[12.5px] text-fg",children:u.text})]},u.id))}),n.transcript&&o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"Transcript"}),o.jsx("pre",{"data-testid":"prompt-session-archive-transcript",className:"whitespace-pre-wrap break-words rounded-md border border-line bg-bg-elev px-3 py-2 text-[11px] text-fg-dim",children:n.transcript})]})]})]}):o.jsx("div",{"data-testid":"prompt-session-archive-view",className:"flex h-full items-center justify-center text-sm text-fg-faint",children:"Loading archive…"})}function T7(){const i=Bc(B=>B.sessions),e=Bc(B=>B.createPromptSession),{rows:n,enriched:r}=iT(),s=z.useMemo(()=>{var Z;const B=new Set,U=[];for(const X of n){const W=((Z=r[X.encoded])==null?void 0:Z.cwd)??Rg(X.encoded);!W||B.has(W)||(B.add(W),U.push(W))}return U},[n,r]),a=Bc(B=>B.markCompleted),u=Bc(B=>B.resumeArchived),[l,d]=z.useState(""),[p,m]=z.useState(""),[f,b]=z.useState(null),[S,w]=z.useState(null),[C,x]=z.useState(null),y=l||s[0]||"",_=f?i[f]:null,E=S?i[S]:null,j=B=>{const U=Bc.getState().sessions[B];U&&(U.status==="completed"?(w(B),b(null)):(b(B),w(null)))};z.useEffect(()=>{const B=yV();B&&j(B);const U=Z=>j(Z.detail);return window.addEventListener("sm:select-prompt-session",U),()=>window.removeEventListener("sm:select-prompt-session",U)},[]);const D=z.useMemo(()=>{const B=new Map;for(const U of Object.values(i)){if(U.status!=="active")continue;const Z=B.get(U.cwd)??[];Z.push(U),B.set(U.cwd,Z)}for(const U of B.values())U.sort((Z,X)=>X.createdAt.localeCompare(Z.createdAt));return Array.from(B.entries()).sort((U,Z)=>U[0].localeCompare(Z[0]))},[i]),$=z.useMemo(()=>Object.values(i).filter(B=>B.status==="completed").sort((B,U)=>(U.completedAt??"").localeCompare(B.completedAt??"")),[i]),I=()=>{const B=p.trim();!y||!B||(e(y,B),m(""))},P=async B=>{x(B);try{await a(B),f===B&&b(null)}catch(U){Ve.error(`Could not mark session completed: ${U instanceof Error?U.message:String(U)}`)}finally{x(null)}},L=B=>{const U=u(B);w(null),b(U.id)};return E?o.jsxs("div",{className:"h-full flex flex-col bg-bg","data-testid":"projects-landing",children:[o.jsxs("div",{className:"shrink-0 border-b border-rule px-3 py-1.5 flex items-center justify-between",children:[o.jsx("button",{"data-testid":"prompt-session-archive-back",onClick:()=>w(null),className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to Projects"}),o.jsx("button",{"data-testid":"prompt-session-resume",onClick:()=>L(E.id),className:"rounded border border-accent/40 px-2 py-1 text-xs text-accent hover:bg-accent/10",children:"Resume"})]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(E7,{cwd:E.cwd,promptSessionId:E.id})})]}):_?o.jsxs("div",{className:"h-full flex flex-col bg-bg","data-testid":"projects-landing",children:[o.jsxs("div",{className:"shrink-0 border-b border-rule px-3 py-1.5 flex items-center justify-between",children:[o.jsx("button",{"data-testid":"prompt-session-back",onClick:()=>b(null),className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to Projects"}),o.jsx("button",{"data-testid":"prompt-session-mark-completed",onClick:()=>void P(_.id),disabled:C===_.id,className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40",children:C===_.id?"Marking completed…":"Mark completed"})]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(C7,{promptSession:_})})]}):o.jsx("div",{className:"h-full overflow-auto bg-bg","data-testid":"projects-landing",children:o.jsxs("div",{className:"max-w-2xl mx-auto px-6 py-8",children:[o.jsxs("div",{className:"mb-6",children:[o.jsx("h1",{className:"font-serif text-[20px] font-medium text-fg",children:"Projects"}),o.jsx("p",{className:"text-[12.5px] text-fg-faint mt-1",children:"Each row is an independent goal-oriented session you can jump into."})]}),o.jsxs("div",{className:"mb-8 p-3 rounded-lg border border-line bg-bg-elev flex flex-col gap-2",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"New starting prompt"}),o.jsxs("select",{"data-testid":"new-prompt-cwd",value:y,onChange:B=>d(B.target.value),className:"px-2 py-1.5 rounded-md border border-line bg-bg text-fg text-[12.5px] font-mono",children:[s.length===0&&o.jsx("option",{value:"",children:"No known projects"}),s.map(B=>o.jsx("option",{value:B,children:fg(B)},B))]}),o.jsx("input",{"data-testid":"new-prompt-goal",type:"text",value:p,onChange:B=>m(B.target.value),onKeyDown:B=>{B.key==="Enter"&&I()},placeholder:"What's the goal for this session?",className:"px-2 py-1.5 rounded-md border border-line bg-bg text-fg text-[12.5px]"}),o.jsx("button",{"data-testid":"new-prompt-submit",onClick:I,disabled:!y||!p.trim(),className:"self-start px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:"New starting prompt"})]}),D.length===0?o.jsx("div",{className:"text-center text-[12.5px] text-fg-faint py-10",children:"No prompt sessions yet — start one above."}):D.map(([B,U])=>o.jsxs("div",{"data-testid":"prompt-session-group",className:"mb-6",children:[o.jsx("div",{className:"text-[11.5px] font-mono text-fg-faint mb-1.5 truncate",title:B,children:fg(B)}),o.jsx("div",{className:"flex flex-col gap-1",children:U.map(Z=>o.jsx(j7,{session:Z,onClick:()=>b(Z.id),onMarkCompleted:()=>void P(Z.id),completing:C===Z.id},Z.id))})]},B)),o.jsxs("div",{className:"mt-10",children:[o.jsx("div",{className:"mb-2 text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"History"}),$.length===0?o.jsx("div",{className:"text-center text-[12.5px] text-fg-faint py-6",children:"No completed prompt sessions yet."}):o.jsx("div",{className:"flex flex-col gap-1",children:$.map(B=>o.jsx(D7,{session:B,onOpen:()=>w(B.id),onResume:()=>L(B.id)},B.id))})]})]})})}function j7({session:i,onClick:e,onMarkCompleted:n,completing:r}){return o.jsxs("div",{"data-testid":"prompt-session-row","data-status":i.status,className:"w-full flex items-center gap-3 px-3 py-2 rounded-md border border-accent/40 bg-accent/5 hover:bg-accent/10 transition-colors",children:[o.jsxs("button",{onClick:e,className:"flex flex-1 min-w-0 items-center gap-3 text-left",children:[o.jsx("span",{"data-testid":"prompt-session-status-badge",className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-accent/20 text-accent",children:"Active"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-[13px] text-fg",children:sA(i.goalText)}),o.jsx("span",{className:"shrink-0 text-[11px] text-fg-faint font-mono",children:Kc(new Date(i.createdAt).getTime(),Date.now())})]}),o.jsx("button",{"data-testid":"prompt-session-row-mark-completed",onClick:s=>{s.stopPropagation(),n()},disabled:r,className:"shrink-0 rounded border border-line px-2 py-1 text-[11px] text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40",children:r?"Marking…":"Mark completed"})]})}function D7({session:i,onOpen:e,onResume:n}){return o.jsxs("div",{"data-testid":"prompt-session-history-row","data-status":i.status,className:"w-full flex items-center gap-3 px-3 py-2 rounded-md border border-line bg-bg-elev hover:bg-bg-hi/50 transition-colors",children:[o.jsxs("button",{onClick:e,className:"flex flex-1 min-w-0 items-center gap-3 text-left",children:[o.jsx("span",{"data-testid":"prompt-session-status-badge",className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-bg-hi text-fg-faint",children:"Completed"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-[13px] text-fg",children:sA(i.goalText)}),o.jsx("span",{className:"shrink-0 text-[11px] text-fg-faint font-mono",children:i.completedAt?Kc(new Date(i.completedAt).getTime(),Date.now()):""})]}),o.jsx("button",{"data-testid":"prompt-session-history-open",onClick:r=>{r.stopPropagation(),e()},className:"shrink-0 rounded border border-line px-2 py-1 text-[11px] text-fg-dim hover:bg-elev hover:text-fg",children:"Open"}),o.jsx("button",{"data-testid":"prompt-session-history-resume",onClick:r=>{r.stopPropagation(),n()},className:"shrink-0 rounded border border-accent/40 px-2 py-1 text-[11px] text-accent hover:bg-accent/10",children:"Resume"})]})}function sA(i,e=80){return i.length<=e?i:`${i.slice(0,e-1)}…`}function oA({visible:i=!0}){const e=Ct(s=>s.tabs),n=Ct(s=>s.activeTabId),r=e.find(s=>s.id===n)??null;return o.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[r?e.map(s=>o.jsx("div",{className:"absolute inset-0",style:{visibility:s.id===n?"inherit":"hidden"},children:o.jsx(rA,{tabId:s.id,cwd:s.cwd})},`${s.id}-${s.generation}`)):o.jsx(T7,{}),o.jsx(k7,{}),i&&o.jsx(A9,{})]})}function A7(){return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no active session"}),o.jsxs("div",{children:["click ",o.jsx("span",{className:"text-fg-dim",children:"+ new session"})," in the sidebar to start one"]})]})})}function N7(){const i=Ir(e=>e.focusedPanelId==="terminal");return o.jsx(oA,{visible:i})}const $7=1;function P7(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:$7,panels:e,dockview:i}}function Fw(i,e){const n=i.views.filter(s=>e.has(s));if(n.length===0)return null;const r=i.activeView&&n.includes(i.activeView)?i.activeView:n[0];return{...i,views:n,activeView:r}}function aA(i,e){if(i.type==="leaf"){const r=Fw(i.data,e);return r?{...i,data:r}:null}const n=i.data.map(r=>aA(r,e)).filter(r=>r!==null);return n.length===0?null:{...i,data:n}}function R7(i,e){const n=Object.keys(i.panels??{}),r=new Set(n.filter(d=>e.has(d)));if(r.size===0)return null;const s=aA(i.grid.root,r);if(!s)return null;const a={};for(const d of r)a[d]=i.panels[d];const u=(i.floatingGroups??[]).map(d=>{const p=Fw(d.data,r);return p?{...d,data:p}:null}).filter(d=>d!==null),l=(i.popoutGroups??[]).map(d=>{const p=Fw(d.data,r);return p?{...d,data:p}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:s},panels:a,floatingGroups:u,popoutGroups:l,activeGroup:i.activeGroup}}function I7(i,e){if(!i||typeof i!="object")return null;const n=i;if(!Array.isArray(n.panels)||!n.dockview||typeof n.dockview!="object")return null;const r=n.dockview;if(!r.grid||!r.panels)return null;try{return R7(r,e)}catch(s){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",s),null}}const M7=500,O7=new Set(au.map(i=>i.id));function M2(i){const e=P7(i);e&&window.api.layout.save(e).catch(n=>{console.warn("[Workbench] layout save failed:",n)})}const lA=z.createContext(null);function L7(i){const e=z.useContext(lA);return e?o.jsx(o.Fragment,{children:B7(i.params.id,e)}):null}const z7={screen:L7},$x=au[0].id;function B7(i,e){return i==="terminal"?o.jsx(N7,{}):o.jsx(UM,{panelId:i,children:o.jsx("div",{className:"h-full overflow-auto bg-bg",children:o.jsx(KT,{children:_9(i,e)})})})}function F7(i){const e=z.useRef(null),n=Ir(S=>S.focusedPanelId)??$x,r=Ir(S=>S.focusToken),s=Ir(S=>S.resetToken),a=At(S=>S.isRecording||S.externalRecording),u=z.useRef(null),[l,d]=z.useState(!1);z.useEffect(()=>{let S=!1;return window.api.layout.load().then(w=>{S||(w&&(u.current=I7(w,O7)),d(!0))}).catch(w=>{console.warn("[Workbench] layout load failed, using default:",w),S||d(!0)}),()=>{S=!0}},[]);const p=z.useCallback(S=>{const w=e.current;if(!w)return;const C=TR(S)??au[0],x=w.getPanel(C.id);if(x)x.api.setActive();else{const y=w.addPanel({id:C.id,component:C.component,title:C.title,params:{id:C.id},renderer:"always"});C.id==="terminal"&&y.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(Lb))})}},[]),m=z.useCallback(S=>{var x;e.current=S.api;const w=u.current;if(w)try{S.api.fromJSON(w);const y=(x=S.api.activePanel)==null?void 0:x.id;y&&Ir.getState().focusPanel(y)}catch(y){console.warn("[Workbench] fromJSON failed, falling back to default layout:",y),S.api.clear(),p(n)}else p(n);S.api.onDidActivePanelChange(y=>{y&&Ir.getState().focusPanel(y.id)}),S.api.onDidRemovePanel(y=>{if(y.id==="terminal"){Ir.getState().openPanel("terminal");return}S.api.totalPanels===0&&(Ir.getState().openPanel($x),p($x))});let C=null;S.api.onDidLayoutChange(()=>{C!==null&&window.clearTimeout(C),C=window.setTimeout(()=>M2(S.api.toJSON()),M7)})},[]);z.useEffect(()=>{p(n)},[r,i.searchMode,p]);const f=z.useRef(!0);z.useEffect(()=>{if(f.current){f.current=!1;return}const S=e.current;S&&(S.clear(),u.current=null,p($x),M2(S.toJSON()))},[s]),z.useEffect(()=>{const S=e.current;S&&(S.layout(S.width,S.height,!0),window.dispatchEvent(new CustomEvent(Lb)))},[a]);const b=z.useMemo(()=>({components:z7,onReady:m,className:"dockview-theme-sm workbench-root"}),[m]);return l?o.jsx(lA.Provider,{value:i,children:o.jsx(eT,{...b})}):null}function G7({onExit:i}){const e=Ct(n=>n.activeTabId);return o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsx("div",{className:"flex items-center justify-end px-3 py-1.5 border-b border-line shrink-0",children:o.jsx("button",{onClick:i,className:"text-[12px] text-fg-dim hover:text-fg px-2 py-1 rounded border border-line hover:bg-bg-hi/40",children:"Exit split view"})}),o.jsxs("div",{className:"flex h-full w-full flex-1 min-h-0",children:[o.jsx("div",{className:"relative w-1/3 min-w-0 border-r border-line",children:e?o.jsx(oA,{}):o.jsx(A7,{})}),o.jsx("div",{className:"relative w-2/3 min-w-0",children:o.jsx(RD,{})})]})]})}function Gw(){return At(e=>e.isRecording||e.externalRecording)?o.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:"fixed inset-x-0 top-0 z-[60] h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),o.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const Wm=5e3;function ea(i,e,n){var r,s;try{(s=(r=window.api)==null?void 0:r.logs)==null||s.write("voice-wizard",i,e,n)}catch{}}function U7({analyser:i}){const[e,n]=z.useState(0);return z.useEffect(()=>{if(!i){n(0);return}let r=0,s=!1;const a=new Uint8Array(new ArrayBuffer(i.fftSize)),u=()=>{if(s)return;i.getByteTimeDomainData(a);let l=0;for(let m=0;m<a.length;m++){const f=a[m]-128;l+=f*f}const d=Math.sqrt(l/a.length)/128,p=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));n(p),r=requestAnimationFrame(u)};return r=requestAnimationFrame(u),()=>{s=!0,cancelAnimationFrame(r)}},[i]),o.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function H7({open:i,onClose:e}){const n=At(re=>re.permissionState),r=At(re=>re.modelStatus),s=At(re=>re.loadingProgress),[a,u]=z.useState("welcome"),[l,d]=z.useState(null),[p,m]=z.useState(!1),[f,b]=z.useState(0),S=z.useRef(null),w=z.useRef(null),C=z.useRef(null),x=z.useRef(null),y=z.useRef(null),_=z.useRef(null),E=z.useRef(null),j=z.useRef(null),[D,$]=z.useState(!1),[I,P]=z.useState(Math.round(Wm/1e3)),[L,B]=z.useState(!1),[U,Z]=z.useState(!1),[X,W]=z.useState(null),[J,te]=z.useState(0),le=z.useCallback(()=>{var re;try{(re=y.current)==null||re.stop()}catch{}if(y.current=null,j.current){try{j.current.disconnect()}catch{}j.current=null}if(x.current){try{x.current.disconnect()}catch{}x.current=null}if(C.current){try{C.current.disconnect()}catch{}C.current=null}if(te(Pe=>Pe+1),w.current){const Pe=w.current;w.current=null;try{Pe.close()}catch{}}if(S.current){try{S.current.getTracks().forEach(Pe=>Pe.stop())}catch{}S.current=null}},[]),ue=z.useCallback(()=>{le(),_.current=null,E.current=null,$(!1),P(Math.round(Wm/1e3)),B(!1),Z(!1),W(null),d(null),m(!1)},[le]);z.useEffect(()=>{i?(ea("info","wizard.opened"),u("welcome")):ue()},[i,ue]),z.useEffect(()=>()=>le(),[le]);const V=z.useCallback(re=>{ea("info","wizard.step",{step:re}),d(null),u(re)},[]),ie=z.useCallback(re=>{if(ea("info","wizard.skipped",{step:a,mode:re}),le(),e(),re==="skip-and-record"){const Pe=At.getState();Pe.setWizardArmed(!1);const _e=Ct.getState().activeTabId;_e&&Pe.startRecording(_e)}else At.getState().setWizardArmed(!1)},[a,e,le]),K=z.useCallback(()=>{if(n==="denied"){V("permission");return}V("permission")},[n,V]);z.useEffect(()=>{i&&a==="permission"&&n==="granted"&&V("device")},[i,a,n,V]),z.useEffect(()=>{if(!i||a!=="device")return;let re=!1;return(async()=>{var Pe;try{if(!((Pe=navigator.mediaDevices)!=null&&Pe.enumerateDevices)){re||m(!0);return}const _e=await navigator.mediaDevices.enumerateDevices();if(re)return;const Qe=_e.filter(st=>st.kind==="audioinput");m(Qe.length===0)}catch(_e){if(re)return;ea("warn","wizard.error",{step:"device",error:_e instanceof Error?_e.message:String(_e)}),m(!0)}})(),()=>{re=!0}},[i,a,f]);const se=z.useCallback(async()=>{d(null),$(!0),P(Math.round(Wm/1e3));try{let re=null;try{const Gt=await window.api.voice.getDevicePref();re=(Gt==null?void 0:Gt.selectedDeviceId)??null}catch{}const Pe={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};re&&(Pe.deviceId={exact:re});const _e=await navigator.mediaDevices.getUserMedia({audio:Pe});S.current=_e;const Qe=new AudioContext;w.current=Qe;const st=Qe.createMediaStreamSource(_e),yt=Qe.createAnalyser();yt.fftSize=2048,yt.smoothingTimeConstant=.8,st.connect(yt),C.current=st,x.current=yt,te(Gt=>Gt+1);const qt=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",ut=new MediaRecorder(_e,qt?{mimeType:qt}:void 0);y.current=ut;const nt=[];ut.ondataavailable=Gt=>{Gt.data&&Gt.data.size>0&&nt.push(Gt.data)},ut.onstop=()=>{const Gt=ut.mimeType||"audio/webm";if(_.current=new Blob(nt,{type:Gt}),$(!1),x.current){try{x.current.disconnect()}catch{}x.current=null}if(C.current){try{C.current.disconnect()}catch{}C.current=null}if(te(di=>di+1),S.current){try{S.current.getTracks().forEach(di=>di.stop())}catch{}S.current=null}V("playback")},ut.onerror=Gt=>{var Ue;const di=((Ue=Gt.error)==null?void 0:Ue.message)??"recorder error";ea("error","wizard.error",{step:"record",error:di}),d(di),$(!1),Ve.error(`Mic wizard: ${di}`)},ut.start();const Le=Date.now(),ht=setInterval(()=>{const Gt=Date.now()-Le,di=Math.max(0,Math.ceil((Wm-Gt)/1e3));if(P(di),Gt>=Wm){clearInterval(ht);try{ut.stop()}catch{}}},250)}catch(re){const Pe=re instanceof Error?re.message:String(re);ea("error","wizard.error",{step:"record",error:Pe}),d(Pe),$(!1),le(),Ve.error(`Mic wizard: ${Pe}`)}},[V,le]),oe=z.useCallback(async()=>{d(null);const re=_.current;if(!re){d("No recording available");return}try{let Pe=w.current;(!Pe||Pe.state==="closed")&&(Pe=new AudioContext,w.current=Pe);let _e=E.current;if(!_e){const st=await re.arrayBuffer();_e=await Pe.decodeAudioData(st.slice(0)),E.current=_e}if(j.current){try{j.current.disconnect()}catch{}j.current=null}const Qe=Pe.createBufferSource();Qe.buffer=_e,Qe.connect(Pe.destination),j.current=Qe,B(!0),Qe.onended=()=>{B(!1);try{Qe.disconnect()}catch{}j.current===Qe&&(j.current=null)},Qe.start()}catch(Pe){const _e=Pe instanceof Error?Pe.message:String(Pe);ea("error","wizard.error",{step:"playback",error:_e}),d(_e),B(!1)}},[]);z.useEffect(()=>{i&&a==="playback"&&oe().catch(()=>{})},[i,a,oe]);const be=z.useCallback(async()=>{d(null),Z(!0),W(null);try{const re=E.current;if(!re)throw new Error("No decoded audio available");const Pe=re.getChannelData(0),_e=new Float32Array(Pe.length);_e.set(Pe);const Qe=await CN(_e);W(Qe)}catch(re){const Pe=re instanceof Error?re.message:String(re);ea("error","wizard.error",{step:"verify",error:Pe}),d(Pe)}finally{Z(!1)}},[]);z.useEffect(()=>{i&&a==="verify"&&r==="ready"&&X===null&&!U&&!l&&be()},[i,a,r,X,U,l,be]);const je=z.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),ea("info","wizard.complete")}catch(re){ea("error","wizard.error",{step:"done",error:re instanceof Error?re.message:String(re)})}At.getState().setWizardArmed(!1),le(),e()},[e,le]),Te=z.useCallback(()=>{ea("info","wizard.skipped",{step:a,mode:"modal-close"}),le(),At.getState().setWizardArmed(!1),e()},[a,le,e]),ve=z.useMemo(()=>{switch(a){case"welcome":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),o.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:K,"data-testid":"wizard-start",children:"Start"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>ie("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),o.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>ie("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return n==="denied"?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),o.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",o.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",o.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),o.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",n]}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>V("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return p?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),o.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{m(!1),b(re=>re+1)},"data-testid":"wizard-device-retry",children:"Try again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),o.jsx(XT,{}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>V("record"),"data-testid":"wizard-device-continue",children:"Continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("p",{className:"text-sm text-fg",children:["Say: ",o.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),o.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),D?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",I,"s"]}),o.jsx(U7,{analyser:x.current},J)]}):o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{se()},"data-testid":"wizard-record-start",children:"Start recording"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),o.jsx("p",{className:"text-xs text-fg-dim",children:L?"Playing back…":"Playback finished."}),o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>V("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{oe()},"data-testid":"wizard-playback-replay",children:"Replay"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{E.current=null,_.current=null,V("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return r==="loading"||r==="idle"?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[o.jsx("span",{children:"Downloading"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`},"data-testid":"wizard-load-progress"})}),o.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:U?"Transcribing your sample…":X===null?"Ready to transcribe.":"We heard:"}),X!==null&&o.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:X||"(no text recognized)"}),o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",disabled:U||X===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>V("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{E.current=null,_.current=null,W(null),V("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),o.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{je()},"data-testid":"wizard-done",children:"Done"})})]})}},[a,K,ie,n,p,D,I,J,L,U,X,r,s,l,V,se,oe,je]);return o.jsx($p,{open:i,onClose:Te,title:"Mic check",children:o.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[o.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",a]}),l?o.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:l}):null,ve]})})}const cA="sm.tour.completedAt",Oc=Xn((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:n=>{e().stepCount!==n&&i({stepCount:n})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:n,stepCount:r}=e();if(n>=r-1){e().complete();return}i({currentStep:n+1})},prev:()=>{const{currentStep:n}=e();n<=0||i({currentStep:n-1})},goTo:n=>{const{stepCount:r}=e();n<0||n>=r||i({currentStep:n})},complete:()=>{try{localStorage.setItem(cA,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function W7(){try{return!!localStorage.getItem(cA)}catch{return!1}}const O2={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function V7(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app",section:"session",run:()=>window.api.app.rebootApp()},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=At.getState(),n=Ct.getState().activeTabId;e.isRecording?e.stopRecording():n&&e.startRecording(n)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>At.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>At.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{Ve.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{Ve.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Oc.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ir.getState().resetLayout()},{id:"nav:overview",label:"Go to Overview",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:browser",label:"Go to Browser",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:keybindings",label:"Go to Keybindings",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:remote",label:"Go to Remote",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0},{id:"nav:repoviz",label:"Go to Repo Viz",section:"nav",emitOnly:!0},{id:"nav:search",label:"Go to Search",section:"nav",emitOnly:!0}]}function q7(i,e){if(!e)return 0;const n=i.toLowerCase(),r=e.toLowerCase();let s=0,a=-1,u=0;for(let l=0;l<n.length&&s<r.length;l++)n[l]===r[s]&&(u+=l-a,a=l,s++);return s!==r.length?null:u}function K7(i,e){if(!e)return i.map(r=>({...r,score:0}));const n=[];for(const r of i){const s=q7(r.label,e);s!==null&&n.push({...r,score:s})}return n.sort((r,s)=>r.score-s.score),n}function Y7({open:i,onClose:e,onCommand:n}){const[r,s]=z.useState(""),[a,u]=z.useState(0),l=z.useRef(null),d=z.useRef(null),p=z.useRef(null),m=z.useRef(null),f=z.useMemo(()=>V7(),[]),b=z.useMemo(()=>K7(f,r),[f,r]);if(z.useEffect(()=>{if(i){const j=document.activeElement;m.current=j instanceof HTMLElement?j:null,s(""),u(0);const D=setTimeout(()=>{var $;return($=l.current)==null?void 0:$.focus()},0);return()=>{clearTimeout(D);const $=m.current;m.current=null,$&&requestAnimationFrame(()=>{try{$.focus()}catch{}})}}},[i]),z.useEffect(()=>{a>=b.length&&u(Math.max(0,b.length-1))},[b.length,a]),z.useEffect(()=>{if(!d.current)return;const j=d.current.querySelector(`[data-cmd-idx="${a}"]`);j&&j.scrollIntoView({block:"nearest"})},[a]),!i)return null;const S=async j=>{var D;if(e(),j.emitOnly){n(j);return}try{await((D=j.run)==null?void 0:D.call(j))}catch($){console.error("[command-palette] run failed",j.id,$);const I=$ instanceof Error?$.message:String($);Ve.error(`Command "${j.label}" failed: ${I}`)}n(j)},w=j=>{var D,$,I,P;if(j.key==="Escape"){j.preventDefault(),e();return}if(j.key==="ArrowDown"){j.preventDefault(),u(L=>Math.min(b.length-1,L+1));return}if(j.key==="ArrowUp"){j.preventDefault(),u(L=>Math.max(0,L-1));return}if(j.key==="Home"){j.preventDefault(),u(0);return}if(j.key==="End"){j.preventDefault(),u(Math.max(0,b.length-1));return}if(j.key==="PageDown"){j.preventDefault(),u(L=>Math.min(b.length-1,L+5));return}if(j.key==="PageUp"){j.preventDefault(),u(L=>Math.max(0,L-5));return}if(j.key==="Tab"){j.preventDefault();const L=document.activeElement;j.shiftKey?L===l.current?(D=p.current)==null||D.focus():($=l.current)==null||$.focus():L===l.current?(I=p.current)==null||I.focus():(P=l.current)==null||P.focus();return}if(j.key==="Enter"){j.preventDefault();const L=b[a];L&&S(L);return}},C=[],x=new Map;b.forEach((j,D)=>{let $=x.get(j.section);$===void 0&&($=C.length,x.set(j.section,$),C.push({section:j.section,items:[]})),C[$].items.push({cmd:j,absIdx:D})});const y=b[a],_=y?`cmdk-opt-${y.id}`:void 0,E=o.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-black/60 pt-[15vh]",onClick:j=>{j.target===j.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:w,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[o.jsxs("div",{className:"border-b border-line flex items-center",children:[o.jsx("input",{ref:l,id:"cmdk-title",type:"text",value:r,onChange:j=>{s(j.target.value),u(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":_,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),o.jsx("button",{ref:p,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),o.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:b.length===0?o.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):C.map(j=>o.jsxs("div",{role:"group","aria-label":O2[j.section],className:"py-1",children:[o.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:O2[j.section]}),j.items.map(({cmd:D,absIdx:$})=>{const I=$===a;return o.jsxs("button",{id:`cmdk-opt-${D.id}`,type:"button",role:"option","aria-selected":I,"data-cmd-idx":$,"data-cmd-id":D.id,tabIndex:-1,onMouseEnter:()=>u($),onClick:()=>S(D),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${I?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[o.jsx("span",{className:"truncate flex-1",children:D.label}),D.hint&&o.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:D.hint})]},D.id)})]},j.section))}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[o.jsx("span",{children:"↑↓ navigate"}),o.jsx("span",{children:"↵ run"}),o.jsx("span",{children:"esc close"}),o.jsxs("span",{className:"ml-auto",children:[b.length," of ",f.length]})]})]})});return typeof document<"u"&&document.body?vu.createPortal(E,document.body):E}const X7={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function Uw(){const i=iu(n=>n.toasts),e=iu(n=>n.dismiss);return i.length===0?null:o.jsx("div",{"data-testid":"toast-host",className:"fixed bottom-3 right-3 z-[55] flex flex-col gap-1.5 pointer-events-none",children:i.map(n=>{const r=X7[n.kind];return o.jsxs("div",{"data-testid":"toast","data-kind":n.kind,role:n.kind==="error"?"alert":"status","aria-live":n.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${r.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[o.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${r.text}`,children:r.label}),o.jsx("span",{className:"flex-1 text-fg-dim break-words",children:n.message}),o.jsx("button",{type:"button",onClick:()=>e(n.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},n.id)})})}function J7(){const i=Ct(s=>s.tabs),e=Ct(s=>s.activeTabId),n=i.find(s=>s.id===e)??null,r=At(s=>s.isRecording);return o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${r?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[o.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),n&&o.jsxs("span",{className:"truncate",children:["· ",n.cwd]})]}),o.jsx("div",{className:"flex-1 min-h-0 relative",children:n?o.jsx(rA,{tabId:n.id,cwd:n.cwd},`${n.id}-${n.generation}`):o.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),o.jsx(Uw,{})]})}const Qd=[{id:"welcome",title:"Welcome to Session Manager",body:"A 30-second tour so you know where everything lives. You can re-run this any time from the command palette.",position:"center"},{id:"tabs",title:"Session tabs",body:"Each tab is a separate Claude session with its own working directory. Click + new to open another, drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"Left navigation",body:"Switch between Terminal, Settings, Skills, MCP servers, History and more. Live dots show which sections are active right now.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"voice",title:"Push-to-talk dictation",body:"Hold the configured hotkey (F1 by default) to dictate into the terminal. You can also click the mic.",target:'[data-testid="mic-button"]',position:"right"},{id:"scheduler",title:"PRD scheduler",body:"Drop a Markdown plan in this project's session-manager-operations/scheduler/prds/ and the scheduler runs it as a token-budget-managed claude -p job.",target:'[data-testid="tour-scheduler"]',position:"right"},{id:"mainpane-actions",title:"Session actions",body:"Press ⌘K / Ctrl+K to open the command palette — restart this session, broadcast a prompt to multiple tabs, or attach a long-running watcher command whose stdout streams back as toasts.",position:"center"},{id:"statusbar",title:"Status bar",body:"Model, 5-hour usage, branch, last activity, and the active working directory. Click restart-app to reload the whole app.",target:'[data-testid="tour-statusbar"]',position:"top"},{id:"new-session",title:"Start a new session",body:"Pick any project directory to spin up another claude session. Tabs persist across reboots — they auto-resume on next launch.",target:'[data-testid="tour-new-session"]',position:"top"}],$c=360,eu=220,In=16;function Nc(i,e,n){return Math.max(e,Math.min(n,i))}function Z7(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const n=window.innerWidth,r=window.innerHeight;switch(e){case"top":return{position:"fixed",top:Nc(i.top-eu-In,In,r-eu-In),left:Nc(i.left+i.width/2-$c/2,In,n-$c-In)};case"bottom":return{position:"fixed",top:Nc(i.bottom+In,In,r-eu-In),left:Nc(i.left+i.width/2-$c/2,In,n-$c-In)};case"left":return{position:"fixed",top:Nc(i.top+i.height/2-eu/2,In,r-eu-In),left:Nc(i.left-$c-In,In,n-$c-In)};case"right":return{position:"fixed",top:Nc(i.top+i.height/2-eu/2,In,r-eu-In),left:Nc(i.right+In,In,n-$c-In)}}}function Q7(){const i=Oc(C=>C.open),e=Oc(C=>C.currentStep),n=Oc(C=>C.next),r=Oc(C=>C.prev),s=Oc(C=>C.complete),a=Oc(C=>C.setStepCount);z.useEffect(()=>{a(Qd.length)},[a]);const[u,l]=z.useState(null),d=z.useRef(null),p=Qd[e]??Qd[0],m=e===0,f=e===Qd.length-1;if(z.useLayoutEffect(()=>{if(!i)return;let C=!1;const x=()=>{if(C)return;if(!p.target){l(null);return}const _=document.querySelector(p.target);if(!_){l(null);return}l(_.getBoundingClientRect())},y=requestAnimationFrame(x);return window.addEventListener("resize",x),()=>{C=!0,cancelAnimationFrame(y),window.removeEventListener("resize",x)}},[i,p.target,e]),z.useEffect(()=>{if(!i)return;const C=x=>{if(x.key==="Escape"){x.stopPropagation(),pt.info("tour","skipped",{step:p.id}),s();return}if(x.key==="ArrowRight"||x.key==="Enter"){x.preventDefault(),n();return}x.key==="ArrowLeft"&&(x.preventDefault(),r())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[i,n,r,s,p.id]),z.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:p.id})},[i,e,p.id]),!i)return null;const b=Z7(u,p.position),S=(e+1)/Qd.length*100,w=o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:"fixed inset-0 z-[200]",children:[u?o.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:u.top-6,left:u.left-6,width:u.width+12,height:u.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):o.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),o.jsxs("div",{ref:d,style:{...b,width:$c},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[o.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",Qd.length]}),o.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:p.title})]}),o.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:p.id}),s()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),o.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.body}),o.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":Qd.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${S}%`}})}),o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:p.id}),s()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),o.jsxs("div",{className:"flex items-center gap-2",children:[!m&&o.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),o.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:f?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?vu.createPortal(w,document.body):w}const eq=3e4,tq=5e3,iq=Xn(()=>({teams:[],loaded:!1}));let L2=!1,z2=!1;async function dA(){try{const i=await Yw(window.api.teams.list(),tq,"teams.list");iq.setState({teams:i.teams,loaded:!0})}catch(i){if(!z2){z2=!0;const e=i instanceof Error?i.message:String(i);Ve.warn(`Teams list fetch failed: ${e}`)}}setTimeout(dA,eq)}function nq(){L2||(L2=!0,dA())}async function k_(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return Ct.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}function rq(i){const e=At(r=>r.ttsEnabled),n=At(r=>r.isRecording);z.useEffect(()=>{if(!i||!e)return;const r=a=>{const u=At.getState().lastBargeInAt;if(u!==null&&performance.now()-u<zN){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-u)});return}jN(a)};return window.api.transcripts.onEvent(i,a=>{if(a.kind!=="message")return;const u=a.data;if(typeof u!="object"||u===null)return;const l=u;if(l.role!=="assistant"||At.getState().isRecording)return;const d=l.content;if(typeof d=="string")r(d);else if(Array.isArray(d)){const p=d.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");p&&r(p)}})},[i,e]),z.useEffect(()=>{n&&(pE(),At.setState({lastBargeInAt:performance.now()}))},[n])}const uA="sm.density",sq="roomy",B2="density-compact";function oq(){try{const i=localStorage.getItem(uA);if(i==="compact"||i==="roomy")return i}catch{}return sq}function hA(i){typeof document>"u"||(i==="compact"?document.body.classList.add(B2):document.body.classList.remove(B2))}let Sp=oq();const Hw=new Set;hA(Sp);function aq(i){if(i!==Sp){Sp=i;try{localStorage.setItem(uA,i)}catch{}hA(i),Hw.forEach(e=>e(i))}}function lq(){const[i,e]=z.useState(Sp);z.useEffect(()=>{const r=s=>e(s);return Hw.add(r),Sp!==i&&e(Sp),()=>{Hw.delete(r)}},[]);const n=z.useCallback(r=>aq(r),[]);return{density:i,setDensity:n}}let F2=!1;function cq(){lq();const i=Ir(W=>W.focusedPanelId)??"overview",[e,n]=z.useState(null),[r,s]=z.useState(!1),[a,u]=z.useState("files"),[l,d]=z.useState(!1),[p,m]=z.useState(!1),[f,b]=z.useState(!1),[S,w]=z.useState(null),C=z.useCallback(W=>{Ir.getState().openPanel(W)},[]);z.useCallback(W=>{Di.getState().openFile(W),C("editor")},[C]),z.useEffect(()=>{const W=()=>C("editor");return window.addEventListener("sm:open-editor",W),()=>window.removeEventListener("sm:open-editor",W)},[C]),z.useEffect(()=>{const W=J=>C(J.detail);return window.addEventListener("sm:navigate",W),()=>window.removeEventListener("sm:navigate",W)},[C]);const x=Ct(W=>W.activeTabId),y=Ct(W=>W.tabs),_=y.find(W=>W.id===x)??null,E=z.useRef(x),j=z.useRef(new Set(y.map(W=>W.id)));z.useEffect(()=>{const W=E.current,J=j.current,te=new Set(y.map(ue=>ue.id));E.current=x,j.current=te,W!==null&&x!==null&&x!==W&&te.size===J.size&&J.has(x)&&te.has(W)&&Ir.getState().openPanel("terminal")},[x,y]),z.useEffect(()=>{if(!S)return;const W=window.setTimeout(()=>w(null),2500);return()=>window.clearTimeout(W)},[S]),z.useEffect(()=>_?window.api.watchers.onLine(J=>{if(J.tabId!==_.id)return;const te=J.line.replace(/\x1b\[[0-9;]*m/g,"");te.trim()&&w(te.length>100?`${te.slice(0,100)}…`:te)}):void 0,[_==null?void 0:_.id]);const D=At(W=>W.isRecording),$=At(W=>W.wizardOpen),I=At(W=>W.closeWizard);rq(x);const P=z.useCallback(()=>{const{activeTabId:W,restartTab:J}=Ct.getState();W&&J(W)},[]);z.useCallback(()=>{window.api.app.rebootApp()},[]);const L=z.useCallback(()=>{d(W=>(W||Ir.getState().openPanel("terminal"),!W))},[]),B=z.useCallback(()=>{m(W=>(W||Ir.getState().openPanel("terminal"),!W))},[]),U=z.useRef(x);U.current=x;const Z=z.useRef("hold"),X=z.useCallback(()=>{Ir.getState().openPanel("terminal"),k_().catch(W=>{console.error("[App] new session failed:",W),Ve.error("Could not start new session. Is the claude CLI on PATH?")})},[]);return z.useEffect(()=>{var le;if(!Fb()){F2||(pt.warn("voice","mic.gate.unsupported"),F2=!0);return}At.getState().initModel();let W=null,J=!1;const te=()=>{if(!W)return;const ue=W.state;At.getState().setPermissionState(ue)};return typeof navigator<"u"&&((le=navigator.permissions)!=null&&le.query)&&navigator.permissions.query({name:"microphone"}).then(ue=>{J||(W=ue,At.getState().setPermissionState(ue.state),ue.addEventListener("change",te))}).catch(ue=>{pt.warn("voice","permission query unsupported",{error:ue==null?void 0:ue.message})}),()=>{J=!0,W&&W.removeEventListener("change",te)}},[]),z.useEffect(()=>{var be;const W=W2[0],J=je=>{if(!je||Ct.getState().tabs.length>0)return;const Te=crypto.randomUUID(),ve=q2(W,{sessionId:Te,cwd:je});Ct.setState(re=>({tabs:[...re.tabs,{id:Te,sessionId:Te,label:je.split("/").filter(Boolean).pop()||je,cwd:je,pid:null,status:"spawning",exitCode:null,startupCommand:ve,presetId:W.id,generation:0}],activeTabId:Te}))},te=je=>{if(!je||Ct.getState().tabs.length>0)return;const Te=crypto.randomUUID();Ct.setState(ve=>({tabs:[...ve.tabs,{id:Te,sessionId:Te,label:je.split("/").filter(Boolean).pop()||je,cwd:je,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:W.id,generation:0}],activeTabId:Te}))};window.api.app.launchMode().then(({simple:je,cwd:Te})=>{if(je){n(!0),J(Te);return}n(!1),j_().then(()=>{Ct.getState().tabs.length>0||p1(W).then(ve=>te(ve||"")).catch(ve=>{console.warn("[App] failed to create initial tab:",ve),Ve.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),j_().then(()=>{Ct.getState().tabs.length>0||p1(W).then(je=>te(je||"")).catch(()=>{})})});const le=window.api.app.onNewSession(()=>{k_().catch(je=>{console.error("[App] new-session from menu failed:",je),Ve.error("Could not start new session. Is the claude CLI on PATH?")})}),ue=window.api.app.onRebootSession(()=>{const{activeTabId:je}=Ct.getState();je&&Ct.getState().restartTab(je)});tg.getState().init(),qN(),nq(),HN(),window.api.app.claudeBinStatus().then(je=>{je.foundOnDisk||Ve.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(je=>{je.ok||Ve.error(`Home-directory self-check failed: ${je.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const V=T3();vz([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]},{uri:"https://json.schemastore.org/claude-code-keybindings.json",fileMatch:["**/keybindings.json"]}]).catch(je=>console.warn("[monaco] schema install failed:",je)),window.api.voice.getHotkeyConfig().then(je=>{Z.current=je.mode}).catch(je=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(je)}));const ie=window.api.voice.onHotkeyConfigChanged(je=>{Z.current=je.mode}),K=window.api.voice.onHotkey(({phase:je,source:Te})=>{At.getState().armHotkey({phase:je,source:Te,mode:Z.current,tabId:U.current})}),se=()=>At.getState().destroyHotkey();window.addEventListener("beforeunload",se);const oe=async()=>{var je;window.dispatchEvent(new Event("mic-device-change"));try{if(!((je=navigator.mediaDevices)!=null&&je.enumerateDevices))return;const ve=(await navigator.mediaDevices.enumerateDevices()).filter(Qe=>Qe.kind==="audioinput"),re=At.getState();if(!re.isRecording)return;let Pe=null;try{Pe=await window.api.voice.getDevicePref()}catch{}if(!Pe||!Pe.selectedDeviceId||ve.some(Qe=>Qe.deviceId===Pe.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:Pe.selectedDeviceId.slice(0,8)}),re.stopRecording(),At.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(Te){pt.warn("voice","devicechange handler failed",{error:Te instanceof Error?Te.message:String(Te)})}};return typeof navigator<"u"&&((be=navigator.mediaDevices)!=null&&be.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",oe),()=>{var je;V(),le(),ue(),ie(),K(),window.removeEventListener("beforeunload",se),typeof navigator<"u"&&((je=navigator.mediaDevices)!=null&&je.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",oe)}},[]),z.useEffect(()=>{try{window.api.voice.setRecording(D)}catch{}},[D]),z.useEffect(()=>{const W=te=>{var se,oe,be;const le=te.target,ue=((se=le==null?void 0:le.tagName)==null?void 0:se.toLowerCase())??"",V=((oe=le==null?void 0:le.classList)==null?void 0:oe.contains("xterm-helper-textarea"))??!1,ie=(be=le==null?void 0:le.getAttribute)==null?void 0:be.call(le,"aria-label");return!!((ue==="input"||ue==="textarea")&&!V&&!(ie==="Search files"||ie==="Search query")||le!=null&&le.closest(".monaco-editor"))},J=te=>{if((te.metaKey||te.ctrlKey)&&(te.key==="k"||te.key==="K")){if(W(te))return;te.preventDefault(),te.stopPropagation(),s(le=>!le)}else if((te.metaKey||te.ctrlKey)&&!te.shiftKey&&(te.key==="p"||te.key==="P")){if(W(te))return;te.preventDefault(),te.stopPropagation(),u("files"),C("search")}else if((te.metaKey||te.ctrlKey)&&te.shiftKey&&(te.key==="f"||te.key==="F")){if(W(te))return;te.preventDefault(),te.stopPropagation(),u("content"),C("search")}else if(te.key==="Escape"&&r)s(!1);else if(te.key==="Escape"&&f)b(!1);else if(te.altKey&&!te.ctrlKey&&!te.metaKey&&!te.shiftKey){const le=/^Digit([1-5])$/.exec(te.code);if(!le||W(te))return;const ue=parseInt(le[1],10)-1,{tabs:V,setActive:ie}=Ct.getState(),K=V[ue];if(!K)return;te.preventDefault(),te.stopPropagation(),ie(K.id)}};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[r,f]),z.useEffect(()=>{let W=!1,J=null;return(async()=>{var te,le;try{const ue=await((le=(te=window.api.voice).getTurnDetector)==null?void 0:le.call(te));if(W||!ue||(At.setState({turnDetectorMode:ue.mode,turnDetectorState:"disabled"}),ue.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:ue.mode}),W))return;J=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),J.addEventListener("message",V=>{const ie=V.data;if(!(!ie||typeof ie!="object")&&ie.type==="status"){const K=ie.status;K==="ready"?At.getState().setTurnDetectorRuntimeState("ok"):(K==="load_failed"||K==="runtime_error")&&At.getState().setTurnDetectorRuntimeState(K)}}),J.addEventListener("error",V=>{pt.error("voice-turn","turn-detector worker error",{message:V.message}),At.getState().setTurnDetectorRuntimeState("runtime_error")}),J.postMessage({type:"load"})}catch(ue){pt.warn("voice-turn","mount.read-settings failed",{error:ue instanceof Error?ue.message:String(ue)})}})(),()=>{if(W=!0,J){try{J.terminate()}catch{}J=null}}},[]),z.useEffect(()=>{let W=!1;return(async()=>{var J,te;try{const le=await((te=(J=window.api.app).isE2E)==null?void 0:te.call(J));if(W||le||W7()||At.getState().wizardOpen)return;Oc.getState().start()}catch{}})(),()=>{W=!0}},[]),z.useEffect(()=>{let W=!1;return(async()=>{var J,te;try{const le=await((te=(J=window.api.app).isE2E)==null?void 0:te.call(J));if(W)return;if(le){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const ue=await window.api.voice.getWizardState();if(W)return;ue.completedSchema!==ue.currentSchema&&(At.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:ue.completedSchema,currentSchema:ue.currentSchema}))}catch(le){pt.warn("voice-wizard","auto-arm failed",{error:le instanceof Error?le.message:String(le)})}})(),()=>{W=!0}},[]),e===!0?o.jsx(J7,{}):f?o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${D?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsx(G7,{onExit:()=>b(!1)}),o.jsx(Uw,{})]}):o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${D?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsx(aN,{splitViewActive:f,onToggleSplitView:()=>b(!0)}),o.jsxs("div",{className:"flex-1 flex min-h-0",children:[o.jsx(i$,{active:i,onNavigate:C,onNewSession:X}),o.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&l&&o.jsx(p$,{onClose:()=>d(!1),onSent:W=>{d(!1),w(`Sent to ${W} tab${W===1?"":"s"}`)}}),i==="terminal"&&_&&p&&o.jsx("div",{className:"absolute top-12 right-4 z-30",children:o.jsx(f$,{tabId:_.id,cwd:_.cwd,onClose:()=>m(!1)})}),o.jsx("div",{className:"flex-1 min-h-0 relative",children:o.jsx(F7,{onNavigate:C,onNewSession:X,onOpenVoice:()=>C("voice"),onOpenScheduler:()=>C("scheduler"),searchMode:a})}),S&&o.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:S})]})]}),o.jsx(c$,{onNavigate:C}),o.jsx(H7,{open:$,onClose:I}),o.jsx(Q7,{}),o.jsx(Uw,{}),o.jsx(Y7,{open:r,onClose:()=>s(!1),onCommand:W=>{if(s(!1),W.id.startsWith("nav:")){C(W.id.slice(4));return}const J=Ct.getState().tabs.find(te=>te.id===Ct.getState().activeTabId)??null;switch(W.id){case"new-tab-pick":k_().catch(te=>{console.error("[App] new tab (pick) failed:",te),Ve.error("Could not start new session. Is the claude CLI on PATH?")});return;case"new-tab-here":{if(!J)return;Ct.getState().addTab({cwd:J.cwd,startupCommand:null,dormant:!0}),Ir.getState().openPanel("terminal");return}case"close-tab":J&&Ct.getState().closeTab(J.id);return;case"restart-session":P();return;case"broadcast":L();return;case"watchers":B();return;case"copy-cwd":J&&window.api.clipboard.writeText(J.cwd).catch(()=>Ve.error("Copy failed"));return;case"copy-transcript":J&&window.api.transcripts.pathFor(J.cwd,J.sessionId).then(te=>window.api.clipboard.writeText(te)).catch(()=>Ve.error("Copy failed"));return;case"open-transcript":J&&window.api.transcripts.pathFor(J.cwd,J.sessionId).then(te=>window.api.shell.open({as:"openPath",path:te})).catch(()=>Ve.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const dq=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","teams","plugins","clipboard","memory"];function uq(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,n=[];for(const r of dq){const s=e[r];s==null?n.push({kind:"namespace-missing",name:r}):typeof s!="object"&&n.push({kind:"namespace-not-object",name:r,actualType:typeof s})}return n}function G2(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function hq(){const i=uq(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",G2(e));return setTimeout(()=>{Dg(async()=>{const{toast:e}=await Promise.resolve().then(()=>J2);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const n=i.length===1?G2(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(n)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");hq();DA.createRoot(document.getElementById("root")).render(o.jsx(cq,{}));export{Rt as R,uR as a,Ww as b,zb as g,o as j,z as r};
|
|
3178
|
+
`),Ve.error(`Terminal failed to start: ${j.message??"spawn failed"}`),Ct.getState().setTabExited(i,-1)})});const _=()=>f();window.addEventListener("resize",_),window.addEventListener(Lb,_);const E=new ResizeObserver(()=>f());return E.observe(r.current),()=>{window.removeEventListener("resize",_),window.removeEventListener(Lb,_),E.disconnect(),x(),y(),b(),p.dispose()}},[i,e]),n?o.jsx(m7,{tabId:i,cwd:e}):o.jsxs("div",{className:"relative h-full w-full",children:[o.jsx("button",{type:"button",onClick:()=>Ct.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),u&&o.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:o.jsx(WD,{path:u,onDismiss:()=>l(null)},u)}),o.jsx("div",{ref:r,onMouseDown:()=>{var d;return(d=s.current)==null?void 0:d.focus()},className:"h-full w-full bg-bg"})]})}const S7={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},k7={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function C7(){const{isRecording:i,statusPill:e,lastPartial:n,lastTranscript:r,submitCountdownStartAt:s}=At(YT(GN)),a=i||!!n||!!r,[u,l]=z.useState(a);if(z.useEffect(()=>{if(a)l(!0);else{const p=setTimeout(()=>l(!1),300);return()=>clearTimeout(p)}},[a]),!u)return null;let d=n;return d.length>200&&(d="…"+d.slice(-200)),o.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${a?"opacity-100":"opacity-0"}`,children:o.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[o.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${S7[e]??"bg-fg-faint"}`}),o.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:k7[e]??e})]}),d&&o.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),s!==null&&o.jsx("div",{className:"shrink-0",children:o.jsx(JT,{})})]})})})}const I2=new Map;function E7({promptSession:i}){const e=i.id,{cwd:n,claudeSessionId:r}=i,s=dn(_=>_.chats[e]),a=dn(_=>_.send),u=dn(_=>_.hydrate),l=Bc(_=>_.appendPromptSessionEvent),[d,p]=z.useState(""),m=z.useRef(null),f=z.useRef(null);z.useEffect(()=>{u({tabId:e,cwd:n,sessionId:r})},[e]);const b=(s==null?void 0:s.turns)??[],S=(s==null?void 0:s.running)??!1,w=(s==null?void 0:s.stream)??"",C=(s==null?void 0:s.queuedPosition)??0;z.useEffect(()=>{var D;const _=b[b.length-1];if(!_||_.role!=="assistant"||S)return;const E=I2.get(i.id)??new Set;if(E.has(_.id))return;E.add(_.id),I2.set(i.id,E);const j=(D=Bc.getState().events[i.id])==null?void 0:D.slice(-1)[0];j&&l(i.id,{kind:"response",causedByEventId:j.id,text:_.text})},[b,S,i.id,l]),z.useEffect(()=>{const _=m.current;_&&(_.scrollTop=_.scrollHeight)},[b.length,w]);const x=()=>{d.trim()&&(a({tabId:e,sessionId:r,cwd:n,prompt:d}),p(""))},y=_=>{_.key==="Enter"&&!_.shiftKey&&(_.preventDefault(),x())};return o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg","data-testid":"prompt-session-conversation",children:[o.jsx("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-serif text-base text-fg truncate",title:i.goalText,children:i.goalText}),o.jsx("div",{className:"truncate font-mono text-[11px] text-fg-dim",title:n,children:n})]})}),o.jsxs("div",{ref:m,className:"min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4","data-testid":"prompt-session-transcript",children:[b.length===0&&!S&&o.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Send a message to work this goal."}),b.map((_,E)=>o.jsx("div",{id:`prompt-session-turn-${_.id}`,className:"rounded-[14px]",children:o.jsx(tA,{turn:_,cwd:n,tabId:e,runActive:S&&_.role==="assistant"&&E===b.length-1,consentActionDisabled:S,enableRawSessionActions:!1,linkTarget:"browser",inlineFilePreview:!0})},_.id)),S&&o.jsx("div",{className:"max-w-[90%]",children:o.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:C>0?o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",C," — waiting for a free run slot"]}):w?o.jsx("span",{className:"whitespace-pre-wrap",children:w}):o.jsxs("span",{className:"inline-flex items-center gap-2",children:[o.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})})]}),o.jsx("div",{className:"border-t border-rule p-3",children:o.jsxs("div",{className:"flex items-end gap-2",children:[o.jsx("textarea",{ref:f,value:d,onChange:_=>p(_.target.value),onKeyDown:y,rows:2,placeholder:S?"Running… send to queue a follow-up prompt":"Type a message (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),S&&o.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:"rounded-md border border-[#b8443c]/40 px-3 py-2 text-sm text-[#8a2f28] hover:bg-[#b8443c]/10",children:"Cancel"}),o.jsx("button",{onClick:x,disabled:!d.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})})]})}function T7({cwd:i,promptSessionId:e}){const[n,r]=z.useState(null),[s,a]=z.useState(null);return z.useEffect(()=>{let u=!1;r(null),a(null);const l=ID(i,e);return window.api.config.readJson(l).then(d=>{if(!u){if(!d.exists||d.parseError||!d.data){a(d.parseError??d.error??"archive not found");return}r(d.data)}}).catch(d=>{u||a(String(d))}),()=>{u=!0}},[i,e]),s?o.jsxs("div",{"data-testid":"prompt-session-archive-view",className:"flex h-full items-center justify-center text-sm text-fg-faint",children:["Could not load archive: ",s]}):n?o.jsxs("div",{className:"flex h-full w-full flex-col bg-bg","data-testid":"prompt-session-archive-view",children:[o.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"font-serif text-base text-fg truncate",title:n.session.goalText,children:n.session.goalText}),o.jsxs("div",{className:"truncate font-mono text-[11px] text-fg-dim",title:n.session.cwd,children:[n.session.cwd," · archived ",n.archivedAt]})]}),o.jsx("span",{className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-bg-hi text-fg-faint",children:"Completed (read-only)"})]}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto px-4 py-4 space-y-4","data-testid":"prompt-session-archive-events",children:[o.jsx("div",{className:"flex flex-col gap-2",children:n.events.map(u=>o.jsxs("div",{"data-testid":"prompt-session-archive-event","data-kind":u.kind,className:"rounded-md border border-line bg-bg-elev px-3 py-2",children:[o.jsxs("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-fg-faint",children:[u.kind,u.prdSlug?` · ${u.prdSlug}`:""]}),u.text&&o.jsx("div",{className:"mt-1 whitespace-pre-wrap text-[12.5px] text-fg",children:u.text})]},u.id))}),n.transcript&&o.jsxs("div",{children:[o.jsx("div",{className:"mb-1 text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"Transcript"}),o.jsx("pre",{"data-testid":"prompt-session-archive-transcript",className:"whitespace-pre-wrap break-words rounded-md border border-line bg-bg-elev px-3 py-2 text-[11px] text-fg-dim",children:n.transcript})]})]})]}):o.jsx("div",{"data-testid":"prompt-session-archive-view",className:"flex h-full items-center justify-center text-sm text-fg-faint",children:"Loading archive…"})}function j7(){const i=Bc(B=>B.sessions),e=Bc(B=>B.createPromptSession),{rows:n,enriched:r}=iT(),s=z.useMemo(()=>{var Z;const B=new Set,U=[];for(const X of n){const W=((Z=r[X.encoded])==null?void 0:Z.cwd)??Rg(X.encoded);!W||B.has(W)||(B.add(W),U.push(W))}return U},[n,r]),a=Bc(B=>B.markCompleted),u=Bc(B=>B.resumeArchived),[l,d]=z.useState(""),[p,m]=z.useState(""),[f,b]=z.useState(null),[S,w]=z.useState(null),[C,x]=z.useState(null),y=l||s[0]||"",_=f?i[f]:null,E=S?i[S]:null,j=B=>{const U=Bc.getState().sessions[B];U&&(U.status==="completed"?(w(B),b(null)):(b(B),w(null)))};z.useEffect(()=>{const B=yV();B&&j(B);const U=Z=>j(Z.detail);return window.addEventListener("sm:select-prompt-session",U),()=>window.removeEventListener("sm:select-prompt-session",U)},[]);const D=z.useMemo(()=>{const B=new Map;for(const U of Object.values(i)){if(U.status!=="active")continue;const Z=B.get(U.cwd)??[];Z.push(U),B.set(U.cwd,Z)}for(const U of B.values())U.sort((Z,X)=>X.createdAt.localeCompare(Z.createdAt));return Array.from(B.entries()).sort((U,Z)=>U[0].localeCompare(Z[0]))},[i]),$=z.useMemo(()=>Object.values(i).filter(B=>B.status==="completed").sort((B,U)=>(U.completedAt??"").localeCompare(B.completedAt??"")),[i]),I=()=>{const B=p.trim();!y||!B||(e(y,B),m(""))},P=async B=>{x(B);try{await a(B),f===B&&b(null)}catch(U){Ve.error(`Could not mark session completed: ${U instanceof Error?U.message:String(U)}`)}finally{x(null)}},L=B=>{const U=u(B);w(null),b(U.id)};return E?o.jsxs("div",{className:"h-full flex flex-col bg-bg","data-testid":"projects-landing",children:[o.jsxs("div",{className:"shrink-0 border-b border-rule px-3 py-1.5 flex items-center justify-between",children:[o.jsx("button",{"data-testid":"prompt-session-archive-back",onClick:()=>w(null),className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to Projects"}),o.jsx("button",{"data-testid":"prompt-session-resume",onClick:()=>L(E.id),className:"rounded border border-accent/40 px-2 py-1 text-xs text-accent hover:bg-accent/10",children:"Resume"})]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(T7,{cwd:E.cwd,promptSessionId:E.id})})]}):_?o.jsxs("div",{className:"h-full flex flex-col bg-bg","data-testid":"projects-landing",children:[o.jsxs("div",{className:"shrink-0 border-b border-rule px-3 py-1.5 flex items-center justify-between",children:[o.jsx("button",{"data-testid":"prompt-session-back",onClick:()=>b(null),className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg",children:"← Back to Projects"}),o.jsx("button",{"data-testid":"prompt-session-mark-completed",onClick:()=>void P(_.id),disabled:C===_.id,className:"rounded border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40",children:C===_.id?"Marking completed…":"Mark completed"})]}),o.jsx("div",{className:"min-h-0 flex-1",children:o.jsx(E7,{promptSession:_})})]}):o.jsx("div",{className:"h-full overflow-auto bg-bg","data-testid":"projects-landing",children:o.jsxs("div",{className:"max-w-2xl mx-auto px-6 py-8",children:[o.jsxs("div",{className:"mb-6",children:[o.jsx("h1",{className:"font-serif text-[20px] font-medium text-fg",children:"Projects"}),o.jsx("p",{className:"text-[12.5px] text-fg-faint mt-1",children:"Each row is an independent goal-oriented session you can jump into."})]}),o.jsxs("div",{className:"mb-8 p-3 rounded-lg border border-line bg-bg-elev flex flex-col gap-2",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"New starting prompt"}),o.jsxs("select",{"data-testid":"new-prompt-cwd",value:y,onChange:B=>d(B.target.value),className:"px-2 py-1.5 rounded-md border border-line bg-bg text-fg text-[12.5px] font-mono",children:[s.length===0&&o.jsx("option",{value:"",children:"No known projects"}),s.map(B=>o.jsx("option",{value:B,children:fg(B)},B))]}),o.jsx("input",{"data-testid":"new-prompt-goal",type:"text",value:p,onChange:B=>m(B.target.value),onKeyDown:B=>{B.key==="Enter"&&I()},placeholder:"What's the goal for this session?",className:"px-2 py-1.5 rounded-md border border-line bg-bg text-fg text-[12.5px]"}),o.jsx("button",{"data-testid":"new-prompt-submit",onClick:I,disabled:!y||!p.trim(),className:"self-start px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:"New starting prompt"})]}),D.length===0?o.jsx("div",{className:"text-center text-[12.5px] text-fg-faint py-10",children:"No prompt sessions yet — start one above."}):D.map(([B,U])=>o.jsxs("div",{"data-testid":"prompt-session-group",className:"mb-6",children:[o.jsx("div",{className:"text-[11.5px] font-mono text-fg-faint mb-1.5 truncate",title:B,children:fg(B)}),o.jsx("div",{className:"flex flex-col gap-1",children:U.map(Z=>o.jsx(D7,{session:Z,onClick:()=>b(Z.id),onMarkCompleted:()=>void P(Z.id),completing:C===Z.id},Z.id))})]},B)),o.jsxs("div",{className:"mt-10",children:[o.jsx("div",{className:"mb-2 text-[11px] font-semibold tracking-[0.05em] text-fg-faint uppercase",children:"History"}),$.length===0?o.jsx("div",{className:"text-center text-[12.5px] text-fg-faint py-6",children:"No completed prompt sessions yet."}):o.jsx("div",{className:"flex flex-col gap-1",children:$.map(B=>o.jsx(A7,{session:B,onOpen:()=>w(B.id),onResume:()=>L(B.id)},B.id))})]})]})})}function D7({session:i,onClick:e,onMarkCompleted:n,completing:r}){return o.jsxs("div",{"data-testid":"prompt-session-row","data-status":i.status,className:"w-full flex items-center gap-3 px-3 py-2 rounded-md border border-accent/40 bg-accent/5 hover:bg-accent/10 transition-colors",children:[o.jsxs("button",{onClick:e,className:"flex flex-1 min-w-0 items-center gap-3 text-left",children:[o.jsx("span",{"data-testid":"prompt-session-status-badge",className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-accent/20 text-accent",children:"Active"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-[13px] text-fg",children:sA(i.goalText)}),o.jsx("span",{className:"shrink-0 text-[11px] text-fg-faint font-mono",children:Kc(new Date(i.createdAt).getTime(),Date.now())})]}),o.jsx("button",{"data-testid":"prompt-session-row-mark-completed",onClick:s=>{s.stopPropagation(),n()},disabled:r,className:"shrink-0 rounded border border-line px-2 py-1 text-[11px] text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40",children:r?"Marking…":"Mark completed"})]})}function A7({session:i,onOpen:e,onResume:n}){return o.jsxs("div",{"data-testid":"prompt-session-history-row","data-status":i.status,className:"w-full flex items-center gap-3 px-3 py-2 rounded-md border border-line bg-bg-elev hover:bg-bg-hi/50 transition-colors",children:[o.jsxs("button",{onClick:e,className:"flex flex-1 min-w-0 items-center gap-3 text-left",children:[o.jsx("span",{"data-testid":"prompt-session-status-badge",className:"shrink-0 px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-bg-hi text-fg-faint",children:"Completed"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-[13px] text-fg",children:sA(i.goalText)}),o.jsx("span",{className:"shrink-0 text-[11px] text-fg-faint font-mono",children:i.completedAt?Kc(new Date(i.completedAt).getTime(),Date.now()):""})]}),o.jsx("button",{"data-testid":"prompt-session-history-open",onClick:r=>{r.stopPropagation(),e()},className:"shrink-0 rounded border border-line px-2 py-1 text-[11px] text-fg-dim hover:bg-elev hover:text-fg",children:"Open"}),o.jsx("button",{"data-testid":"prompt-session-history-resume",onClick:r=>{r.stopPropagation(),n()},className:"shrink-0 rounded border border-accent/40 px-2 py-1 text-[11px] text-accent hover:bg-accent/10",children:"Resume"})]})}function sA(i,e=80){return i.length<=e?i:`${i.slice(0,e-1)}…`}function oA({visible:i=!0}){const e=Ct(s=>s.tabs),n=Ct(s=>s.activeTabId),r=e.find(s=>s.id===n)??null;return o.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[r?e.map(s=>o.jsx("div",{className:"absolute inset-0",style:{visibility:s.id===n?"inherit":"hidden"},children:o.jsx(rA,{tabId:s.id,cwd:s.cwd})},`${s.id}-${s.generation}`)):o.jsx(j7,{}),o.jsx(C7,{}),i&&o.jsx(A9,{})]})}function N7(){return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no active session"}),o.jsxs("div",{children:["click ",o.jsx("span",{className:"text-fg-dim",children:"+ new session"})," in the sidebar to start one"]})]})})}function $7(){const i=Ir(e=>e.focusedPanelId==="terminal");return o.jsx(oA,{visible:i})}const P7=1;function R7(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:P7,panels:e,dockview:i}}function Fw(i,e){const n=i.views.filter(s=>e.has(s));if(n.length===0)return null;const r=i.activeView&&n.includes(i.activeView)?i.activeView:n[0];return{...i,views:n,activeView:r}}function aA(i,e){if(i.type==="leaf"){const r=Fw(i.data,e);return r?{...i,data:r}:null}const n=i.data.map(r=>aA(r,e)).filter(r=>r!==null);return n.length===0?null:{...i,data:n}}function I7(i,e){const n=Object.keys(i.panels??{}),r=new Set(n.filter(d=>e.has(d)));if(r.size===0)return null;const s=aA(i.grid.root,r);if(!s)return null;const a={};for(const d of r)a[d]=i.panels[d];const u=(i.floatingGroups??[]).map(d=>{const p=Fw(d.data,r);return p?{...d,data:p}:null}).filter(d=>d!==null),l=(i.popoutGroups??[]).map(d=>{const p=Fw(d.data,r);return p?{...d,data:p}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:s},panels:a,floatingGroups:u,popoutGroups:l,activeGroup:i.activeGroup}}function M7(i,e){if(!i||typeof i!="object")return null;const n=i;if(!Array.isArray(n.panels)||!n.dockview||typeof n.dockview!="object")return null;const r=n.dockview;if(!r.grid||!r.panels)return null;try{return I7(r,e)}catch(s){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",s),null}}const O7=500,L7=new Set(au.map(i=>i.id));function M2(i){const e=R7(i);e&&window.api.layout.save(e).catch(n=>{console.warn("[Workbench] layout save failed:",n)})}const lA=z.createContext(null);function z7(i){const e=z.useContext(lA);return e?o.jsx(o.Fragment,{children:F7(i.params.id,e)}):null}const B7={screen:z7},$x=au[0].id;function F7(i,e){return i==="terminal"?o.jsx($7,{}):o.jsx(UM,{panelId:i,children:o.jsx("div",{className:"h-full overflow-auto bg-bg",children:o.jsx(KT,{children:_9(i,e)})})})}function G7(i){const e=z.useRef(null),n=Ir(S=>S.focusedPanelId)??$x,r=Ir(S=>S.focusToken),s=Ir(S=>S.resetToken),a=At(S=>S.isRecording||S.externalRecording),u=z.useRef(null),[l,d]=z.useState(!1);z.useEffect(()=>{let S=!1;return window.api.layout.load().then(w=>{S||(w&&(u.current=M7(w,L7)),d(!0))}).catch(w=>{console.warn("[Workbench] layout load failed, using default:",w),S||d(!0)}),()=>{S=!0}},[]);const p=z.useCallback(S=>{const w=e.current;if(!w)return;const C=TR(S)??au[0],x=w.getPanel(C.id);if(x)x.api.setActive();else{const y=w.addPanel({id:C.id,component:C.component,title:C.title,params:{id:C.id},renderer:"always"});C.id==="terminal"&&y.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(Lb))})}},[]),m=z.useCallback(S=>{var x;e.current=S.api;const w=u.current;if(w)try{S.api.fromJSON(w);const y=(x=S.api.activePanel)==null?void 0:x.id;y&&Ir.getState().focusPanel(y)}catch(y){console.warn("[Workbench] fromJSON failed, falling back to default layout:",y),S.api.clear(),p(n)}else p(n);S.api.onDidActivePanelChange(y=>{y&&Ir.getState().focusPanel(y.id)}),S.api.onDidRemovePanel(y=>{if(y.id==="terminal"){Ir.getState().openPanel("terminal");return}S.api.totalPanels===0&&(Ir.getState().openPanel($x),p($x))});let C=null;S.api.onDidLayoutChange(()=>{C!==null&&window.clearTimeout(C),C=window.setTimeout(()=>M2(S.api.toJSON()),O7)})},[]);z.useEffect(()=>{p(n)},[r,i.searchMode,p]);const f=z.useRef(!0);z.useEffect(()=>{if(f.current){f.current=!1;return}const S=e.current;S&&(S.clear(),u.current=null,p($x),M2(S.toJSON()))},[s]),z.useEffect(()=>{const S=e.current;S&&(S.layout(S.width,S.height,!0),window.dispatchEvent(new CustomEvent(Lb)))},[a]);const b=z.useMemo(()=>({components:B7,onReady:m,className:"dockview-theme-sm workbench-root"}),[m]);return l?o.jsx(lA.Provider,{value:i,children:o.jsx(eT,{...b})}):null}function U7({onExit:i}){const e=Ct(n=>n.activeTabId);return o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsx("div",{className:"flex items-center justify-end px-3 py-1.5 border-b border-line shrink-0",children:o.jsx("button",{onClick:i,className:"text-[12px] text-fg-dim hover:text-fg px-2 py-1 rounded border border-line hover:bg-bg-hi/40",children:"Exit split view"})}),o.jsxs("div",{className:"flex h-full w-full flex-1 min-h-0",children:[o.jsx("div",{className:"relative w-1/3 min-w-0 border-r border-line",children:e?o.jsx(oA,{}):o.jsx(N7,{})}),o.jsx("div",{className:"relative w-2/3 min-w-0",children:o.jsx(RD,{})})]})]})}function Gw(){return At(e=>e.isRecording||e.externalRecording)?o.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:"fixed inset-x-0 top-0 z-[60] h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),o.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const Wm=5e3;function ea(i,e,n){var r,s;try{(s=(r=window.api)==null?void 0:r.logs)==null||s.write("voice-wizard",i,e,n)}catch{}}function H7({analyser:i}){const[e,n]=z.useState(0);return z.useEffect(()=>{if(!i){n(0);return}let r=0,s=!1;const a=new Uint8Array(new ArrayBuffer(i.fftSize)),u=()=>{if(s)return;i.getByteTimeDomainData(a);let l=0;for(let m=0;m<a.length;m++){const f=a[m]-128;l+=f*f}const d=Math.sqrt(l/a.length)/128,p=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));n(p),r=requestAnimationFrame(u)};return r=requestAnimationFrame(u),()=>{s=!0,cancelAnimationFrame(r)}},[i]),o.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function W7({open:i,onClose:e}){const n=At(re=>re.permissionState),r=At(re=>re.modelStatus),s=At(re=>re.loadingProgress),[a,u]=z.useState("welcome"),[l,d]=z.useState(null),[p,m]=z.useState(!1),[f,b]=z.useState(0),S=z.useRef(null),w=z.useRef(null),C=z.useRef(null),x=z.useRef(null),y=z.useRef(null),_=z.useRef(null),E=z.useRef(null),j=z.useRef(null),[D,$]=z.useState(!1),[I,P]=z.useState(Math.round(Wm/1e3)),[L,B]=z.useState(!1),[U,Z]=z.useState(!1),[X,W]=z.useState(null),[J,te]=z.useState(0),le=z.useCallback(()=>{var re;try{(re=y.current)==null||re.stop()}catch{}if(y.current=null,j.current){try{j.current.disconnect()}catch{}j.current=null}if(x.current){try{x.current.disconnect()}catch{}x.current=null}if(C.current){try{C.current.disconnect()}catch{}C.current=null}if(te(Pe=>Pe+1),w.current){const Pe=w.current;w.current=null;try{Pe.close()}catch{}}if(S.current){try{S.current.getTracks().forEach(Pe=>Pe.stop())}catch{}S.current=null}},[]),ue=z.useCallback(()=>{le(),_.current=null,E.current=null,$(!1),P(Math.round(Wm/1e3)),B(!1),Z(!1),W(null),d(null),m(!1)},[le]);z.useEffect(()=>{i?(ea("info","wizard.opened"),u("welcome")):ue()},[i,ue]),z.useEffect(()=>()=>le(),[le]);const V=z.useCallback(re=>{ea("info","wizard.step",{step:re}),d(null),u(re)},[]),ie=z.useCallback(re=>{if(ea("info","wizard.skipped",{step:a,mode:re}),le(),e(),re==="skip-and-record"){const Pe=At.getState();Pe.setWizardArmed(!1);const _e=Ct.getState().activeTabId;_e&&Pe.startRecording(_e)}else At.getState().setWizardArmed(!1)},[a,e,le]),K=z.useCallback(()=>{if(n==="denied"){V("permission");return}V("permission")},[n,V]);z.useEffect(()=>{i&&a==="permission"&&n==="granted"&&V("device")},[i,a,n,V]),z.useEffect(()=>{if(!i||a!=="device")return;let re=!1;return(async()=>{var Pe;try{if(!((Pe=navigator.mediaDevices)!=null&&Pe.enumerateDevices)){re||m(!0);return}const _e=await navigator.mediaDevices.enumerateDevices();if(re)return;const Qe=_e.filter(st=>st.kind==="audioinput");m(Qe.length===0)}catch(_e){if(re)return;ea("warn","wizard.error",{step:"device",error:_e instanceof Error?_e.message:String(_e)}),m(!0)}})(),()=>{re=!0}},[i,a,f]);const se=z.useCallback(async()=>{d(null),$(!0),P(Math.round(Wm/1e3));try{let re=null;try{const Gt=await window.api.voice.getDevicePref();re=(Gt==null?void 0:Gt.selectedDeviceId)??null}catch{}const Pe={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};re&&(Pe.deviceId={exact:re});const _e=await navigator.mediaDevices.getUserMedia({audio:Pe});S.current=_e;const Qe=new AudioContext;w.current=Qe;const st=Qe.createMediaStreamSource(_e),yt=Qe.createAnalyser();yt.fftSize=2048,yt.smoothingTimeConstant=.8,st.connect(yt),C.current=st,x.current=yt,te(Gt=>Gt+1);const qt=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",ut=new MediaRecorder(_e,qt?{mimeType:qt}:void 0);y.current=ut;const nt=[];ut.ondataavailable=Gt=>{Gt.data&&Gt.data.size>0&&nt.push(Gt.data)},ut.onstop=()=>{const Gt=ut.mimeType||"audio/webm";if(_.current=new Blob(nt,{type:Gt}),$(!1),x.current){try{x.current.disconnect()}catch{}x.current=null}if(C.current){try{C.current.disconnect()}catch{}C.current=null}if(te(di=>di+1),S.current){try{S.current.getTracks().forEach(di=>di.stop())}catch{}S.current=null}V("playback")},ut.onerror=Gt=>{var Ue;const di=((Ue=Gt.error)==null?void 0:Ue.message)??"recorder error";ea("error","wizard.error",{step:"record",error:di}),d(di),$(!1),Ve.error(`Mic wizard: ${di}`)},ut.start();const Le=Date.now(),ht=setInterval(()=>{const Gt=Date.now()-Le,di=Math.max(0,Math.ceil((Wm-Gt)/1e3));if(P(di),Gt>=Wm){clearInterval(ht);try{ut.stop()}catch{}}},250)}catch(re){const Pe=re instanceof Error?re.message:String(re);ea("error","wizard.error",{step:"record",error:Pe}),d(Pe),$(!1),le(),Ve.error(`Mic wizard: ${Pe}`)}},[V,le]),oe=z.useCallback(async()=>{d(null);const re=_.current;if(!re){d("No recording available");return}try{let Pe=w.current;(!Pe||Pe.state==="closed")&&(Pe=new AudioContext,w.current=Pe);let _e=E.current;if(!_e){const st=await re.arrayBuffer();_e=await Pe.decodeAudioData(st.slice(0)),E.current=_e}if(j.current){try{j.current.disconnect()}catch{}j.current=null}const Qe=Pe.createBufferSource();Qe.buffer=_e,Qe.connect(Pe.destination),j.current=Qe,B(!0),Qe.onended=()=>{B(!1);try{Qe.disconnect()}catch{}j.current===Qe&&(j.current=null)},Qe.start()}catch(Pe){const _e=Pe instanceof Error?Pe.message:String(Pe);ea("error","wizard.error",{step:"playback",error:_e}),d(_e),B(!1)}},[]);z.useEffect(()=>{i&&a==="playback"&&oe().catch(()=>{})},[i,a,oe]);const be=z.useCallback(async()=>{d(null),Z(!0),W(null);try{const re=E.current;if(!re)throw new Error("No decoded audio available");const Pe=re.getChannelData(0),_e=new Float32Array(Pe.length);_e.set(Pe);const Qe=await CN(_e);W(Qe)}catch(re){const Pe=re instanceof Error?re.message:String(re);ea("error","wizard.error",{step:"verify",error:Pe}),d(Pe)}finally{Z(!1)}},[]);z.useEffect(()=>{i&&a==="verify"&&r==="ready"&&X===null&&!U&&!l&&be()},[i,a,r,X,U,l,be]);const je=z.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),ea("info","wizard.complete")}catch(re){ea("error","wizard.error",{step:"done",error:re instanceof Error?re.message:String(re)})}At.getState().setWizardArmed(!1),le(),e()},[e,le]),Te=z.useCallback(()=>{ea("info","wizard.skipped",{step:a,mode:"modal-close"}),le(),At.getState().setWizardArmed(!1),e()},[a,le,e]),ve=z.useMemo(()=>{switch(a){case"welcome":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),o.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:K,"data-testid":"wizard-start",children:"Start"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>ie("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),o.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>ie("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return n==="denied"?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),o.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",o.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",o.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),o.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",n]}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>V("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return p?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),o.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{m(!1),b(re=>re+1)},"data-testid":"wizard-device-retry",children:"Try again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),o.jsx(XT,{}),o.jsxs("div",{className:"flex gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>V("record"),"data-testid":"wizard-device-continue",children:"Continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return o.jsxs("div",{className:"space-y-3",children:[o.jsxs("p",{className:"text-sm text-fg",children:["Say: ",o.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),o.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),D?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",I,"s"]}),o.jsx(H7,{analyser:x.current},J)]}):o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{se()},"data-testid":"wizard-record-start",children:"Start recording"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),o.jsx("p",{className:"text-xs text-fg-dim",children:L?"Playing back…":"Playback finished."}),o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>V("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{oe()},"data-testid":"wizard-playback-replay",children:"Replay"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{E.current=null,_.current=null,V("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return r==="loading"||r==="idle"?o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),o.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[o.jsx("span",{children:"Downloading"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`},"data-testid":"wizard-load-progress"})}),o.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:U?"Transcribing your sample…":X===null?"Ready to transcribe.":"We heard:"}),X!==null&&o.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:X||"(no text recognized)"}),o.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[o.jsx("button",{type:"button",disabled:U||X===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>V("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{E.current=null,_.current=null,W(null),V("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),o.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>ie("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return o.jsxs("div",{className:"space-y-3",children:[o.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),o.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),o.jsx("div",{className:"flex gap-2 pt-1",children:o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{je()},"data-testid":"wizard-done",children:"Done"})})]})}},[a,K,ie,n,p,D,I,J,L,U,X,r,s,l,V,se,oe,je]);return o.jsx($p,{open:i,onClose:Te,title:"Mic check",children:o.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[o.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",a]}),l?o.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:l}):null,ve]})})}const cA="sm.tour.completedAt",Oc=Xn((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:n=>{e().stepCount!==n&&i({stepCount:n})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:n,stepCount:r}=e();if(n>=r-1){e().complete();return}i({currentStep:n+1})},prev:()=>{const{currentStep:n}=e();n<=0||i({currentStep:n-1})},goTo:n=>{const{stepCount:r}=e();n<0||n>=r||i({currentStep:n})},complete:()=>{try{localStorage.setItem(cA,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function V7(){try{return!!localStorage.getItem(cA)}catch{return!1}}const O2={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function q7(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app",section:"session",run:()=>window.api.app.rebootApp()},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=At.getState(),n=Ct.getState().activeTabId;e.isRecording?e.stopRecording():n&&e.startRecording(n)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>At.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>At.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{Ve.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{Ve.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Oc.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ir.getState().resetLayout()},{id:"nav:overview",label:"Go to Overview",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:browser",label:"Go to Browser",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:keybindings",label:"Go to Keybindings",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:remote",label:"Go to Remote",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0},{id:"nav:repoviz",label:"Go to Repo Viz",section:"nav",emitOnly:!0},{id:"nav:search",label:"Go to Search",section:"nav",emitOnly:!0}]}function K7(i,e){if(!e)return 0;const n=i.toLowerCase(),r=e.toLowerCase();let s=0,a=-1,u=0;for(let l=0;l<n.length&&s<r.length;l++)n[l]===r[s]&&(u+=l-a,a=l,s++);return s!==r.length?null:u}function Y7(i,e){if(!e)return i.map(r=>({...r,score:0}));const n=[];for(const r of i){const s=K7(r.label,e);s!==null&&n.push({...r,score:s})}return n.sort((r,s)=>r.score-s.score),n}function X7({open:i,onClose:e,onCommand:n}){const[r,s]=z.useState(""),[a,u]=z.useState(0),l=z.useRef(null),d=z.useRef(null),p=z.useRef(null),m=z.useRef(null),f=z.useMemo(()=>q7(),[]),b=z.useMemo(()=>Y7(f,r),[f,r]);if(z.useEffect(()=>{if(i){const j=document.activeElement;m.current=j instanceof HTMLElement?j:null,s(""),u(0);const D=setTimeout(()=>{var $;return($=l.current)==null?void 0:$.focus()},0);return()=>{clearTimeout(D);const $=m.current;m.current=null,$&&requestAnimationFrame(()=>{try{$.focus()}catch{}})}}},[i]),z.useEffect(()=>{a>=b.length&&u(Math.max(0,b.length-1))},[b.length,a]),z.useEffect(()=>{if(!d.current)return;const j=d.current.querySelector(`[data-cmd-idx="${a}"]`);j&&j.scrollIntoView({block:"nearest"})},[a]),!i)return null;const S=async j=>{var D;if(e(),j.emitOnly){n(j);return}try{await((D=j.run)==null?void 0:D.call(j))}catch($){console.error("[command-palette] run failed",j.id,$);const I=$ instanceof Error?$.message:String($);Ve.error(`Command "${j.label}" failed: ${I}`)}n(j)},w=j=>{var D,$,I,P;if(j.key==="Escape"){j.preventDefault(),e();return}if(j.key==="ArrowDown"){j.preventDefault(),u(L=>Math.min(b.length-1,L+1));return}if(j.key==="ArrowUp"){j.preventDefault(),u(L=>Math.max(0,L-1));return}if(j.key==="Home"){j.preventDefault(),u(0);return}if(j.key==="End"){j.preventDefault(),u(Math.max(0,b.length-1));return}if(j.key==="PageDown"){j.preventDefault(),u(L=>Math.min(b.length-1,L+5));return}if(j.key==="PageUp"){j.preventDefault(),u(L=>Math.max(0,L-5));return}if(j.key==="Tab"){j.preventDefault();const L=document.activeElement;j.shiftKey?L===l.current?(D=p.current)==null||D.focus():($=l.current)==null||$.focus():L===l.current?(I=p.current)==null||I.focus():(P=l.current)==null||P.focus();return}if(j.key==="Enter"){j.preventDefault();const L=b[a];L&&S(L);return}},C=[],x=new Map;b.forEach((j,D)=>{let $=x.get(j.section);$===void 0&&($=C.length,x.set(j.section,$),C.push({section:j.section,items:[]})),C[$].items.push({cmd:j,absIdx:D})});const y=b[a],_=y?`cmdk-opt-${y.id}`:void 0,E=o.jsx("div",{className:"fixed inset-0 z-50 flex items-start justify-center bg-black/60 pt-[15vh]",onClick:j=>{j.target===j.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:w,children:o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[o.jsxs("div",{className:"border-b border-line flex items-center",children:[o.jsx("input",{ref:l,id:"cmdk-title",type:"text",value:r,onChange:j=>{s(j.target.value),u(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":_,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),o.jsx("button",{ref:p,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),o.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:b.length===0?o.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):C.map(j=>o.jsxs("div",{role:"group","aria-label":O2[j.section],className:"py-1",children:[o.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:O2[j.section]}),j.items.map(({cmd:D,absIdx:$})=>{const I=$===a;return o.jsxs("button",{id:`cmdk-opt-${D.id}`,type:"button",role:"option","aria-selected":I,"data-cmd-idx":$,"data-cmd-id":D.id,tabIndex:-1,onMouseEnter:()=>u($),onClick:()=>S(D),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${I?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[o.jsx("span",{className:"truncate flex-1",children:D.label}),D.hint&&o.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:D.hint})]},D.id)})]},j.section))}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[o.jsx("span",{children:"↑↓ navigate"}),o.jsx("span",{children:"↵ run"}),o.jsx("span",{children:"esc close"}),o.jsxs("span",{className:"ml-auto",children:[b.length," of ",f.length]})]})]})});return typeof document<"u"&&document.body?vu.createPortal(E,document.body):E}const J7={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function Uw(){const i=iu(n=>n.toasts),e=iu(n=>n.dismiss);return i.length===0?null:o.jsx("div",{"data-testid":"toast-host",className:"fixed bottom-3 right-3 z-[55] flex flex-col gap-1.5 pointer-events-none",children:i.map(n=>{const r=J7[n.kind];return o.jsxs("div",{"data-testid":"toast","data-kind":n.kind,role:n.kind==="error"?"alert":"status","aria-live":n.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${r.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[o.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${r.text}`,children:r.label}),o.jsx("span",{className:"flex-1 text-fg-dim break-words",children:n.message}),o.jsx("button",{type:"button",onClick:()=>e(n.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},n.id)})})}function Z7(){const i=Ct(s=>s.tabs),e=Ct(s=>s.activeTabId),n=i.find(s=>s.id===e)??null,r=At(s=>s.isRecording);return o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${r?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[o.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),n&&o.jsxs("span",{className:"truncate",children:["· ",n.cwd]})]}),o.jsx("div",{className:"flex-1 min-h-0 relative",children:n?o.jsx(rA,{tabId:n.id,cwd:n.cwd},`${n.id}-${n.generation}`):o.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),o.jsx(Uw,{})]})}const Qd=[{id:"welcome",title:"Welcome to Session Manager",body:"A 30-second tour so you know where everything lives. You can re-run this any time from the command palette.",position:"center"},{id:"tabs",title:"Session tabs",body:"Each tab is a separate Claude session with its own working directory. Click + new to open another, drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"Left navigation",body:"Switch between Terminal, Settings, Skills, MCP servers, History and more. Live dots show which sections are active right now.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"voice",title:"Push-to-talk dictation",body:"Hold the configured hotkey (F1 by default) to dictate into the terminal. You can also click the mic.",target:'[data-testid="mic-button"]',position:"right"},{id:"scheduler",title:"PRD scheduler",body:"Drop a Markdown plan in this project's session-manager-operations/scheduler/prds/ and the scheduler runs it as a token-budget-managed claude -p job.",target:'[data-testid="tour-scheduler"]',position:"right"},{id:"mainpane-actions",title:"Session actions",body:"Press ⌘K / Ctrl+K to open the command palette — restart this session, broadcast a prompt to multiple tabs, or attach a long-running watcher command whose stdout streams back as toasts.",position:"center"},{id:"statusbar",title:"Status bar",body:"Model, 5-hour usage, branch, last activity, and the active working directory. Click restart-app to reload the whole app.",target:'[data-testid="tour-statusbar"]',position:"top"},{id:"new-session",title:"Start a new session",body:"Pick any project directory to spin up another claude session. Tabs persist across reboots — they auto-resume on next launch.",target:'[data-testid="tour-new-session"]',position:"top"}],$c=360,eu=220,In=16;function Nc(i,e,n){return Math.max(e,Math.min(n,i))}function Q7(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const n=window.innerWidth,r=window.innerHeight;switch(e){case"top":return{position:"fixed",top:Nc(i.top-eu-In,In,r-eu-In),left:Nc(i.left+i.width/2-$c/2,In,n-$c-In)};case"bottom":return{position:"fixed",top:Nc(i.bottom+In,In,r-eu-In),left:Nc(i.left+i.width/2-$c/2,In,n-$c-In)};case"left":return{position:"fixed",top:Nc(i.top+i.height/2-eu/2,In,r-eu-In),left:Nc(i.left-$c-In,In,n-$c-In)};case"right":return{position:"fixed",top:Nc(i.top+i.height/2-eu/2,In,r-eu-In),left:Nc(i.right+In,In,n-$c-In)}}}function eq(){const i=Oc(C=>C.open),e=Oc(C=>C.currentStep),n=Oc(C=>C.next),r=Oc(C=>C.prev),s=Oc(C=>C.complete),a=Oc(C=>C.setStepCount);z.useEffect(()=>{a(Qd.length)},[a]);const[u,l]=z.useState(null),d=z.useRef(null),p=Qd[e]??Qd[0],m=e===0,f=e===Qd.length-1;if(z.useLayoutEffect(()=>{if(!i)return;let C=!1;const x=()=>{if(C)return;if(!p.target){l(null);return}const _=document.querySelector(p.target);if(!_){l(null);return}l(_.getBoundingClientRect())},y=requestAnimationFrame(x);return window.addEventListener("resize",x),()=>{C=!0,cancelAnimationFrame(y),window.removeEventListener("resize",x)}},[i,p.target,e]),z.useEffect(()=>{if(!i)return;const C=x=>{if(x.key==="Escape"){x.stopPropagation(),pt.info("tour","skipped",{step:p.id}),s();return}if(x.key==="ArrowRight"||x.key==="Enter"){x.preventDefault(),n();return}x.key==="ArrowLeft"&&(x.preventDefault(),r())};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[i,n,r,s,p.id]),z.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:p.id})},[i,e,p.id]),!i)return null;const b=Q7(u,p.position),S=(e+1)/Qd.length*100,w=o.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:"fixed inset-0 z-[200]",children:[u?o.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:u.top-6,left:u.left-6,width:u.width+12,height:u.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):o.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),o.jsxs("div",{ref:d,style:{...b,width:$c},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[o.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[o.jsxs("div",{children:[o.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",Qd.length]}),o.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:p.title})]}),o.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:p.id}),s()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),o.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.body}),o.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":Qd.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${S}%`}})}),o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:p.id}),s()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),o.jsxs("div",{className:"flex items-center gap-2",children:[!m&&o.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),o.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:f?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?vu.createPortal(w,document.body):w}const tq=3e4,iq=5e3,nq=Xn(()=>({teams:[],loaded:!1}));let L2=!1,z2=!1;async function dA(){try{const i=await Yw(window.api.teams.list(),iq,"teams.list");nq.setState({teams:i.teams,loaded:!0})}catch(i){if(!z2){z2=!0;const e=i instanceof Error?i.message:String(i);Ve.warn(`Teams list fetch failed: ${e}`)}}setTimeout(dA,tq)}function rq(){L2||(L2=!0,dA())}async function k_(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return Ct.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}function sq(i){const e=At(r=>r.ttsEnabled),n=At(r=>r.isRecording);z.useEffect(()=>{if(!i||!e)return;const r=a=>{const u=At.getState().lastBargeInAt;if(u!==null&&performance.now()-u<zN){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-u)});return}jN(a)};return window.api.transcripts.onEvent(i,a=>{if(a.kind!=="message")return;const u=a.data;if(typeof u!="object"||u===null)return;const l=u;if(l.role!=="assistant"||At.getState().isRecording)return;const d=l.content;if(typeof d=="string")r(d);else if(Array.isArray(d)){const p=d.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");p&&r(p)}})},[i,e]),z.useEffect(()=>{n&&(pE(),At.setState({lastBargeInAt:performance.now()}))},[n])}const uA="sm.density",oq="roomy",B2="density-compact";function aq(){try{const i=localStorage.getItem(uA);if(i==="compact"||i==="roomy")return i}catch{}return oq}function hA(i){typeof document>"u"||(i==="compact"?document.body.classList.add(B2):document.body.classList.remove(B2))}let Sp=aq();const Hw=new Set;hA(Sp);function lq(i){if(i!==Sp){Sp=i;try{localStorage.setItem(uA,i)}catch{}hA(i),Hw.forEach(e=>e(i))}}function cq(){const[i,e]=z.useState(Sp);z.useEffect(()=>{const r=s=>e(s);return Hw.add(r),Sp!==i&&e(Sp),()=>{Hw.delete(r)}},[]);const n=z.useCallback(r=>lq(r),[]);return{density:i,setDensity:n}}let F2=!1;function dq(){cq();const i=Ir(W=>W.focusedPanelId)??"overview",[e,n]=z.useState(null),[r,s]=z.useState(!1),[a,u]=z.useState("files"),[l,d]=z.useState(!1),[p,m]=z.useState(!1),[f,b]=z.useState(!1),[S,w]=z.useState(null),C=z.useCallback(W=>{Ir.getState().openPanel(W)},[]);z.useCallback(W=>{Di.getState().openFile(W),C("editor")},[C]),z.useEffect(()=>{const W=()=>C("editor");return window.addEventListener("sm:open-editor",W),()=>window.removeEventListener("sm:open-editor",W)},[C]),z.useEffect(()=>{const W=J=>C(J.detail);return window.addEventListener("sm:navigate",W),()=>window.removeEventListener("sm:navigate",W)},[C]);const x=Ct(W=>W.activeTabId),y=Ct(W=>W.tabs),_=y.find(W=>W.id===x)??null,E=z.useRef(x),j=z.useRef(new Set(y.map(W=>W.id)));z.useEffect(()=>{const W=E.current,J=j.current,te=new Set(y.map(ue=>ue.id));E.current=x,j.current=te,W!==null&&x!==null&&x!==W&&te.size===J.size&&J.has(x)&&te.has(W)&&Ir.getState().openPanel("terminal")},[x,y]),z.useEffect(()=>{if(!S)return;const W=window.setTimeout(()=>w(null),2500);return()=>window.clearTimeout(W)},[S]),z.useEffect(()=>_?window.api.watchers.onLine(J=>{if(J.tabId!==_.id)return;const te=J.line.replace(/\x1b\[[0-9;]*m/g,"");te.trim()&&w(te.length>100?`${te.slice(0,100)}…`:te)}):void 0,[_==null?void 0:_.id]);const D=At(W=>W.isRecording),$=At(W=>W.wizardOpen),I=At(W=>W.closeWizard);sq(x);const P=z.useCallback(()=>{const{activeTabId:W,restartTab:J}=Ct.getState();W&&J(W)},[]);z.useCallback(()=>{window.api.app.rebootApp()},[]);const L=z.useCallback(()=>{d(W=>(W||Ir.getState().openPanel("terminal"),!W))},[]),B=z.useCallback(()=>{m(W=>(W||Ir.getState().openPanel("terminal"),!W))},[]),U=z.useRef(x);U.current=x;const Z=z.useRef("hold"),X=z.useCallback(()=>{Ir.getState().openPanel("terminal"),k_().catch(W=>{console.error("[App] new session failed:",W),Ve.error("Could not start new session. Is the claude CLI on PATH?")})},[]);return z.useEffect(()=>{var le;if(!Fb()){F2||(pt.warn("voice","mic.gate.unsupported"),F2=!0);return}At.getState().initModel();let W=null,J=!1;const te=()=>{if(!W)return;const ue=W.state;At.getState().setPermissionState(ue)};return typeof navigator<"u"&&((le=navigator.permissions)!=null&&le.query)&&navigator.permissions.query({name:"microphone"}).then(ue=>{J||(W=ue,At.getState().setPermissionState(ue.state),ue.addEventListener("change",te))}).catch(ue=>{pt.warn("voice","permission query unsupported",{error:ue==null?void 0:ue.message})}),()=>{J=!0,W&&W.removeEventListener("change",te)}},[]),z.useEffect(()=>{var be;const W=W2[0],J=je=>{if(!je||Ct.getState().tabs.length>0)return;const Te=crypto.randomUUID(),ve=q2(W,{sessionId:Te,cwd:je});Ct.setState(re=>({tabs:[...re.tabs,{id:Te,sessionId:Te,label:je.split("/").filter(Boolean).pop()||je,cwd:je,pid:null,status:"spawning",exitCode:null,startupCommand:ve,presetId:W.id,generation:0}],activeTabId:Te}))},te=je=>{if(!je||Ct.getState().tabs.length>0)return;const Te=crypto.randomUUID();Ct.setState(ve=>({tabs:[...ve.tabs,{id:Te,sessionId:Te,label:je.split("/").filter(Boolean).pop()||je,cwd:je,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:W.id,generation:0}],activeTabId:Te}))};window.api.app.launchMode().then(({simple:je,cwd:Te})=>{if(je){n(!0),J(Te);return}n(!1),j_().then(()=>{Ct.getState().tabs.length>0||p1(W).then(ve=>te(ve||"")).catch(ve=>{console.warn("[App] failed to create initial tab:",ve),Ve.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),j_().then(()=>{Ct.getState().tabs.length>0||p1(W).then(je=>te(je||"")).catch(()=>{})})});const le=window.api.app.onNewSession(()=>{k_().catch(je=>{console.error("[App] new-session from menu failed:",je),Ve.error("Could not start new session. Is the claude CLI on PATH?")})}),ue=window.api.app.onRebootSession(()=>{const{activeTabId:je}=Ct.getState();je&&Ct.getState().restartTab(je)});tg.getState().init(),qN(),rq(),HN(),window.api.app.claudeBinStatus().then(je=>{je.foundOnDisk||Ve.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(je=>{je.ok||Ve.error(`Home-directory self-check failed: ${je.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const V=T3();vz([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]},{uri:"https://json.schemastore.org/claude-code-keybindings.json",fileMatch:["**/keybindings.json"]}]).catch(je=>console.warn("[monaco] schema install failed:",je)),window.api.voice.getHotkeyConfig().then(je=>{Z.current=je.mode}).catch(je=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(je)}));const ie=window.api.voice.onHotkeyConfigChanged(je=>{Z.current=je.mode}),K=window.api.voice.onHotkey(({phase:je,source:Te})=>{At.getState().armHotkey({phase:je,source:Te,mode:Z.current,tabId:U.current})}),se=()=>At.getState().destroyHotkey();window.addEventListener("beforeunload",se);const oe=async()=>{var je;window.dispatchEvent(new Event("mic-device-change"));try{if(!((je=navigator.mediaDevices)!=null&&je.enumerateDevices))return;const ve=(await navigator.mediaDevices.enumerateDevices()).filter(Qe=>Qe.kind==="audioinput"),re=At.getState();if(!re.isRecording)return;let Pe=null;try{Pe=await window.api.voice.getDevicePref()}catch{}if(!Pe||!Pe.selectedDeviceId||ve.some(Qe=>Qe.deviceId===Pe.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:Pe.selectedDeviceId.slice(0,8)}),re.stopRecording(),At.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(Te){pt.warn("voice","devicechange handler failed",{error:Te instanceof Error?Te.message:String(Te)})}};return typeof navigator<"u"&&((be=navigator.mediaDevices)!=null&&be.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",oe),()=>{var je;V(),le(),ue(),ie(),K(),window.removeEventListener("beforeunload",se),typeof navigator<"u"&&((je=navigator.mediaDevices)!=null&&je.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",oe)}},[]),z.useEffect(()=>{try{window.api.voice.setRecording(D)}catch{}},[D]),z.useEffect(()=>{const W=te=>{var se,oe,be;const le=te.target,ue=((se=le==null?void 0:le.tagName)==null?void 0:se.toLowerCase())??"",V=((oe=le==null?void 0:le.classList)==null?void 0:oe.contains("xterm-helper-textarea"))??!1,ie=(be=le==null?void 0:le.getAttribute)==null?void 0:be.call(le,"aria-label");return!!((ue==="input"||ue==="textarea")&&!V&&!(ie==="Search files"||ie==="Search query")||le!=null&&le.closest(".monaco-editor"))},J=te=>{if((te.metaKey||te.ctrlKey)&&(te.key==="k"||te.key==="K")){if(W(te))return;te.preventDefault(),te.stopPropagation(),s(le=>!le)}else if((te.metaKey||te.ctrlKey)&&!te.shiftKey&&(te.key==="p"||te.key==="P")){if(W(te))return;te.preventDefault(),te.stopPropagation(),u("files"),C("search")}else if((te.metaKey||te.ctrlKey)&&te.shiftKey&&(te.key==="f"||te.key==="F")){if(W(te))return;te.preventDefault(),te.stopPropagation(),u("content"),C("search")}else if(te.key==="Escape"&&r)s(!1);else if(te.key==="Escape"&&f)b(!1);else if(te.altKey&&!te.ctrlKey&&!te.metaKey&&!te.shiftKey){const le=/^Digit([1-5])$/.exec(te.code);if(!le||W(te))return;const ue=parseInt(le[1],10)-1,{tabs:V,setActive:ie}=Ct.getState(),K=V[ue];if(!K)return;te.preventDefault(),te.stopPropagation(),ie(K.id)}};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[r,f]),z.useEffect(()=>{let W=!1,J=null;return(async()=>{var te,le;try{const ue=await((le=(te=window.api.voice).getTurnDetector)==null?void 0:le.call(te));if(W||!ue||(At.setState({turnDetectorMode:ue.mode,turnDetectorState:"disabled"}),ue.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:ue.mode}),W))return;J=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),J.addEventListener("message",V=>{const ie=V.data;if(!(!ie||typeof ie!="object")&&ie.type==="status"){const K=ie.status;K==="ready"?At.getState().setTurnDetectorRuntimeState("ok"):(K==="load_failed"||K==="runtime_error")&&At.getState().setTurnDetectorRuntimeState(K)}}),J.addEventListener("error",V=>{pt.error("voice-turn","turn-detector worker error",{message:V.message}),At.getState().setTurnDetectorRuntimeState("runtime_error")}),J.postMessage({type:"load"})}catch(ue){pt.warn("voice-turn","mount.read-settings failed",{error:ue instanceof Error?ue.message:String(ue)})}})(),()=>{if(W=!0,J){try{J.terminate()}catch{}J=null}}},[]),z.useEffect(()=>{let W=!1;return(async()=>{var J,te;try{const le=await((te=(J=window.api.app).isE2E)==null?void 0:te.call(J));if(W||le||V7()||At.getState().wizardOpen)return;Oc.getState().start()}catch{}})(),()=>{W=!0}},[]),z.useEffect(()=>{let W=!1;return(async()=>{var J,te;try{const le=await((te=(J=window.api.app).isE2E)==null?void 0:te.call(J));if(W)return;if(le){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const ue=await window.api.voice.getWizardState();if(W)return;ue.completedSchema!==ue.currentSchema&&(At.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:ue.completedSchema,currentSchema:ue.currentSchema}))}catch(le){pt.warn("voice-wizard","auto-arm failed",{error:le instanceof Error?le.message:String(le)})}})(),()=>{W=!0}},[]),e===!0?o.jsx(Z7,{}):f?o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${D?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsx(U7,{onExit:()=>b(!1)}),o.jsx(Uw,{})]}):o.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${D?"pt-7":""}`,children:[o.jsx(Gw,{}),o.jsx(aN,{splitViewActive:f,onToggleSplitView:()=>b(!0)}),o.jsxs("div",{className:"flex-1 flex min-h-0",children:[o.jsx(i$,{active:i,onNavigate:C,onNewSession:X}),o.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&l&&o.jsx(p$,{onClose:()=>d(!1),onSent:W=>{d(!1),w(`Sent to ${W} tab${W===1?"":"s"}`)}}),i==="terminal"&&_&&p&&o.jsx("div",{className:"absolute top-12 right-4 z-30",children:o.jsx(f$,{tabId:_.id,cwd:_.cwd,onClose:()=>m(!1)})}),o.jsx("div",{className:"flex-1 min-h-0 relative",children:o.jsx(G7,{onNavigate:C,onNewSession:X,onOpenVoice:()=>C("voice"),onOpenScheduler:()=>C("scheduler"),searchMode:a})}),S&&o.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:S})]})]}),o.jsx(c$,{onNavigate:C}),o.jsx(W7,{open:$,onClose:I}),o.jsx(eq,{}),o.jsx(Uw,{}),o.jsx(X7,{open:r,onClose:()=>s(!1),onCommand:W=>{if(s(!1),W.id.startsWith("nav:")){C(W.id.slice(4));return}const J=Ct.getState().tabs.find(te=>te.id===Ct.getState().activeTabId)??null;switch(W.id){case"new-tab-pick":k_().catch(te=>{console.error("[App] new tab (pick) failed:",te),Ve.error("Could not start new session. Is the claude CLI on PATH?")});return;case"new-tab-here":{if(!J)return;Ct.getState().addTab({cwd:J.cwd,startupCommand:null,dormant:!0}),Ir.getState().openPanel("terminal");return}case"close-tab":J&&Ct.getState().closeTab(J.id);return;case"restart-session":P();return;case"broadcast":L();return;case"watchers":B();return;case"copy-cwd":J&&window.api.clipboard.writeText(J.cwd).catch(()=>Ve.error("Copy failed"));return;case"copy-transcript":J&&window.api.transcripts.pathFor(J.cwd,J.sessionId).then(te=>window.api.clipboard.writeText(te)).catch(()=>Ve.error("Copy failed"));return;case"open-transcript":J&&window.api.transcripts.pathFor(J.cwd,J.sessionId).then(te=>window.api.shell.open({as:"openPath",path:te})).catch(()=>Ve.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const uq=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","teams","plugins","clipboard","memory"];function hq(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,n=[];for(const r of uq){const s=e[r];s==null?n.push({kind:"namespace-missing",name:r}):typeof s!="object"&&n.push({kind:"namespace-not-object",name:r,actualType:typeof s})}return n}function G2(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function pq(){const i=hq(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",G2(e));return setTimeout(()=>{Dg(async()=>{const{toast:e}=await Promise.resolve().then(()=>J2);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const n=i.length===1?G2(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(n)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");pq();DA.createRoot(document.getElementById("root")).render(o.jsx(dq,{}));export{Rt as R,uR as a,Ww as b,zb as g,o as j,z as r};
|