claude-code-session-manager 0.45.0 → 0.45.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-Pv4sVeQ8.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-CFlF9v--.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
2
2
  var AA=Object.defineProperty;var $A=(n,e,i)=>e in n?AA(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var qn=(n,e,i)=>$A(n,typeof e!="symbol"?e+"":e,i);import{_ as qg}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 d of a.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(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=i(s);fetch(s.href,a)}})();function cy(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Gy={exports:{}},km={},Uy={exports:{}},xn={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -40,7 +40,7 @@ var AA=Object.defineProperty;var $A=(n,e,i)=>e in n?AA(n,e,{enumerable:!0,config
40
40
  Error generating stack: `+X.message+`
41
41
  `+X.stack}return{value:h,source:v,stack:G,digest:null}}function Eh(h,v,T){return{value:h,source:null,stack:T??null,digest:v??null}}function Th(h,v){try{console.error(v.value)}catch(T){setTimeout(function(){throw T})}}var Mv=typeof WeakMap=="function"?WeakMap:Map;function Wf(h,v,T){T=mo(-1,T),T.tag=3,T.payload={element:null};var I=v.value;return T.callback=function(){Hd||(Hd=!0,Kh=I),Th(h,v)},T}function Vf(h,v,T){T=mo(-1,T),T.tag=3;var I=h.type.getDerivedStateFromError;if(typeof I=="function"){var G=v.value;T.payload=function(){return I(G)},T.callback=function(){Th(h,v)}}var X=h.stateNode;return X!==null&&typeof X.componentDidCatch=="function"&&(T.callback=function(){Th(h,v),typeof I!="function"&&(Yo===null?Yo=new Set([this]):Yo.add(this));var he=v.stack;this.componentDidCatch(v.value,{componentStack:he!==null?he:""})}),T}function qf(h,v,T){var I=h.pingCache;if(I===null){I=h.pingCache=new Mv;var G=new Set;I.set(v,G)}else G=I.get(v),G===void 0&&(G=new Set,I.set(v,G));G.has(T)||(G.add(T),h=Kv.bind(null,h,v,T),v.then(h,h))}function Ov(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 pr(h,v,T,I,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=mo(-1,1),v.tag=2,Wo(T,v,1))),T.lanes|=1),h):(h.flags|=65536,h.lanes=G,h)}var Lv=j.ReactCurrentOwner,$r=!1;function Ji(h,v,T,I){v.child=h===null?oh(v,null,T,I):ml(v,h.child,T,I)}function Kf(h,v,T,I,G){T=T.render;var X=v.ref;return gl(v,G),I=yh(h,v,T,I,X,G),T=_h(),h!==null&&!$r?(v.updateQueue=h.updateQueue,v.flags&=-2053,h.lanes&=~G,vo(h,v,G)):(ti&&T&&_i(v),v.flags|=1,Ji(h,v,I,G),v.child)}function yc(h,v,T,I,G){if(h===null){var X=T.type;return typeof X=="function"&&!tp(X)&&X.defaultProps===void 0&&T.compare===null&&T.defaultProps===void 0?(v.tag=15,v.type=X,Yf(h,v,X,I,G)):(h=Yd(T.type,null,I,v,v.mode,G),h.ref=v.ref,h.return=v,v.child=h)}if(X=h.child,(h.lanes&G)===0){var he=X.memoizedProps;if(T=T.compare,T=T!==null?T:ac,T(he,I)&&h.ref===v.ref)return vo(h,v,G)}return v.flags|=1,h=Zo(X,I),h.ref=v.ref,h.return=v,v.child=h}function Yf(h,v,T,I,G){if(h!==null){var X=h.memoizedProps;if(ac(X,I)&&h.ref===v.ref)if($r=!1,v.pendingProps=I=X,(h.lanes&G)!==0)(h.flags&131072)!==0&&($r=!0);else return v.lanes=h.lanes,vo(h,v,G)}return jh(h,v,T,I,G)}function Xf(h,v,T){var I=v.pendingProps,G=I.children,X=h!==null?h.memoizedState:null;if(I.mode==="hidden")if((v.mode&1)===0)v.memoizedState={baseLanes:0,cachePool:null,transitions:null},Fn(_l,Ur),Ur|=T;else{if((T&1073741824)===0)return h=X!==null?X.baseLanes|T:T,v.lanes=v.childLanes=1073741824,v.memoizedState={baseLanes:h,cachePool:null,transitions:null},v.updateQueue=null,Fn(_l,Ur),Ur|=h,null;v.memoizedState={baseLanes:0,cachePool:null,transitions:null},I=X!==null?X.baseLanes:T,Fn(_l,Ur),Ur|=I}else X!==null?(I=X.baseLanes|T,v.memoizedState=null):I=T,Fn(_l,Ur),Ur|=I;return Ji(h,v,G,T),v.child}function Jf(h,v){var T=v.ref;(h===null&&T!==null||h!==null&&h.ref!==T)&&(v.flags|=512,v.flags|=2097152)}function jh(h,v,T,I,G){var X=Tr(T)?ya:ur.current;return X=hr(v,X),gl(v,G),T=yh(h,v,T,I,X,G),I=_h(),h!==null&&!$r?(v.updateQueue=h.updateQueue,v.flags&=-2053,h.lanes&=~G,vo(h,v,G)):(ti&&I&&_i(v),v.flags|=1,Ji(h,v,T,G),v.child)}function Zf(h,v,T,I,G){if(Tr(T)){var X=!0;Sd(v)}else X=!1;if(gl(v,G),v.stateNode===null)Ld(h,v),Uf(v,T,I),Ch(v,T,I,G),I=!0;else if(h===null){var he=v.stateNode,ke=v.memoizedProps;he.props=ke;var Ne=he.context,He=T.contextType;typeof He=="object"&&He!==null?He=ns(He):(He=Tr(T)?ya:ur.current,He=hr(v,He));var lt=T.getDerivedStateFromProps,ct=typeof lt=="function"||typeof he.getSnapshotBeforeUpdate=="function";ct||typeof he.UNSAFE_componentWillReceiveProps!="function"&&typeof he.componentWillReceiveProps!="function"||(ke!==I||Ne!==He)&&Hf(v,he,I,He),Ys=!1;var at=v.memoizedState;he.state=at,Ad(v,I,he,G),Ne=v.memoizedState,ke!==I||at!==Ne||Er.current||Ys?(typeof lt=="function"&&(Js(v,T,lt,I),Ne=v.memoizedState),(ke=Ys||Da(v,T,ke,I,at,Ne,He))?(ct||typeof he.UNSAFE_componentWillMount!="function"&&typeof he.componentWillMount!="function"||(typeof he.componentWillMount=="function"&&he.componentWillMount(),typeof he.UNSAFE_componentWillMount=="function"&&he.UNSAFE_componentWillMount()),typeof he.componentDidMount=="function"&&(v.flags|=4194308)):(typeof he.componentDidMount=="function"&&(v.flags|=4194308),v.memoizedProps=I,v.memoizedState=Ne),he.props=I,he.state=Ne,he.context=He,I=ke):(typeof he.componentDidMount=="function"&&(v.flags|=4194308),I=!1)}else{he=v.stateNode,uh(h,v),ke=v.memoizedProps,He=v.type===v.elementType?ke:Si(v.type,ke),he.props=He,ct=v.pendingProps,at=he.context,Ne=T.contextType,typeof Ne=="object"&&Ne!==null?Ne=ns(Ne):(Ne=Tr(T)?ya:ur.current,Ne=hr(v,Ne));var Tt=T.getDerivedStateFromProps;(lt=typeof Tt=="function"||typeof he.getSnapshotBeforeUpdate=="function")||typeof he.UNSAFE_componentWillReceiveProps!="function"&&typeof he.componentWillReceiveProps!="function"||(ke!==ct||at!==Ne)&&Hf(v,he,I,Ne),Ys=!1,at=v.memoizedState,he.state=at,Ad(v,I,he,G);var Mt=v.memoizedState;ke!==ct||at!==Mt||Er.current||Ys?(typeof Tt=="function"&&(Js(v,T,Tt,I),Mt=v.memoizedState),(He=Ys||Da(v,T,He,I,at,Mt,Ne)||!1)?(lt||typeof he.UNSAFE_componentWillUpdate!="function"&&typeof he.componentWillUpdate!="function"||(typeof he.componentWillUpdate=="function"&&he.componentWillUpdate(I,Mt,Ne),typeof he.UNSAFE_componentWillUpdate=="function"&&he.UNSAFE_componentWillUpdate(I,Mt,Ne)),typeof he.componentDidUpdate=="function"&&(v.flags|=4),typeof he.getSnapshotBeforeUpdate=="function"&&(v.flags|=1024)):(typeof he.componentDidUpdate!="function"||ke===h.memoizedProps&&at===h.memoizedState||(v.flags|=4),typeof he.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&at===h.memoizedState||(v.flags|=1024),v.memoizedProps=I,v.memoizedState=Mt),he.props=I,he.state=Mt,he.context=Ne,I=He):(typeof he.componentDidUpdate!="function"||ke===h.memoizedProps&&at===h.memoizedState||(v.flags|=4),typeof he.getSnapshotBeforeUpdate!="function"||ke===h.memoizedProps&&at===h.memoizedState||(v.flags|=1024),I=!1)}return Dh(h,v,T,I,X,G)}function Dh(h,v,T,I,G,X){Jf(h,v);var he=(v.flags&128)!==0;if(!I&&!he)return G&&vf(v,T,!1),vo(h,v,X);I=v.stateNode,Lv.current=v;var ke=he&&typeof T.getDerivedStateFromError!="function"?null:I.render();return v.flags|=1,h!==null&&he?(v.child=ml(v,h.child,null,X),v.child=ml(v,null,ke,X)):Ji(h,v,ke,X),v.memoizedState=I.state,G&&vf(v,T,!0),v.child}function Nh(h){var v=h.stateNode;v.pendingContext?mf(h,v.pendingContext,v.pendingContext!==v.context):v.context&&mf(h,v.context,!1),hh(h,v.containerInfo)}function Qf(h,v,T,I,G){return wa(),rh(G),v.flags|=256,Ji(h,v,T,I),v.child}var Ah={dehydrated:null,treeContext:null,retryLane:0};function $h(h){return{baseLanes:h,cachePool:null,transitions:null}}function em(h,v,T){var I=v.pendingProps,G=ii.current,X=!1,he=(v.flags&128)!==0,ke;if((ke=he)||(ke=h!==null&&h.memoizedState===null?!1:(G&2)!==0),ke?(X=!0,v.flags&=-129):(h===null||h.memoizedState!==null)&&(G|=1),Fn(ii,G&1),h===null)return nh(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):(he=I.children,h=I.fallback,X?(I=v.mode,X=v.child,he={mode:"hidden",children:he},(I&1)===0&&X!==null?(X.childLanes=0,X.pendingProps=he):X=Xd(he,I,0,null),h=kl(h,I,T,null),X.return=v,h.return=v,X.sibling=h,v.child=X,v.child.memoizedState=$h(T),v.memoizedState=Ah,h):_c(v,he));if(G=h.memoizedState,G!==null&&(ke=G.dehydrated,ke!==null))return zv(h,v,he,I,ke,G,T);if(X){X=I.fallback,he=v.mode,G=h.child,ke=G.sibling;var Ne={mode:"hidden",children:I.children};return(he&1)===0&&v.child!==G?(I=v.child,I.childLanes=0,I.pendingProps=Ne,v.deletions=null):(I=Zo(G,Ne),I.subtreeFlags=G.subtreeFlags&14680064),ke!==null?X=Zo(ke,X):(X=kl(X,he,T,null),X.flags|=2),X.return=v,I.return=v,I.sibling=X,v.child=I,I=X,X=v.child,he=h.child.memoizedState,he=he===null?$h(T):{baseLanes:he.baseLanes|T,cachePool:null,transitions:he.transitions},X.memoizedState=he,X.childLanes=h.childLanes&~T,v.memoizedState=Ah,I}return X=h.child,h=X.sibling,I=Zo(X,{mode:"visible",children:I.children}),(v.mode&1)===0&&(I.lanes=T),I.return=v,I.sibling=null,h!==null&&(T=v.deletions,T===null?(v.deletions=[h],v.flags|=16):T.push(h)),v.child=I,v.memoizedState=null,I}function _c(h,v){return v=Xd({mode:"visible",children:v},h.mode,0,null),v.return=h,h.child=v}function Od(h,v,T,I){return I!==null&&rh(I),ml(v,h.child,null,T),h=_c(v,v.pendingProps.children),h.flags|=2,v.memoizedState=null,h}function zv(h,v,T,I,G,X,he){if(T)return v.flags&256?(v.flags&=-257,I=Eh(Error(i(422))),Od(h,v,he,I)):v.memoizedState!==null?(v.child=h.child,v.flags|=128,null):(X=I.fallback,G=v.mode,I=Xd({mode:"visible",children:I.children},G,0,null),X=kl(X,G,he,null),X.flags|=2,I.return=v,X.return=v,I.sibling=X,v.child=I,(v.mode&1)!==0&&ml(v,h.child,null,he),v.child.memoizedState=$h(he),v.memoizedState=Ah,X);if((v.mode&1)===0)return Od(h,v,he,null);if(G.data==="$!"){if(I=G.nextSibling&&G.nextSibling.dataset,I)var ke=I.dgst;return I=ke,X=Error(i(419)),I=Eh(X,I,void 0),Od(h,v,he,I)}if(ke=(he&h.childLanes)!==0,$r||ke){if(I=ki,I!==null){switch(he&-he){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&(I.suspendedLanes|he))!==0?0:G,G!==0&&G!==X.retryLane&&(X.retryLane=G,fo(h,G),Ts(I,h,G,-1))}return ep(),I=Eh(Error(i(421))),Od(h,v,he,I)}return G.data==="$?"?(v.flags|=128,v.child=h.child,v=Xv.bind(null,h),G._reactRetry=v,null):(h=X.treeContext,Gr=Fo(G.nextSibling),Nr=v,ti=!0,Ar=null,h!==null&&(es[Ss++]=jr,es[Ss++]=Dr,es[Ss++]=ts,jr=h.id,Dr=h.overflow,ts=v),v=_c(v,I.children),v.flags|=4096,v)}function tm(h,v,T){h.lanes|=v;var I=h.alternate;I!==null&&(I.lanes|=v),_f(h.return,v,T)}function Ph(h,v,T,I,G){var X=h.memoizedState;X===null?h.memoizedState={isBackwards:v,rendering:null,renderingStartTime:0,last:I,tail:T,tailMode:G}:(X.isBackwards=v,X.rendering=null,X.renderingStartTime=0,X.last=I,X.tail=T,X.tailMode=G)}function Rh(h,v,T){var I=v.pendingProps,G=I.revealOrder,X=I.tail;if(Ji(h,v,I.children,T),I=ii.current,(I&2)!==0)I=I&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&&tm(h,T,v);else if(h.tag===19)tm(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}I&=1}if(Fn(ii,I),(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&&$d(h)===null&&(G=T),T=T.sibling;T=G,T===null?(G=v.child,v.child=null):(G=T.sibling,T.sibling=null),Ph(v,!1,G,T,X);break;case"backwards":for(T=null,G=v.child,v.child=null;G!==null;){if(h=G.alternate,h!==null&&$d(h)===null){v.child=G;break}h=G.sibling,G.sibling=T,T=G,G=h}Ph(v,!0,T,null,X);break;case"together":Ph(v,!1,null,null,void 0);break;default:v.memoizedState=null}return v.child}function Ld(h,v){(v.mode&1)===0&&h!==null&&(h.alternate=null,v.alternate=null,v.flags|=2)}function vo(h,v,T){if(h!==null&&(v.dependencies=h.dependencies),Na|=v.lanes,(T&v.childLanes)===0)return null;if(h!==null&&v.child!==h.child)throw Error(i(153));if(v.child!==null){for(h=v.child,T=Zo(h,h.pendingProps),v.child=T,T.return=v;h.sibling!==null;)h=h.sibling,T=T.sibling=Zo(h,h.pendingProps),T.return=v;T.sibling=null}return v.child}function Iy(h,v,T){switch(v.tag){case 3:Nh(v),wa();break;case 5:wf(v);break;case 1:Tr(v.type)&&Sd(v);break;case 4:hh(v,v.stateNode.containerInfo);break;case 10:var I=v.type._context,G=v.memoizedProps.value;Fn(Sa,I._currentValue),I._currentValue=G;break;case 13:if(I=v.memoizedState,I!==null)return I.dehydrated!==null?(Fn(ii,ii.current&1),v.flags|=128,null):(T&v.child.childLanes)!==0?em(h,v,T):(Fn(ii,ii.current&1),h=vo(h,v,T),h!==null?h.sibling:null);Fn(ii,ii.current&1);break;case 19:if(I=(T&v.childLanes)!==0,(h.flags&128)!==0){if(I)return Rh(h,v,T);v.flags|=128}if(G=v.memoizedState,G!==null&&(G.rendering=null,G.tail=null,G.lastEffect=null),Fn(ii,ii.current),I)break;return null;case 22:case 23:return v.lanes=0,Xf(h,v,T)}return vo(h,v,T)}var Ih,Mh,nm,im;Ih=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}},Mh=function(){},nm=function(h,v,T,I){var G=h.memoizedProps;if(G!==I){h=v.stateNode,Ca(Xs.current);var X=null;switch(T){case"input":G=Xt(h,G),I=Xt(h,I),X=[];break;case"select":G=re({},G,{value:void 0}),I=re({},I,{value:void 0}),X=[];break;case"textarea":G=Ct(h,G),I=Ct(h,I),X=[];break;default:typeof G.onClick!="function"&&typeof I.onClick=="function"&&(h.onclick=yd)}Is(T,I);var he;T=null;for(He in G)if(!I.hasOwnProperty(He)&&G.hasOwnProperty(He)&&G[He]!=null)if(He==="style"){var ke=G[He];for(he in ke)ke.hasOwnProperty(he)&&(T||(T={}),T[he]="")}else He!=="dangerouslySetInnerHTML"&&He!=="children"&&He!=="suppressContentEditableWarning"&&He!=="suppressHydrationWarning"&&He!=="autoFocus"&&(s.hasOwnProperty(He)?X||(X=[]):(X=X||[]).push(He,null));for(He in I){var Ne=I[He];if(ke=G!=null?G[He]:void 0,I.hasOwnProperty(He)&&Ne!==ke&&(Ne!=null||ke!=null))if(He==="style")if(ke){for(he in ke)!ke.hasOwnProperty(he)||Ne&&Ne.hasOwnProperty(he)||(T||(T={}),T[he]="");for(he in Ne)Ne.hasOwnProperty(he)&&ke[he]!==Ne[he]&&(T||(T={}),T[he]=Ne[he])}else T||(X||(X=[]),X.push(He,T)),T=Ne;else He==="dangerouslySetInnerHTML"?(Ne=Ne?Ne.__html:void 0,ke=ke?ke.__html:void 0,Ne!=null&&ke!==Ne&&(X=X||[]).push(He,Ne)):He==="children"?typeof Ne!="string"&&typeof Ne!="number"||(X=X||[]).push(He,""+Ne):He!=="suppressContentEditableWarning"&&He!=="suppressHydrationWarning"&&(s.hasOwnProperty(He)?(Ne!=null&&He==="onScroll"&&Wn("scroll",h),X||ke===Ne||(X=[])):(X=X||[]).push(He,Ne))}T&&(X=X||[]).push("style",T);var He=X;(v.updateQueue=He)&&(v.flags|=4)}},im=function(h,v,T,I){T!==I&&(v.flags|=4)};function zd(h,v){if(!ti)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 I=null;T!==null;)T.alternate!==null&&(I=T),T=T.sibling;I===null?v||h.tail===null?h.tail=null:h.tail.sibling=null:I.sibling=null}}function Zi(h){var v=h.alternate!==null&&h.alternate.child===h.child,T=0,I=0;if(v)for(var G=h.child;G!==null;)T|=G.lanes|G.childLanes,I|=G.subtreeFlags&14680064,I|=G.flags&14680064,G.return=h,G=G.sibling;else for(G=h.child;G!==null;)T|=G.lanes|G.childLanes,I|=G.subtreeFlags,I|=G.flags,G.return=h,G=G.sibling;return h.subtreeFlags|=I,h.childLanes=T,v}function Bv(h,v,T){var I=v.pendingProps;switch(Zu(v),v.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Zi(v),null;case 1:return Tr(v.type)&&wd(),Zi(v),null;case 3:return I=v.stateNode,Ea(),Vn(Er),Vn(ur),mh(),I.pendingContext&&(I.context=I.pendingContext,I.pendingContext=null),(h===null||h.child===null)&&(mc(v)?v.flags|=4:h===null||h.memoizedState.isDehydrated&&(v.flags&256)===0||(v.flags|=1024,Ar!==null&&(Jh(Ar),Ar=null))),Mh(h,v),Zi(v),null;case 5:ph(v);var G=Ca(xl.current);if(T=v.type,h!==null&&v.stateNode!=null)nm(h,v,T,I,G),h.ref!==v.ref&&(v.flags|=512,v.flags|=2097152);else{if(!I){if(v.stateNode===null)throw Error(i(166));return Zi(v),null}if(h=Ca(Xs.current),mc(v)){I=v.stateNode,T=v.type;var X=v.memoizedProps;switch(I[qs]=v,I[pc]=X,h=(v.mode&1)!==0,T){case"dialog":Wn("cancel",I),Wn("close",I);break;case"iframe":case"object":case"embed":Wn("load",I);break;case"video":case"audio":for(G=0;G<dc.length;G++)Wn(dc[G],I);break;case"source":Wn("error",I);break;case"img":case"image":case"link":Wn("error",I),Wn("load",I);break;case"details":Wn("toggle",I);break;case"input":pt(I,X),Wn("invalid",I);break;case"select":I._wrapperState={wasMultiple:!!X.multiple},Wn("invalid",I);break;case"textarea":vt(I,X),Wn("invalid",I)}Is(T,X),G=null;for(var he in X)if(X.hasOwnProperty(he)){var ke=X[he];he==="children"?typeof ke=="string"?I.textContent!==ke&&(X.suppressHydrationWarning!==!0&&bd(I.textContent,ke,h),G=["children",ke]):typeof ke=="number"&&I.textContent!==""+ke&&(X.suppressHydrationWarning!==!0&&bd(I.textContent,ke,h),G=["children",""+ke]):s.hasOwnProperty(he)&&ke!=null&&he==="onScroll"&&Wn("scroll",I)}switch(T){case"input":Xe(I),Nt(I,X,!0);break;case"textarea":Xe(I),An(I);break;case"select":case"option":break;default:typeof X.onClick=="function"&&(I.onclick=yd)}I=G,v.updateQueue=I,I!==null&&(v.flags|=4)}else{he=G.nodeType===9?G:G.ownerDocument,h==="http://www.w3.org/1999/xhtml"&&(h=er(T)),h==="http://www.w3.org/1999/xhtml"?T==="script"?(h=he.createElement("div"),h.innerHTML="<script><\/script>",h=h.removeChild(h.firstChild)):typeof I.is=="string"?h=he.createElement(T,{is:I.is}):(h=he.createElement(T),T==="select"&&(he=h,I.multiple?he.multiple=!0:I.size&&(he.size=I.size))):h=he.createElementNS(h,T),h[qs]=v,h[pc]=I,Ih(h,v,!1,!1),v.stateNode=h;e:{switch(he=kn(T,I),T){case"dialog":Wn("cancel",h),Wn("close",h),G=I;break;case"iframe":case"object":case"embed":Wn("load",h),G=I;break;case"video":case"audio":for(G=0;G<dc.length;G++)Wn(dc[G],h);G=I;break;case"source":Wn("error",h),G=I;break;case"img":case"image":case"link":Wn("error",h),Wn("load",h),G=I;break;case"details":Wn("toggle",h),G=I;break;case"input":pt(h,I),G=Xt(h,I),Wn("invalid",h);break;case"option":G=I;break;case"select":h._wrapperState={wasMultiple:!!I.multiple},G=re({},I,{value:void 0}),Wn("invalid",h);break;case"textarea":vt(h,I),G=Ct(h,I),Wn("invalid",h);break;default:G=I}Is(T,G),ke=G;for(X in ke)if(ke.hasOwnProperty(X)){var Ne=ke[X];X==="style"?nl(h,Ne):X==="dangerouslySetInnerHTML"?(Ne=Ne?Ne.__html:void 0,Ne!=null&&Hi(h,Ne)):X==="children"?typeof Ne=="string"?(T!=="textarea"||Ne!=="")&&Yn(h,Ne):typeof Ne=="number"&&Yn(h,""+Ne):X!=="suppressContentEditableWarning"&&X!=="suppressHydrationWarning"&&X!=="autoFocus"&&(s.hasOwnProperty(X)?Ne!=null&&X==="onScroll"&&Wn("scroll",h):Ne!=null&&E(h,X,Ne,he))}switch(T){case"input":Xe(h),Nt(h,I,!1);break;case"textarea":Xe(h),An(h);break;case"option":I.value!=null&&h.setAttribute("value",""+Z(I.value));break;case"select":h.multiple=!!I.multiple,X=I.value,X!=null?Je(h,!!I.multiple,X,!1):I.defaultValue!=null&&Je(h,!!I.multiple,I.defaultValue,!0);break;default:typeof G.onClick=="function"&&(h.onclick=yd)}switch(T){case"button":case"input":case"select":case"textarea":I=!!I.autoFocus;break e;case"img":I=!0;break e;default:I=!1}}I&&(v.flags|=4)}v.ref!==null&&(v.flags|=512,v.flags|=2097152)}return Zi(v),null;case 6:if(h&&v.stateNode!=null)im(h,v,h.memoizedProps,I);else{if(typeof I!="string"&&v.stateNode===null)throw Error(i(166));if(T=Ca(xl.current),Ca(Xs.current),mc(v)){if(I=v.stateNode,T=v.memoizedProps,I[qs]=v,(X=I.nodeValue!==T)&&(h=Nr,h!==null))switch(h.tag){case 3:bd(I.nodeValue,T,(h.mode&1)!==0);break;case 5:h.memoizedProps.suppressHydrationWarning!==!0&&bd(I.nodeValue,T,(h.mode&1)!==0)}X&&(v.flags|=4)}else I=(T.nodeType===9?T:T.ownerDocument).createTextNode(I),I[qs]=v,v.stateNode=I}return Zi(v),null;case 13:if(Vn(ii),I=v.memoizedState,h===null||h.memoizedState!==null&&h.memoizedState.dehydrated!==null){if(ti&&Gr!==null&&(v.mode&1)!==0&&(v.flags&128)===0)bf(),wa(),v.flags|=98560,X=!1;else if(X=mc(v),I!==null&&I.dehydrated!==null){if(h===null){if(!X)throw Error(i(318));if(X=v.memoizedState,X=X!==null?X.dehydrated:null,!X)throw Error(i(317));X[qs]=v}else wa(),(v.flags&128)===0&&(v.memoizedState=null),v.flags|=4;Zi(v),X=!1}else Ar!==null&&(Jh(Ar),Ar=null),X=!0;if(!X)return v.flags&65536?v:null}return(v.flags&128)!==0?(v.lanes=T,v):(I=I!==null,I!==(h!==null&&h.memoizedState!==null)&&I&&(v.child.flags|=8192,(v.mode&1)!==0&&(h===null||(ii.current&1)!==0?$i===0&&($i=3):ep())),v.updateQueue!==null&&(v.flags|=4),Zi(v),null);case 4:return Ea(),Mh(h,v),h===null&&uc(v.stateNode.containerInfo),Zi(v),null;case 10:return ch(v.type._context),Zi(v),null;case 17:return Tr(v.type)&&wd(),Zi(v),null;case 19:if(Vn(ii),X=v.memoizedState,X===null)return Zi(v),null;if(I=(v.flags&128)!==0,he=X.rendering,he===null)if(I)zd(X,!1);else{if($i!==0||h!==null&&(h.flags&128)!==0)for(h=v.child;h!==null;){if(he=$d(h),he!==null){for(v.flags|=128,zd(X,!1),I=he.updateQueue,I!==null&&(v.updateQueue=I,v.flags|=4),v.subtreeFlags=0,I=T,T=v.child;T!==null;)X=T,h=I,X.flags&=14680066,he=X.alternate,he===null?(X.childLanes=0,X.lanes=h,X.child=null,X.subtreeFlags=0,X.memoizedProps=null,X.memoizedState=null,X.updateQueue=null,X.dependencies=null,X.stateNode=null):(X.childLanes=he.childLanes,X.lanes=he.lanes,X.child=he.child,X.subtreeFlags=0,X.deletions=null,X.memoizedProps=he.memoizedProps,X.memoizedState=he.memoizedState,X.updateQueue=he.updateQueue,X.type=he.type,h=he.dependencies,X.dependencies=h===null?null:{lanes:h.lanes,firstContext:h.firstContext}),T=T.sibling;return Fn(ii,ii.current&1|2),v.child}h=h.sibling}X.tail!==null&&Dn()>wl&&(v.flags|=128,I=!0,zd(X,!1),v.lanes=4194304)}else{if(!I)if(h=$d(he),h!==null){if(v.flags|=128,I=!0,T=h.updateQueue,T!==null&&(v.updateQueue=T,v.flags|=4),zd(X,!0),X.tail===null&&X.tailMode==="hidden"&&!he.alternate&&!ti)return Zi(v),null}else 2*Dn()-X.renderingStartTime>wl&&T!==1073741824&&(v.flags|=128,I=!0,zd(X,!1),v.lanes=4194304);X.isBackwards?(he.sibling=v.child,v.child=he):(T=X.last,T!==null?T.sibling=he:v.child=he,X.last=he)}return X.tail!==null?(v=X.tail,X.rendering=v,X.tail=v.sibling,X.renderingStartTime=Dn(),v.sibling=null,T=ii.current,Fn(ii,I?T&1|2:T&1),v):(Zi(v),null);case 22:case 23:return Qh(),I=v.memoizedState!==null,h!==null&&h.memoizedState!==null!==I&&(v.flags|=8192),I&&(v.mode&1)!==0?(Ur&1073741824)!==0&&(Zi(v),v.subtreeFlags&6&&(v.flags|=8192)):Zi(v),null;case 24:return null;case 25:return null}throw Error(i(156,v.tag))}function Fv(h,v){switch(Zu(v),v.tag){case 1:return Tr(v.type)&&wd(),h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 3:return Ea(),Vn(Er),Vn(ur),mh(),h=v.flags,(h&65536)!==0&&(h&128)===0?(v.flags=h&-65537|128,v):null;case 5:return ph(v),null;case 13:if(Vn(ii),h=v.memoizedState,h!==null&&h.dehydrated!==null){if(v.alternate===null)throw Error(i(340));wa()}return h=v.flags,h&65536?(v.flags=h&-65537|128,v):null;case 19:return Vn(ii),null;case 4:return Ea(),null;case 10:return ch(v.type._context),null;case 22:case 23:return Qh(),null;case 24:return null;default:return null}}var Oh=!1,Qi=!1,Gv=typeof WeakSet=="function"?WeakSet:Set,It=null;function yl(h,v){var T=h.ref;if(T!==null)if(typeof T=="function")try{T(null)}catch(I){ri(h,v,I)}else T.current=null}function Lh(h,v,T){try{T()}catch(I){ri(h,v,I)}}var rm=!1;function Uv(h,v){if(Hu=zo,h=Mu(),Ou(h)){if("selectionStart"in h)var T={start:h.selectionStart,end:h.selectionEnd};else e:{T=(T=h.ownerDocument)&&T.defaultView||window;var I=T.getSelection&&T.getSelection();if(I&&I.rangeCount!==0){T=I.anchorNode;var G=I.anchorOffset,X=I.focusNode;I=I.focusOffset;try{T.nodeType,X.nodeType}catch{T=null;break e}var he=0,ke=-1,Ne=-1,He=0,lt=0,ct=h,at=null;t:for(;;){for(var Tt;ct!==T||G!==0&&ct.nodeType!==3||(ke=he+G),ct!==X||I!==0&&ct.nodeType!==3||(Ne=he+I),ct.nodeType===3&&(he+=ct.nodeValue.length),(Tt=ct.firstChild)!==null;)at=ct,ct=Tt;for(;;){if(ct===h)break t;if(at===T&&++He===G&&(ke=he),at===X&&++lt===I&&(Ne=he),(Tt=ct.nextSibling)!==null)break;ct=at,at=ct.parentNode}ct=Tt}T=ke===-1||Ne===-1?null:{start:ke,end:Ne}}else T=null}T=T||{start:0,end:0}}else T=null;for(Wu={focusedElem:h,selectionRange:T},zo=!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,Gn=Mt.memoizedState,Ge=v.stateNode,Re=Ge.getSnapshotBeforeUpdate(v.elementType===v.type?Ot:Si(v.type,Ot),Gn);Ge.__reactInternalSnapshotBeforeUpdate=Re}break;case 3:var We=v.stateNode.containerInfo;We.nodeType===1?We.textContent="":We.nodeType===9&&We.documentElement&&We.removeChild(We.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(i(163))}}catch(ft){ri(v,v.return,ft)}if(h=v.sibling,h!==null){h.return=v.return,It=h;break}It=v.return}return Mt=rm,rm=!1,Mt}function wc(h,v,T){var I=v.updateQueue;if(I=I!==null?I.lastEffect:null,I!==null){var G=I=I.next;do{if((G.tag&h)===h){var X=G.destroy;G.destroy=void 0,X!==void 0&&Lh(v,T,X)}G=G.next}while(G!==I)}}function zh(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 I=T.create;T.destroy=I()}T=T.next}while(T!==v)}}function Bh(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 sm(h){var v=h.alternate;v!==null&&(h.alternate=null,sm(v)),h.child=null,h.deletions=null,h.sibling=null,h.tag===5&&(v=h.stateNode,v!==null&&(delete v[qs],delete v[pc],delete v[Yu],delete v[pf],delete v[ff])),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 om(h){return h.tag===5||h.tag===3||h.tag===4}function am(h){e:for(;;){for(;h.sibling===null;){if(h.return===null||om(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 Fh(h,v,T){var I=h.tag;if(I===5||I===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=yd));else if(I!==4&&(h=h.child,h!==null))for(Fh(h,v,T),h=h.sibling;h!==null;)Fh(h,v,T),h=h.sibling}function Gh(h,v,T){var I=h.tag;if(I===5||I===6)h=h.stateNode,v?T.insertBefore(h,v):T.appendChild(h);else if(I!==4&&(h=h.child,h!==null))for(Gh(h,v,T),h=h.sibling;h!==null;)Gh(h,v,T),h=h.sibling}var Li=null,Cs=!1;function qo(h,v,T){for(T=T.child;T!==null;)Hv(h,v,T),T=T.sibling}function Hv(h,v,T){if(ji&&typeof ji.onCommitFiberUnmount=="function")try{ji.onCommitFiberUnmount(Sr,T)}catch{}switch(T.tag){case 5:Qi||yl(T,v);case 6:var I=Li,G=Cs;Li=null,qo(h,v,T),Li=I,Cs=G,Li!==null&&(Cs?(h=Li,T=T.stateNode,h.nodeType===8?h.parentNode.removeChild(T):h.removeChild(T)):Li.removeChild(T.stateNode));break;case 18:Li!==null&&(Cs?(h=Li,T=T.stateNode,h.nodeType===8?Ku(h.parentNode,T):h.nodeType===1&&Ku(h,T),co(h)):Ku(Li,T.stateNode));break;case 4:I=Li,G=Cs,Li=T.stateNode.containerInfo,Cs=!0,qo(h,v,T),Li=I,Cs=G;break;case 0:case 11:case 14:case 15:if(!Qi&&(I=T.updateQueue,I!==null&&(I=I.lastEffect,I!==null))){G=I=I.next;do{var X=G,he=X.destroy;X=X.tag,he!==void 0&&((X&2)!==0||(X&4)!==0)&&Lh(T,v,he),G=G.next}while(G!==I)}qo(h,v,T);break;case 1:if(!Qi&&(yl(T,v),I=T.stateNode,typeof I.componentWillUnmount=="function"))try{I.props=T.memoizedProps,I.state=T.memoizedState,I.componentWillUnmount()}catch(ke){ri(T,v,ke)}qo(h,v,T);break;case 21:qo(h,v,T);break;case 22:T.mode&1?(Qi=(I=Qi)||T.memoizedState!==null,qo(h,v,T),Qi=I):qo(h,v,T);break;default:qo(h,v,T)}}function Sc(h){var v=h.updateQueue;if(v!==null){h.updateQueue=null;var T=h.stateNode;T===null&&(T=h.stateNode=new Gv),v.forEach(function(I){var G=Jv.bind(null,h,I);T.has(I)||(T.add(I),I.then(G,G))})}}function rs(h,v){var T=v.deletions;if(T!==null)for(var I=0;I<T.length;I++){var G=T[I];try{var X=h,he=v,ke=he;e:for(;ke!==null;){switch(ke.tag){case 5:Li=ke.stateNode,Cs=!1;break e;case 3:Li=ke.stateNode.containerInfo,Cs=!0;break e;case 4:Li=ke.stateNode.containerInfo,Cs=!0;break e}ke=ke.return}if(Li===null)throw Error(i(160));Hv(X,he,G),Li=null,Cs=!1;var Ne=G.alternate;Ne!==null&&(Ne.return=null),G.return=null}catch(He){ri(G,v,He)}}if(v.subtreeFlags&12854)for(v=v.child;v!==null;)Uh(v,h),v=v.sibling}function Uh(h,v){var T=h.alternate,I=h.flags;switch(h.tag){case 0:case 11:case 14:case 15:if(rs(v,h),Es(h),I&4){try{wc(3,h,h.return),zh(3,h)}catch(Ot){ri(h,h.return,Ot)}try{wc(5,h,h.return)}catch(Ot){ri(h,h.return,Ot)}}break;case 1:rs(v,h),Es(h),I&512&&T!==null&&yl(T,T.return);break;case 5:if(rs(v,h),Es(h),I&512&&T!==null&&yl(T,T.return),h.flags&32){var G=h.stateNode;try{Yn(G,"")}catch(Ot){ri(h,h.return,Ot)}}if(I&4&&(G=h.stateNode,G!=null)){var X=h.memoizedProps,he=T!==null?T.memoizedProps:X,ke=h.type,Ne=h.updateQueue;if(h.updateQueue=null,Ne!==null)try{ke==="input"&&X.type==="radio"&&X.name!=null&&it(G,X),kn(ke,he);var He=kn(ke,X);for(he=0;he<Ne.length;he+=2){var lt=Ne[he],ct=Ne[he+1];lt==="style"?nl(G,ct):lt==="dangerouslySetInnerHTML"?Hi(G,ct):lt==="children"?Yn(G,ct):E(G,lt,ct,He)}switch(ke){case"input":ot(G,X);break;case"textarea":hn(G,X);break;case"select":var at=G._wrapperState.wasMultiple;G._wrapperState.wasMultiple=!!X.multiple;var Tt=X.value;Tt!=null?Je(G,!!X.multiple,Tt,!1):at!==!!X.multiple&&(X.defaultValue!=null?Je(G,!!X.multiple,X.defaultValue,!0):Je(G,!!X.multiple,X.multiple?[]:"",!1))}G[pc]=X}catch(Ot){ri(h,h.return,Ot)}}break;case 6:if(rs(v,h),Es(h),I&4){if(h.stateNode===null)throw Error(i(162));G=h.stateNode,X=h.memoizedProps;try{G.nodeValue=X}catch(Ot){ri(h,h.return,Ot)}}break;case 3:if(rs(v,h),Es(h),I&4&&T!==null&&T.memoizedState.isDehydrated)try{co(v.containerInfo)}catch(Ot){ri(h,h.return,Ot)}break;case 4:rs(v,h),Es(h);break;case 13:rs(v,h),Es(h),G=h.child,G.flags&8192&&(X=G.memoizedState!==null,G.stateNode.isHidden=X,!X||G.alternate!==null&&G.alternate.memoizedState!==null||(qh=Dn())),I&4&&Sc(h);break;case 22:if(lt=T!==null&&T.memoizedState!==null,h.mode&1?(Qi=(He=Qi)||lt,rs(v,h),Qi=He):rs(v,h),Es(h),I&8192){if(He=h.memoizedState!==null,(h.stateNode.isHidden=He)&&!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:wc(4,at,at.return);break;case 1:yl(at,at.return);var Mt=at.stateNode;if(typeof Mt.componentWillUnmount=="function"){I=at,T=at.return;try{v=I,Mt.props=v.memoizedProps,Mt.state=v.memoizedState,Mt.componentWillUnmount()}catch(Ot){ri(I,T,Ot)}}break;case 5:yl(at,at.return);break;case 22:if(at.memoizedState!==null){Hh(ct);continue}}Tt!==null?(Tt.return=at,It=Tt):Hh(ct)}lt=lt.sibling}e:for(lt=null,ct=h;;){if(ct.tag===5){if(lt===null){lt=ct;try{G=ct.stateNode,He?(X=G.style,typeof X.setProperty=="function"?X.setProperty("display","none","important"):X.display="none"):(ke=ct.stateNode,Ne=ct.memoizedProps.style,he=Ne!=null&&Ne.hasOwnProperty("display")?Ne.display:null,ke.style.display=Rs("display",he))}catch(Ot){ri(h,h.return,Ot)}}}else if(ct.tag===6){if(lt===null)try{ct.stateNode.nodeValue=He?"":ct.memoizedProps}catch(Ot){ri(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:rs(v,h),Es(h),I&4&&Sc(h);break;case 21:break;default:rs(v,h),Es(h)}}function Es(h){var v=h.flags;if(v&2){try{e:{for(var T=h.return;T!==null;){if(om(T)){var I=T;break e}T=T.return}throw Error(i(160))}switch(I.tag){case 5:var G=I.stateNode;I.flags&32&&(Yn(G,""),I.flags&=-33);var X=am(h);Gh(h,X,G);break;case 3:case 4:var he=I.stateNode.containerInfo,ke=am(h);Fh(h,ke,he);break;default:throw Error(i(161))}}catch(Ne){ri(h,h.return,Ne)}h.flags&=-3}v&4096&&(h.flags&=-4097)}function lm(h,v,T){It=h,cm(h)}function cm(h,v,T){for(var I=(h.mode&1)!==0;It!==null;){var G=It,X=G.child;if(G.tag===22&&I){var he=G.memoizedState!==null||Oh;if(!he){var ke=G.alternate,Ne=ke!==null&&ke.memoizedState!==null||Qi;ke=Oh;var He=Qi;if(Oh=he,(Qi=Ne)&&!He)for(It=G;It!==null;)he=It,Ne=he.child,he.tag===22&&he.memoizedState!==null?Wh(G):Ne!==null?(Ne.return=he,It=Ne):Wh(G);for(;X!==null;)It=X,cm(X),X=X.sibling;It=G,Oh=ke,Qi=He}dm(h)}else(G.subtreeFlags&8772)!==0&&X!==null?(X.return=G,It=X):dm(h)}}function dm(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:Qi||zh(5,v);break;case 1:var I=v.stateNode;if(v.flags&4&&!Qi)if(T===null)I.componentDidMount();else{var G=v.elementType===v.type?T.memoizedProps:Si(v.type,T.memoizedProps);I.componentDidUpdate(G,T.memoizedState,I.__reactInternalSnapshotBeforeUpdate)}var X=v.updateQueue;X!==null&&jv(v,X,I);break;case 3:var he=v.updateQueue;if(he!==null){if(T=null,v.child!==null)switch(v.child.tag){case 5:T=v.child.stateNode;break;case 1:T=v.child.stateNode}jv(v,he,T)}break;case 5:var ke=v.stateNode;if(T===null&&v.flags&4){T=ke;var Ne=v.memoizedProps;switch(v.type){case"button":case"input":case"select":case"textarea":Ne.autoFocus&&T.focus();break;case"img":Ne.src&&(T.src=Ne.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(v.memoizedState===null){var He=v.alternate;if(He!==null){var lt=He.memoizedState;if(lt!==null){var ct=lt.dehydrated;ct!==null&&co(ct)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(i(163))}Qi||v.flags&512&&Bh(v)}catch(at){ri(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 Hh(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 Wh(h){for(;It!==null;){var v=It;try{switch(v.tag){case 0:case 11:case 15:var T=v.return;try{zh(4,v)}catch(Ne){ri(v,T,Ne)}break;case 1:var I=v.stateNode;if(typeof I.componentDidMount=="function"){var G=v.return;try{I.componentDidMount()}catch(Ne){ri(v,G,Ne)}}var X=v.return;try{Bh(v)}catch(Ne){ri(v,X,Ne)}break;case 5:var he=v.return;try{Bh(v)}catch(Ne){ri(v,he,Ne)}}}catch(Ne){ri(v,v.return,Ne)}if(v===h){It=null;break}var ke=v.sibling;if(ke!==null){ke.return=v.return,It=ke;break}It=v.return}}var Wv=Math.ceil,Bd=j.ReactCurrentDispatcher,Fd=j.ReactCurrentOwner,ss=j.ReactCurrentBatchConfig,wn=0,ki=null,bi=null,zi=0,Ur=0,_l=ho(0),$i=0,kc=null,Na=0,Gd=0,Vh=0,Ud=null,Pr=null,qh=0,wl=1/0,Ko=null,Hd=!1,Kh=null,Yo=null,Wd=!1,Aa=null,Vd=0,Cc=0,Yh=null,Ec=-1,qd=0;function fr(){return(wn&6)!==0?Dn():Ec!==-1?Ec:Ec=Dn()}function Xo(h){return(h.mode&1)===0?1:(wn&2)!==0&&zi!==0?zi&-zi:sh.transition!==null?(qd===0&&(qd=Fr()),qd):(h=Ie,h!==0||(h=window.event,h=h===void 0?16:me(h.type)),h)}function Ts(h,v,T,I){if(50<Cc)throw Cc=0,Yh=null,Error(i(185));sr(h,T,I),((wn&2)===0||h!==ki)&&(h===ki&&((wn&2)===0&&(Gd|=T),$i===4&&Jo(h,zi)),Rr(h,I),T===1&&wn===0&&(v.mode&1)===0&&(wl=Dn()+500,kd&&Uo()))}function Rr(h,v){var T=h.callbackNode;Cr(h,v);var I=Gs(h,h===ki?zi:0);if(I===0)T!==null&&Oi(T),h.callbackNode=null,h.callbackPriority=0;else if(v=I&-I,h.callbackPriority!==v){if(T!=null&&Oi(T),v===1)h.tag===0?$y(pm.bind(null,h)):xf(pm.bind(null,h)),kv(function(){(wn&6)===0&&Uo()}),T=null;else{switch(Ze(I)){case 1:T=Qn;break;case 4:T=Ki;break;case 16:T=gs;break;case 536870912:T=zs;break;default:T=gs}T=bm(T,um.bind(null,h))}h.callbackPriority=v,h.callbackNode=T}}function um(h,v){if(Ec=-1,qd=0,(wn&6)!==0)throw Error(i(327));var T=h.callbackNode;if(Sl()&&h.callbackNode!==T)return null;var I=Gs(h,h===ki?zi:0);if(I===0)return null;if((I&30)!==0||(I&h.expiredLanes)!==0||v)v=Kd(h,I);else{v=I;var G=wn;wn|=2;var X=Vv();(ki!==h||zi!==v)&&(Ko=null,wl=Dn()+500,Pa(h,v));do try{My();break}catch(ke){fm(h,ke)}while(!0);lh(),Bd.current=X,wn=G,bi!==null?v=0:(ki=null,zi=0,v=$i)}if(v!==0){if(v===2&&(G=ao(h),G!==0&&(I=G,v=Xh(h,G))),v===1)throw T=kc,Pa(h,0),Jo(h,I),Rr(h,Dn()),T;if(v===6)Jo(h,I);else{if(G=h.current.alternate,(I&30)===0&&!hm(G)&&(v=Kd(h,I),v===2&&(X=ao(h),X!==0&&(I=X,v=Xh(h,X))),v===1))throw T=kc,Pa(h,0),Jo(h,I),Rr(h,Dn()),T;switch(h.finishedWork=G,h.finishedLanes=I,v){case 0:case 1:throw Error(i(345));case 2:Ra(h,Pr,Ko);break;case 3:if(Jo(h,I),(I&130023424)===I&&(v=qh+500-Dn(),10<v)){if(Gs(h,0)!==0)break;if(G=h.suspendedLanes,(G&I)!==I){fr(),h.pingedLanes|=h.suspendedLanes&G;break}h.timeoutHandle=qu(Ra.bind(null,h,Pr,Ko),v);break}Ra(h,Pr,Ko);break;case 4:if(Jo(h,I),(I&4194240)===I)break;for(v=h.eventTimes,G=-1;0<I;){var he=31-ei(I);X=1<<he,he=v[he],he>G&&(G=he),I&=~X}if(I=G,I=Dn()-I,I=(120>I?120:480>I?480:1080>I?1080:1920>I?1920:3e3>I?3e3:4320>I?4320:1960*Wv(I/1960))-I,10<I){h.timeoutHandle=qu(Ra.bind(null,h,Pr,Ko),I);break}Ra(h,Pr,Ko);break;case 5:Ra(h,Pr,Ko);break;default:throw Error(i(329))}}}return Rr(h,Dn()),h.callbackNode===T?um.bind(null,h):null}function Xh(h,v){var T=Ud;return h.current.memoizedState.isDehydrated&&(Pa(h,v).flags|=256),h=Kd(h,v),h!==2&&(v=Pr,Pr=T,v!==null&&Jh(v)),h}function Jh(h){Pr===null?Pr=h:Pr.push.apply(Pr,h)}function hm(h){for(var v=h;;){if(v.flags&16384){var T=v.updateQueue;if(T!==null&&(T=T.stores,T!==null))for(var I=0;I<T.length;I++){var G=T[I],X=G.getSnapshot;G=G.value;try{if(!ws(X(),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 Jo(h,v){for(v&=~Vh,v&=~Gd,h.suspendedLanes|=v,h.pingedLanes&=~v,h=h.expirationTimes;0<v;){var T=31-ei(v),I=1<<T;h[T]=-1,v&=~I}}function pm(h){if((wn&6)!==0)throw Error(i(327));Sl();var v=Gs(h,0);if((v&1)===0)return Rr(h,Dn()),null;var T=Kd(h,v);if(h.tag!==0&&T===2){var I=ao(h);I!==0&&(v=I,T=Xh(h,I))}if(T===1)throw T=kc,Pa(h,0),Jo(h,v),Rr(h,Dn()),T;if(T===6)throw Error(i(345));return h.finishedWork=h.current.alternate,h.finishedLanes=v,Ra(h,Pr,Ko),Rr(h,Dn()),null}function Zh(h,v){var T=wn;wn|=1;try{return h(v)}finally{wn=T,wn===0&&(wl=Dn()+500,kd&&Uo())}}function $a(h){Aa!==null&&Aa.tag===0&&(wn&6)===0&&Sl();var v=wn;wn|=1;var T=ss.transition,I=Ie;try{if(ss.transition=null,Ie=1,h)return h()}finally{Ie=I,ss.transition=T,wn=v,(wn&6)===0&&Uo()}}function Qh(){Ur=_l.current,Vn(_l)}function Pa(h,v){h.finishedWork=null,h.finishedLanes=0;var T=h.timeoutHandle;if(T!==-1&&(h.timeoutHandle=-1,Sv(T)),bi!==null)for(T=bi.return;T!==null;){var I=T;switch(Zu(I),I.tag){case 1:I=I.type.childContextTypes,I!=null&&wd();break;case 3:Ea(),Vn(Er),Vn(ur),mh();break;case 5:ph(I);break;case 4:Ea();break;case 13:Vn(ii);break;case 19:Vn(ii);break;case 10:ch(I.type._context);break;case 22:case 23:Qh()}T=T.return}if(ki=h,bi=h=Zo(h.current,null),zi=Ur=v,$i=0,kc=null,Vh=Gd=Na=0,Pr=Ud=null,vl!==null){for(v=0;v<vl.length;v++)if(T=vl[v],I=T.interleaved,I!==null){T.interleaved=null;var G=I.next,X=T.pending;if(X!==null){var he=X.next;X.next=G,I.next=he}T.pending=I}vl=null}return h}function fm(h,v){do{var T=bi;try{if(lh(),gh.current=Md,xh){for(var I=ni.memoizedState;I!==null;){var G=I.queue;G!==null&&(G.pending=null),I=I.next}xh=!1}if(Ta=0,Ai=wi=ni=null,ja=!1,Vo=0,Fd.current=null,T===null||T.return===null){$i=1,kc=v,bi=null;break}e:{var X=h,he=T.return,ke=T,Ne=v;if(v=zi,ke.flags|=32768,Ne!==null&&typeof Ne=="object"&&typeof Ne.then=="function"){var He=Ne,lt=ke,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=Ov(he);if(Tt!==null){Tt.flags&=-257,pr(Tt,he,ke,X,v),Tt.mode&1&&qf(X,He,v),v=Tt,Ne=He;var Mt=v.updateQueue;if(Mt===null){var Ot=new Set;Ot.add(Ne),v.updateQueue=Ot}else Mt.add(Ne);break e}else{if((v&1)===0){qf(X,He,v),ep();break e}Ne=Error(i(426))}}else if(ti&&ke.mode&1){var Gn=Ov(he);if(Gn!==null){(Gn.flags&65536)===0&&(Gn.flags|=256),pr(Gn,he,ke,X,v),rh(bl(Ne,ke));break e}}X=Ne=bl(Ne,ke),$i!==4&&($i=2),Ud===null?Ud=[X]:Ud.push(X),X=he;do{switch(X.tag){case 3:X.flags|=65536,v&=-v,X.lanes|=v;var Ge=Wf(X,Ne,v);Tv(X,Ge);break e;case 1:ke=Ne;var Re=X.type,We=X.stateNode;if((X.flags&128)===0&&(typeof Re.getDerivedStateFromError=="function"||We!==null&&typeof We.componentDidCatch=="function"&&(Yo===null||!Yo.has(We)))){X.flags|=65536,v&=-v,X.lanes|=v;var ft=Vf(X,ke,v);Tv(X,ft);break e}}X=X.return}while(X!==null)}Tc(T)}catch(Gt){v=Gt,bi===T&&T!==null&&(bi=T=T.return);continue}break}while(!0)}function Vv(){var h=Bd.current;return Bd.current=Md,h===null?Md:h}function ep(){($i===0||$i===3||$i===2)&&($i=4),ki===null||(Na&268435455)===0&&(Gd&268435455)===0||Jo(ki,zi)}function Kd(h,v){var T=wn;wn|=2;var I=Vv();(ki!==h||zi!==v)&&(Ko=null,Pa(h,v));do try{qv();break}catch(G){fm(h,G)}while(!0);if(lh(),wn=T,Bd.current=I,bi!==null)throw Error(i(261));return ki=null,zi=0,$i}function qv(){for(;bi!==null;)mm(bi)}function My(){for(;bi!==null&&!rl();)mm(bi)}function mm(h){var v=xm(h.alternate,h,Ur);h.memoizedProps=h.pendingProps,v===null?Tc(h):bi=v,Fd.current=null}function Tc(h){var v=h;do{var T=v.alternate;if(h=v.return,(v.flags&32768)===0){if(T=Bv(T,v,Ur),T!==null){bi=T;return}}else{if(T=Fv(T,v),T!==null){T.flags&=32767,bi=T;return}if(h!==null)h.flags|=32768,h.subtreeFlags=0,h.deletions=null;else{$i=6,bi=null;return}}if(v=v.sibling,v!==null){bi=v;return}bi=v=h}while(v!==null);$i===0&&($i=5)}function Ra(h,v,T){var I=Ie,G=ss.transition;try{ss.transition=null,Ie=1,gm(h,v,T,I)}finally{ss.transition=G,Ie=I}return null}function gm(h,v,T,I){do Sl();while(Aa!==null);if((wn&6)!==0)throw Error(i(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(i(177));h.callbackNode=null,h.callbackPriority=0;var X=T.lanes|T.childLanes;if(mt(h,X),h===ki&&(bi=ki=null,zi=0),(T.subtreeFlags&2064)===0&&(T.flags&2064)===0||Wd||(Wd=!0,bm(gs,function(){return Sl(),null})),X=(T.flags&15990)!==0,(T.subtreeFlags&15990)!==0||X){X=ss.transition,ss.transition=null;var he=Ie;Ie=1;var ke=wn;wn|=4,Fd.current=null,Uv(h,T),Uh(T,h),xv(Wu),zo=!!Hu,Wu=Hu=null,h.current=T,lm(T),sl(),wn=ke,Ie=he,ss.transition=X}else h.current=T;if(Wd&&(Wd=!1,Aa=h,Vd=G),X=h.pendingLanes,X===0&&(Yo=null),Ft(T.stateNode),Rr(h,Dn()),v!==null)for(I=h.onRecoverableError,T=0;T<v.length;T++)G=v[T],I(G.value,{componentStack:G.stack,digest:G.digest});if(Hd)throw Hd=!1,h=Kh,Kh=null,h;return(Vd&1)!==0&&h.tag!==0&&Sl(),X=h.pendingLanes,(X&1)!==0?h===Yh?Cc++:(Cc=0,Yh=h):Cc=0,Uo(),null}function Sl(){if(Aa!==null){var h=Ze(Vd),v=ss.transition,T=Ie;try{if(ss.transition=null,Ie=16>h?16:h,Aa===null)var I=!1;else{if(h=Aa,Aa=null,Vd=0,(wn&6)!==0)throw Error(i(331));var G=wn;for(wn|=4,It=h.current;It!==null;){var X=It,he=X.child;if((It.flags&16)!==0){var ke=X.deletions;if(ke!==null){for(var Ne=0;Ne<ke.length;Ne++){var He=ke[Ne];for(It=He;It!==null;){var lt=It;switch(lt.tag){case 0:case 11:case 15:wc(8,lt,X)}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(sm(lt),lt===He){It=null;break}if(at!==null){at.return=Tt,It=at;break}It=Tt}}}var Mt=X.alternate;if(Mt!==null){var Ot=Mt.child;if(Ot!==null){Mt.child=null;do{var Gn=Ot.sibling;Ot.sibling=null,Ot=Gn}while(Ot!==null)}}It=X}}if((X.subtreeFlags&2064)!==0&&he!==null)he.return=X,It=he;else e:for(;It!==null;){if(X=It,(X.flags&2048)!==0)switch(X.tag){case 0:case 11:case 15:wc(9,X,X.return)}var Ge=X.sibling;if(Ge!==null){Ge.return=X.return,It=Ge;break e}It=X.return}}var Re=h.current;for(It=Re;It!==null;){he=It;var We=he.child;if((he.subtreeFlags&2064)!==0&&We!==null)We.return=he,It=We;else e:for(he=Re;It!==null;){if(ke=It,(ke.flags&2048)!==0)try{switch(ke.tag){case 0:case 11:case 15:zh(9,ke)}}catch(Gt){ri(ke,ke.return,Gt)}if(ke===he){It=null;break e}var ft=ke.sibling;if(ft!==null){ft.return=ke.return,It=ft;break e}It=ke.return}}if(wn=G,Uo(),ji&&typeof ji.onPostCommitFiberRoot=="function")try{ji.onPostCommitFiberRoot(Sr,h)}catch{}I=!0}return I}finally{Ie=T,ss.transition=v}}return!1}function vm(h,v,T){v=bl(T,v),v=Wf(h,v,1),h=Wo(h,v,1),v=fr(),h!==null&&(sr(h,1,v),Rr(h,v))}function ri(h,v,T){if(h.tag===3)vm(h,h,T);else for(;v!==null;){if(v.tag===3){vm(v,h,T);break}else if(v.tag===1){var I=v.stateNode;if(typeof v.type.getDerivedStateFromError=="function"||typeof I.componentDidCatch=="function"&&(Yo===null||!Yo.has(I))){h=bl(T,h),h=Vf(v,h,1),v=Wo(v,h,1),h=fr(),v!==null&&(sr(v,1,h),Rr(v,h));break}}v=v.return}}function Kv(h,v,T){var I=h.pingCache;I!==null&&I.delete(v),v=fr(),h.pingedLanes|=h.suspendedLanes&T,ki===h&&(zi&T)===T&&($i===4||$i===3&&(zi&130023424)===zi&&500>Dn()-qh?Pa(h,0):Vh|=T),Rr(h,v)}function Yv(h,v){v===0&&((h.mode&1)===0?v=1:(v=rr,rr<<=1,(rr&130023424)===0&&(rr=4194304)));var T=fr();h=fo(h,v),h!==null&&(sr(h,v,T),Rr(h,T))}function Xv(h){var v=h.memoizedState,T=0;v!==null&&(T=v.retryLane),Yv(h,T)}function Jv(h,v){var T=0;switch(h.tag){case 13:var I=h.stateNode,G=h.memoizedState;G!==null&&(T=G.retryLane);break;case 19:I=h.stateNode;break;default:throw Error(i(314))}I!==null&&I.delete(v),Yv(h,T)}var xm;xm=function(h,v,T){if(h!==null)if(h.memoizedProps!==v.pendingProps||Er.current)$r=!0;else{if((h.lanes&T)===0&&(v.flags&128)===0)return $r=!1,Iy(h,v,T);$r=(h.flags&131072)!==0}else $r=!1,ti&&(v.flags&1048576)!==0&&_a(v,Ed,v.index);switch(v.lanes=0,v.tag){case 2:var I=v.type;Ld(h,v),h=v.pendingProps;var G=hr(v,ur.current);gl(v,T),G=yh(null,v,I,h,G,T);var X=_h();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,Tr(I)?(X=!0,Sd(v)):X=!1,v.memoizedState=G.state!==null&&G.state!==void 0?G.state:null,Nd(v),G.updater=go,v.stateNode=G,G._reactInternals=v,Ch(v,I,h,T),v=Dh(null,v,I,!0,X,T)):(v.tag=0,ti&&X&&_i(v),Ji(null,v,G,T),v=v.child),v;case 16:I=v.elementType;e:{switch(Ld(h,v),h=v.pendingProps,G=I._init,I=G(I._payload),v.type=I,G=v.tag=Zv(I),h=Si(I,h),G){case 0:v=jh(null,v,I,h,T);break e;case 1:v=Zf(null,v,I,h,T);break e;case 11:v=Kf(null,v,I,h,T);break e;case 14:v=yc(null,v,I,Si(I.type,h),T);break e}throw Error(i(306,I,""))}return v;case 0:return I=v.type,G=v.pendingProps,G=v.elementType===I?G:Si(I,G),jh(h,v,I,G,T);case 1:return I=v.type,G=v.pendingProps,G=v.elementType===I?G:Si(I,G),Zf(h,v,I,G,T);case 3:e:{if(Nh(v),h===null)throw Error(i(387));I=v.pendingProps,X=v.memoizedState,G=X.element,uh(h,v),Ad(v,I,null,T);var he=v.memoizedState;if(I=he.element,X.isDehydrated)if(X={element:I,isDehydrated:!1,cache:he.cache,pendingSuspenseBoundaries:he.pendingSuspenseBoundaries,transitions:he.transitions},v.updateQueue.baseState=X,v.memoizedState=X,v.flags&256){G=bl(Error(i(423)),v),v=Qf(h,v,I,T,G);break e}else if(I!==G){G=bl(Error(i(424)),v),v=Qf(h,v,I,T,G);break e}else for(Gr=Fo(v.stateNode.containerInfo.firstChild),Nr=v,ti=!0,Ar=null,T=oh(v,null,I,T),v.child=T;T;)T.flags=T.flags&-3|4096,T=T.sibling;else{if(wa(),I===G){v=vo(h,v,T);break e}Ji(h,v,I,T)}v=v.child}return v;case 5:return wf(v),h===null&&nh(v),I=v.type,G=v.pendingProps,X=h!==null?h.memoizedProps:null,he=G.children,Vu(I,G)?he=null:X!==null&&Vu(I,X)&&(v.flags|=32),Jf(h,v),Ji(h,v,he,T),v.child;case 6:return h===null&&nh(v),null;case 13:return em(h,v,T);case 4:return hh(v,v.stateNode.containerInfo),I=v.pendingProps,h===null?v.child=ml(v,null,I,T):Ji(h,v,I,T),v.child;case 11:return I=v.type,G=v.pendingProps,G=v.elementType===I?G:Si(I,G),Kf(h,v,I,G,T);case 7:return Ji(h,v,v.pendingProps,T),v.child;case 8:return Ji(h,v,v.pendingProps.children,T),v.child;case 12:return Ji(h,v,v.pendingProps.children,T),v.child;case 10:e:{if(I=v.type._context,G=v.pendingProps,X=v.memoizedProps,he=G.value,Fn(Sa,I._currentValue),I._currentValue=he,X!==null)if(ws(X.value,he)){if(X.children===G.children&&!Er.current){v=vo(h,v,T);break e}}else for(X=v.child,X!==null&&(X.return=v);X!==null;){var ke=X.dependencies;if(ke!==null){he=X.child;for(var Ne=ke.firstContext;Ne!==null;){if(Ne.context===I){if(X.tag===1){Ne=mo(-1,T&-T),Ne.tag=2;var He=X.updateQueue;if(He!==null){He=He.shared;var lt=He.pending;lt===null?Ne.next=Ne:(Ne.next=lt.next,lt.next=Ne),He.pending=Ne}}X.lanes|=T,Ne=X.alternate,Ne!==null&&(Ne.lanes|=T),_f(X.return,T,v),ke.lanes|=T;break}Ne=Ne.next}}else if(X.tag===10)he=X.type===v.type?null:X.child;else if(X.tag===18){if(he=X.return,he===null)throw Error(i(341));he.lanes|=T,ke=he.alternate,ke!==null&&(ke.lanes|=T),_f(he,T,v),he=X.sibling}else he=X.child;if(he!==null)he.return=X;else for(he=X;he!==null;){if(he===v){he=null;break}if(X=he.sibling,X!==null){X.return=he.return,he=X;break}he=he.return}X=he}Ji(h,v,G.children,T),v=v.child}return v;case 9:return G=v.type,I=v.pendingProps.children,gl(v,T),G=ns(G),I=I(G),v.flags|=1,Ji(h,v,I,T),v.child;case 14:return I=v.type,G=Si(I,v.pendingProps),G=Si(I.type,G),yc(h,v,I,G,T);case 15:return Yf(h,v,v.type,v.pendingProps,T);case 17:return I=v.type,G=v.pendingProps,G=v.elementType===I?G:Si(I,G),Ld(h,v),v.tag=1,Tr(I)?(h=!0,Sd(v)):h=!1,gl(v,T),Uf(v,I,G),Ch(v,I,G,T),Dh(null,v,I,!0,h,T);case 19:return Rh(h,v,T);case 22:return Xf(h,v,T)}throw Error(i(156,v.tag))};function bm(h,v){return ma(h,v)}function Oy(h,v,T,I){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=I,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Hr(h,v,T,I){return new Oy(h,v,T,I)}function tp(h){return h=h.prototype,!(!h||!h.isReactComponent)}function Zv(h){if(typeof h=="function")return tp(h)?1:0;if(h!=null){if(h=h.$$typeof,h===J)return 11;if(h===V)return 14}return 2}function Zo(h,v){var T=h.alternate;return T===null?(T=Hr(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 Yd(h,v,T,I,G,X){var he=2;if(I=h,typeof h=="function")tp(h)&&(he=1);else if(typeof h=="string")he=5;else e:switch(h){case P:return kl(T.children,G,X,v);case R:he=8,G|=8;break;case O:return h=Hr(12,T,v,G|2),h.elementType=O,h.lanes=X,h;case Q:return h=Hr(13,T,v,G),h.elementType=Q,h.lanes=X,h;case Y:return h=Hr(19,T,v,G),h.elementType=Y,h.lanes=X,h;case fe:return Xd(T,G,X,v);default:if(typeof h=="object"&&h!==null)switch(h.$$typeof){case B:he=10;break e;case U:he=9;break e;case J:he=11;break e;case V:he=14;break e;case ee:he=16,I=null;break e}throw Error(i(130,h==null?h:typeof h,""))}return v=Hr(he,T,v,G),v.elementType=h,v.type=I,v.lanes=X,v}function kl(h,v,T,I){return h=Hr(7,h,I,v),h.lanes=T,h}function Xd(h,v,T,I){return h=Hr(22,h,I,v),h.elementType=fe,h.lanes=T,h.stateNode={isHidden:!1},h}function np(h,v,T){return h=Hr(6,h,null,v),h.lanes=T,h}function ip(h,v,T){return v=Hr(4,h.children!==null?h.children:[],h.key,v),v.lanes=T,v.stateNode={containerInfo:h.containerInfo,pendingChildren:null,implementation:h.implementation},v}function Ly(h,v,T,I,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=Ke(0),this.expirationTimes=Ke(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ke(0),this.identifierPrefix=I,this.onRecoverableError=G,this.mutableSourceEagerHydrationData=null}function rp(h,v,T,I,G,X,he,ke,Ne){return h=new Ly(h,v,T,ke,Ne),v===1?(v=1,X===!0&&(v|=8)):v=0,X=Hr(3,null,null,v),h.current=X,X.stateNode=h,X.memoizedState={element:I,isDehydrated:T,cache:null,transitions:null,pendingSuspenseBoundaries:null},Nd(X),h}function zy(h,v,T){var I=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:$,key:I==null?null:""+I,children:h,containerInfo:v,implementation:T}}function ym(h){if(!h)return Go;h=h._reactInternals;e:{if(Et(h)!==h||h.tag!==1)throw Error(i(170));var v=h;do{switch(v.tag){case 3:v=v.stateNode.context;break e;case 1:if(Tr(v.type)){v=v.stateNode.__reactInternalMemoizedMergedChildContext;break e}}v=v.return}while(v!==null);throw Error(i(171))}if(h.tag===1){var T=h.type;if(Tr(T))return gf(h,T,v)}return v}function Qv(h,v,T,I,G,X,he,ke,Ne){return h=rp(T,I,!0,h,G,X,he,ke,Ne),h.context=ym(null),T=h.current,I=fr(),G=Xo(T),X=mo(I,G),X.callback=v??null,Wo(T,X,G),h.current.lanes=G,sr(h,G,I),Rr(h,I),h}function Jd(h,v,T,I){var G=v.current,X=fr(),he=Xo(G);return T=ym(T),v.context===null?v.context=T:v.pendingContext=T,v=mo(X,he),v.payload={element:h},I=I===void 0?null:I,I!==null&&(v.callback=I),h=Wo(G,v,he),h!==null&&(Ts(h,G,he,X),gc(h,G,he)),he}function Zd(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 _m(h,v){if(h=h.memoizedState,h!==null&&h.dehydrated!==null){var T=h.retryLane;h.retryLane=T!==0&&T<v?T:v}}function sp(h,v){_m(h,v),(h=h.alternate)&&_m(h,v)}function ex(){return null}var tx=typeof reportError=="function"?reportError:function(h){console.error(h)};function op(h){this._internalRoot=h}Cl.prototype.render=op.prototype.render=function(h){var v=this._internalRoot;if(v===null)throw Error(i(409));Jd(h,v,null,null)},Cl.prototype.unmount=op.prototype.unmount=function(){var h=this._internalRoot;if(h!==null){this._internalRoot=null;var v=h.containerInfo;$a(function(){Jd(null,h,null,null)}),v[Ks]=null}};function Cl(h){this._internalRoot=h}Cl.prototype.unstable_scheduleHydration=function(h){if(h){var v=On();h={blockedOn:null,target:h,priority:v};for(var T=0;T<vs.length&&v!==0&&v<vs[T].priority;T++);vs.splice(T,0,h),T===0&&Ql(h)}};function ap(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)}function Qd(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11&&(h.nodeType!==8||h.nodeValue!==" react-mount-point-unstable "))}function nx(){}function ix(h,v,T,I,G){if(G){if(typeof I=="function"){var X=I;I=function(){var He=Zd(he);X.call(He)}}var he=Qv(v,I,h,0,null,!1,!1,"",nx);return h._reactRootContainer=he,h[Ks]=he.current,uc(h.nodeType===8?h.parentNode:h),$a(),he}for(;G=h.lastChild;)h.removeChild(G);if(typeof I=="function"){var ke=I;I=function(){var He=Zd(Ne);ke.call(He)}}var Ne=rp(h,0,!1,null,null,!1,!1,"",nx);return h._reactRootContainer=Ne,h[Ks]=Ne.current,uc(h.nodeType===8?h.parentNode:h),$a(function(){Jd(v,Ne,T,I)}),Ne}function jc(h,v,T,I,G){var X=T._reactRootContainer;if(X){var he=X;if(typeof G=="function"){var ke=G;G=function(){var Ne=Zd(he);ke.call(Ne)}}Jd(v,he,h,G)}else he=ix(T,v,h,G,I);return Zd(he)}jt=function(h){switch(h.tag){case 3:var v=h.stateNode;if(v.current.memoizedState.isDehydrated){var T=Yr(v.pendingLanes);T!==0&&(we(v,T|1),Rr(v,Dn()),(wn&6)===0&&(wl=Dn()+500,Uo()))}break;case 13:$a(function(){var I=fo(h,1);if(I!==null){var G=fr();Ts(I,h,1,G)}}),sp(h,1)}},sn=function(h){if(h.tag===13){var v=fo(h,134217728);if(v!==null){var T=fr();Ts(v,h,134217728,T)}sp(h,134217728)}},dn=function(h){if(h.tag===13){var v=Xo(h),T=fo(h,v);if(T!==null){var I=fr();Ts(T,h,v,I)}sp(h,v)}},On=function(){return Ie},In=function(h,v){var T=Ie;try{return Ie=h,v()}finally{Ie=T}},Ms=function(h,v,T){switch(v){case"input":if(ot(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 I=T[v];if(I!==h&&I.form===h.form){var G=_d(I);if(!G)throw Error(i(90));nt(I),ot(I,G)}}}break;case"textarea":hn(h,T);break;case"select":v=T.value,v!=null&&Je(h,!!T.multiple,v,!1)}},Kr=Zh,Wi=$a;var wm={usingClientEntryPoint:!1,Events:[fc,dl,_d,Os,Ls,Zh]},js={findFiberByHostInstance:ba,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},rx={bundleType:js.bundleType,version:js.version,rendererPackageName:js.rendererPackageName,rendererConfig:js.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=Po(h),h===null?null:h.stateNode},findFiberByHostInstance:js.findFiberByHostInstance||ex,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 Dc=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Dc.isDisabled&&Dc.supportsFiber)try{Sr=Dc.inject(rx),ji=Dc}catch{}}return Ds.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=wm,Ds.createPortal=function(h,v){var T=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!ap(v))throw Error(i(200));return zy(h,v,null,T)},Ds.createRoot=function(h,v){if(!ap(h))throw Error(i(299));var T=!1,I="",G=tx;return v!=null&&(v.unstable_strictMode===!0&&(T=!0),v.identifierPrefix!==void 0&&(I=v.identifierPrefix),v.onRecoverableError!==void 0&&(G=v.onRecoverableError)),v=rp(h,1,!1,null,null,T,!1,I,G),h[Ks]=v.current,uc(h.nodeType===8?h.parentNode:h),new op(v)},Ds.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(i(188)):(h=Object.keys(h).join(","),Error(i(268,h)));return h=Po(v),h=h===null?null:h.stateNode,h},Ds.flushSync=function(h){return $a(h)},Ds.hydrate=function(h,v,T){if(!Qd(v))throw Error(i(200));return jc(null,h,v,!0,T)},Ds.hydrateRoot=function(h,v,T){if(!ap(h))throw Error(i(405));var I=T!=null&&T.hydratedSources||null,G=!1,X="",he=tx;if(T!=null&&(T.unstable_strictMode===!0&&(G=!0),T.identifierPrefix!==void 0&&(X=T.identifierPrefix),T.onRecoverableError!==void 0&&(he=T.onRecoverableError)),v=Qv(v,null,h,1,T??null,G,!1,X,he),h[Ks]=v.current,uc(h),I)for(h=0;h<I.length;h++)T=I[h],G=T._getVersion,G=G(T._source),v.mutableSourceEagerHydrationData==null?v.mutableSourceEagerHydrationData=[T,G]:v.mutableSourceEagerHydrationData.push(T,G);return new Cl(v)},Ds.render=function(h,v,T){if(!Qd(v))throw Error(i(200));return jc(null,h,v,!1,T)},Ds.unmountComponentAtNode=function(h){if(!Qd(h))throw Error(i(40));return h._reactRootContainer?($a(function(){jc(null,null,h,!1,function(){h._reactRootContainer=null,h[Ks]=null})}),!0):!1},Ds.unstable_batchedUpdates=Zh,Ds.unstable_renderSubtreeIntoContainer=function(h,v,T,I){if(!Qd(T))throw Error(i(200));if(h==null||h._reactInternals===void 0)throw Error(i(38));return jc(h,v,T,!1,I)},Ds.version="18.3.1-next-f1338f8080-20240426",Ds}var rS;function eT(){if(rS)return Hy.exports;rS=1;function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}return n(),Hy.exports=LA(),Hy.exports}var sS;function zA(){if(sS)return ox;sS=1;var n=eT();return ox.createRoot=n.createRoot,ox.hydrateRoot=n.hydrateRoot,ox}var BA=zA();const FA=cy(BA);var M=S0();const Rt=cy(M),oS=n=>{let e;const i=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),i.forEach(y=>y(e,b))}},s=()=>e,l={setState:r,getState:s,getInitialState:()=>c,subscribe:p=>(i.add(p),()=>i.delete(p))},c=e=n(r,s,l);return l},GA=(n=>n?oS(n):oS),UA=n=>n;function HA(n,e=UA){const i=Rt.useSyncExternalStore(n.subscribe,Rt.useCallback(()=>e(n.getState()),[n,e]),Rt.useCallback(()=>e(n.getInitialState()),[n,e]));return Rt.useDebugValue(i),i}const aS=n=>{const e=GA(n),i=r=>HA(e,r);return Object.assign(i,e),i},Ti=(n=>n?aS(n):aS);function Ya(n){return"'"+n.replace(/'/g,"'\\''")+"'"}const qy=({sessionId:n})=>`claude --dangerously-skip-permissions --session-id ${Ya(n)}`,lS=({sessionId:n})=>`claude --session-id ${Ya(n)}`,WA=()=>"claude --resume",tT=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:qy},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:lS},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:qy},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:qy},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:lS},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:WA},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let bo=null;async function VA(){if(bo)return bo;try{const n=await window.api.app.engageRulesPath();if(!n)return bo=[],bo;const e=await window.api.config.readJson(n);if(!e.exists||e.parseError||!e.data)return bo=[],bo;const i=e.data;if(!i.presets||!Array.isArray(i.presets))return bo=[],bo;const r=i.projectPath;return bo=i.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 ${Ya(r)} && ${s.cliEntry}`})),bo}catch(n){return console.warn("[presets] Failed to load engage presets:",n),bo=[],bo}}async function nT(n){const e=tT.find(r=>r.id===n);return e||((await VA()).find(r=>r.id===n)??null)}async function cS(n){return n.cwd==="app-cwd"?window.api.app.cwd():n.cwd==="home"?window.api.app.homeDir():n.cwd==="pick"?window.api.app.pickDirectory():n.cwd}function iT(n,e){return n.command?n.command(e):null}const rT=["opus","sonnet","haiku"],sT="sm.rawSessionModel",qA="opus";function KA(n){return rT.includes(n)}function YA(){try{const n=localStorage.getItem(sT);if(n&&KA(n))return n}catch{}return qA}let Sp=YA();const iw=new Set;function k0(){return Sp}function XA(n){if(n!==Sp){Sp=n;try{localStorage.setItem(sT,n)}catch{}iw.forEach(e=>e(n))}}function JA(){const[n,e]=M.useState(Sp);M.useEffect(()=>{const r=s=>e(s);return iw.add(r),Sp!==n&&e(Sp),()=>{iw.delete(r)}},[]);const i=M.useCallback(r=>XA(r),[]);return{model:n,setModel:i}}async function dy(n,e){const i=await window.api.transcripts.pathFor(n,e);return window.api.config.exists(i)}const ZA=5,dS=100,QA=5e3,rw=new Map;function uS(n){const e=rw.get(n);e!==void 0&&(clearTimeout(e),rw.delete(n))}function e$(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const cu=Ti((n,e)=>({toasts:[],history:[],unreadCount:0,show:(i,r)=>{const s=e$(),a=Date.now();n(l=>{const c=[...l.toasts,{id:s,kind:i,message:r,createdAt:a}];for(;c.length>ZA;){const f=c.shift();f&&uS(f.id)}const m=[{id:s,kind:i,message:r,createdAt:a,read:!1},...l.history];return m.length>dS&&(m.length=dS),{toasts:c,history:m,unreadCount:l.unreadCount+1}});const d=setTimeout(()=>e().dismiss(s),QA);return rw.set(s,d),s},dismiss:i=>{uS(i),n(r=>({toasts:r.toasts.filter(s=>s.id!==i)}))},markAllRead:()=>{n(i=>i.unreadCount===0?i:{history:i.history.map(r=>r.read?r:{...r,read:!0}),unreadCount:0})},clearHistory:()=>{n({history:[],unreadCount:0})},dismissHistoryEntry:i=>{n(r=>{const s=r.history.filter(d=>d.id!==i);if(s.length===r.history.length)return r;const a=r.history.find(d=>d.id===i&&!d.read);return{history:s,unreadCount:a?Math.max(0,r.unreadCount-1):r.unreadCount}})}})),Be={info:n=>cu.getState().show("info",n),warn:n=>cu.getState().show("warn",n),error:n=>cu.getState().show("error",n),fromOutcome:n=>cu.getState().show(n.kind??(n.ok?"info":"warn"),n.message)},oT=Object.freeze(Object.defineProperty({__proto__:null,toast:Be,useToast:cu},Symbol.toStringTag,{value:"Module"}));async function t$(n){var e,i;if(typeof window>"u"||typeof((i=(e=window.api)==null?void 0:e.chat)==null?void 0:i.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:n})==="develop"?"develop":"inline"}catch{return"inline"}}const n$={feature:{bg:"bg-sage/20",text:"text-sage",border:!0,label:"Feature"},bug:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"Bug"},discussion:{bg:"bg-butter/25",text:"text-fg-dim",border:!0,label:"Discussion"}};function i$(n){return n$[n]}function r$(n){return n==="discussion"}function s$(n,e){return`${n.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/${e}.json`}function C0(n){return`${n.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/active-index.json`}function hS(n,e){const i=Date.parse(n.at),r=Date.parse(e.at),s=!Number.isNaN(i),a=!Number.isNaN(r);return s&&a&&i!==r?i-r:e.causedByEventId===n.id?-1:n.causedByEventId===e.id?1:s&&a?0:s?-1:a?1:0}let pS=0;function Ky(n){return pS+=1,`${n}-${Date.now().toString(36)}-${pS}`}const fS=new Map,og=new Map;function o$(n){return(og.get(n)??0)>0}function Cm(n,e,i){var l,c;if(typeof window>"u"||!((c=(l=window.api)==null?void 0:l.config)!=null&&c.writeJson))return;const r={sessions:Object.fromEntries(Object.entries(e).filter(([,p])=>p.cwd===n&&(p.status==="active"||p.status==="proposed"))),events:{}};for(const p of Object.keys(r.sessions))r.events[p]=i[p]??[];const s=C0(n);og.set(s,(og.get(s)??0)+1);const d=(fS.get(s)??Promise.resolve()).then(()=>window.api.config.writeJson(s,r,"epics")).then(()=>{},p=>{var f,b;const m=p instanceof Error?p.message:String(p);(b=(f=window.api)==null?void 0:f.logs)==null||b.write("promptSessions","warn",`persistActiveIndex failed for ${n}: ${m}`)}).finally(()=>{og.set(s,Math.max(0,(og.get(s)??1)-1))});fS.set(s,d)}const yn=Ti((n,e)=>({sessions:{},events:{},createPromptSession:(i,r,s,a="active")=>{const d=new Date().toISOString(),l={id:Ky("psess"),cwd:i,goalText:r,claudeSessionId:crypto.randomUUID(),status:a,createdAt:d,completedAt:null,...s?{tag:s}:{}},c={id:Ky("pevt"),promptSessionId:l.id,kind:"prompt",causedByEventId:null,at:d,text:r},p={...e().sessions,[l.id]:l},m={...e().events,[l.id]:[c]};return n({sessions:p,events:m}),Cm(i,p,m),l},approveProposed:i=>{const r=e().sessions[i];if(!r||r.status!=="proposed")return null;const s={...r,status:"active"},a={...e().sessions,[i]:s};return n({sessions:a}),Cm(r.cwd,a,e().events),s},appendPromptSessionEvent:(i,r)=>{if(!e().sessions[i])throw new Error(`appendPromptSessionEvent: no PromptSession with id "${i}"`);const s=e().events[i]??[],a=s[s.length-1]??null;if(r.causedByEventId!==null){if(!a||r.causedByEventId!==a.id)throw new Error(`appendPromptSessionEvent: causedByEventId "${r.causedByEventId}" does not reference the current tail event of promptSession "${i}"`)}else if(s.length>0)throw new Error(`appendPromptSessionEvent: causedByEventId may only be null for a session's first event (promptSession "${i}" already has ${s.length})`);if(r.kind==="prd_created"&&!r.prdSlug)throw new Error("appendPromptSessionEvent: kind 'prd_created' requires prdSlug");const d={...r,id:Ky("pevt"),promptSessionId:i,at:new Date().toISOString()},l={...e().events,[i]:[...s,d]};n({events:l});const c=e().sessions[i];return Cm(c.cwd,e().sessions,l),d},markCompleted:async i=>{var f;const r=e().sessions[i];if(!r)throw new Error(`markCompleted: no PromptSession with id "${i}"`);if(r.status==="completed")return;await window.api.chat.cancel(i),window.api.pty.kill(r.claudeSessionId);const s=((f=e().events[i])==null?void 0:f.slice(-1)[0])??null;s&&e().appendPromptSessionEvent(i,{kind:"closed",causedByEventId:s.id});const a=new Date().toISOString(),d={...r,status:"completed",completedAt:a},l={...e().sessions,[i]:d};n({sessions:l}),Cm(r.cwd,l,e().events);let c="";try{const b=await window.api.transcripts.pathFor(r.cwd,r.claudeSessionId),y=await window.api.config.readText(b);c=y.exists?y.text:""}catch{c=""}let p;if(!c)try{const{turns:b}=await window.api.promptSessionTranscript.read(r.cwd,i);b.length>0&&(p=b.map(y=>({role:y.role,text:y.text,at:y.at})))}catch{p=void 0}const m={session:d,events:e().events[i]??[],transcript:c,archivedAt:a,...p?{durableTurns:p}:{}};await window.api.config.writeJson(s$(r.cwd,i),m,"epics")},resumeArchived:i=>{const r=e().sessions[i];if(!r)throw new Error(`resumeArchived: no PromptSession with id "${i}"`);const s=e().createPromptSession(r.cwd,r.goalText),a={...s,resumedFromId:i},d={...e().sessions,[s.id]:a};return n({sessions:d}),Cm(s.cwd,d,e().events),a},hydrate:async i=>{var r,s,a,d;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.readJson)))try{const l=C0(i),c=await window.api.config.readJson(l),p=c.exists&&c.data?c.data:{},m=p.sessions??{},f=p.events??{},b=e().sessions,y=Object.keys(m).filter(S=>!b[S]),_=o$(l)?[]:Object.keys(b).filter(S=>b[S].cwd===i&&(b[S].status==="active"||b[S].status==="proposed")&&!m[S]),k={...b},x={...e().events};let w=!1;for(const S of y)k[S]=m[S],x[S]=f[S]??[],w=!0;for(const S of _)delete k[S],delete x[S],w=!0;for(const S of Object.keys(f)){if(!b[S]||y.includes(S))continue;const E=f[S]??[],j=x[S]??[],D=new Set(j.map(P=>P.id)),$=E.filter(P=>!D.has(P.id));$.length>0&&(x[S]=[...j,...$].sort(hS),w=!0)}if(!w)return;n({sessions:k,events:x})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("promptSessions","warn",`hydrate failed for ${i}: ${c}`)}},hydrateArchived:async i=>{var r,s,a,d,l,c;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.listDir)||!((d=(a=window.api)==null?void 0:a.config)!=null&&d.readJson)))try{const p=`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions`,m=await window.api.config.listDir(p,{filesOnly:!0});if(!m.ok)return;const b={...e().sessions},y={...e().events};let _=!1;for(const k of m.entries){if(!k.name.endsWith(".json")||k.name==="active-index.json")continue;const x=k.name.slice(0,-5);if(b[x])continue;const w=await window.api.config.readJson(k.path);if(!w.exists||!w.data)continue;const S=w.data;!S.session||S.session.id!==x||(b[x]={...S.session,status:"completed"},y[x]=S.events??[],_=!0)}if(!_)return;n({sessions:b,events:y})}catch(p){const m=p instanceof Error?p.message:String(p);(c=(l=window.api)==null?void 0:l.logs)==null||c.write("promptSessions","warn",`hydrateArchived failed for ${i}: ${m}`)}},mergeAppendedEvent:(i,r,s)=>{const a=e().sessions[r];if(!a||a.cwd!==i)return;const d=e().events[r]??[];if(d.some(c=>c.id===s.id))return;const l={...e().events,[r]:[...d,s].sort(hS)};n({events:l})}}));var ZE;typeof window<"u"&&((ZE=window.api)!=null&&ZE.promptSessions)&&window.api.promptSessions.onEventAppended(({cwd:n,promptSessionId:e,event:i})=>{yn.getState().mergeAppendedEvent(n,e,i)});const fu=Ti((n,e)=>({modes:{},attached:{},setMode:(i,r)=>n(s=>({modes:{...s.modes,[i]:r}})),setAttached:(i,r)=>n(s=>({attached:{...s.attached,[i]:r}})),isAttached:i=>!!e().attached[i]})),Yc={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},mS=20;function Sb(n,e){const i=[...n,e];return i.length>mS?i.slice(i.length-mS):i}let gS=0;function Zc(){return gS+=1,`t${Date.now().toString(36)}-${gS}`}const vS=60;function aT(n){const e=n.trim();if(e.length<=vS)return e;const i=e.slice(0,vS),r=i.lastIndexOf(" ");return(r>0?i.slice(0,r):i).trim()}const zn=Ti((n,e)=>({chats:{},hydratedTabs:{},get:i=>e().chats[i]??Yc,hydrate:async({tabId:i,cwd:r,sessionId:s})=>{var a,d,l;if(!e().hydratedTabs[i]&&(n({hydratedTabs:{...e().hydratedTabs,[i]:!0}}),!(typeof window>"u"||!((a=window.api)!=null&&a.exchanges))))try{const c=await window.api.exchanges.list({cwd:r,sessionId:s});if(!c.length)return;const p=[];for(const f of[...c].reverse()){const b=new Date(f.ts).getTime();p.push({id:Zc(),role:"user",text:f.prompt,at:b}),p.push({id:Zc(),role:"assistant",text:f.result,at:b})}const m=e().chats[i]??Yc;n({chats:{...e().chats,[i]:{...m,turns:[...p,...m.turns],started:!0}}})}catch(c){const p=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`exchange hydration failed for tab ${i}: ${p}`)}},send:({tabId:i,sessionId:r,cwd:s,prompt:a,tag:d,chainRootId:l,external:c})=>{const p=a.trim();if(!p)return;if(fu.getState().isAttached(i)){Be.error("Terminal mode is active for this Epic — switch back to Chat to send a message.");return}const m=e().chats[i]??Yc;if(m.running){const f={id:crypto.randomUUID(),tabId:i,sessionId:r,cwd:s,text:p,status:"queued",createdAt:Date.now(),tag:d,chainRootId:l,external:c};n({chats:{...e().chats,[i]:{...m,queue:[...m.queue,f]}}});return}a$(i),lT({tabId:i,sessionId:r,cwd:s,text:p,tag:d,chainRootId:l})},resetThread:i=>{n({chats:{...e().chats,[i]:{...Yc}}})},pushNotice:(i,r)=>{kb(i,"",r)},setPendingVoiceText:(i,r)=>{as(i,s=>({...s,pendingVoiceText:r}))},clearPendingVoiceText:i=>{as(i,r=>({...r,pendingVoiceText:void 0}))}}));function as(n,e){const i=zn.getState().chats[n]??Yc;zn.setState({chats:{...zn.getState().chats,[n]:e(i)}})}function eb(n,e,i={},r="done",s={}){as(n,a=>{const d=a.activeTicket?Sb(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:d,...i}}),sw(n)}function a$(n){as(n,e=>{const i=e.ticketHistory??[];return i.some(r=>r.status==="needs-input")?{...e,ticketHistory:i.map(r=>r.status==="needs-input"?{...r,status:"done"}:r)}:e})}function lT(n){const{tabId:e,sessionId:i,cwd:r,text:s,promptId:a,tag:d,chainRootId:l}=n,c=zn.getState().chats[e]??Yc,p={id:Zc(),role:"user",text:s,at:Date.now()};ow(e,"user",s);const m=c.activeTicket??{id:a??crypto.randomUUID(),tabId:e,sessionId:i,cwd:r,text:s,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:d,chainRootId:l};zn.setState({chats:{...zn.getState().chats,[e]:{...c,turns:[...c.turns,p],running:!0,queuedPosition:0,stream:"",activeTicket:m}}}),dy(r,i).catch(f=>{var y,_;const b=f instanceof Error?f.message:String(f);return(_=(y=window.api)==null?void 0:y.logs)==null||_.write("chat","warn",`transcript-exists check failed for tab ${e}: ${b}`),c.started}).then(f=>window.api.chat.run({tabId:e,sessionId:i,prompt:s,cwd:r,resume:f,promptId:a})).catch(f=>{const b=f instanceof Error?f.message:String(f);dT(e,i,b)})}function sw(n){const e=zn.getState().chats[n]??Yc;if(e.queue.length===0)return;const[i,...r]=e.queue;if(as(n,s=>({...s,queue:r,running:!0,queuedPosition:0,activeTicket:i})),i.external){Yy(n,i);return}if(r$(i.tag)){Yy(n,i);return}t$(i.text).then(s=>{if(s==="develop"){d$(n,i);return}Yy(n,i)})}function Yy(n,e){const i={...e,status:"running",startedAt:Date.now()};as(n,r=>({...r,activeTicket:i})),lT({tabId:i.tabId,sessionId:i.sessionId,cwd:i.cwd,text:i.text,promptId:i.id,tag:i.tag,chainRootId:i.chainRootId})}function cT(n,e){var i,r,s,a,d;try{const l=(i=yn.getState().events[n])==null?void 0:i.slice(-1)[0];if(!l){(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendPrdCreatedEvent: PromptSession ${n} has no tail event — skipping prd_created append for ${e}`);return}yn.getState().appendPromptSessionEvent(n,{kind:"prd_created",causedByEventId:l.id,prdSlug:e})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("chat","warn",`appendPrdCreatedEvent failed for ${n}: ${c}`)}}const xS=2e3;function ow(n,e,i){var s,a,d,l;const r=yn.getState().sessions[n];if(r)try{(a=(s=window.api)==null?void 0:s.promptSessionTranscript)==null||a.append(r.cwd,n,{role:e,text:i})}catch(c){const p=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`capturePromptSessionTurn failed for ${n}: ${p}`)}}function bS(n,e){var i,r,s;try{const a=(i=yn.getState().events[n])==null?void 0:i.slice(-1)[0];if(!a)return;const d=e.length>xS?`${e.slice(0,xS)}…`:e;yn.getState().appendPromptSessionEvent(n,{kind:"response",causedByEventId:a.id,text:d})}catch(a){const d=a instanceof Error?a.message:String(a);(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendResponseEvent failed for ${n}: ${d}`)}}async function l$(n,e,i,r){try{const s=await window.api.chat.createPrd({title:aT(i),cwd:e,estimateMinutes:15,goal:i,acceptanceCriteria:["Implement the request described in Goal.","timeout 300 npm run typecheck passes"],implementationNotes:`Target project: ${e}`,sourcePromptId:n,tag:r});if(!(s!=null&&s.ok))return Be.error(`PRD authoring failed: ${(s==null?void 0:s.error)??"unknown error"}`),null;const a=s.filename,d=a.endsWith(".md")?a.slice(0,-3):a;return cT(n,d),d}catch(s){const a=s instanceof Error?s.message:String(s);return Be.error(`PRD authoring failed: ${a}`),null}}function c$(n,e){var i,r;if(e.chainRootId){const a=((zn.getState().chats[n]??Yc).ticketHistory??[]).find(d=>d.id===e.chainRootId);if(a!=null&&a.promptSessionId)return a.promptSessionId;(r=(i=window.api)==null?void 0:i.logs)==null||r.write("chat","warn",`continuation ticket ${e.id}: no resolvable PromptSession for chainRootId ${e.chainRootId} — minting a new one`)}return yn.getState().createPromptSession(e.cwd,e.text).id}function d$(n,e){const i=s=>{as(n,a=>({...a,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:Sb(a.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),kb(n,e.sessionId,s),Be.error(s),sw(n)},r=c$(n,e);window.api.chat.createPrd({title:aT(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:r,sourceTabId:e.tabId,tag:e.tag}).then(s=>{if(!(s!=null&&s.ok)){i(`→ PRD authoring failed for ticket ${e.id}: ${(s==null?void 0:s.error)??"unknown error"}`);return}const a=s.filename,d=a.endsWith(".md")?a.slice(0,-3):a;cT(r,d);const l={...e,status:"dispatched-to-prd",completedAt:Date.now(),promptSessionId:r,...e.chainRootId?{}:{prdSlugs:[d]}};kb(n,l.sessionId,`→ dispatched to PRD ${a} (ticket ${l.id})`),as(n,c=>{let p=Sb(c.ticketHistory??[],l);if(e.chainRootId){const m=e.chainRootId;p=p.map(f=>f.id===m?{...f,prdSlugs:[...f.prdSlugs??[],d]}:f)}return{...c,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:p}}),sw(n)}).catch(s=>{const a=s instanceof Error?s.message:String(s);i(`→ PRD authoring failed for ticket ${e.id}: ${a}`)})}function dT(n,e,i){as(n,r=>r.activeTicket?{...r,activeTicket:null,ticketHistory:Sb(r.ticketHistory??[],{...r.activeTicket,status:"failed",completedAt:Date.now()})}:r),eb(n,{id:Zc(),role:"error",text:i,at:Date.now()}),Be.error(i)}function kb(n,e,i){as(n,r=>({...r,turns:[...r.turns,{id:Zc(),role:"notice",text:i,at:Date.now()}]}))}var QE;typeof window<"u"&&((QE=window.api)!=null&&QE.chat)&&(window.api.chat.onQueued(({tabId:n,position:e})=>{as(n,i=>({...i,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:n})=>{as(n,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:n,delta:e})=>{as(n,i=>({...i,stream:i.stream+e}))}),window.api.chat.onToolUse(({tabId:n,id:e,kind:i,label:r})=>{as(n,s=>({...s,liveToolUses:[...s.liveToolUses,{id:e,kind:i,label:r}]}))}),window.api.chat.onComplete(({tabId:n,finalMessage:e})=>{ow(n,"assistant",e),bS(n,e),eb(n,{id:Zc(),role:"assistant",text:e,at:Date.now()})}),window.api.chat.onNeedsInput(({tabId:n,questions:e,answerBody:i})=>{const r=Zc();if(i&&i.trim()){ow(n,"assistant",i),bS(n,i),as(n,s=>({...s,turns:[...s.turns,{id:Zc(),role:"assistant",text:i,at:Date.now(),toolUses:s.liveToolUses}],liveToolUses:[]})),eb(n,{id:r,role:"question",text:e.join(`
42
42
  `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r});return}eb(n,{id:r,role:"question",text:e.join(`
43
- `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{dT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{kb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=bt.getState().tabs.find(c=>c.id===n);if(i){zn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=yn.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}zn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function u$(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function uT(n,e=!1,i=k0()){let r=!e;r&&(r=await dy(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Ya(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Ya(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const bt=Ti((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??u$(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{});const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?nT(r.presetId).then(d=>{a(d?iT(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=zn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Be.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await uT({cwd:s.cwd,sessionId:s.sessionId},!1,r??k0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function aw(){var i;if(bt.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 uT(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),c=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;bt.getState().restoreTabs(l,c)}else bt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),bt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=bt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;bt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const h$=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:aw,useSessions:bt},Symbol.toStringTag,{value:"Module"})),yS=200,p$=/\x1b\[[0-9;]*m/g;function f$(n){return n.replace(p$,"")}const gg=Ti((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Be.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Be.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=f$(i.line),a=r.lines.length>=yS?[...r.lines.slice(r.lines.length-yS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),m$="~/.claude/session-manager/browser/history.json",_S="~/.claude/session-manager/browser/bookmarks.json",g$=.25,v$=3,wS=.1,SS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let kS=0;function x$(){const n=SS[kS%SS.length];return kS+=1,n}const Cb=new Map;function b$(n){if(Cb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Cb.set(n,e)}function y$(n){const e=Cb.get(n);e&&(e(),Cb.delete(n))}const lw=new Map;let tb=null;function CS(n){const e=lw.get(n);e&&(e(),lw.delete(n))}function ES(){tb&&(clearInterval(tb),tb=null)}const cw=new Map;function Xy(n){const e=cw.get(n);e&&(e(),cw.delete(n))}const Pt=Ti((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??x$(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),b$(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,p;const l=d instanceof Error?d.message:String(d);(p=(c=window.api)==null?void 0:c.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(y$(r.viewId),Xy(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),CS(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});lw.set(i,r),ES(),tb=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),CS(i),ES(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(_S),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(_S,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(m$),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(v$,Math.max(g$,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+wS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-wS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),Xy(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});cw.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(Xy(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({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:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),lp=["home"],Em=["project"],jl=["home","project"],E0=[{key:"project-home",group:"Workspace",label:"Home",icon:"home",hint:"What this project is, and what is in flight",faces:Em},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics, grouped by project",faces:jl},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:lp},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project",faces:Em},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs",faces:jl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:jl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:jl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:jl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:lp},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:jl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:jl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:lp},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Em},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:jl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:jl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:lp},{key:"sm-config",group:"Configure",label:"Session-Manager",icon:"settings",hint:"Global session pool, guardrails, scheduler policy",faces:lp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:lp},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:Em},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:Em}];function _$(n){return E0.filter(e=>e.faces.includes(n))}const w$=Object.fromEntries(E0.map(n=>[n.key,n.group])),Jy={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."},hT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","sm-config","voice","repoviz","search","editor"],S$={editor:"Editor"},k$=Object.fromEntries(E0.map(n=>[n.key,n.label])),C$=Object.fromEntries(hT.map(n=>[n,S$[n]??k$[n]??n])),pT="~/.claude/session-manager/app-prefs.json";async function T0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(pT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function E$(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await T0();await window.api.config.writeJson(pT,{...e,...n})}const du=hT.map(n=>({id:n,title:C$[n],component:"screen"})),bn=Ti((n,e)=>{var i;return{panels:[...du],focusedPanelId:((i=du[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=du[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1}})},hydrateOpenToHomePref:async()=>{var s;(await T0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=du[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview"})}}});function T$(n){return bn.getState().panels.find(e=>e.id===n)}function j$(n,e){return n==="projects"&&e===null}function an({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){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"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});default:return null}}const D$=4,TS=40,jS=6;function N$(n){const{onReorder:e,onActivate:i}=n,r=M.useRef(null),s=M.useRef(null),a=M.useRef(0),d=M.useRef(0),[l,c]=M.useState(!1),[,p]=M.useState(0),m=M.useRef(i);m.current=i;const f=M.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=M.useCallback((x,w,S)=>{for(let E=0;E<w.length;E++){const j=w[E].left+w[E].width/2;if(x<j)return E<=S?E:E-1}return w.length-1},[]),y=M.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-S.left,D=S.right-E;j<TS?w.scrollLeft-=jS:D<TS&&(w.scrollLeft+=jS),a.current=requestAnimationFrame(y)},[]);M.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,p(D=>D+1)}))},E=D=>{var B;const $=s.current;if(!$)return;const P=D.clientX-$.startX;if(!$.active&&Math.abs(P)<D$)return;if(!$.active){$.active=!0,$.tabRects=f().map(U=>U.getBoundingClientRect()),c(!0);try{(B=r.current)==null||B.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(y)}$.deltaX=P;const R=$.tabRects[$.fromIndex],O=R.left+R.width/2+P;$.currentIndex=b(O,$.tabRects,$.fromIndex),S()},j=D=>{const $=s.current;if($&&$.pointerId===D.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,c(!1),p(P=>P+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(d.current)}},[e,f,b,y]);const _=M.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:M.useCallback(x=>{var E;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const j=w.fromIndex,D=w.currentIndex,P=(((E=w.tabRects[j])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",j<D&&x>j&&x<=D?S.transform=`translateX(-${P}px)`:j>D&&x>=D&&x<j?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:j=>_(j,x),style:S,"data-drag-index":x}},[_]),isDragging:l,containerRef:r}}const A$=3e4;function $$({onToggleSplitView:n,splitViewActive:e}={}){const i=bt(D=>D.tabs),r=bt(D=>D.activeTabId),s=bt(D=>D.closeTab),a=bt(D=>D.setActive),d=bt(D=>D.reorderTab),l=gg(D=>D.watchers),c=Pt(D=>D.tabs.length>0),p=r!=null&&c,m=bn(D=>D.focusedPanelId),f=bn(D=>D.openPanel),b=bn(D=>D.setEpicsWorkspaceOpen),y=m==="overview",[_,k]=M.useState(()=>Date.now());M.useEffect(()=>{const D=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(D)},[]);const x=D=>{for(const $ of Object.values(l))if($.tabId===D&&$.lastLineAt&&_-$.lastLineAt<A$)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:E}=N$({tabCount:i.length,onReorder:d,onActivate:D=>{const $=i[D];$&&(a($.id),b(!1),f("terminal"))}}),j=["#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.jsxs("button",{onClick:()=>f("overview"),title:"This machine — home","aria-current":y?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${y?"bg-bg text-fg font-medium relative z-10 -mb-px shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((D,$)=>{const P=D.id===r,R=w($),O=j[$%j.length];return o.jsxs("div",{...R,style:R.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 ${S?"":"cursor-grab"} ${P?"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:D.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:D.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:D.label}),D.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(D.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:B=>{B.stopPropagation(),s(D.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${D.label}`,children:"×"})]},D.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&n&&o.jsxs("button",{onClick:n,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.45.0"]})]})]})}var Zy={},Tm={},DS;function fT(){if(DS)return Tm;DS=1,Object.defineProperty(Tm,"__esModule",{value:!0}),Tm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Tm.baseAssetPath=i,Tm}var jm={},NS;function j0(){if(NS)return jm;NS=1,Object.defineProperty(jm,"__esModule",{value:!0}),jm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return jm.defaultModelFetcher=n,jm}var Dl={},Dm={},AS;function Kg(){if(AS)return Dm;AS=1,Object.defineProperty(Dm,"__esModule",{value:!0}),Dm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Dm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Dm}var Nm={},$S;function uy(){if($S)return Nm;$S=1,Object.defineProperty(Nm,"__esModule",{value:!0}),Nm.Message=void 0;var n;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"})(n||(Nm.Message=n={})),Nm}var PS;function D0(){if(PS)return Dl;PS=1,Object.defineProperty(Dl,"__esModule",{value:!0}),Dl.FrameProcessor=Dl.validateOptions=Dl.defaultFrameProcessorOptions=void 0;const n=Kg(),e=uy();Dl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}Dl.validateOptions=i;const r=d=>{const l=d.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),c=new Float32Array(l.at(-1));return d.forEach((p,m)=>{const f=l[m];c.set(p,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),p=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,c,p,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=_=>{this.options={...this.options,..._};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=_=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(_):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=_=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));_({msg:e.Message.SpeechEnd,audio:S})}else _({msg:e.Message.VADMisfire});return{}},this.process=async(_,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(_),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:_}),this.audioBuffer.push({frame:_,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({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 S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((j,D)=>D.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(S.map(D=>D.frame));k({msg:e.Message.SpeechEnd,audio:j})}else k({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:y}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=y,this.reset()}}return Dl.FrameProcessor=a,Dl}var Nl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Qy={exports:{}};/*!
43
+ `),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{dT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{kb(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=bt.getState().tabs.find(c=>c.id===n);if(i){zn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=yn.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}zn.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function u$(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function uT(n,e=!1,i=k0()){let r=!e;r&&(r=await dy(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Ya(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Ya(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const bt=Ti((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??u$(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{});const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?nT(r.presetId).then(d=>{a(d?iT(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=zn.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Be.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await uT({cwd:s.cwd,sessionId:s.sessionId},!1,r??k0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function aw(){var i;if(bt.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 uT(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),c=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;bt.getState().restoreTabs(l,c)}else bt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),bt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=bt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;bt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const h$=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:aw,useSessions:bt},Symbol.toStringTag,{value:"Module"})),yS=200,p$=/\x1b\[[0-9;]*m/g;function f$(n){return n.replace(p$,"")}const gg=Ti((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Be.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Be.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=f$(i.line),a=r.lines.length>=yS?[...r.lines.slice(r.lines.length-yS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),m$="~/.claude/session-manager/browser/history.json",_S="~/.claude/session-manager/browser/bookmarks.json",g$=.25,v$=3,wS=.1,SS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let kS=0;function x$(){const n=SS[kS%SS.length];return kS+=1,n}const Cb=new Map;function b$(n){if(Cb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Cb.set(n,e)}function y$(n){const e=Cb.get(n);e&&(e(),Cb.delete(n))}const lw=new Map;let tb=null;function CS(n){const e=lw.get(n);e&&(e(),lw.delete(n))}function ES(){tb&&(clearInterval(tb),tb=null)}const cw=new Map;function Xy(n){const e=cw.get(n);e&&(e(),cw.delete(n))}const Pt=Ti((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??x$(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),b$(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,p;const l=d instanceof Error?d.message:String(d);(p=(c=window.api)==null?void 0:c.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(y$(r.viewId),Xy(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),CS(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});lw.set(i,r),ES(),tb=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),CS(i),ES(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(_S),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(_S,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(m$),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(v$,Math.max(g$,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+wS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-wS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),Xy(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});cw.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(Xy(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({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:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),lp=["home"],Em=["project"],jl=["home","project"],E0=[{key:"project-home",group:"Workspace",label:"Home",icon:"home",hint:"What this project is, and what is in flight",faces:Em},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics, grouped by project",faces:jl},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:lp},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project",faces:Em},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs",faces:jl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:jl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:jl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:jl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:lp},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:jl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:jl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:lp},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Em},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:jl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:jl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:lp},{key:"sm-config",group:"Configure",label:"Session-Manager",icon:"settings",hint:"Global session pool, guardrails, scheduler policy",faces:lp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:lp},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:Em},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:Em}];function _$(n){return E0.filter(e=>e.faces.includes(n))}const w$=Object.fromEntries(E0.map(n=>[n.key,n.group])),Jy={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."},hT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","sm-config","voice","repoviz","search","editor"],S$={editor:"Editor"},k$=Object.fromEntries(E0.map(n=>[n.key,n.label])),C$=Object.fromEntries(hT.map(n=>[n,S$[n]??k$[n]??n])),pT="~/.claude/session-manager/app-prefs.json";async function T0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(pT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function E$(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await T0();await window.api.config.writeJson(pT,{...e,...n})}const du=hT.map(n=>({id:n,title:C$[n],component:"screen"})),bn=Ti((n,e)=>{var i;return{panels:[...du],focusedPanelId:((i=du[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=du[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1}})},hydrateOpenToHomePref:async()=>{var s;(await T0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=du[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview"})}}});function T$(n){return bn.getState().panels.find(e=>e.id===n)}function j$(n,e){return n==="projects"&&e===null}function an({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){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"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});default:return null}}const D$=4,TS=40,jS=6;function N$(n){const{onReorder:e,onActivate:i}=n,r=M.useRef(null),s=M.useRef(null),a=M.useRef(0),d=M.useRef(0),[l,c]=M.useState(!1),[,p]=M.useState(0),m=M.useRef(i);m.current=i;const f=M.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=M.useCallback((x,w,S)=>{for(let E=0;E<w.length;E++){const j=w[E].left+w[E].width/2;if(x<j)return E<=S?E:E-1}return w.length-1},[]),y=M.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-S.left,D=S.right-E;j<TS?w.scrollLeft-=jS:D<TS&&(w.scrollLeft+=jS),a.current=requestAnimationFrame(y)},[]);M.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,p(D=>D+1)}))},E=D=>{var B;const $=s.current;if(!$)return;const P=D.clientX-$.startX;if(!$.active&&Math.abs(P)<D$)return;if(!$.active){$.active=!0,$.tabRects=f().map(U=>U.getBoundingClientRect()),c(!0);try{(B=r.current)==null||B.setPointerCapture($.pointerId)}catch{}a.current=requestAnimationFrame(y)}$.deltaX=P;const R=$.tabRects[$.fromIndex],O=R.left+R.width/2+P;$.currentIndex=b(O,$.tabRects,$.fromIndex),S()},j=D=>{const $=s.current;if($&&$.pointerId===D.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture($.pointerId)}catch{}$.active&&$.fromIndex!==$.currentIndex?e($.fromIndex,$.currentIndex):m.current($.fromIndex),s.current=null,c(!1),p(P=>P+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(d.current)}},[e,f,b,y]);const _=M.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:M.useCallback(x=>{var E;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const j=w.fromIndex,D=w.currentIndex,P=(((E=w.tabRects[j])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",j<D&&x>j&&x<=D?S.transform=`translateX(-${P}px)`:j>D&&x>=D&&x<j?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:j=>_(j,x),style:S,"data-drag-index":x}},[_]),isDragging:l,containerRef:r}}const A$=3e4;function $$({onToggleSplitView:n,splitViewActive:e}={}){const i=bt(D=>D.tabs),r=bt(D=>D.activeTabId),s=bt(D=>D.closeTab),a=bt(D=>D.setActive),d=bt(D=>D.reorderTab),l=gg(D=>D.watchers),c=Pt(D=>D.tabs.length>0),p=r!=null&&c,m=bn(D=>D.focusedPanelId),f=bn(D=>D.openPanel),b=bn(D=>D.setEpicsWorkspaceOpen),y=m==="overview",[_,k]=M.useState(()=>Date.now());M.useEffect(()=>{const D=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(D)},[]);const x=D=>{for(const $ of Object.values(l))if($.tabId===D&&$.lastLineAt&&_-$.lastLineAt<A$)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:E}=N$({tabCount:i.length,onReorder:d,onActivate:D=>{const $=i[D];$&&(a($.id),b(!1),f("terminal"))}}),j=["#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.jsxs("button",{onClick:()=>f("overview"),title:"This machine — home","aria-current":y?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${y?"bg-bg text-fg font-medium relative z-10 -mb-px shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((D,$)=>{const P=D.id===r,R=w($),O=j[$%j.length];return o.jsxs("div",{...R,style:R.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 ${S?"":"cursor-grab"} ${P?"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:D.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:D.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:D.label}),D.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(D.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:B=>{B.stopPropagation(),s(D.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${D.label}`,children:"×"})]},D.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&n&&o.jsxs("button",{onClick:n,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.45.1"]})]})]})}var Zy={},Tm={},DS;function fT(){if(DS)return Tm;DS=1,Object.defineProperty(Tm,"__esModule",{value:!0}),Tm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Tm.baseAssetPath=i,Tm}var jm={},NS;function j0(){if(NS)return jm;NS=1,Object.defineProperty(jm,"__esModule",{value:!0}),jm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return jm.defaultModelFetcher=n,jm}var Dl={},Dm={},AS;function Kg(){if(AS)return Dm;AS=1,Object.defineProperty(Dm,"__esModule",{value:!0}),Dm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Dm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Dm}var Nm={},$S;function uy(){if($S)return Nm;$S=1,Object.defineProperty(Nm,"__esModule",{value:!0}),Nm.Message=void 0;var n;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"})(n||(Nm.Message=n={})),Nm}var PS;function D0(){if(PS)return Dl;PS=1,Object.defineProperty(Dl,"__esModule",{value:!0}),Dl.FrameProcessor=Dl.validateOptions=Dl.defaultFrameProcessorOptions=void 0;const n=Kg(),e=uy();Dl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}Dl.validateOptions=i;const r=d=>{const l=d.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),c=new Float32Array(l.at(-1));return d.forEach((p,m)=>{const f=l[m];c.set(p,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),p=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,c,p,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=_=>{this.options={...this.options,..._};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=_=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(_):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=_=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));_({msg:e.Message.SpeechEnd,audio:S})}else _({msg:e.Message.VADMisfire});return{}},this.process=async(_,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(_),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:_}),this.audioBuffer.push({frame:_,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({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 S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((j,D)=>D.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(S.map(D=>D.frame));k({msg:e.Message.SpeechEnd,audio:j})}else k({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:y}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=y,this.reset()}}return Dl.FrameProcessor=a,Dl}var Nl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Qy={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 @@ ${L}`,F=C.createShaderModule({code:z,label:u.name});cn("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 GS;function z$(){return GS||(GS=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(se=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(se,{get:(me,_e)=>(typeof Eo<"u"?Eo:me)[_e]}):se)(function(se){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+se+'" is not supported')}),c=(se,me)=>()=>(se&&(me=se(se=0)),me),p=(se,me)=>{for(var _e in me)r(se,_e,{get:me[_e],enumerable:!0})},m=(se,me,_e,De)=>{if(me&&typeof me=="object"||typeof me=="function")for(let Ee of a(me))!d.call(se,Ee)&&Ee!==_e&&r(se,Ee,{get:()=>me[Ee],enumerable:!(De=s(me,Ee))||De.enumerable});return se},f=se=>m(r({},"__esModule",{value:!0}),se),b,y,_,k,x,w=c(()=>{b=new Map,y=[],_=(se,me,_e)=>{if(me&&typeof me.init=="function"&&typeof me.createInferenceSessionHandler=="function"){let De=b.get(se);if(De===void 0)b.set(se,{backend:me,priority:_e});else{if(De.priority>_e)return;if(De.priority===_e&&De.backend!==me)throw new Error(`cannot register backend "${se}" using priority ${_e}`)}if(_e>=0){let Ee=y.indexOf(se);Ee!==-1&&y.splice(Ee,1);for(let ze=0;ze<y.length;ze++)if(b.get(y[ze]).priority<=_e){y.splice(ze,0,se);return}y.push(se)}return}throw new TypeError("not a valid backend")},k=async se=>{let me=b.get(se);if(!me)return"backend not found.";if(me.initialized)return me.backend;if(me.aborted)return me.error;{let _e=!!me.initPromise;try{return _e||(me.initPromise=me.backend.init(se)),await me.initPromise,me.initialized=!0,me.backend}catch(De){return _e||(me.error=`${De}`,me.aborted=!0),me.error}finally{delete me.initPromise}}},x=async se=>{let me=se.executionProviders||[],_e=me.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=_e.length===0?y:_e,Ee,ze=[],Ae=new Set;for(let Fe of De){let et=await k(Fe);typeof et=="string"?ze.push({name:Fe,err:et}):(Ee||(Ee=et),Ee===et&&Ae.add(Fe))}if(!Ee)throw new Error(`no available backend found. ERR: ${ze.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of ze)_e.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let $e=me.filter(Fe=>Ae.has(typeof Fe=="string"?Fe:Fe.name));return[Ee,new Proxy(se,{get:(Fe,et)=>et==="executionProviders"?$e:Reflect.get(Fe,et)})]}}),S=c(()=>{w()}),E,j=c(()=>{E="1.26.0"}),D,$,P=c(()=>{j(),D="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(se){if(se!==void 0){if(typeof se!="string"||["verbose","info","warning","error","fatal"].indexOf(se)===-1)throw new Error(`Unsupported logging level: ${se}`);D=se}},get logLevel(){return D}},Object.defineProperty($,"logLevel",{enumerable:!0})}),R,O=c(()=>{P(),R=$}),B,U,J=c(()=>{B=(se,me)=>{let _e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_e.width=se.dims[3],_e.height=se.dims[2];let De=_e.getContext("2d");if(De!=null){let Ee,ze;(me==null?void 0:me.tensorLayout)!==void 0&&me.tensorLayout==="NHWC"?(Ee=se.dims[2],ze=se.dims[3]):(Ee=se.dims[3],ze=se.dims[2]);let Ae=(me==null?void 0:me.format)!==void 0?me.format:"RGB",$e=me==null?void 0:me.norm,Fe,et;$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?et=[0,0,0,0]:typeof $e.bias=="number"?et=[$e.bias,$e.bias,$e.bias,$e.bias]:(et=[$e.bias[0],$e.bias[1],$e.bias[2],0],$e.bias[3]!==void 0&&(et[3]=$e.bias[3]));let st=ze*Ee,tt=0,Ye=st,$t=st*2,Le=-1;Ae==="RGBA"?(tt=0,Ye=st,$t=st*2,Le=st*3):Ae==="RGB"?(tt=0,Ye=st,$t=st*2):Ae==="RBG"&&(tt=0,$t=st,Ye=st*2);for(let dt=0;dt<ze;dt++)for(let Pn=0;Pn<Ee;Pn++){let en=(se.data[tt++]-et[0])*Fe[0],tn=(se.data[Ye++]-et[1])*Fe[1],Rn=(se.data[$t++]-et[2])*Fe[2],Lt=Le===-1?255:(se.data[Le++]-et[3])*Fe[3];De.fillStyle="rgba("+en+","+tn+","+Rn+","+Lt+")",De.fillRect(Pn,dt,1,1)}if("toDataURL"in _e)return _e.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},U=(se,me)=>{let _e=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(_e!=null){let Ee,ze,Ae;(me==null?void 0:me.tensorLayout)!==void 0&&me.tensorLayout==="NHWC"?(Ee=se.dims[2],ze=se.dims[1],Ae=se.dims[3]):(Ee=se.dims[3],ze=se.dims[2],Ae=se.dims[1]);let $e=me!==void 0&&me.format!==void 0?me.format:"RGB",Fe=me==null?void 0:me.norm,et,st;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?st=[0,0,0,0]:typeof Fe.bias=="number"?st=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(st=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(st[3]=Fe.bias[3]));let tt=ze*Ee;if(me!==void 0&&(me.format!==void 0&&Ae===4&&me.format!=="RGBA"||Ae===3&&me.format!=="RGB"&&me.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ye=4,$t=0,Le=1,dt=2,Pn=3,en=0,tn=tt,Rn=tt*2,Lt=-1;$e==="RGBA"?(en=0,tn=tt,Rn=tt*2,Lt=tt*3):$e==="RGB"?(en=0,tn=tt,Rn=tt*2):$e==="RBG"&&(en=0,Rn=tt,tn=tt*2),De=_e.createImageData(Ee,ze);for(let Bn=0;Bn<ze*Ee;$t+=Ye,Le+=Ye,dt+=Ye,Pn+=Ye,Bn++)De.data[$t]=(se.data[en++]-st[0])*et[0],De.data[Le]=(se.data[tn++]-st[1])*et[1],De.data[dt]=(se.data[Rn++]-st[2])*et[2],De.data[Pn]=Lt===-1?255:(se.data[Lt++]-st[3])*et[3]}else throw new Error("Can not access image data");return De}}),Q,Y,V,ee,fe,oe,W=c(()=>{Se(),Q=(se,me)=>{if(se===void 0)throw new Error("Image buffer must be defined");if(me.height===void 0||me.width===void 0)throw new Error("Image height and width must be defined");if(me.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:_e,width:De}=me,Ee=me.norm??{mean:255,bias:0},ze,Ae;typeof Ee.mean=="number"?ze=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:ze=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?Ae=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:Ae=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let $e=me.format!==void 0?me.format:"RGBA",Fe=me.tensorFormat!==void 0&&me.tensorFormat!==void 0?me.tensorFormat:"RGB",et=_e*De,st=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Ye=0,$t=1,Le=2,dt=3,Pn=0,en=et,tn=et*2,Rn=-1;$e==="RGB"&&(tt=3,Ye=0,$t=1,Le=2,dt=-1),Fe==="RGBA"?Rn=et*3:Fe==="RBG"?(Pn=0,tn=et,en=et*2):Fe==="BGR"&&(tn=0,en=et,Pn=et*2);for(let Lt=0;Lt<et;Lt++,Ye+=tt,Le+=tt,$t+=tt,dt+=tt)st[Pn++]=(se[Ye]+Ae[0])/ze[0],st[en++]=(se[$t]+Ae[1])/ze[1],st[tn++]=(se[Le]+Ae[2])/ze[2],Rn!==-1&&dt!==-1&&(st[Rn++]=(se[dt]+Ae[3])/ze[3]);return Fe==="RGBA"?new Z("float32",st,[1,4,_e,De]):new Z("float32",st,[1,3,_e,De])},Y=async(se,me)=>{let _e=typeof HTMLImageElement<"u"&&se instanceof HTMLImageElement,De=typeof ImageData<"u"&&se instanceof ImageData,Ee=typeof ImageBitmap<"u"&&se instanceof ImageBitmap,ze=typeof se=="string",Ae,$e=me??{},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")},et=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(_e){let st=Fe();st.width=se.width,st.height=se.height;let tt=et(st);if(tt!=null){let Ye=se.height,$t=se.width;if(me!==void 0&&me.resizedHeight!==void 0&&me.resizedWidth!==void 0&&(Ye=me.resizedHeight,$t=me.resizedWidth),me!==void 0){if($e=me,me.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$e.tensorFormat="RGBA",$e.height=Ye,$e.width=$t}else $e.tensorFormat="RGBA",$e.height=Ye,$e.width=$t;tt.drawImage(se,0,0),Ae=tt.getImageData(0,0,$t,Ye).data}else throw new Error("Can not access image data")}else if(De){let st,tt;if(me!==void 0&&me.resizedWidth!==void 0&&me.resizedHeight!==void 0?(st=me.resizedHeight,tt=me.resizedWidth):(st=se.height,tt=se.width),me!==void 0&&($e=me),$e.format="RGBA",$e.height=st,$e.width=tt,me!==void 0){let Ye=Fe();Ye.width=tt,Ye.height=st;let $t=et(Ye);if($t!=null)$t.putImageData(se,0,0),Ae=$t.getImageData(0,0,tt,st).data;else throw new Error("Can not access image data")}else Ae=se.data}else if(Ee){if(me===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Fe();st.width=se.width,st.height=se.height;let tt=et(st);if(tt!=null){let Ye=se.height,$t=se.width;return tt.drawImage(se,0,0,$t,Ye),Ae=tt.getImageData(0,0,$t,Ye).data,$e.height=Ye,$e.width=$t,Q(Ae,$e)}else throw new Error("Can not access image data")}else{if(ze)return new Promise((st,tt)=>{let Ye=Fe(),$t=et(Ye);if(!se||!$t)return tt();let Le=new Image;Le.crossOrigin="Anonymous",Le.src=se,Le.onload=()=>{Ye.width=Le.width,Ye.height=Le.height,$t.drawImage(Le,0,0,Ye.width,Ye.height);let dt=$t.getImageData(0,0,Ye.width,Ye.height);$e.height=Ye.height,$e.width=Ye.width,st(Q(dt.data,$e))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ae!==void 0)return Q(Ae,$e);throw new Error("Input data provided is not supported - aborted tensor creation")},V=(se,me)=>{let{width:_e,height:De,download:Ee,dispose:ze}=me,Ae=[1,De,_e,4];return new Z({location:"texture",type:"float32",texture:se,dims:Ae,download:Ee,dispose:ze})},ee=(se,me)=>{let{dataType:_e,dims:De,download:Ee,dispose:ze}=me;return new Z({location:"gpu-buffer",type:_e??"float32",gpuBuffer:se,dims:De,download:Ee,dispose:ze})},fe=(se,me)=>{let{dataType:_e,dims:De,download:Ee,dispose:ze}=me;return new Z({location:"ml-tensor",type:_e??"float32",mlTensor:se,dims:De,download:Ee,dispose:ze})},oe=(se,me,_e)=>new Z({location:"cpu-pinned",type:se,data:me,dims:_e??[me.length]})}),re,q,ie,ae,ce=c(()=>{re=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ie=!1,ae=()=>{if(!ie){ie=!0;let se=typeof BigInt64Array<"u"&&BigInt64Array.from,me=typeof BigUint64Array<"u"&&BigUint64Array.from,_e=globalThis.Float16Array,De=typeof _e<"u"&&_e.from;se&&(re.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),me&&(re.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),De?(re.set("float16",_e),q.set(_e,"float16")):re.set("float16",Uint16Array)}}}),ye,Pe,de=c(()=>{Se(),ye=se=>{let me=1;for(let _e=0;_e<se.length;_e++){let De=se[_e];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${_e}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${_e}] must be a non-negative integer, got: ${De}`);me*=De}return me},Pe=(se,me)=>{switch(se.location){case"cpu":return new Z(se.type,se.data,me);case"cpu-pinned":return new Z({location:"cpu-pinned",data:se.data,type:se.type,dims:me});case"texture":return new Z({location:"texture",texture:se.texture,type:se.type,dims:me});case"gpu-buffer":return new Z({location:"gpu-buffer",gpuBuffer:se.gpuBuffer,type:se.type,dims:me});case"ml-tensor":return new Z({location:"ml-tensor",mlTensor:se.mlTensor,type:se.type,dims:me});default:throw new Error(`tensorReshape: tensor location ${se.location} is not supported`)}}}),Z,Se=c(()=>{J(),W(),ce(),de(),Z=class{constructor(se,me,_e){ae();let De,Ee;if(typeof se=="object"&&"location"in se)switch(this.dataLocation=se.location,De=se.type,Ee=se.dims,se.location){case"cpu-pinned":{let Ae=re.get(De);if(!Ae)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(se.data instanceof Ae))throw new TypeError(`buffer should be of type ${Ae.name}`);this.cpuData=se.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=se.texture,this.downloader=se.download,this.disposer=se.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=se.gpuBuffer,this.downloader=se.download,this.disposer=se.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=se.mlTensor,this.downloader=se.download,this.disposer=se.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ae,$e;if(typeof se=="string")if(De=se,$e=_e,se==="string"){if(!Array.isArray(me))throw new TypeError("A string tensor's data must be a string array.");Ae=me}else{let Fe=re.get(se);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${se}.`);if(Array.isArray(me)){if(se==="float16"&&Fe===Uint16Array||se==="uint4"||se==="int4")throw new TypeError(`Creating a ${se} tensor from number array is not supported. Please use ${Fe.name} as data.`);se==="uint64"||se==="int64"?Ae=Fe.from(me,BigInt):Ae=Fe.from(me)}else if(me instanceof Fe)Ae=me;else if(me instanceof Uint8ClampedArray)if(se==="uint8")Ae=Uint8Array.from(me);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(se==="float16"&&me instanceof Uint16Array&&Fe!==Uint16Array)Ae=new globalThis.Float16Array(me.buffer,me.byteOffset,me.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if($e=me,Array.isArray(se)){if(se.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof se[0];if(Fe==="string")De="string",Ae=se;else if(Fe==="boolean")De="bool",Ae=Uint8Array.from(se);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(se instanceof Uint8ClampedArray)De="uint8",Ae=Uint8Array.from(se);else{let Fe=q.get(se.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${se.constructor}.`);De=Fe,Ae=se}if($e===void 0)$e=[Ae.length];else if(!Array.isArray($e))throw new TypeError("A tensor's dims must be a number array");Ee=$e,this.cpuData=Ae,this.dataLocation="cpu"}let ze=ye(Ee);if(this.cpuData&&ze!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(ze/2)===this.cpuData.length))throw new Error(`Tensor's size(${ze}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Ee,this.size=ze}static async fromImage(se,me){return Y(se,me)}static fromTexture(se,me){return V(se,me)}static fromGpuBuffer(se,me){return ee(se,me)}static fromMLTensor(se,me){return fe(se,me)}static fromPinnedBuffer(se,me,_e){return oe(se,me,_e)}toDataURL(se){return B(this,se)}toImageData(se){return U(this,se)}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(se){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 me=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=me,se&&this.disposer&&(this.disposer(),this.disposer=void 0),me}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(se){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Pe(this,se)}}}),xe,Xe=c(()=>{Se(),xe=Z}),nt,ut,Xt,pt,it,ot,Nt=c(()=>{P(),nt=(se,me)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${se}::ORT::${me}`)},ut=(se,me)=>{var Ee;let _e=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let ze=0;ze<_e.length;ze++){if(De&&!_e[ze].includes("TRACE_FUNC")){let Ae=`FUNC_${se}::${_e[ze].trim().split(" ")[1]}`;me&&(Ae+=`::${me}`),nt("CPU",Ae);return}_e[ze].includes("TRACE_FUNC")&&(De=!0)}},Xt=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||ut("BEGIN",se)},pt=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||ut("END",se)},it=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${se}`)},ot=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${se}`)}}),rn,fn=c(()=>{w(),Xe(),Nt(),rn=class bT{constructor(me){this.handler=me}async run(me,_e,De){Xt(),it("InferenceSession.run");let Ee={},ze={};if(typeof me!="object"||me===null||me instanceof xe||Array.isArray(me))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ae=!0;if(typeof _e=="object"){if(_e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_e instanceof xe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_e)){if(_e.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ae=!1;for(let et of _e){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ee[et]=null}if(typeof De=="object"&&De!==null)ze=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,st=Object.getOwnPropertyNames(_e);for(let tt of this.outputNames)if(st.indexOf(tt)!==-1){let Ye=_e[tt];(Ye===null||Ye instanceof xe)&&(et=!0,Ae=!1,Ee[tt]=Ye)}if(et){if(typeof De=="object"&&De!==null)ze=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else ze=_e}}else if(typeof _e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof me[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Ae)for(let et of this.outputNames)Ee[et]=null;let $e=await this.handler.run(me,Ee,ze),Fe={};for(let et in $e)if(Object.hasOwnProperty.call($e,et)){let st=$e[et];st instanceof xe?Fe[et]=st:Fe[et]=new xe(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Fe}async release(){return this.handler.dispose()}static async create(me,_e,De,Ee){Xt(),it("InferenceSession.create");let ze,Ae={};if(typeof me=="string"){if(ze=me,typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(me instanceof Uint8Array){if(ze=me,typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(me instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&me instanceof SharedArrayBuffer){let st=me,tt=0,Ye=me.byteLength;if(typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e=="number"){if(tt=_e,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Ye=me.byteLength-tt,typeof De=="number"){if(Ye=De,!Number.isSafeInteger(Ye))throw new RangeError("'byteLength' must be an integer.");if(Ye<=0||tt+Ye>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-tt}].`);if(typeof Ee=="object"&&Ee!==null)Ae=Ee;else if(typeof Ee<"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 _e<"u")throw new TypeError("'options' must be an object.");ze=new Uint8Array(st,tt,Ye)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$e,Fe]=await x(Ae),et=await $e.createInferenceSessionHandler(ze,Fe);return ot("InferenceSession.create"),pt(),new bT(et)}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}}}),Je,Ct=c(()=>{fn(),Je=rn}),vt=c(()=>{}),hn=c(()=>{}),An=c(()=>{}),er=c(()=>{}),yr={};p(yr,{InferenceSession:()=>Je,TRACE:()=>nt,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>Xt,TRACE_FUNC_END:()=>pt,Tensor:()=>xe,env:()=>R,registerBackend:()=>_});var mn=c(()=>{S(),O(),Ct(),Xe(),vt(),hn(),Nt(),An(),er()}),Hi=c(()=>{}),Yn={};p(Yn,{default:()=>Rs});var ci,gn,Rs,nl=c(()=>{var se;we(),ir(),nr(),ci="ort-wasm-proxy-worker",gn=((se=globalThis.self)==null?void 0:se.name)===ci,gn&&(self.onmessage=me=>{let{type:_e,in:De}=me.data;try{switch(_e){case"init-wasm":ms(De.wasm).then(()=>{ga(De).then(()=>{postMessage({type:_e})},Ee=>{postMessage({type:_e,err:Ee})})},Ee=>{postMessage({type:_e,err:Ee})});break;case"init-ep":{let{epName:Ee,env:ze}=De;Fs(ze,Ee).then(()=>{postMessage({type:_e})},Ae=>{postMessage({type:_e,err:Ae})});break}case"copy-from":{let{buffer:Ee}=De,ze=cn(Ee);postMessage({type:_e,out:ze});break}case"create":{let{model:Ee,options:ze}=De;Cr(Ee,ze).then(Ae=>{postMessage({type:_e,out:Ae})},Ae=>{postMessage({type:_e,err:Ae})});break}case"release":ao(De),postMessage({type:_e});break;case"run":{let{sessionId:Ee,inputIndices:ze,inputs:Ae,outputIndices:$e,options:Fe}=De;Ke(Ee,ze,Ae,$e,new Array($e.length).fill(null),Fe).then(et=>{et.some(st=>st[3]!=="cpu")?postMessage({type:_e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:_e,out:et},mt([...Ae,...et]))},et=>{postMessage({type:_e,err:et})});break}case"end-profiling":sr(De),postMessage({type:_e});break;default:}}catch(Ee){postMessage({type:_e,err:Ee})}}),Rs=gn?null:me=>new Worker(me??kn,{type:"classic",name:ci})}),fa,Is,kn,tr,di,Ms,qr,_r,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),fa=typeof location>"u"?void 0:location.origin,Is=()=>{var se,me;return typeof document<"u"?(se=document.currentScript)==null?void 0:se.src:typeof self<"u"?(me=self.location)==null?void 0:me.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},di=(se,me)=>{try{let _e=me??kn;return(_e?new URL(se,_e):new URL(se)).origin===fa}catch{return!1}},Ms=(se,me)=>{let _e=me??kn;try{return(_e?new URL(se,_e):new URL(se)).href}catch{return}},qr=(se,me)=>`${me??"./"}${se}`,_r=async se=>{let me=await(await fetch(se,{credentials:"same-origin"})).blob();return URL.createObjectURL(me)},ro=async se=>(await import(se)).default,Os=(nl(),f(Yn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(di(kn))return[void 0,Os()];let se=await _r(kn);return[se,Os(se)]},Kr=void 0,Wi=async(se,me,_e,De)=>{let Ee=Kr&&!(se||me);if(Ee)if(kn)Ee=di(kn)||De&&!_e;else if(De&&!_e)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let ze="ort-wasm-simd-threaded.mjs",Ae=se??Ms(ze,me),$e=_e&&Ae&&!di(Ae,me),Fe=$e?await _r(Ae):Ae??qr(ze,me);return[$e?Fe:void 0,await ro(Fe)]}}}),hs,Vi,wr,Br,Ao,ps,fs,ms,Bt,ir=c(()=>{nr(),Vi=!1,wr=!1,Br=!1,Ao=()=>{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}},ps=()=>{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}},fs=()=>{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}},ms=async se=>{if(Vi)return Promise.resolve();if(wr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");wr=!0;let me=se.initTimeout,_e=se.numThreads;if(se.simd!==!1){if(se.simd==="relaxed"){if(!fs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ps())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=Ao();_e>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+_e+", 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."),se.numThreads=_e=1);let Ee=se.wasmPaths,ze=typeof Ee=="string"?Ee:void 0,Ae=Ee==null?void 0:Ee.mjs,$e=(Ae==null?void 0:Ae.href)??Ae,Fe=Ee==null?void 0:Ee.wasm,et=(Fe==null?void 0:Fe.href)??Fe,st=se.wasmBinary,[tt,Ye]=await Wi($e,ze,_e>1,!!st||!!et),$t=!1,Le=[];if(me>0&&Le.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},me)})),Le.push(new Promise((dt,Pn)=>{let en={numThreads:_e};if(st)en.wasmBinary=st,en.locateFile=tn=>tn;else if(et||ze)en.locateFile=tn=>et??ze+tn;else if($e&&$e.indexOf("blob:")!==0)en.locateFile=tn=>new URL(tn,$e).href;else if(tt){let tn=tr();tn&&(en.locateFile=Rn=>tn+Rn)}Ye(en).then(tn=>{wr=!1,Vi=!0,hs=tn,dt(),tt&&URL.revokeObjectURL(tt)},tn=>{wr=!1,Br=!0,Pn(tn)})})),await Promise.race(Le),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${me}ms`)},Bt=()=>{if(Vi&&hs)return hs;throw new Error("WebAssembly is not initialized yet.")}}),Xn,jn,Et,so=c(()=>{ir(),Xn=(se,me)=>{let _e=Bt(),De=_e.lengthBytesUTF8(se)+1,Ee=_e._malloc(De);return _e.stringToUTF8(se,Ee,De),me.push(Ee),Ee},jn=(se,me,_e,De)=>{if(typeof se=="object"&&se!==null){if(_e.has(se))throw new Error("Circular reference in options");_e.add(se)}Object.entries(se).forEach(([Ee,ze])=>{let Ae=me?me+Ee:Ee;if(typeof ze=="object")jn(ze,Ae+".",_e,De);else if(typeof ze=="string"||typeof ze=="number")De(Ae,ze.toString());else if(typeof ze=="boolean")De(Ae,ze?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof ze}`)})},Et=se=>{let me=Bt(),_e=me.stackSave();try{let De=me.PTR_SIZE,Ee=me.stackAlloc(2*De);me._OrtGetLastError(Ee,Ee+De);let ze=Number(me.getValue(Ee,De===4?"i32":"i64")),Ae=me.getValue(Ee+De,"*"),$e=Ae?me.UTF8ToString(Ae):"";throw new Error(`${se} ERROR_CODE: ${ze}, ERROR_MESSAGE: ${$e}`)}finally{me.stackRestore(_e)}}}),$o,il=c(()=>{ir(),so(),$o=se=>{let me=Bt(),_e=0,De=[],Ee=se||{};try{if((se==null?void 0:se.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof se.logSeverityLevel!="number"||!Number.isInteger(se.logSeverityLevel)||se.logSeverityLevel<0||se.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${se.logSeverityLevel}`);if((se==null?void 0:se.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof se.logVerbosityLevel!="number"||!Number.isInteger(se.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${se.logVerbosityLevel}`);(se==null?void 0:se.terminate)===void 0&&(Ee.terminate=!1);let ze=0;return(se==null?void 0:se.tag)!==void 0&&(ze=Xn(se.tag,De)),_e=me._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,ze),_e===0&&Et("Can't create run options."),(se==null?void 0:se.extra)!==void 0&&jn(se.extra,"",new WeakSet,(Ae,$e)=>{let Fe=Xn(Ae,De),et=Xn($e,De);me._OrtAddRunConfigEntry(_e,Fe,et)!==0&&Et(`Can't set a run config entry: ${Ae} - ${$e}.`)}),[_e,De]}catch(ze){throw _e!==0&&me._OrtReleaseRunOptions(_e),De.forEach(Ae=>me._free(Ae)),ze}}}),Po,Ro,ma,Oi,rl,sl,Dn=c(()=>{ir(),so(),Po=se=>{switch(se){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: ${se}`)}},Ro=se=>{switch(se){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${se}`)}},ma=se=>{se.extra||(se.extra={}),se.extra.session||(se.extra.session={});let me=se.extra.session;me.use_ort_model_bytes_directly||(me.use_ort_model_bytes_directly="1"),se.executionProviders&&se.executionProviders.some(_e=>(typeof _e=="string"?_e:_e.name)==="webgpu")&&(se.enableMemPattern=!1)},Oi=(se,me,_e,De)=>{let Ee=Xn(me,De),ze=Xn(_e,De);Bt()._OrtAddSessionConfigEntry(se,Ee,ze)!==0&&Et(`Can't set a session config entry: ${me} - ${_e}.`)},rl=async(se,me,_e)=>{let De=me.executionProviders;for(let Ee of De){let ze=typeof Ee=="string"?Ee:Ee.name,Ae=[];switch(ze){case"webnn":if(ze="WEBNN",Oi(se,"session.disable_quant_qdq","1",_e),Oi(se,"session.disable_qdq_constant_folding","1",_e),typeof Ee!="string"){let tt=Ee==null?void 0:Ee.deviceType;tt&&Oi(se,"deviceType",tt,_e)}break;case"webgpu":if(ze="JS",typeof Ee!="string"){let tt=Ee;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Oi(se,"preferredLayout",tt.preferredLayout,_e)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${ze}`)}let $e=Xn(ze,_e),Fe=Ae.length,et=0,st=0;if(Fe>0){et=Bt()._malloc(Fe*Bt().PTR_SIZE),_e.push(et),st=Bt()._malloc(Fe*Bt().PTR_SIZE),_e.push(st);for(let tt=0;tt<Fe;tt++)Bt().setValue(et+tt*Bt().PTR_SIZE,Ae[tt][0],"*"),Bt().setValue(st+tt*Bt().PTR_SIZE,Ae[tt][1],"*")}await Bt()._OrtAppendExecutionProvider(se,$e,et,st,Fe)!==0&&Et(`Can't append execution provider: ${ze}.`)}},sl=async se=>{let me=Bt(),_e=0,De=[],Ee=se||{};ma(Ee);try{let ze=Po(Ee.graphOptimizationLevel??"all"),Ae=Ro(Ee.executionMode??"sequential"),$e=typeof Ee.logId=="string"?Xn(Ee.logId,De):0,Fe=Ee.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ee.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let st=typeof Ee.optimizedModelFilePath=="string"?Xn(Ee.optimizedModelFilePath,De):0;if(_e=me._OrtCreateSessionOptions(ze,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,Ae,!!Ee.enableProfiling,0,$e,Fe,et,st),_e===0&&Et("Can't create session options."),Ee.executionProviders&&await rl(_e,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Oi(_e,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[tt,Ye]of Object.entries(Ee.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Ye!="number"||!Number.isInteger(Ye)||Ye<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ye}`);let $t=Xn(tt,De);me._OrtAddFreeDimensionOverride(_e,$t,Ye)!==0&&Et(`Can't set a free dimension override: ${tt} - ${Ye}.`)}return Ee.extra!==void 0&&jn(Ee.extra,"",new WeakSet,(tt,Ye)=>{Oi(_e,tt,Ye,De)}),[_e,De]}catch(ze){throw _e!==0&&me._OrtReleaseSessionOptions(_e)!==0&&Et("Can't release session options."),De.forEach(Ae=>me._free(Ae)),ze}}}),qi,Qn,Ki,gs,oo,zs,Sr,ji,Ft=c(()=>{qi=se=>{switch(se){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: ${se}`)}},Qn=se=>{switch(se){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: ${se}`)}},Ki=(se,me)=>{let _e=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][se],De=typeof me=="number"?me:me.reduce((Ee,ze)=>Ee*ze,1);return _e>0?Math.ceil(De*_e):void 0},gs=se=>{switch(se){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: ${se}`)}},oo=se=>{switch(se){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: ${se}`)}},zs=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Sr=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint64"||se==="int8"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",ji=se=>{switch(se){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: ${se}`)}}}),ei,Bs=c(()=>{Hi(),ei=async se=>{if(typeof se=="string"){let me=await fetch(se);if(!me.ok)throw new Error(`failed to load external data file: ${se}`);let _e=me.headers.get("Content-Length"),De=_e?parseInt(_e,10):0;if(De<1073741824)return new Uint8Array(await me.arrayBuffer());{if(!me.body)throw new Error(`failed to load external data file: ${se}, no response body.`);let Ee=me.body.getReader(),ze;try{ze=new ArrayBuffer(De)}catch($e){if($e instanceof RangeError){let Fe=Math.ceil(De/65536);ze=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw $e}let Ae=0;for(;;){let{done:$e,value:Fe}=await Ee.read();if($e)break;let et=Fe.byteLength;new Uint8Array(ze,Ae,et).set(Fe),Ae+=et}return new Uint8Array(ze,0,De)}}else return se instanceof Blob?new Uint8Array(await se.arrayBuffer()):se instanceof Uint8Array?se:new Uint8Array(se)}}),kr,ga,Fs,rr,Yr,Gs,cn,Cr,ao,Fr,Ke,sr,mt,we=c(()=>{mn(),il(),Dn(),Ft(),ir(),so(),Bs(),kr=(se,me)=>{Bt()._OrtInit(se,me)!==0&&Et("Can't initialize onnxruntime.")},ga=async se=>{kr(se.wasm.numThreads,oo(se.logLevel))},Fs=async(se,me)=>{var De,Ee;(Ee=(De=Bt()).asyncInit)==null||Ee.call(De);let _e=se.webgpu.adapter;if(me==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(_e){if(typeof _e.limits!="object"||typeof _e.features!="object"||typeof _e.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let ze=se.webgpu.powerPreference;if(ze!==void 0&&ze!=="low-power"&&ze!=="high-performance")throw new Error(`Invalid powerPreference setting: "${ze}"`);let Ae=se.webgpu.forceFallbackAdapter;if(Ae!==void 0&&typeof Ae!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ae}"`);if(_e=await navigator.gpu.requestAdapter({powerPreference:ze,forceFallbackAdapter:Ae}),!_e)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(me==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rr=new Map,Yr=se=>{let me=Bt(),_e=me.stackSave();try{let De=me.PTR_SIZE,Ee=me.stackAlloc(2*De);me._OrtGetInputOutputCount(se,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let ze=De===4?"i32":"i64";return[Number(me.getValue(Ee,ze)),Number(me.getValue(Ee+De,ze))]}finally{me.stackRestore(_e)}},Gs=(se,me)=>{let _e=Bt(),De=_e.stackSave(),Ee=0;try{let ze=_e.PTR_SIZE,Ae=_e.stackAlloc(2*ze);_e._OrtGetInputOutputMetadata(se,me,Ae,Ae+ze)!==0&&Et("Can't get session input/output metadata.");let $e=Number(_e.getValue(Ae,"*"));Ee=Number(_e.getValue(Ae+ze,"*"));let Fe=_e.HEAP32[Ee/4];if(Fe===0)return[$e,0];let et=_e.HEAPU32[Ee/4+1],st=[];for(let tt=0;tt<et;tt++){let Ye=Number(_e.getValue(Ee+8+tt*ze,"*"));st.push(Ye!==0?_e.UTF8ToString(Ye):Number(_e.getValue(Ee+8+(tt+et)*ze,"*")))}return[$e,Fe,st]}finally{_e.stackRestore(De),Ee!==0&&_e._OrtFree(Ee)}},cn=se=>{let me=Bt(),_e=me._malloc(se.byteLength);if(_e===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${se.byteLength}.`);return me.HEAPU8.set(se,_e),[_e,se.byteLength]},Cr=async(se,me)=>{var st,tt,Ye;let _e,De,Ee=Bt();Array.isArray(se)?[_e,De]=se:se.buffer===Ee.HEAPU8.buffer?[_e,De]=[se.byteOffset,se.byteLength]:[_e,De]=cn(se);let ze=0,Ae=0,$e=[],Fe=[],et=[];try{if([Ae,$e]=await sl(me),(me==null?void 0:me.externalData)&&Ee.mountExternalData){let Bn=[];for(let pn of me.externalData){let Di=typeof pn=="string"?pn:pn.path;Bn.push(ei(typeof pn=="string"?pn:pn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(me==null?void 0:me.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let pn=Bn,Di=pn==null?void 0:pn.context,Yi=pn==null?void 0:pn.gpuDevice,or=pn==null?void 0:pn.deviceType,al=pn==null?void 0:pn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:al})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}ze=await Ee._OrtCreateSession(_e,De,Ae),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,ze),ze===0&&Et("Can't create a session."),(tt=Ee.jsepOnCreateSession)==null||tt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(ze,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,Le]=Yr(ze),dt=!!(me!=null&&me.enableGraphCapture),Pn=[],en=[],tn=[],Rn=[],Lt=[];for(let Bn=0;Bn<$t;Bn++){let[pn,Di,Yi]=Gs(ze,Bn);pn===0&&Et("Can't get an input name."),Fe.push(pn);let or=Ee.UTF8ToString(pn);Pn.push(or),tn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:Qn(Di),shape:Yi})}for(let Bn=0;Bn<Le;Bn++){let[pn,Di,Yi]=Gs(ze,Bn+$t);pn===0&&Et("Can't get an output name."),et.push(pn);let or=Ee.UTF8ToString(pn);en.push(or),Rn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:Qn(Di),shape:Yi})}return rr.set(ze,[ze,Fe,et,null,dt,!1]),[ze,Pn,en,tn,Rn]}catch($t){throw Fe.forEach(Le=>Ee._OrtFree(Le)),et.forEach(Le=>Ee._OrtFree(Le)),ze!==0&&Ee._OrtReleaseSession(ze)!==0&&Et("Can't release session."),$t}finally{Ee._free(_e),Ae!==0&&Ee._OrtReleaseSessionOptions(Ae)!==0&&Et("Can't release session options."),$e.forEach($t=>Ee._free($t)),(Ye=Ee.unmountExternalData)==null||Ye.call(Ee)}},ao=se=>{var Fe,et,st;let me=Bt(),_e=rr.get(se);if(!_e)throw new Error(`cannot release session. invalid session id: ${se}`);let[De,Ee,ze,Ae,$e]=_e;Ae&&($e&&me._OrtClearBoundOutputs(Ae.handle)!==0&&Et("Can't clear bound outputs."),me._OrtReleaseBinding(Ae.handle)!==0&&Et("Can't release IO binding.")),(Fe=me.jsepOnReleaseSession)==null||Fe.call(me,se),(et=me.webnnOnReleaseSession)==null||et.call(me,se),(st=me.webgpuOnReleaseSession)==null||st.call(me,se),Ee.forEach(tt=>me._OrtFree(tt)),ze.forEach(tt=>me._OrtFree(tt)),me._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(se)},Fr=async(se,me,_e,De,Ee,ze,Ae=!1)=>{if(!se){me.push(0);return}let $e=Bt(),Fe=$e.PTR_SIZE,et=se[0],st=se[1],tt=se[3],Ye=tt,$t,Le;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ae&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${ze} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let en=se[2].gpuBuffer;Le=Ki(qi(et),st);{let tn=$e.jsepRegisterBuffer;if(!tn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=tn(De,ze,en,Le)}}else if(tt==="ml-tensor"){let en=se[2].mlTensor;Le=Ki(qi(et),st);let tn=$e.webnnRegisterMLTensor;if(!tn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=tn(De,en,qi(et),st)}else{let en=se[2];if(Array.isArray(en)){Le=Fe*en.length,$t=$e._malloc(Le),_e.push($t);for(let tn=0;tn<en.length;tn++){if(typeof en[tn]!="string")throw new TypeError(`tensor data at index ${tn} is not a string`);$e.setValue($t+tn*Fe,Xn(en[tn],_e),"*")}}else{let tn=$e.webnnIsGraphInput,Rn=$e.webnnIsGraphOutput;if(et!=="string"&&tn&&Rn){let Lt=$e.UTF8ToString(Ee);if(tn(De,Lt)||Rn(De,Lt)){let Bn=qi(et);Le=Ki(Bn,st),Ye="ml-tensor";let pn=$e.webnnCreateTemporaryTensor,Di=$e.webnnUploadTensor;if(!pn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await pn(De,Bn,st);Di(Yi,new Uint8Array(en.buffer,en.byteOffset,en.byteLength)),$t=Yi}else Le=en.byteLength,$t=$e._malloc(Le),_e.push($t),$e.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,Le),$t)}else Le=en.byteLength,$t=$e._malloc(Le),_e.push($t),$e.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,Le),$t)}}let dt=$e.stackSave(),Pn=$e.stackAlloc(4*st.length);try{st.forEach((tn,Rn)=>$e.setValue(Pn+Rn*Fe,tn,Fe===4?"i32":"i64"));let en=$e._OrtCreateTensor(qi(et),$t,Le,Pn,st.length,ji(Ye));en===0&&Et(`Can't create tensor for input/output. session=${De}, index=${ze}.`),me.push(en)}finally{$e.stackRestore(dt)}},Ke=async(se,me,_e,De,Ee,ze)=>{var ar,ic,ld;let Ae=Bt(),$e=Ae.PTR_SIZE,Fe=rr.get(se);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${se}`);let et=Fe[0],st=Fe[1],tt=Fe[2],Ye=Fe[3],$t=Fe[4];Fe[5];let Le=me.length,dt=De.length,Pn=0,en=[],tn=[],Rn=[],Lt=[],Bn=[],pn=Ae.stackSave(),Di=Ae.stackAlloc(Le*$e),Yi=Ae.stackAlloc(Le*$e),or=Ae.stackAlloc(dt*$e),al=Ae.stackAlloc(dt*$e);try{[Pn,en]=$o(ze),it("wasm prepareInputOutputTensor");for(let un=0;un<Le;un++)await Fr(_e[un],tn,Lt,se,st[me[un]],me[un],$t);for(let un=0;un<dt;un++)await Fr(Ee[un],Rn,Lt,se,tt[De[un]],Le+De[un],$t);ot("wasm prepareInputOutputTensor");for(let un=0;un<Le;un++)Ae.setValue(Di+un*$e,tn[un],"*"),Ae.setValue(Yi+un*$e,st[me[un]],"*");for(let un=0;un<dt;un++)Ae.setValue(or+un*$e,Rn[un],"*"),Ae.setValue(al+un*$e,tt[De[un]],"*");(ar=Ae.jsepOnRunStart)==null||ar.call(Ae,et),(ic=Ae.webnnOnRunStart)==null||ic.call(Ae,et);let Ni;Ni=await Ae._OrtRun(et,Yi,Di,Le,al,dt,or,Pn),Ni!==0&&Et("failed to call OrtRun().");let xs=[],cd=[];it("wasm ProcessOutputTensor");for(let un=0;un<dt;un++){let Jr=Number(Ae.getValue(or+un*$e,"*"));if(Jr===Rn[un]||Bn.includes(Rn[un])){xs.push(Ee[un]),Jr!==Rn[un]&&Ae._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let Nu=Ae.stackSave(),Ws=Ae.stackAlloc(4*$e),va=!1,vi,lr=0;try{Ae._OrtGetTensorData(Jr,Ws,Ws+$e,Ws+2*$e,Ws+3*$e)!==0&&Et(`Can't access output tensor data on index ${un}.`);let rc=$e===4?"i32":"i64",cr=Number(Ae.getValue(Ws,rc));lr=Ae.getValue(Ws+$e,"*");let dd=Ae.getValue(Ws+$e*2,"*"),Au=Number(Ae.getValue(Ws+$e*3,rc)),Vs=[];for(let xi=0;xi<Au;xi++)Vs.push(Number(Ae.getValue(dd+xi*$e,rc)));Ae._OrtFree(dd)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Jn)=>xi*Jn,1);vi=Qn(cr);let bs=Ye==null?void 0:Ye.outputPreferredLocations[De[un]];if(vi==="string"){if(bs==="gpu-buffer"||bs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Jn=0;Jn<Zr;Jn++){let Qr=Ae.getValue(lr+Jn*$e,"*"),ud=Ae.getValue(lr+(Jn+1)*$e,"*"),hd=Jn===Zr-1?void 0:ud-Qr;xi.push(Ae.UTF8ToString(Qr,hd))}xs.push([vi,Vs,xi,"cpu"])}else if(bs==="gpu-buffer"&&Zr>0){let xi=Ae.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Jn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);va=!0,xs.push([vi,Vs,{gpuBuffer:Jn,download:Ae.jsepCreateDownloader(Jn,Qr,vi),dispose:()=>{Ae._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(bs==="ml-tensor"&&Zr>0){let xi=Ae.webnnEnsureTensor,Jn=Ae.webnnIsGraphInputOutputTypeSupported;if(!xi||!Jn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Jn(se,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(se,lr,cr,Vs,!1);va=!0,xs.push([vi,Vs,{mlTensor:Qr,download:Ae.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{Ae.webnnReleaseTensorId(lr),Ae._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(bs==="ml-tensor-cpu-output"&&Zr>0){let xi=Ae.webnnCreateMLTensorDownloader(lr,vi)(),Jn=xs.length;va=!0,cd.push((async()=>{let Qr=[Jn,await xi];return Ae.webnnReleaseTensorId(lr),Ae._OrtReleaseTensor(Jr),Qr})()),xs.push([vi,Vs,[],"cpu"])}else{let xi=gs(vi),Jn=new xi(Zr);new Uint8Array(Jn.buffer,Jn.byteOffset,Jn.byteLength).set(Ae.HEAPU8.subarray(lr,lr+Jn.byteLength)),xs.push([vi,Vs,Jn,"cpu"])}}finally{Ae.stackRestore(Nu),vi==="string"&&lr&&Ae._free(lr),va||Ae._OrtReleaseTensor(Jr)}}Ye&&!$t&&(Ae._OrtClearBoundOutputs(Ye.handle)!==0&&Et("Can't clear bound outputs."),rr.set(se,[et,st,tt,Ye,$t,!1]));for(let[un,Jr]of await Promise.all(cd))xs[un][2]=Jr;return ot("wasm ProcessOutputTensor"),xs}finally{(ld=Ae.webnnOnRunEnd)==null||ld.call(Ae,et),Ae.stackRestore(pn),tn.forEach(Ni=>Ae._OrtReleaseTensor(Ni)),Rn.forEach(Ni=>Ae._OrtReleaseTensor(Ni)),Lt.forEach(Ni=>Ae._free(Ni)),Pn!==0&&Ae._OrtReleaseRunOptions(Pn),en.forEach(Ni=>Ae._free(Ni))}},sr=se=>{let me=Bt(),_e=rr.get(se);if(!_e)throw new Error("invalid session id");let De=_e[0],Ee=me._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),me._OrtFree(Ee)},mt=se=>{let me=[];for(let _e of se){let De=_e[2];!Array.isArray(De)&&"buffer"in De&&me.push(De.buffer)}return me}}),Ie,Ze,jt,sn,dn,On,In,ui,Hn,gi,Mn,Xr,lo,Io,vs,Du,Mo,Oo,sd=c(()=>{mn(),we(),ir(),nr(),Ie=()=>!!R.wasm.proxy&&typeof document<"u",jt=!1,sn=!1,dn=!1,ui=new Map,Hn=(se,me)=>{let _e=ui.get(se);_e?_e.push(me):ui.set(se,[me])},gi=()=>{if(jt||!sn||dn||!Ze)throw new Error("worker not ready")},Mn=se=>{switch(se.data.type){case"init-wasm":jt=!1,se.data.err?(dn=!0,In[1](se.data.err)):(sn=!0,In[0]()),On&&(URL.revokeObjectURL(On),On=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let me=ui.get(se.data.type);se.data.err?me.shift()[1](se.data.err):me.shift()[0](se.data.out);break}}},Xr=async()=>{if(!sn){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(dn)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Ie())return new Promise((se,me)=>{Ze==null||Ze.terminate(),Ls().then(([_e,De])=>{try{Ze=De,Ze.onerror=ze=>me(ze),Ze.onmessage=Mn,In=[se,me];let Ee={type:"init-wasm",in:R};if(!Ee.in.wasm.wasmPaths&&_e){let ze=tr();ze&&(Ee.in.wasm.wasmPaths=ze)}Ze.postMessage(Ee),On=_e}catch(Ee){me(Ee)}},me)});try{await ms(R.wasm),await ga(R),sn=!0}catch(se){throw dn=!0,se}finally{jt=!1}}},lo=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("init-ep",[me,_e]);let De={type:"init-ep",in:{epName:se,env:R}};Ze.postMessage(De)});await Fs(R,se)},Io=async se=>Ie()?(gi(),new Promise((me,_e)=>{Hn("copy-from",[me,_e]);let De={type:"copy-from",in:{buffer:se}};Ze.postMessage(De,[se.buffer])})):cn(se),vs=async(se,me)=>{if(Ie()){if(me!=null&&me.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((_e,De)=>{Hn("create",[_e,De]);let Ee={type:"create",in:{model:se,options:{...me}}},ze=[];se instanceof Uint8Array&&ze.push(se.buffer),Ze.postMessage(Ee,ze)})}else return Cr(se,me)},Du=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("release",[me,_e]);let De={type:"release",in:se};Ze.postMessage(De)});ao(se)},Mo=async(se,me,_e,De,Ee,ze)=>{if(Ie()){if(_e.some(Ae=>Ae[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some(Ae=>Ae))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise((Ae,$e)=>{Hn("run",[Ae,$e]);let Fe=_e,et={type:"run",in:{sessionId:se,inputIndices:me,inputs:Fe,outputIndices:De,options:ze}};Ze.postMessage(et,mt(Fe))})}else return Ke(se,me,_e,De,Ee,ze)},Oo=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("end-profiling",[me,_e]);let De={type:"end-profiling",in:se};Ze.postMessage(De)});sr(se)}}),Ql,Lo,ol,ec=c(()=>{mn(),sd(),Ft(),Hi(),Bs(),Ql=(se,me)=>{switch(se.location){case"cpu":return[se.type,se.dims,se.data,"cpu"];case"gpu-buffer":return[se.type,se.dims,{gpuBuffer:se.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[se.type,se.dims,{mlTensor:se.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${se.location} for ${me()}`)}},Lo=se=>{switch(se[3]){case"cpu":return new xe(se[0],se[2],se[1]);case"gpu-buffer":{let me=se[0];if(!zs(me))throw new Error(`not supported data type: ${me} for deserializing GPU tensor`);let{gpuBuffer:_e,download:De,dispose:Ee}=se[2];return xe.fromGpuBuffer(_e,{dataType:me,dims:se[1],download:De,dispose:Ee})}case"ml-tensor":{let me=se[0];if(!Sr(me))throw new Error(`not supported data type: ${me} for deserializing MLTensor tensor`);let{mlTensor:_e,download:De,dispose:Ee}=se[2];return xe.fromMLTensor(_e,{dataType:me,dims:se[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${se[3]}`)}},ol=class{async fetchModelAndCopyToWasmMemory(se){return Io(await ei(se))}async loadModel(se,me){Xt();let _e;typeof se=="string"?_e=await this.fetchModelAndCopyToWasmMemory(se):_e=se,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await vs(_e,me),pt()}async dispose(){return Du(this.sessionId)}async run(se,me,_e){Xt();let De=[],Ee=[];Object.entries(se).forEach(tt=>{let Ye=tt[0],$t=tt[1],Le=this.inputNames.indexOf(Ye);if(Le===-1)throw new Error(`invalid input '${Ye}'`);De.push($t),Ee.push(Le)});let ze=[],Ae=[];Object.entries(me).forEach(tt=>{let Ye=tt[0],$t=tt[1],Le=this.outputNames.indexOf(Ye);if(Le===-1)throw new Error(`invalid output '${Ye}'`);ze.push($t),Ae.push(Le)});let $e=De.map((tt,Ye)=>Ql(tt,()=>`input "${this.inputNames[Ee[Ye]]}"`)),Fe=ze.map((tt,Ye)=>tt?Ql(tt,()=>`output "${this.outputNames[Ae[Ye]]}"`):null),et=await Mo(this.sessionId,Ee,$e,Ae,Fe,_e),st={};for(let tt=0;tt<et.length;tt++)st[this.outputNames[Ae[tt]]]=ze[tt]??Lo(et[tt]);return pt(),st}startProfiling(){}endProfiling(){Oo(this.sessionId)}}}),Us={};p(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>zo});var co,Hs,zo,od=c(()=>{mn(),sd(),ec(),co=()=>{(typeof R.wasm.initTimeout!="number"||R.wasm.initTimeout<0)&&(R.wasm.initTimeout=0);let se=R.wasm.simd;if(typeof se!="boolean"&&se!==void 0&&se!=="fixed"&&se!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${se}". Reset it to \`false\` and ignore SIMD feature checking.`),R.wasm.simd=!1),typeof R.wasm.proxy!="boolean"&&(R.wasm.proxy=!1),typeof R.wasm.trace!="boolean"&&(R.wasm.trace=!1),typeof R.wasm.numThreads!="number"||!Number.isInteger(R.wasm.numThreads)||R.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)R.wasm.numThreads=1;else{let me=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;R.wasm.numThreads=Math.min(4,Math.ceil((me||1)/2))}},Hs=class{async init(se){co(),await Xr(),await lo(se)}async createInferenceSessionHandler(se,me){let _e=new ol;return await _e.loadModel(se,me),_e}},zo=new Hs}),ad={};p(ad,{InferenceSession:()=>Je,TRACE:()=>nt,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>Xt,TRACE_FUNC_END:()=>pt,Tensor:()=>xe,default:()=>nc,env:()=>R,registerBackend:()=>_}),mn(),mn(),mn();var tc="1.26.0",nc=yr;{let se=(od(),f(Us)).wasmBackend;_("cpu",se,10),_("wasm",se,10)}return Object.defineProperty(R.versions,"web",{value:tc,enumerable:!0}),f(ad)})();n.exports=i})(t_)),t_.exports}var US;function B$(){return US||(US=1,(function(n){var e=Al&&Al.__createBinding||(Object.create?(function(E,j,D,$){$===void 0&&($=D);var P=Object.getOwnPropertyDescriptor(j,D);(!P||("get"in P?!j.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return j[D]}}),Object.defineProperty(E,$,P)}):(function(E,j,D,$){$===void 0&&($=D),E[$]=j[D]})),i=Al&&Al.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=Al&&Al.__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 i(j,E),j};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(z$()),a=j0(),d=D0(),l=Kg(),c=uy(),p=vT(),m=xT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",y="silero_vad_legacy.onnx",_=E=>({...d.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"});n.getDefaultRealTimeVADOptions=_;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,D,$,P){await D.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:$};const R=new AudioWorkletNode(D,"vad-helper-worklet",j);return R.port.onmessage=async O=>{const B=O.data;if(!(typeof B=="object"&&B&&"message"in B)){console.error("Invalid message event",B);return}switch(B.message){case c.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 P(U);break}}},R}async function w(E,j,D){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const R=E.createScriptProcessor(4096,1,1);let O=!1;return R.onaudioprocess=async B=>{if(!O){O=!0;try{const U=B.inputBuffer.getChannelData(0);B.outputBuffer.getChannelData(0).fill(0);const Q=$.process(U);for(const Y of Q)await D(Y)}catch(U){console.error("Error processing audio:",U)}finally{O=!1}}},R.connect(E.destination),R}class S{constructor(j,D,$,P,R=!1,O=null,B=null,U=null,J=null,Q=null,Y=null,V="uninitialized",ee=!1){this.options=j,this.frameProcessor=D,this.model=$,this.frameSamples=P,this.listening=R,this.errored=O,this._stream=B,this._audioContext=U,this._vadNode=J,this._mediaStreamAudioSourceNode=Q,this._audioProcessorAdapterType=Y,this.initializationState=V,this.ownsAudioContext=ee,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=fe=>{this.initializationState="errored",this.errored=fe},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(fe){throw fe instanceof Error?this.setErrored(fe.message):this.setErrored(String(fe)),fe}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"?k(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 w(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:fe,audioContext:oe,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(fe);const re=new MediaStreamAudioSourceNode(oe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=re,re.connect(W);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:fe,mediaStreamAudioSourceNode:oe}=this.getAudioInstances();await this.options.pauseStream(fe),oe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var oe;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:fe}=this.getAudioInstances();fe instanceof AudioWorkletNode&&fe.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((oe=this._audioContext)==null?void 0:oe.close())},this.setOptions=fe=>{this.frameProcessor.setOptions(fe)},this.processFrame=async fe=>{await this.frameProcessor.process(fe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=fe=>{switch(fe.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(fe.probs,fe.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(fe.audio);break}}}static async new(j={}){const D={...(0,n.getDefaultRealTimeVADOptions)(j.model??n.DEFAULT_MODEL),...j};(0,d.validateOptions)(D),n.ort.env.wasm.wasmPaths=D.onnxWASMBasePath,D.ortConfig!==void 0&&D.ortConfig(n.ort);const $=D.model==="v5"?b:y,P=D.baseAssetPath+$,R=D.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let O;try{O=await R(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(Y){throw console.error(`Encountered an error while loading model file ${P}`),Y}const B=D.model==="v5"?512:1536,U=B/16,J=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:D.positiveSpeechThreshold,negativeSpeechThreshold:D.negativeSpeechThreshold,redemptionMs:D.redemptionMs,preSpeechPadMs:D.preSpeechPadMs,minSpeechMs:D.minSpeechMs,submitUserSpeechOnPause:D.submitUserSpeechOnPause},U),Q=new S(D,J,O,B);if(D.startOnLoad)try{await Q.start()}catch(Y){throw console.error("Error starting micVad",Y),Y}return Q}}n.MicVAD=S})(Al)),Al}var HS;function F$(){return HS||(HS=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=fT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=j0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=D0();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=uy();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=O$();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=L$();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=B$();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(Zy)),Zy}var G$=F$();function ax(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>ax(n,"debug",e,i),info:(n,e,i)=>ax(n,"info",e,i),warn:(n,e,i)=>ax(n,"warn",e,i),error:(n,e,i,r)=>ax(n,"error",e,i,r)},yT=16e3,U$=6,cp=yT*U$,H$=400,W$=yT*H$/1e3,WS=300,VS=2e3,qS=1500,KS=3e3,V$=600,_T=.5,wT=.35,YS=.85,XS=.7;let Ns=null,qa=!1,cs=!1;const dw=new Set;function lx(n){for(const e of Array.from(dw))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let n_=0;const JS=2;let kp=!1,ST=!1;function kT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),q$(`error:${e.message||"unknown"}`)})}function Eb(){return Ns||(Ns=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),kT(Ns),ht.info("speech","worker spawned"),Ns)}let cx=!1;function q$(n){if(!kp){if(cx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(cx=!0,n_+=1,ST=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:n_}),lx({reason:n,respawned:!1,finalOnly:!0}),n_>JS){if(kp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:JS}),Ns)try{Ns.terminate()}catch{}Ns=null,qa=!1,cs=!1,lx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),cx=!1;return}if(Ns)try{Ns.terminate()}catch{}Ns=null,qa=!1,cs=!1;try{Ns=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),kT(Ns),cs=!0,Ns.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),lx({reason:n,respawned:!0,finalOnly:!0})}catch(e){kp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),lx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{cx=!1}}}function K$(n,e){if(qa||cs)return;cs=!0;const i=Eb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(qa=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function Y$(){ht.info("speech","resetModel: clearing load flags"),qa=!1,cs=!1}function hy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function X$(n){const e=Eb();return!qa&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((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")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(qa=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function CT(n){let e=Eb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],p=new Set;let m=null,f=0,b=!1,y=0,_=!1,k=!1,x=0,w=0,S=0,E=-1,j=WS,D=0,$=null,P="",R="",O=!1,B=0;function U(ae,ce){const ye=Math.min(ae.length,ce.length);let Pe=0;for(;Pe<ye&&ae.charCodeAt(Pe)===ce.charCodeAt(Pe);)Pe++;return Pe}function J(ae){const ce=U(P,ae);return P=ae,ce>R.length&&(R=ae.slice(0,ce)),R.length>ae.length&&(R=ae),R}const Q=()=>(m||(m=new Float32Array(cp)),m),Y=()=>{f=0},V=ae=>{const ce=Q(),ye=ae.length;if(ye>=cp){ce.set(ae.subarray(ye-cp)),f=cp;return}if(f+ye<=cp){ce.set(ae,f),f+=ye;return}const Pe=f+ye-cp;ce.copyWithin(0,Pe,f),f-=Pe,ce.set(ae,f),f+=ye},ee=()=>{$&&(clearTimeout($),$=null)},fe=()=>{ee(),b=!1,_=!1,k=!1,j=WS,P="",R="",O=!1,B=0,Y()},oe=()=>{if(i||!b||k||_||$)return;if(f<W$){$=setTimeout(()=>{$=null,oe()},j);return}const ae=performance.now()-x;if(ae<j&&x!==0){$=setTimeout(()=>{$=null,oe()},j-ae);return}if(ST||kp||n.partialsEnabled&&!n.partialsEnabled())return;const ce=Q(),ye=new Float32Array(f);ye.set(ce.subarray(0,f)),w+=1,S=w,_=!0,D=performance.now(),x=D,e.postMessage({type:"transcribe-partial",audio:ye,seq:w},[ye.buffer])},W=ae=>ae.length===0?Promise.resolve():kp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ce=>{c.push(ce),w+=1;const ye=w;E=ye,e.postMessage({type:"transcribe",audio:ae,seq:ye},[ae.buffer])}),re=ae=>{const ce=W(ae);return p.add(ce),ce.finally(()=>{p.delete(ce)}),ce},q=ae=>{var ce,ye,Pe,de,Z;if(ae.data.type==="result"){const Se=ae.data.text,xe=ae.data.seq??0;xe&&xe<E&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:xe,latestFinalSeq:E}),!i&&Se&&n.onFinal(Se),(ce=c.shift())==null||ce()}else if(ae.data.type==="partial"){const Se=ae.data.seq??0,xe=ae.data.text??"",Xe=performance.now()-D;_=!1,Xe>=KS?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Xe),seq:Se})):Xe>=qS&&(j=Math.min(j*2,VS),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Xe),newIntervalMs:j,seq:Se})),O||(O=!0,Xe>V$&&j<500&&(j=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Xe),newIntervalMs:500})));const nt=Se!==S||Se<=E;if(!i&&!nt&&xe){const ut=J(xe);ut&&((ye=n.onPartial)==null||ye.call(n,ut),B===0&&(B=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(B-y)})))}oe()}else if(ae.data.type==="partial-error"){const Se=performance.now()-D;_=!1,Se>=KS?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Se),seq:ae.data.seq})):Se>=qS&&(j=Math.min(j*2,VS),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Se),newIntervalMs:j,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),oe()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Pe=c.shift())==null||Pe()):ae.data.type==="status"?(i||(de=n.onModelStatus)==null||de.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(qa=!0,cs=!1)):ae.data.type==="progress"&&(i||(Z=n.onProgress)==null||Z.call(n,ae.data.pct))};e.addEventListener("message",q);const ie=ae=>{var ce,ye;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(ce=n.onStatusChange)==null||ce.call(n,"restarting");c.length;)(ye=c.shift())==null||ye();if(p.clear(),ee(),_=!1,ae.respawned){try{e.removeEventListener("message",q)}catch{}e=Eb(),e.addEventListener("message",q)}}};return dw.add(ie),{start:async()=>{if(!i){if(kp){n.onError("Speech recognition disabled — please reload the app.");return}!qa&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:qa,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,ce=n.inputDeviceId||null,ye={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ce&&(ye.deviceId={exact:ce}),ht.info("speech","getUserMedia",{hasDeviceId:!!ce,deviceIdPrefix:ce?ce.slice(0,8):null});const Pe=await navigator.mediaDevices.getUserMedia({audio:ye});s=Pe,a=new AudioContext;for(const de of Pe.getAudioTracks())de.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(de){ht.warn("speech","analyser init failed",{error:de instanceof Error?de.message:String(de)}),l=null,d=null}r=await G$.MicVAD.new({audioContext:a,getStream:async()=>Pe,resumeStream:async()=>Pe,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:_T,negativeSpeechThreshold:wT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(de,Z)=>{var Se;i||((Se=n.onFrame)==null||Se.call(n,de),b&&(V(Z),oe()))},onSpeechStart:()=>{var de;i||(fe(),b=!0,y=performance.now(),(de=n.onSpeechStart)==null||de.call(n))},onSpeechEnd:de=>{var Z;i||((Z=n.onStatusChange)==null||Z.call(n,"transcribing"),fe(),re(de))},onVADMisfire:()=>{var de,Z;i||((de=n.onStatusChange)==null||de.call(n,"idle"),fe(),(Z=n.onMisfire)==null||Z.call(n))}}),r.start()}catch(ae){const ce=ae instanceof Error?ae.message:"Microphone access denied",ye=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:ce,stack:ye}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Pe=>Pe.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(ce)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(fe();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,ce)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:ce})}catch(ye){ht.warn("speech","setVadThresholds failed",{error:ye instanceof Error?ye.message:String(ye)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,fe(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}dw.delete(ie),e.removeEventListener("message",q)}}}let vg=null;const uw=new Set,hw=new Set;function J$(){for(const n of uw)try{n()}catch{}}function pw(){for(const n of hw)try{n()}catch{}}function Z$(n){return n.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 Q$(n){if(!window.speechSynthesis)return;const e=Z$(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{vg=performance.now(),J$()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vg=null,pw())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vg=null,pw())},window.speechSynthesis.speak(i)}function ET(){window.speechSynthesis&&(window.speechSynthesis.cancel(),vg=null,pw())}function TT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function eP(){return vg}function tP(n){return uw.add(n),()=>{uw.delete(n)}}function nP(n){return hw.add(n),()=>{hw.delete(n)}}function iP(n){TT()&&(n.setVadThresholds(YS,XS),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=tP(()=>{n.setVadThresholds(YS,XS),ht.info("voice","tts.duck.on")}),i=nP(()=>{n.setVadThresholds(_T,wT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const rP=[{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 sP(n){const e=n.trim();return rP.find(i=>i.match.test(e))??null}const oP=4e4;let uu=null;function Cp(){uu&&clearTimeout(uu),uu=setTimeout(()=>{uu=null,kt.getState().stopRecording()},oP)}function dx(){uu&&(clearTimeout(uu),uu=null)}let Xc=null,qc=null;const aP=.04,lP=.3;let Tb=0,fw=0;function cP(n){qc!==null&&cancelAnimationFrame(qc);const e=()=>{if(Xc===null||kt.getState().submitCountdownStartAt===null){qc=null;return}const i=performance.now();if(i-fw<200&&Tb>lP){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Tb.toFixed(2),msIntoCountdown:Math.round(s)}),Gc(),Cp();return}const r=jT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>aP){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Gc(),Cp();return}}qc=requestAnimationFrame(e)};qc=requestAnimationFrame(e)}function ZS(n){Xc&&clearTimeout(Xc);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),Xc=setTimeout(()=>{var s;Xc=null,kt.setState({submitCountdownStartAt:null});const r=bt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=zn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(zn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),zn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Cp()},e),cP(i)}function Gc(){qc!==null&&(cancelAnimationFrame(qc),qc=null),Xc&&(clearTimeout(Xc),Xc=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Rm=null;function jT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const ux=1e4;let xg=null;function hx(){xg&&(clearTimeout(xg),xg=null)}let ib=null,rb=null;function px(){ib=null,rb&&(rb(),rb=null)}const dP=1500,uP=9e4;let fx=0,sb=null,mw=-1;function mx(){sb&&(clearTimeout(sb),sb=null,mw=-1)}const hP=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=Ti((n,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;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++fx,r=()=>{i===fx&&(mx(),mw=i,sb=setTimeout(()=>{mw===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},uP))};r(),K$((s,a)=>{i===fx&&(s==="ready"?(mx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(mx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===fx&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),mx(),Y$(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!hy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=CT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Tb=l.isSpeech,fw=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),dx(),Gc(),TT()){const c=eP(),p=c!==null?performance.now()-c:null;ET(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Cp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Cp();const c=l.trim();if(!c||hP.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Rm){Rm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=bt.getState().tabs.find(y=>y.id===i))==null?void 0:b.status)==="dormant"){zn.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&ZS(i);const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:c}),y.__transcripts.length>500&&y.__transcripts.shift());return}const m=sP(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Gc();const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:c}),y.__transcripts.length>500&&y.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&ZS(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Gc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,dx(),xr==null||xr.destroy(),xr=null,Rm=null,Be.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Rm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Cp(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=iP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Be.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(dx(),Gc(),Tb=0,fw=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Rm=null),e().hotkeyState==="stopping"&&(hx(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;dx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await qg(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>h$);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Gc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=jb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),hx(),xg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:ux}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),px(),ib={tabId:a,source:r,mode:s},rb=kt.subscribe((p,m)=>{if(ib&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=ib;if(px(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){px(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),hx(),xg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:ux}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(px(),Gc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(hx(),n({hotkeyState:"destroyed"}))}})),pP=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),jb=n=>hy()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}function N0(n,e,i){return new Promise((r,s)=>{const a=setTimeout(()=>s(new Error(`${i} timed out after ${e}ms`)),e);n.then(d=>{clearTimeout(a),r(d)},d=>{clearTimeout(a),s(d)})})}const fP=5e3,to=Ti(()=>({snapshot:null,loaded:!1}));let QS=!1,ek=!1,Im;async function mP(){var n;if(!QS){QS=!0;try{const e=await N0(window.api.schedule.state(),fP,"schedule.state");to.setState({snapshot:e,loaded:!0}),Im=((n=e.paused)==null?void 0:n.reason)??null}catch(e){if(!ek){ek=!0;const i=e instanceof Error?e.message:String(e);Be.error(`Scheduler state hydrate failed: ${i}`)}Im=null}window.api.schedule.onState(e=>{var r;const i=((r=e.paused)==null?void 0:r.reason)??null;Im!==void 0&&i!==Im&&(i==="auth"?Be.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):i==="network"&&Be.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Im=i,to.setState({snapshot:e,loaded:!0})})}}const gP=6e4,vP=5e3,bg=Ti(()=>({data:null,refreshing:!1}));let tk=!1,ob=null,nk=null,ik=!1;async function A0(){bg.setState({refreshing:!0});let n=gP;try{const e=await N0(window.api.billing.fetch(),vP,"billing.fetch");bg.setState({data:e,refreshing:!1}),e.kind==="transient"?n=nk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),nk=e.kind}catch(e){if(bg.setState({refreshing:!1}),!ik){ik=!0;const i=e instanceof Error?e.message:String(e);Be.warn(`Billing usage fetch failed: ${i}`)}}ob=setTimeout(A0,n)}function xP(){tk||(tk=!0,A0())}function DT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function bP(){ob!==null&&(clearTimeout(ob),ob=null),A0()}function Yg(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const gx=new Map,yP=3e4;function $0(n){const[e,i]=M.useState(()=>{var r;return n?((r=gx.get(n))==null?void 0:r.value)??null:null});return M.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=gx.get(n);if(a&&Date.now()-a.ts<yP){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;gx.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;gx.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function Za(n){return n==="overview"?"home":"project"}function _P(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const gw="sm.almanac.sidebarWidth",NT=180,AT=480,vw=252;function wP(){try{const n=parseInt(localStorage.getItem(gw)??"",10);if(Number.isFinite(n))return Math.min(AT,Math.max(NT,n))}catch{}return vw}const SP=52,$T="sm.almanac.sidebarCollapsed";function kP(){try{return localStorage.getItem($T)==="1"}catch{}return!1}const PT="sm.almanac.collapsedGroups";function CP(){try{const n=localStorage.getItem(PT);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function EP(){const n=bt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function TP({active:n,onNavigate:e,onNewSession:i}){const[r,s]=M.useState(()=>CP()),a=M.useCallback(P=>{s(R=>{const O=new Set(R);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(PT,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=M.useState(()=>kP()),c=M.useCallback(()=>{l(P=>{const R=!P;try{localStorage.setItem($T,R?"1":"0")}catch{}return R})},[]),p=bt(P=>P.tabs),m=bt(P=>P.activeTabId),f=p.find(P=>P.id===m)??null,b=EP(),y=Za(n),_=_$(y),k=_.filter(P=>P.group==="Workspace"),x=_.filter(P=>P.group==="Configure"),w=_P(_),[S,E]=M.useState(()=>wP()),j=M.useRef(S);j.current=S;const D=M.useCallback(P=>{P.preventDefault();const R=P.clientX,O=j.current;let B=O;const U=Q=>{B=Math.min(AT,Math.max(NT,O+(Q.clientX-R))),E(B)},J=()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",J),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(gw,String(B))}catch{}};window.addEventListener("pointermove",U),window.addEventListener("pointerup",J),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),$=M.useCallback(()=>{E(vw);try{localStorage.setItem(gw,String(vw))}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:d?SP:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(jP,{tab:f,navFace:y,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(i_,{label:"Workspace",desc:Jy.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(rk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(i_,{label:"Configure",desc:Jy.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(rk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(i_,{label:"Tools",desc:Jy.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(DP,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(NP,{rail:d,navFace:y}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:D,onDoubleClick:$,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 jP({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=$0((n==null?void 0:n.cwd)??null);return r?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:i,"data-testid":"tour-new-session",title:"Open / Start Project",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(an,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,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(an,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?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:"Session Manager"}),o.jsx("button",{onClick:s,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(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):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:s,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(an,{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:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function i_({label:n,desc:e,collapsed:i,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":!i,title:i?`Expand ${n}`:`Collapse ${n}`,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:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&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 rk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.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(an,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&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 DP({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.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(an,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function NP({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=bt(c=>c.tabs),s=bt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=M.useState(null);return M.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return nT(a.presetId).then(p=>{c||l((p==null?void 0:p.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?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 ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"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 ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${Yg(d)}`:"Claude Code"})]})}function AP(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function $P(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const ab=Ti((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:$P(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await qg(async()=>{const{toast:f}=await Promise.resolve().then(()=>oT);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],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||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const y of["command","file_path","pattern","url","query","subagent_type","description"])f&&y in f&&(b[y]=f[y]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const y=m.input,_=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(y==null?void 0:y.file_path)=="string"?y.file_path:void 0,x=typeof(y==null?void 0:y.command)=="string"?y.command:void 0,w=k?k.split("/").pop()??k:x?p(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),_&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${p(k.split("/").pop()??k,34)}`,target:k,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:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,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,y=m.output_tokens??m.outputTokens??0,_=f+b+y;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+y,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(_/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(_/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=AP(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function PP(n){const e=ab(s=>s.subscribe),i=ab(s=>s.unsubscribe),r=ab(s=>n?s.tabs[n.id]:void 0);return M.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function RP({onNavigate:n}){const e=bt(E=>E.tabs),i=bt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=PP(r),a=(s==null?void 0:s.lastEventAt)??0,d=bg(E=>E.data),l=to(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),c=$0((r==null?void 0:r.cwd)??null),[,p]=M.useState(0);M.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=M.useState(!1),y=M.useRef(null);M.useEffect(()=>{if(!f)return;const E=j=>{y.current&&!y.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),M.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const _=DT(d),k=(_==null?void 0:_.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?OP(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:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("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,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(IP,{ref:y,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.45.0"]})]})}const IP=M.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.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 ",i?"▾":"▴"]})]}),i&&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((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(MP,{status:d.status}),o.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},l))})})]})});function MP({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="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 OP(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function LP({onClose:n,onSent:e}){const i=bt(P=>P.tabs),[r,s]=M.useState(""),[a,d]=M.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=M.useState(!1),[p,m]=M.useState({}),f=M.useRef(null),b=M.useRef(e);M.useEffect(()=>{b.current=e},[e]),M.useEffect(()=>{d(P=>{const R={};for(const O of i)R[O.id]=P[O.id]??!0;return R})},[i]),M.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),M.useEffect(()=>window.api.pty.onWriteError(R=>{m(O=>R.tabId in O?{...O,[R.tabId]:"skipped"}:O)}),[]),M.useEffect(()=>{if(Object.keys(p).length===0)return;const P=Object.values(p).filter(O=>O==="sent").length,R=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(R)},[p]);const y=i.filter(P=>a[P.id]).map(P=>P.id),_=y.length,k=Object.keys(p).length>0,x=r.length>0&&_>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=bt.getState().tabs,R=new Set(P.map(B=>B.id)),O={};for(const B of y)R.has(B)?(window.api.pty.write({tabId:B,data:r+"\r"}),O[B]="sent"):O[B]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},E=i.length>0&&i.every(P=>a[P.id]),j=()=>{const P=!E;d(Object.fromEntries(i.map(R=>[R.id,P])))},D=Object.values(p).some(P=>P==="skipped"),$=k?D?"Sent (some skipped)":"Sent":`Send to ${_} tab${_===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:S,"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:P=>s(P.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 (",_,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>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[P.id],onChange:R=>d(O=>({...O,[P.id]:R.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),p[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,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:w,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 zP({tabId:n,cwd:e,onClose:i}){const r=gg(_=>_.watchersForTab(n)),s=gg(_=>_.add),a=gg(_=>_.remove),d=M.useRef(null),[l,c]=M.useState(""),[p,m]=M.useState(""),[f,b]=M.useState(!1);M.useEffect(()=>{const _=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i]),M.useEffect(()=>{const _=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[i]);const y=async()=>{const _=p.trim();if(!_||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:_,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,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:i,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:_=>c(_.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:_=>m(_.target.value),onKeyDown:_=>{_.key==="Enter"&&y()},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:y,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(_=>{const k=_.lines[_.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:_.label}),o.jsxs("span",{className:"text-fg-faint",children:[_.lineCount," line",_.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(_.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${_.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:_.command,children:_.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},_.watcherId)})})]})}/**
2897
+ */var GS;function z$(){return GS||(GS=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(se=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(se,{get:(me,_e)=>(typeof Eo<"u"?Eo:me)[_e]}):se)(function(se){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+se+'" is not supported')}),c=(se,me)=>()=>(se&&(me=se(se=0)),me),p=(se,me)=>{for(var _e in me)r(se,_e,{get:me[_e],enumerable:!0})},m=(se,me,_e,De)=>{if(me&&typeof me=="object"||typeof me=="function")for(let Ee of a(me))!d.call(se,Ee)&&Ee!==_e&&r(se,Ee,{get:()=>me[Ee],enumerable:!(De=s(me,Ee))||De.enumerable});return se},f=se=>m(r({},"__esModule",{value:!0}),se),b,y,_,k,x,w=c(()=>{b=new Map,y=[],_=(se,me,_e)=>{if(me&&typeof me.init=="function"&&typeof me.createInferenceSessionHandler=="function"){let De=b.get(se);if(De===void 0)b.set(se,{backend:me,priority:_e});else{if(De.priority>_e)return;if(De.priority===_e&&De.backend!==me)throw new Error(`cannot register backend "${se}" using priority ${_e}`)}if(_e>=0){let Ee=y.indexOf(se);Ee!==-1&&y.splice(Ee,1);for(let ze=0;ze<y.length;ze++)if(b.get(y[ze]).priority<=_e){y.splice(ze,0,se);return}y.push(se)}return}throw new TypeError("not a valid backend")},k=async se=>{let me=b.get(se);if(!me)return"backend not found.";if(me.initialized)return me.backend;if(me.aborted)return me.error;{let _e=!!me.initPromise;try{return _e||(me.initPromise=me.backend.init(se)),await me.initPromise,me.initialized=!0,me.backend}catch(De){return _e||(me.error=`${De}`,me.aborted=!0),me.error}finally{delete me.initPromise}}},x=async se=>{let me=se.executionProviders||[],_e=me.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=_e.length===0?y:_e,Ee,ze=[],Ae=new Set;for(let Fe of De){let et=await k(Fe);typeof et=="string"?ze.push({name:Fe,err:et}):(Ee||(Ee=et),Ee===et&&Ae.add(Fe))}if(!Ee)throw new Error(`no available backend found. ERR: ${ze.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of ze)_e.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let $e=me.filter(Fe=>Ae.has(typeof Fe=="string"?Fe:Fe.name));return[Ee,new Proxy(se,{get:(Fe,et)=>et==="executionProviders"?$e:Reflect.get(Fe,et)})]}}),S=c(()=>{w()}),E,j=c(()=>{E="1.26.0"}),D,$,P=c(()=>{j(),D="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(se){if(se!==void 0){if(typeof se!="string"||["verbose","info","warning","error","fatal"].indexOf(se)===-1)throw new Error(`Unsupported logging level: ${se}`);D=se}},get logLevel(){return D}},Object.defineProperty($,"logLevel",{enumerable:!0})}),R,O=c(()=>{P(),R=$}),B,U,J=c(()=>{B=(se,me)=>{let _e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_e.width=se.dims[3],_e.height=se.dims[2];let De=_e.getContext("2d");if(De!=null){let Ee,ze;(me==null?void 0:me.tensorLayout)!==void 0&&me.tensorLayout==="NHWC"?(Ee=se.dims[2],ze=se.dims[3]):(Ee=se.dims[3],ze=se.dims[2]);let Ae=(me==null?void 0:me.format)!==void 0?me.format:"RGB",$e=me==null?void 0:me.norm,Fe,et;$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?et=[0,0,0,0]:typeof $e.bias=="number"?et=[$e.bias,$e.bias,$e.bias,$e.bias]:(et=[$e.bias[0],$e.bias[1],$e.bias[2],0],$e.bias[3]!==void 0&&(et[3]=$e.bias[3]));let st=ze*Ee,tt=0,Ye=st,$t=st*2,Le=-1;Ae==="RGBA"?(tt=0,Ye=st,$t=st*2,Le=st*3):Ae==="RGB"?(tt=0,Ye=st,$t=st*2):Ae==="RBG"&&(tt=0,$t=st,Ye=st*2);for(let dt=0;dt<ze;dt++)for(let Pn=0;Pn<Ee;Pn++){let en=(se.data[tt++]-et[0])*Fe[0],tn=(se.data[Ye++]-et[1])*Fe[1],Rn=(se.data[$t++]-et[2])*Fe[2],Lt=Le===-1?255:(se.data[Le++]-et[3])*Fe[3];De.fillStyle="rgba("+en+","+tn+","+Rn+","+Lt+")",De.fillRect(Pn,dt,1,1)}if("toDataURL"in _e)return _e.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},U=(se,me)=>{let _e=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(_e!=null){let Ee,ze,Ae;(me==null?void 0:me.tensorLayout)!==void 0&&me.tensorLayout==="NHWC"?(Ee=se.dims[2],ze=se.dims[1],Ae=se.dims[3]):(Ee=se.dims[3],ze=se.dims[2],Ae=se.dims[1]);let $e=me!==void 0&&me.format!==void 0?me.format:"RGB",Fe=me==null?void 0:me.norm,et,st;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?st=[0,0,0,0]:typeof Fe.bias=="number"?st=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(st=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(st[3]=Fe.bias[3]));let tt=ze*Ee;if(me!==void 0&&(me.format!==void 0&&Ae===4&&me.format!=="RGBA"||Ae===3&&me.format!=="RGB"&&me.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ye=4,$t=0,Le=1,dt=2,Pn=3,en=0,tn=tt,Rn=tt*2,Lt=-1;$e==="RGBA"?(en=0,tn=tt,Rn=tt*2,Lt=tt*3):$e==="RGB"?(en=0,tn=tt,Rn=tt*2):$e==="RBG"&&(en=0,Rn=tt,tn=tt*2),De=_e.createImageData(Ee,ze);for(let Bn=0;Bn<ze*Ee;$t+=Ye,Le+=Ye,dt+=Ye,Pn+=Ye,Bn++)De.data[$t]=(se.data[en++]-st[0])*et[0],De.data[Le]=(se.data[tn++]-st[1])*et[1],De.data[dt]=(se.data[Rn++]-st[2])*et[2],De.data[Pn]=Lt===-1?255:(se.data[Lt++]-st[3])*et[3]}else throw new Error("Can not access image data");return De}}),Q,Y,V,ee,fe,oe,W=c(()=>{Se(),Q=(se,me)=>{if(se===void 0)throw new Error("Image buffer must be defined");if(me.height===void 0||me.width===void 0)throw new Error("Image height and width must be defined");if(me.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:_e,width:De}=me,Ee=me.norm??{mean:255,bias:0},ze,Ae;typeof Ee.mean=="number"?ze=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:ze=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?Ae=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:Ae=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let $e=me.format!==void 0?me.format:"RGBA",Fe=me.tensorFormat!==void 0&&me.tensorFormat!==void 0?me.tensorFormat:"RGB",et=_e*De,st=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Ye=0,$t=1,Le=2,dt=3,Pn=0,en=et,tn=et*2,Rn=-1;$e==="RGB"&&(tt=3,Ye=0,$t=1,Le=2,dt=-1),Fe==="RGBA"?Rn=et*3:Fe==="RBG"?(Pn=0,tn=et,en=et*2):Fe==="BGR"&&(tn=0,en=et,Pn=et*2);for(let Lt=0;Lt<et;Lt++,Ye+=tt,Le+=tt,$t+=tt,dt+=tt)st[Pn++]=(se[Ye]+Ae[0])/ze[0],st[en++]=(se[$t]+Ae[1])/ze[1],st[tn++]=(se[Le]+Ae[2])/ze[2],Rn!==-1&&dt!==-1&&(st[Rn++]=(se[dt]+Ae[3])/ze[3]);return Fe==="RGBA"?new Z("float32",st,[1,4,_e,De]):new Z("float32",st,[1,3,_e,De])},Y=async(se,me)=>{let _e=typeof HTMLImageElement<"u"&&se instanceof HTMLImageElement,De=typeof ImageData<"u"&&se instanceof ImageData,Ee=typeof ImageBitmap<"u"&&se instanceof ImageBitmap,ze=typeof se=="string",Ae,$e=me??{},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")},et=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(_e){let st=Fe();st.width=se.width,st.height=se.height;let tt=et(st);if(tt!=null){let Ye=se.height,$t=se.width;if(me!==void 0&&me.resizedHeight!==void 0&&me.resizedWidth!==void 0&&(Ye=me.resizedHeight,$t=me.resizedWidth),me!==void 0){if($e=me,me.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$e.tensorFormat="RGBA",$e.height=Ye,$e.width=$t}else $e.tensorFormat="RGBA",$e.height=Ye,$e.width=$t;tt.drawImage(se,0,0),Ae=tt.getImageData(0,0,$t,Ye).data}else throw new Error("Can not access image data")}else if(De){let st,tt;if(me!==void 0&&me.resizedWidth!==void 0&&me.resizedHeight!==void 0?(st=me.resizedHeight,tt=me.resizedWidth):(st=se.height,tt=se.width),me!==void 0&&($e=me),$e.format="RGBA",$e.height=st,$e.width=tt,me!==void 0){let Ye=Fe();Ye.width=tt,Ye.height=st;let $t=et(Ye);if($t!=null)$t.putImageData(se,0,0),Ae=$t.getImageData(0,0,tt,st).data;else throw new Error("Can not access image data")}else Ae=se.data}else if(Ee){if(me===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Fe();st.width=se.width,st.height=se.height;let tt=et(st);if(tt!=null){let Ye=se.height,$t=se.width;return tt.drawImage(se,0,0,$t,Ye),Ae=tt.getImageData(0,0,$t,Ye).data,$e.height=Ye,$e.width=$t,Q(Ae,$e)}else throw new Error("Can not access image data")}else{if(ze)return new Promise((st,tt)=>{let Ye=Fe(),$t=et(Ye);if(!se||!$t)return tt();let Le=new Image;Le.crossOrigin="Anonymous",Le.src=se,Le.onload=()=>{Ye.width=Le.width,Ye.height=Le.height,$t.drawImage(Le,0,0,Ye.width,Ye.height);let dt=$t.getImageData(0,0,Ye.width,Ye.height);$e.height=Ye.height,$e.width=Ye.width,st(Q(dt.data,$e))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ae!==void 0)return Q(Ae,$e);throw new Error("Input data provided is not supported - aborted tensor creation")},V=(se,me)=>{let{width:_e,height:De,download:Ee,dispose:ze}=me,Ae=[1,De,_e,4];return new Z({location:"texture",type:"float32",texture:se,dims:Ae,download:Ee,dispose:ze})},ee=(se,me)=>{let{dataType:_e,dims:De,download:Ee,dispose:ze}=me;return new Z({location:"gpu-buffer",type:_e??"float32",gpuBuffer:se,dims:De,download:Ee,dispose:ze})},fe=(se,me)=>{let{dataType:_e,dims:De,download:Ee,dispose:ze}=me;return new Z({location:"ml-tensor",type:_e??"float32",mlTensor:se,dims:De,download:Ee,dispose:ze})},oe=(se,me,_e)=>new Z({location:"cpu-pinned",type:se,data:me,dims:_e??[me.length]})}),re,q,ie,ae,ce=c(()=>{re=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ie=!1,ae=()=>{if(!ie){ie=!0;let se=typeof BigInt64Array<"u"&&BigInt64Array.from,me=typeof BigUint64Array<"u"&&BigUint64Array.from,_e=globalThis.Float16Array,De=typeof _e<"u"&&_e.from;se&&(re.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),me&&(re.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),De?(re.set("float16",_e),q.set(_e,"float16")):re.set("float16",Uint16Array)}}}),ye,Pe,de=c(()=>{Se(),ye=se=>{let me=1;for(let _e=0;_e<se.length;_e++){let De=se[_e];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${_e}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${_e}] must be a non-negative integer, got: ${De}`);me*=De}return me},Pe=(se,me)=>{switch(se.location){case"cpu":return new Z(se.type,se.data,me);case"cpu-pinned":return new Z({location:"cpu-pinned",data:se.data,type:se.type,dims:me});case"texture":return new Z({location:"texture",texture:se.texture,type:se.type,dims:me});case"gpu-buffer":return new Z({location:"gpu-buffer",gpuBuffer:se.gpuBuffer,type:se.type,dims:me});case"ml-tensor":return new Z({location:"ml-tensor",mlTensor:se.mlTensor,type:se.type,dims:me});default:throw new Error(`tensorReshape: tensor location ${se.location} is not supported`)}}}),Z,Se=c(()=>{J(),W(),ce(),de(),Z=class{constructor(se,me,_e){ae();let De,Ee;if(typeof se=="object"&&"location"in se)switch(this.dataLocation=se.location,De=se.type,Ee=se.dims,se.location){case"cpu-pinned":{let Ae=re.get(De);if(!Ae)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(se.data instanceof Ae))throw new TypeError(`buffer should be of type ${Ae.name}`);this.cpuData=se.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=se.texture,this.downloader=se.download,this.disposer=se.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=se.gpuBuffer,this.downloader=se.download,this.disposer=se.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=se.mlTensor,this.downloader=se.download,this.disposer=se.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ae,$e;if(typeof se=="string")if(De=se,$e=_e,se==="string"){if(!Array.isArray(me))throw new TypeError("A string tensor's data must be a string array.");Ae=me}else{let Fe=re.get(se);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${se}.`);if(Array.isArray(me)){if(se==="float16"&&Fe===Uint16Array||se==="uint4"||se==="int4")throw new TypeError(`Creating a ${se} tensor from number array is not supported. Please use ${Fe.name} as data.`);se==="uint64"||se==="int64"?Ae=Fe.from(me,BigInt):Ae=Fe.from(me)}else if(me instanceof Fe)Ae=me;else if(me instanceof Uint8ClampedArray)if(se==="uint8")Ae=Uint8Array.from(me);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(se==="float16"&&me instanceof Uint16Array&&Fe!==Uint16Array)Ae=new globalThis.Float16Array(me.buffer,me.byteOffset,me.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if($e=me,Array.isArray(se)){if(se.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof se[0];if(Fe==="string")De="string",Ae=se;else if(Fe==="boolean")De="bool",Ae=Uint8Array.from(se);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(se instanceof Uint8ClampedArray)De="uint8",Ae=Uint8Array.from(se);else{let Fe=q.get(se.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${se.constructor}.`);De=Fe,Ae=se}if($e===void 0)$e=[Ae.length];else if(!Array.isArray($e))throw new TypeError("A tensor's dims must be a number array");Ee=$e,this.cpuData=Ae,this.dataLocation="cpu"}let ze=ye(Ee);if(this.cpuData&&ze!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(ze/2)===this.cpuData.length))throw new Error(`Tensor's size(${ze}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Ee,this.size=ze}static async fromImage(se,me){return Y(se,me)}static fromTexture(se,me){return V(se,me)}static fromGpuBuffer(se,me){return ee(se,me)}static fromMLTensor(se,me){return fe(se,me)}static fromPinnedBuffer(se,me,_e){return oe(se,me,_e)}toDataURL(se){return B(this,se)}toImageData(se){return U(this,se)}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(se){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 me=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=me,se&&this.disposer&&(this.disposer(),this.disposer=void 0),me}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(se){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Pe(this,se)}}}),xe,Xe=c(()=>{Se(),xe=Z}),nt,ut,Xt,pt,it,ot,Nt=c(()=>{P(),nt=(se,me)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${se}::ORT::${me}`)},ut=(se,me)=>{var Ee;let _e=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let ze=0;ze<_e.length;ze++){if(De&&!_e[ze].includes("TRACE_FUNC")){let Ae=`FUNC_${se}::${_e[ze].trim().split(" ")[1]}`;me&&(Ae+=`::${me}`),nt("CPU",Ae);return}_e[ze].includes("TRACE_FUNC")&&(De=!0)}},Xt=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||ut("BEGIN",se)},pt=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||ut("END",se)},it=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${se}`)},ot=se=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${se}`)}}),rn,fn=c(()=>{w(),Xe(),Nt(),rn=class bT{constructor(me){this.handler=me}async run(me,_e,De){Xt(),it("InferenceSession.run");let Ee={},ze={};if(typeof me!="object"||me===null||me instanceof xe||Array.isArray(me))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ae=!0;if(typeof _e=="object"){if(_e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_e instanceof xe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_e)){if(_e.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ae=!1;for(let et of _e){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ee[et]=null}if(typeof De=="object"&&De!==null)ze=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,st=Object.getOwnPropertyNames(_e);for(let tt of this.outputNames)if(st.indexOf(tt)!==-1){let Ye=_e[tt];(Ye===null||Ye instanceof xe)&&(et=!0,Ae=!1,Ee[tt]=Ye)}if(et){if(typeof De=="object"&&De!==null)ze=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else ze=_e}}else if(typeof _e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof me[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Ae)for(let et of this.outputNames)Ee[et]=null;let $e=await this.handler.run(me,Ee,ze),Fe={};for(let et in $e)if(Object.hasOwnProperty.call($e,et)){let st=$e[et];st instanceof xe?Fe[et]=st:Fe[et]=new xe(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Fe}async release(){return this.handler.dispose()}static async create(me,_e,De,Ee){Xt(),it("InferenceSession.create");let ze,Ae={};if(typeof me=="string"){if(ze=me,typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(me instanceof Uint8Array){if(ze=me,typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(me instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&me instanceof SharedArrayBuffer){let st=me,tt=0,Ye=me.byteLength;if(typeof _e=="object"&&_e!==null)Ae=_e;else if(typeof _e=="number"){if(tt=_e,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Ye=me.byteLength-tt,typeof De=="number"){if(Ye=De,!Number.isSafeInteger(Ye))throw new RangeError("'byteLength' must be an integer.");if(Ye<=0||tt+Ye>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-tt}].`);if(typeof Ee=="object"&&Ee!==null)Ae=Ee;else if(typeof Ee<"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 _e<"u")throw new TypeError("'options' must be an object.");ze=new Uint8Array(st,tt,Ye)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$e,Fe]=await x(Ae),et=await $e.createInferenceSessionHandler(ze,Fe);return ot("InferenceSession.create"),pt(),new bT(et)}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}}}),Je,Ct=c(()=>{fn(),Je=rn}),vt=c(()=>{}),hn=c(()=>{}),An=c(()=>{}),er=c(()=>{}),yr={};p(yr,{InferenceSession:()=>Je,TRACE:()=>nt,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>Xt,TRACE_FUNC_END:()=>pt,Tensor:()=>xe,env:()=>R,registerBackend:()=>_});var mn=c(()=>{S(),O(),Ct(),Xe(),vt(),hn(),Nt(),An(),er()}),Hi=c(()=>{}),Yn={};p(Yn,{default:()=>Rs});var ci,gn,Rs,nl=c(()=>{var se;we(),ir(),nr(),ci="ort-wasm-proxy-worker",gn=((se=globalThis.self)==null?void 0:se.name)===ci,gn&&(self.onmessage=me=>{let{type:_e,in:De}=me.data;try{switch(_e){case"init-wasm":ms(De.wasm).then(()=>{ga(De).then(()=>{postMessage({type:_e})},Ee=>{postMessage({type:_e,err:Ee})})},Ee=>{postMessage({type:_e,err:Ee})});break;case"init-ep":{let{epName:Ee,env:ze}=De;Fs(ze,Ee).then(()=>{postMessage({type:_e})},Ae=>{postMessage({type:_e,err:Ae})});break}case"copy-from":{let{buffer:Ee}=De,ze=cn(Ee);postMessage({type:_e,out:ze});break}case"create":{let{model:Ee,options:ze}=De;Cr(Ee,ze).then(Ae=>{postMessage({type:_e,out:Ae})},Ae=>{postMessage({type:_e,err:Ae})});break}case"release":ao(De),postMessage({type:_e});break;case"run":{let{sessionId:Ee,inputIndices:ze,inputs:Ae,outputIndices:$e,options:Fe}=De;Ke(Ee,ze,Ae,$e,new Array($e.length).fill(null),Fe).then(et=>{et.some(st=>st[3]!=="cpu")?postMessage({type:_e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:_e,out:et},mt([...Ae,...et]))},et=>{postMessage({type:_e,err:et})});break}case"end-profiling":sr(De),postMessage({type:_e});break;default:}}catch(Ee){postMessage({type:_e,err:Ee})}}),Rs=gn?null:me=>new Worker(me??kn,{type:"classic",name:ci})}),fa,Is,kn,tr,di,Ms,qr,_r,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),fa=typeof location>"u"?void 0:location.origin,Is=()=>{var se,me;return typeof document<"u"?(se=document.currentScript)==null?void 0:se.src:typeof self<"u"?(me=self.location)==null?void 0:me.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},di=(se,me)=>{try{let _e=me??kn;return(_e?new URL(se,_e):new URL(se)).origin===fa}catch{return!1}},Ms=(se,me)=>{let _e=me??kn;try{return(_e?new URL(se,_e):new URL(se)).href}catch{return}},qr=(se,me)=>`${me??"./"}${se}`,_r=async se=>{let me=await(await fetch(se,{credentials:"same-origin"})).blob();return URL.createObjectURL(me)},ro=async se=>(await import(se)).default,Os=(nl(),f(Yn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(di(kn))return[void 0,Os()];let se=await _r(kn);return[se,Os(se)]},Kr=void 0,Wi=async(se,me,_e,De)=>{let Ee=Kr&&!(se||me);if(Ee)if(kn)Ee=di(kn)||De&&!_e;else if(De&&!_e)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let ze="ort-wasm-simd-threaded.mjs",Ae=se??Ms(ze,me),$e=_e&&Ae&&!di(Ae,me),Fe=$e?await _r(Ae):Ae??qr(ze,me);return[$e?Fe:void 0,await ro(Fe)]}}}),hs,Vi,wr,Br,Ao,ps,fs,ms,Bt,ir=c(()=>{nr(),Vi=!1,wr=!1,Br=!1,Ao=()=>{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}},ps=()=>{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}},fs=()=>{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}},ms=async se=>{if(Vi)return Promise.resolve();if(wr)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");wr=!0;let me=se.initTimeout,_e=se.numThreads;if(se.simd!==!1){if(se.simd==="relaxed"){if(!fs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ps())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=Ao();_e>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+_e+", 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."),se.numThreads=_e=1);let Ee=se.wasmPaths,ze=typeof Ee=="string"?Ee:void 0,Ae=Ee==null?void 0:Ee.mjs,$e=(Ae==null?void 0:Ae.href)??Ae,Fe=Ee==null?void 0:Ee.wasm,et=(Fe==null?void 0:Fe.href)??Fe,st=se.wasmBinary,[tt,Ye]=await Wi($e,ze,_e>1,!!st||!!et),$t=!1,Le=[];if(me>0&&Le.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},me)})),Le.push(new Promise((dt,Pn)=>{let en={numThreads:_e};if(st)en.wasmBinary=st,en.locateFile=tn=>tn;else if(et||ze)en.locateFile=tn=>et??ze+tn;else if($e&&$e.indexOf("blob:")!==0)en.locateFile=tn=>new URL(tn,$e).href;else if(tt){let tn=tr();tn&&(en.locateFile=Rn=>tn+Rn)}Ye(en).then(tn=>{wr=!1,Vi=!0,hs=tn,dt(),tt&&URL.revokeObjectURL(tt)},tn=>{wr=!1,Br=!0,Pn(tn)})})),await Promise.race(Le),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${me}ms`)},Bt=()=>{if(Vi&&hs)return hs;throw new Error("WebAssembly is not initialized yet.")}}),Xn,jn,Et,so=c(()=>{ir(),Xn=(se,me)=>{let _e=Bt(),De=_e.lengthBytesUTF8(se)+1,Ee=_e._malloc(De);return _e.stringToUTF8(se,Ee,De),me.push(Ee),Ee},jn=(se,me,_e,De)=>{if(typeof se=="object"&&se!==null){if(_e.has(se))throw new Error("Circular reference in options");_e.add(se)}Object.entries(se).forEach(([Ee,ze])=>{let Ae=me?me+Ee:Ee;if(typeof ze=="object")jn(ze,Ae+".",_e,De);else if(typeof ze=="string"||typeof ze=="number")De(Ae,ze.toString());else if(typeof ze=="boolean")De(Ae,ze?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof ze}`)})},Et=se=>{let me=Bt(),_e=me.stackSave();try{let De=me.PTR_SIZE,Ee=me.stackAlloc(2*De);me._OrtGetLastError(Ee,Ee+De);let ze=Number(me.getValue(Ee,De===4?"i32":"i64")),Ae=me.getValue(Ee+De,"*"),$e=Ae?me.UTF8ToString(Ae):"";throw new Error(`${se} ERROR_CODE: ${ze}, ERROR_MESSAGE: ${$e}`)}finally{me.stackRestore(_e)}}}),$o,il=c(()=>{ir(),so(),$o=se=>{let me=Bt(),_e=0,De=[],Ee=se||{};try{if((se==null?void 0:se.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof se.logSeverityLevel!="number"||!Number.isInteger(se.logSeverityLevel)||se.logSeverityLevel<0||se.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${se.logSeverityLevel}`);if((se==null?void 0:se.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof se.logVerbosityLevel!="number"||!Number.isInteger(se.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${se.logVerbosityLevel}`);(se==null?void 0:se.terminate)===void 0&&(Ee.terminate=!1);let ze=0;return(se==null?void 0:se.tag)!==void 0&&(ze=Xn(se.tag,De)),_e=me._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,ze),_e===0&&Et("Can't create run options."),(se==null?void 0:se.extra)!==void 0&&jn(se.extra,"",new WeakSet,(Ae,$e)=>{let Fe=Xn(Ae,De),et=Xn($e,De);me._OrtAddRunConfigEntry(_e,Fe,et)!==0&&Et(`Can't set a run config entry: ${Ae} - ${$e}.`)}),[_e,De]}catch(ze){throw _e!==0&&me._OrtReleaseRunOptions(_e),De.forEach(Ae=>me._free(Ae)),ze}}}),Po,Ro,ma,Oi,rl,sl,Dn=c(()=>{ir(),so(),Po=se=>{switch(se){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: ${se}`)}},Ro=se=>{switch(se){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${se}`)}},ma=se=>{se.extra||(se.extra={}),se.extra.session||(se.extra.session={});let me=se.extra.session;me.use_ort_model_bytes_directly||(me.use_ort_model_bytes_directly="1"),se.executionProviders&&se.executionProviders.some(_e=>(typeof _e=="string"?_e:_e.name)==="webgpu")&&(se.enableMemPattern=!1)},Oi=(se,me,_e,De)=>{let Ee=Xn(me,De),ze=Xn(_e,De);Bt()._OrtAddSessionConfigEntry(se,Ee,ze)!==0&&Et(`Can't set a session config entry: ${me} - ${_e}.`)},rl=async(se,me,_e)=>{let De=me.executionProviders;for(let Ee of De){let ze=typeof Ee=="string"?Ee:Ee.name,Ae=[];switch(ze){case"webnn":if(ze="WEBNN",Oi(se,"session.disable_quant_qdq","1",_e),Oi(se,"session.disable_qdq_constant_folding","1",_e),typeof Ee!="string"){let tt=Ee==null?void 0:Ee.deviceType;tt&&Oi(se,"deviceType",tt,_e)}break;case"webgpu":if(ze="JS",typeof Ee!="string"){let tt=Ee;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Oi(se,"preferredLayout",tt.preferredLayout,_e)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${ze}`)}let $e=Xn(ze,_e),Fe=Ae.length,et=0,st=0;if(Fe>0){et=Bt()._malloc(Fe*Bt().PTR_SIZE),_e.push(et),st=Bt()._malloc(Fe*Bt().PTR_SIZE),_e.push(st);for(let tt=0;tt<Fe;tt++)Bt().setValue(et+tt*Bt().PTR_SIZE,Ae[tt][0],"*"),Bt().setValue(st+tt*Bt().PTR_SIZE,Ae[tt][1],"*")}await Bt()._OrtAppendExecutionProvider(se,$e,et,st,Fe)!==0&&Et(`Can't append execution provider: ${ze}.`)}},sl=async se=>{let me=Bt(),_e=0,De=[],Ee=se||{};ma(Ee);try{let ze=Po(Ee.graphOptimizationLevel??"all"),Ae=Ro(Ee.executionMode??"sequential"),$e=typeof Ee.logId=="string"?Xn(Ee.logId,De):0,Fe=Ee.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ee.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let st=typeof Ee.optimizedModelFilePath=="string"?Xn(Ee.optimizedModelFilePath,De):0;if(_e=me._OrtCreateSessionOptions(ze,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,Ae,!!Ee.enableProfiling,0,$e,Fe,et,st),_e===0&&Et("Can't create session options."),Ee.executionProviders&&await rl(_e,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Oi(_e,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[tt,Ye]of Object.entries(Ee.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Ye!="number"||!Number.isInteger(Ye)||Ye<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ye}`);let $t=Xn(tt,De);me._OrtAddFreeDimensionOverride(_e,$t,Ye)!==0&&Et(`Can't set a free dimension override: ${tt} - ${Ye}.`)}return Ee.extra!==void 0&&jn(Ee.extra,"",new WeakSet,(tt,Ye)=>{Oi(_e,tt,Ye,De)}),[_e,De]}catch(ze){throw _e!==0&&me._OrtReleaseSessionOptions(_e)!==0&&Et("Can't release session options."),De.forEach(Ae=>me._free(Ae)),ze}}}),qi,Qn,Ki,gs,oo,zs,Sr,ji,Ft=c(()=>{qi=se=>{switch(se){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: ${se}`)}},Qn=se=>{switch(se){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: ${se}`)}},Ki=(se,me)=>{let _e=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][se],De=typeof me=="number"?me:me.reduce((Ee,ze)=>Ee*ze,1);return _e>0?Math.ceil(De*_e):void 0},gs=se=>{switch(se){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: ${se}`)}},oo=se=>{switch(se){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: ${se}`)}},zs=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Sr=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint64"||se==="int8"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",ji=se=>{switch(se){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: ${se}`)}}}),ei,Bs=c(()=>{Hi(),ei=async se=>{if(typeof se=="string"){let me=await fetch(se);if(!me.ok)throw new Error(`failed to load external data file: ${se}`);let _e=me.headers.get("Content-Length"),De=_e?parseInt(_e,10):0;if(De<1073741824)return new Uint8Array(await me.arrayBuffer());{if(!me.body)throw new Error(`failed to load external data file: ${se}, no response body.`);let Ee=me.body.getReader(),ze;try{ze=new ArrayBuffer(De)}catch($e){if($e instanceof RangeError){let Fe=Math.ceil(De/65536);ze=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw $e}let Ae=0;for(;;){let{done:$e,value:Fe}=await Ee.read();if($e)break;let et=Fe.byteLength;new Uint8Array(ze,Ae,et).set(Fe),Ae+=et}return new Uint8Array(ze,0,De)}}else return se instanceof Blob?new Uint8Array(await se.arrayBuffer()):se instanceof Uint8Array?se:new Uint8Array(se)}}),kr,ga,Fs,rr,Yr,Gs,cn,Cr,ao,Fr,Ke,sr,mt,we=c(()=>{mn(),il(),Dn(),Ft(),ir(),so(),Bs(),kr=(se,me)=>{Bt()._OrtInit(se,me)!==0&&Et("Can't initialize onnxruntime.")},ga=async se=>{kr(se.wasm.numThreads,oo(se.logLevel))},Fs=async(se,me)=>{var De,Ee;(Ee=(De=Bt()).asyncInit)==null||Ee.call(De);let _e=se.webgpu.adapter;if(me==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(_e){if(typeof _e.limits!="object"||typeof _e.features!="object"||typeof _e.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let ze=se.webgpu.powerPreference;if(ze!==void 0&&ze!=="low-power"&&ze!=="high-performance")throw new Error(`Invalid powerPreference setting: "${ze}"`);let Ae=se.webgpu.forceFallbackAdapter;if(Ae!==void 0&&typeof Ae!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ae}"`);if(_e=await navigator.gpu.requestAdapter({powerPreference:ze,forceFallbackAdapter:Ae}),!_e)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(me==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rr=new Map,Yr=se=>{let me=Bt(),_e=me.stackSave();try{let De=me.PTR_SIZE,Ee=me.stackAlloc(2*De);me._OrtGetInputOutputCount(se,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let ze=De===4?"i32":"i64";return[Number(me.getValue(Ee,ze)),Number(me.getValue(Ee+De,ze))]}finally{me.stackRestore(_e)}},Gs=(se,me)=>{let _e=Bt(),De=_e.stackSave(),Ee=0;try{let ze=_e.PTR_SIZE,Ae=_e.stackAlloc(2*ze);_e._OrtGetInputOutputMetadata(se,me,Ae,Ae+ze)!==0&&Et("Can't get session input/output metadata.");let $e=Number(_e.getValue(Ae,"*"));Ee=Number(_e.getValue(Ae+ze,"*"));let Fe=_e.HEAP32[Ee/4];if(Fe===0)return[$e,0];let et=_e.HEAPU32[Ee/4+1],st=[];for(let tt=0;tt<et;tt++){let Ye=Number(_e.getValue(Ee+8+tt*ze,"*"));st.push(Ye!==0?_e.UTF8ToString(Ye):Number(_e.getValue(Ee+8+(tt+et)*ze,"*")))}return[$e,Fe,st]}finally{_e.stackRestore(De),Ee!==0&&_e._OrtFree(Ee)}},cn=se=>{let me=Bt(),_e=me._malloc(se.byteLength);if(_e===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${se.byteLength}.`);return me.HEAPU8.set(se,_e),[_e,se.byteLength]},Cr=async(se,me)=>{var st,tt,Ye;let _e,De,Ee=Bt();Array.isArray(se)?[_e,De]=se:se.buffer===Ee.HEAPU8.buffer?[_e,De]=[se.byteOffset,se.byteLength]:[_e,De]=cn(se);let ze=0,Ae=0,$e=[],Fe=[],et=[];try{if([Ae,$e]=await sl(me),(me==null?void 0:me.externalData)&&Ee.mountExternalData){let Bn=[];for(let pn of me.externalData){let Di=typeof pn=="string"?pn:pn.path;Bn.push(ei(typeof pn=="string"?pn:pn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(me==null?void 0:me.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let pn=Bn,Di=pn==null?void 0:pn.context,Yi=pn==null?void 0:pn.gpuDevice,or=pn==null?void 0:pn.deviceType,al=pn==null?void 0:pn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:al})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}ze=await Ee._OrtCreateSession(_e,De,Ae),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,ze),ze===0&&Et("Can't create a session."),(tt=Ee.jsepOnCreateSession)==null||tt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(ze,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,Le]=Yr(ze),dt=!!(me!=null&&me.enableGraphCapture),Pn=[],en=[],tn=[],Rn=[],Lt=[];for(let Bn=0;Bn<$t;Bn++){let[pn,Di,Yi]=Gs(ze,Bn);pn===0&&Et("Can't get an input name."),Fe.push(pn);let or=Ee.UTF8ToString(pn);Pn.push(or),tn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:Qn(Di),shape:Yi})}for(let Bn=0;Bn<Le;Bn++){let[pn,Di,Yi]=Gs(ze,Bn+$t);pn===0&&Et("Can't get an output name."),et.push(pn);let or=Ee.UTF8ToString(pn);en.push(or),Rn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:Qn(Di),shape:Yi})}return rr.set(ze,[ze,Fe,et,null,dt,!1]),[ze,Pn,en,tn,Rn]}catch($t){throw Fe.forEach(Le=>Ee._OrtFree(Le)),et.forEach(Le=>Ee._OrtFree(Le)),ze!==0&&Ee._OrtReleaseSession(ze)!==0&&Et("Can't release session."),$t}finally{Ee._free(_e),Ae!==0&&Ee._OrtReleaseSessionOptions(Ae)!==0&&Et("Can't release session options."),$e.forEach($t=>Ee._free($t)),(Ye=Ee.unmountExternalData)==null||Ye.call(Ee)}},ao=se=>{var Fe,et,st;let me=Bt(),_e=rr.get(se);if(!_e)throw new Error(`cannot release session. invalid session id: ${se}`);let[De,Ee,ze,Ae,$e]=_e;Ae&&($e&&me._OrtClearBoundOutputs(Ae.handle)!==0&&Et("Can't clear bound outputs."),me._OrtReleaseBinding(Ae.handle)!==0&&Et("Can't release IO binding.")),(Fe=me.jsepOnReleaseSession)==null||Fe.call(me,se),(et=me.webnnOnReleaseSession)==null||et.call(me,se),(st=me.webgpuOnReleaseSession)==null||st.call(me,se),Ee.forEach(tt=>me._OrtFree(tt)),ze.forEach(tt=>me._OrtFree(tt)),me._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(se)},Fr=async(se,me,_e,De,Ee,ze,Ae=!1)=>{if(!se){me.push(0);return}let $e=Bt(),Fe=$e.PTR_SIZE,et=se[0],st=se[1],tt=se[3],Ye=tt,$t,Le;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ae&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${ze} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let en=se[2].gpuBuffer;Le=Ki(qi(et),st);{let tn=$e.jsepRegisterBuffer;if(!tn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=tn(De,ze,en,Le)}}else if(tt==="ml-tensor"){let en=se[2].mlTensor;Le=Ki(qi(et),st);let tn=$e.webnnRegisterMLTensor;if(!tn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=tn(De,en,qi(et),st)}else{let en=se[2];if(Array.isArray(en)){Le=Fe*en.length,$t=$e._malloc(Le),_e.push($t);for(let tn=0;tn<en.length;tn++){if(typeof en[tn]!="string")throw new TypeError(`tensor data at index ${tn} is not a string`);$e.setValue($t+tn*Fe,Xn(en[tn],_e),"*")}}else{let tn=$e.webnnIsGraphInput,Rn=$e.webnnIsGraphOutput;if(et!=="string"&&tn&&Rn){let Lt=$e.UTF8ToString(Ee);if(tn(De,Lt)||Rn(De,Lt)){let Bn=qi(et);Le=Ki(Bn,st),Ye="ml-tensor";let pn=$e.webnnCreateTemporaryTensor,Di=$e.webnnUploadTensor;if(!pn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await pn(De,Bn,st);Di(Yi,new Uint8Array(en.buffer,en.byteOffset,en.byteLength)),$t=Yi}else Le=en.byteLength,$t=$e._malloc(Le),_e.push($t),$e.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,Le),$t)}else Le=en.byteLength,$t=$e._malloc(Le),_e.push($t),$e.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,Le),$t)}}let dt=$e.stackSave(),Pn=$e.stackAlloc(4*st.length);try{st.forEach((tn,Rn)=>$e.setValue(Pn+Rn*Fe,tn,Fe===4?"i32":"i64"));let en=$e._OrtCreateTensor(qi(et),$t,Le,Pn,st.length,ji(Ye));en===0&&Et(`Can't create tensor for input/output. session=${De}, index=${ze}.`),me.push(en)}finally{$e.stackRestore(dt)}},Ke=async(se,me,_e,De,Ee,ze)=>{var ar,ic,ld;let Ae=Bt(),$e=Ae.PTR_SIZE,Fe=rr.get(se);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${se}`);let et=Fe[0],st=Fe[1],tt=Fe[2],Ye=Fe[3],$t=Fe[4];Fe[5];let Le=me.length,dt=De.length,Pn=0,en=[],tn=[],Rn=[],Lt=[],Bn=[],pn=Ae.stackSave(),Di=Ae.stackAlloc(Le*$e),Yi=Ae.stackAlloc(Le*$e),or=Ae.stackAlloc(dt*$e),al=Ae.stackAlloc(dt*$e);try{[Pn,en]=$o(ze),it("wasm prepareInputOutputTensor");for(let un=0;un<Le;un++)await Fr(_e[un],tn,Lt,se,st[me[un]],me[un],$t);for(let un=0;un<dt;un++)await Fr(Ee[un],Rn,Lt,se,tt[De[un]],Le+De[un],$t);ot("wasm prepareInputOutputTensor");for(let un=0;un<Le;un++)Ae.setValue(Di+un*$e,tn[un],"*"),Ae.setValue(Yi+un*$e,st[me[un]],"*");for(let un=0;un<dt;un++)Ae.setValue(or+un*$e,Rn[un],"*"),Ae.setValue(al+un*$e,tt[De[un]],"*");(ar=Ae.jsepOnRunStart)==null||ar.call(Ae,et),(ic=Ae.webnnOnRunStart)==null||ic.call(Ae,et);let Ni;Ni=await Ae._OrtRun(et,Yi,Di,Le,al,dt,or,Pn),Ni!==0&&Et("failed to call OrtRun().");let xs=[],cd=[];it("wasm ProcessOutputTensor");for(let un=0;un<dt;un++){let Jr=Number(Ae.getValue(or+un*$e,"*"));if(Jr===Rn[un]||Bn.includes(Rn[un])){xs.push(Ee[un]),Jr!==Rn[un]&&Ae._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let Nu=Ae.stackSave(),Ws=Ae.stackAlloc(4*$e),va=!1,vi,lr=0;try{Ae._OrtGetTensorData(Jr,Ws,Ws+$e,Ws+2*$e,Ws+3*$e)!==0&&Et(`Can't access output tensor data on index ${un}.`);let rc=$e===4?"i32":"i64",cr=Number(Ae.getValue(Ws,rc));lr=Ae.getValue(Ws+$e,"*");let dd=Ae.getValue(Ws+$e*2,"*"),Au=Number(Ae.getValue(Ws+$e*3,rc)),Vs=[];for(let xi=0;xi<Au;xi++)Vs.push(Number(Ae.getValue(dd+xi*$e,rc)));Ae._OrtFree(dd)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Jn)=>xi*Jn,1);vi=Qn(cr);let bs=Ye==null?void 0:Ye.outputPreferredLocations[De[un]];if(vi==="string"){if(bs==="gpu-buffer"||bs==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Jn=0;Jn<Zr;Jn++){let Qr=Ae.getValue(lr+Jn*$e,"*"),ud=Ae.getValue(lr+(Jn+1)*$e,"*"),hd=Jn===Zr-1?void 0:ud-Qr;xi.push(Ae.UTF8ToString(Qr,hd))}xs.push([vi,Vs,xi,"cpu"])}else if(bs==="gpu-buffer"&&Zr>0){let xi=Ae.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Jn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);va=!0,xs.push([vi,Vs,{gpuBuffer:Jn,download:Ae.jsepCreateDownloader(Jn,Qr,vi),dispose:()=>{Ae._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(bs==="ml-tensor"&&Zr>0){let xi=Ae.webnnEnsureTensor,Jn=Ae.webnnIsGraphInputOutputTypeSupported;if(!xi||!Jn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Jn(se,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(se,lr,cr,Vs,!1);va=!0,xs.push([vi,Vs,{mlTensor:Qr,download:Ae.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{Ae.webnnReleaseTensorId(lr),Ae._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(bs==="ml-tensor-cpu-output"&&Zr>0){let xi=Ae.webnnCreateMLTensorDownloader(lr,vi)(),Jn=xs.length;va=!0,cd.push((async()=>{let Qr=[Jn,await xi];return Ae.webnnReleaseTensorId(lr),Ae._OrtReleaseTensor(Jr),Qr})()),xs.push([vi,Vs,[],"cpu"])}else{let xi=gs(vi),Jn=new xi(Zr);new Uint8Array(Jn.buffer,Jn.byteOffset,Jn.byteLength).set(Ae.HEAPU8.subarray(lr,lr+Jn.byteLength)),xs.push([vi,Vs,Jn,"cpu"])}}finally{Ae.stackRestore(Nu),vi==="string"&&lr&&Ae._free(lr),va||Ae._OrtReleaseTensor(Jr)}}Ye&&!$t&&(Ae._OrtClearBoundOutputs(Ye.handle)!==0&&Et("Can't clear bound outputs."),rr.set(se,[et,st,tt,Ye,$t,!1]));for(let[un,Jr]of await Promise.all(cd))xs[un][2]=Jr;return ot("wasm ProcessOutputTensor"),xs}finally{(ld=Ae.webnnOnRunEnd)==null||ld.call(Ae,et),Ae.stackRestore(pn),tn.forEach(Ni=>Ae._OrtReleaseTensor(Ni)),Rn.forEach(Ni=>Ae._OrtReleaseTensor(Ni)),Lt.forEach(Ni=>Ae._free(Ni)),Pn!==0&&Ae._OrtReleaseRunOptions(Pn),en.forEach(Ni=>Ae._free(Ni))}},sr=se=>{let me=Bt(),_e=rr.get(se);if(!_e)throw new Error("invalid session id");let De=_e[0],Ee=me._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),me._OrtFree(Ee)},mt=se=>{let me=[];for(let _e of se){let De=_e[2];!Array.isArray(De)&&"buffer"in De&&me.push(De.buffer)}return me}}),Ie,Ze,jt,sn,dn,On,In,ui,Hn,gi,Mn,Xr,lo,Io,vs,Du,Mo,Oo,sd=c(()=>{mn(),we(),ir(),nr(),Ie=()=>!!R.wasm.proxy&&typeof document<"u",jt=!1,sn=!1,dn=!1,ui=new Map,Hn=(se,me)=>{let _e=ui.get(se);_e?_e.push(me):ui.set(se,[me])},gi=()=>{if(jt||!sn||dn||!Ze)throw new Error("worker not ready")},Mn=se=>{switch(se.data.type){case"init-wasm":jt=!1,se.data.err?(dn=!0,In[1](se.data.err)):(sn=!0,In[0]()),On&&(URL.revokeObjectURL(On),On=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let me=ui.get(se.data.type);se.data.err?me.shift()[1](se.data.err):me.shift()[0](se.data.out);break}}},Xr=async()=>{if(!sn){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(dn)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Ie())return new Promise((se,me)=>{Ze==null||Ze.terminate(),Ls().then(([_e,De])=>{try{Ze=De,Ze.onerror=ze=>me(ze),Ze.onmessage=Mn,In=[se,me];let Ee={type:"init-wasm",in:R};if(!Ee.in.wasm.wasmPaths&&_e){let ze=tr();ze&&(Ee.in.wasm.wasmPaths=ze)}Ze.postMessage(Ee),On=_e}catch(Ee){me(Ee)}},me)});try{await ms(R.wasm),await ga(R),sn=!0}catch(se){throw dn=!0,se}finally{jt=!1}}},lo=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("init-ep",[me,_e]);let De={type:"init-ep",in:{epName:se,env:R}};Ze.postMessage(De)});await Fs(R,se)},Io=async se=>Ie()?(gi(),new Promise((me,_e)=>{Hn("copy-from",[me,_e]);let De={type:"copy-from",in:{buffer:se}};Ze.postMessage(De,[se.buffer])})):cn(se),vs=async(se,me)=>{if(Ie()){if(me!=null&&me.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((_e,De)=>{Hn("create",[_e,De]);let Ee={type:"create",in:{model:se,options:{...me}}},ze=[];se instanceof Uint8Array&&ze.push(se.buffer),Ze.postMessage(Ee,ze)})}else return Cr(se,me)},Du=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("release",[me,_e]);let De={type:"release",in:se};Ze.postMessage(De)});ao(se)},Mo=async(se,me,_e,De,Ee,ze)=>{if(Ie()){if(_e.some(Ae=>Ae[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some(Ae=>Ae))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise((Ae,$e)=>{Hn("run",[Ae,$e]);let Fe=_e,et={type:"run",in:{sessionId:se,inputIndices:me,inputs:Fe,outputIndices:De,options:ze}};Ze.postMessage(et,mt(Fe))})}else return Ke(se,me,_e,De,Ee,ze)},Oo=async se=>{if(Ie())return gi(),new Promise((me,_e)=>{Hn("end-profiling",[me,_e]);let De={type:"end-profiling",in:se};Ze.postMessage(De)});sr(se)}}),Ql,Lo,ol,ec=c(()=>{mn(),sd(),Ft(),Hi(),Bs(),Ql=(se,me)=>{switch(se.location){case"cpu":return[se.type,se.dims,se.data,"cpu"];case"gpu-buffer":return[se.type,se.dims,{gpuBuffer:se.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[se.type,se.dims,{mlTensor:se.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${se.location} for ${me()}`)}},Lo=se=>{switch(se[3]){case"cpu":return new xe(se[0],se[2],se[1]);case"gpu-buffer":{let me=se[0];if(!zs(me))throw new Error(`not supported data type: ${me} for deserializing GPU tensor`);let{gpuBuffer:_e,download:De,dispose:Ee}=se[2];return xe.fromGpuBuffer(_e,{dataType:me,dims:se[1],download:De,dispose:Ee})}case"ml-tensor":{let me=se[0];if(!Sr(me))throw new Error(`not supported data type: ${me} for deserializing MLTensor tensor`);let{mlTensor:_e,download:De,dispose:Ee}=se[2];return xe.fromMLTensor(_e,{dataType:me,dims:se[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${se[3]}`)}},ol=class{async fetchModelAndCopyToWasmMemory(se){return Io(await ei(se))}async loadModel(se,me){Xt();let _e;typeof se=="string"?_e=await this.fetchModelAndCopyToWasmMemory(se):_e=se,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await vs(_e,me),pt()}async dispose(){return Du(this.sessionId)}async run(se,me,_e){Xt();let De=[],Ee=[];Object.entries(se).forEach(tt=>{let Ye=tt[0],$t=tt[1],Le=this.inputNames.indexOf(Ye);if(Le===-1)throw new Error(`invalid input '${Ye}'`);De.push($t),Ee.push(Le)});let ze=[],Ae=[];Object.entries(me).forEach(tt=>{let Ye=tt[0],$t=tt[1],Le=this.outputNames.indexOf(Ye);if(Le===-1)throw new Error(`invalid output '${Ye}'`);ze.push($t),Ae.push(Le)});let $e=De.map((tt,Ye)=>Ql(tt,()=>`input "${this.inputNames[Ee[Ye]]}"`)),Fe=ze.map((tt,Ye)=>tt?Ql(tt,()=>`output "${this.outputNames[Ae[Ye]]}"`):null),et=await Mo(this.sessionId,Ee,$e,Ae,Fe,_e),st={};for(let tt=0;tt<et.length;tt++)st[this.outputNames[Ae[tt]]]=ze[tt]??Lo(et[tt]);return pt(),st}startProfiling(){}endProfiling(){Oo(this.sessionId)}}}),Us={};p(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>zo});var co,Hs,zo,od=c(()=>{mn(),sd(),ec(),co=()=>{(typeof R.wasm.initTimeout!="number"||R.wasm.initTimeout<0)&&(R.wasm.initTimeout=0);let se=R.wasm.simd;if(typeof se!="boolean"&&se!==void 0&&se!=="fixed"&&se!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${se}". Reset it to \`false\` and ignore SIMD feature checking.`),R.wasm.simd=!1),typeof R.wasm.proxy!="boolean"&&(R.wasm.proxy=!1),typeof R.wasm.trace!="boolean"&&(R.wasm.trace=!1),typeof R.wasm.numThreads!="number"||!Number.isInteger(R.wasm.numThreads)||R.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)R.wasm.numThreads=1;else{let me=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;R.wasm.numThreads=Math.min(4,Math.ceil((me||1)/2))}},Hs=class{async init(se){co(),await Xr(),await lo(se)}async createInferenceSessionHandler(se,me){let _e=new ol;return await _e.loadModel(se,me),_e}},zo=new Hs}),ad={};p(ad,{InferenceSession:()=>Je,TRACE:()=>nt,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>Xt,TRACE_FUNC_END:()=>pt,Tensor:()=>xe,default:()=>nc,env:()=>R,registerBackend:()=>_}),mn(),mn(),mn();var tc="1.26.0",nc=yr;{let se=(od(),f(Us)).wasmBackend;_("cpu",se,10),_("wasm",se,10)}return Object.defineProperty(R.versions,"web",{value:tc,enumerable:!0}),f(ad)})();n.exports=i})(t_)),t_.exports}var US;function B$(){return US||(US=1,(function(n){var e=Al&&Al.__createBinding||(Object.create?(function(E,j,D,$){$===void 0&&($=D);var P=Object.getOwnPropertyDescriptor(j,D);(!P||("get"in P?!j.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return j[D]}}),Object.defineProperty(E,$,P)}):(function(E,j,D,$){$===void 0&&($=D),E[$]=j[D]})),i=Al&&Al.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=Al&&Al.__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 i(j,E),j};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(z$()),a=j0(),d=D0(),l=Kg(),c=uy(),p=vT(),m=xT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",y="silero_vad_legacy.onnx",_=E=>({...d.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"});n.getDefaultRealTimeVADOptions=_;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,D,$,P){await D.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:$};const R=new AudioWorkletNode(D,"vad-helper-worklet",j);return R.port.onmessage=async O=>{const B=O.data;if(!(typeof B=="object"&&B&&"message"in B)){console.error("Invalid message event",B);return}switch(B.message){case c.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 P(U);break}}},R}async function w(E,j,D){const $=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const R=E.createScriptProcessor(4096,1,1);let O=!1;return R.onaudioprocess=async B=>{if(!O){O=!0;try{const U=B.inputBuffer.getChannelData(0);B.outputBuffer.getChannelData(0).fill(0);const Q=$.process(U);for(const Y of Q)await D(Y)}catch(U){console.error("Error processing audio:",U)}finally{O=!1}}},R.connect(E.destination),R}class S{constructor(j,D,$,P,R=!1,O=null,B=null,U=null,J=null,Q=null,Y=null,V="uninitialized",ee=!1){this.options=j,this.frameProcessor=D,this.model=$,this.frameSamples=P,this.listening=R,this.errored=O,this._stream=B,this._audioContext=U,this._vadNode=J,this._mediaStreamAudioSourceNode=Q,this._audioProcessorAdapterType=Y,this.initializationState=V,this.ownsAudioContext=ee,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=fe=>{this.initializationState="errored",this.errored=fe},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(fe){throw fe instanceof Error?this.setErrored(fe.message):this.setErrored(String(fe)),fe}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"?k(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 w(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:fe,audioContext:oe,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(fe);const re=new MediaStreamAudioSourceNode(oe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=re,re.connect(W);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:fe,mediaStreamAudioSourceNode:oe}=this.getAudioInstances();await this.options.pauseStream(fe),oe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var oe;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:fe}=this.getAudioInstances();fe instanceof AudioWorkletNode&&fe.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((oe=this._audioContext)==null?void 0:oe.close())},this.setOptions=fe=>{this.frameProcessor.setOptions(fe)},this.processFrame=async fe=>{await this.frameProcessor.process(fe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=fe=>{switch(fe.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(fe.probs,fe.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(fe.audio);break}}}static async new(j={}){const D={...(0,n.getDefaultRealTimeVADOptions)(j.model??n.DEFAULT_MODEL),...j};(0,d.validateOptions)(D),n.ort.env.wasm.wasmPaths=D.onnxWASMBasePath,D.ortConfig!==void 0&&D.ortConfig(n.ort);const $=D.model==="v5"?b:y,P=D.baseAssetPath+$,R=D.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let O;try{O=await R(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(Y){throw console.error(`Encountered an error while loading model file ${P}`),Y}const B=D.model==="v5"?512:1536,U=B/16,J=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:D.positiveSpeechThreshold,negativeSpeechThreshold:D.negativeSpeechThreshold,redemptionMs:D.redemptionMs,preSpeechPadMs:D.preSpeechPadMs,minSpeechMs:D.minSpeechMs,submitUserSpeechOnPause:D.submitUserSpeechOnPause},U),Q=new S(D,J,O,B);if(D.startOnLoad)try{await Q.start()}catch(Y){throw console.error("Error starting micVad",Y),Y}return Q}}n.MicVAD=S})(Al)),Al}var HS;function F$(){return HS||(HS=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=fT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=j0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=D0();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=uy();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=O$();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=L$();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=B$();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(Zy)),Zy}var G$=F$();function ax(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>ax(n,"debug",e,i),info:(n,e,i)=>ax(n,"info",e,i),warn:(n,e,i)=>ax(n,"warn",e,i),error:(n,e,i,r)=>ax(n,"error",e,i,r)},yT=16e3,U$=6,cp=yT*U$,H$=400,W$=yT*H$/1e3,WS=300,VS=2e3,qS=1500,KS=3e3,V$=600,_T=.5,wT=.35,YS=.85,XS=.7;let Ns=null,qa=!1,cs=!1;const dw=new Set;function lx(n){for(const e of Array.from(dw))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let n_=0;const JS=2;let kp=!1,ST=!1;function kT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),q$(`error:${e.message||"unknown"}`)})}function Eb(){return Ns||(Ns=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),kT(Ns),ht.info("speech","worker spawned"),Ns)}let cx=!1;function q$(n){if(!kp){if(cx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(cx=!0,n_+=1,ST=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:n_}),lx({reason:n,respawned:!1,finalOnly:!0}),n_>JS){if(kp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:JS}),Ns)try{Ns.terminate()}catch{}Ns=null,qa=!1,cs=!1,lx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),cx=!1;return}if(Ns)try{Ns.terminate()}catch{}Ns=null,qa=!1,cs=!1;try{Ns=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),kT(Ns),cs=!0,Ns.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),lx({reason:n,respawned:!0,finalOnly:!0})}catch(e){kp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),lx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{cx=!1}}}function K$(n,e){if(qa||cs)return;cs=!0;const i=Eb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(qa=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function Y$(){ht.info("speech","resetModel: clearing load flags"),qa=!1,cs=!1}function hy(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function X$(n){const e=Eb();return!qa&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((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")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(qa=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function CT(n){let e=Eb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],p=new Set;let m=null,f=0,b=!1,y=0,_=!1,k=!1,x=0,w=0,S=0,E=-1,j=WS,D=0,$=null,P="",R="",O=!1,B=0;function U(ae,ce){const ye=Math.min(ae.length,ce.length);let Pe=0;for(;Pe<ye&&ae.charCodeAt(Pe)===ce.charCodeAt(Pe);)Pe++;return Pe}function J(ae){const ce=U(P,ae);return P=ae,ce>R.length&&(R=ae.slice(0,ce)),R.length>ae.length&&(R=ae),R}const Q=()=>(m||(m=new Float32Array(cp)),m),Y=()=>{f=0},V=ae=>{const ce=Q(),ye=ae.length;if(ye>=cp){ce.set(ae.subarray(ye-cp)),f=cp;return}if(f+ye<=cp){ce.set(ae,f),f+=ye;return}const Pe=f+ye-cp;ce.copyWithin(0,Pe,f),f-=Pe,ce.set(ae,f),f+=ye},ee=()=>{$&&(clearTimeout($),$=null)},fe=()=>{ee(),b=!1,_=!1,k=!1,j=WS,P="",R="",O=!1,B=0,Y()},oe=()=>{if(i||!b||k||_||$)return;if(f<W$){$=setTimeout(()=>{$=null,oe()},j);return}const ae=performance.now()-x;if(ae<j&&x!==0){$=setTimeout(()=>{$=null,oe()},j-ae);return}if(ST||kp||n.partialsEnabled&&!n.partialsEnabled())return;const ce=Q(),ye=new Float32Array(f);ye.set(ce.subarray(0,f)),w+=1,S=w,_=!0,D=performance.now(),x=D,e.postMessage({type:"transcribe-partial",audio:ye,seq:w},[ye.buffer])},W=ae=>ae.length===0?Promise.resolve():kp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ce=>{c.push(ce),w+=1;const ye=w;E=ye,e.postMessage({type:"transcribe",audio:ae,seq:ye},[ae.buffer])}),re=ae=>{const ce=W(ae);return p.add(ce),ce.finally(()=>{p.delete(ce)}),ce},q=ae=>{var ce,ye,Pe,de,Z;if(ae.data.type==="result"){const Se=ae.data.text,xe=ae.data.seq??0;xe&&xe<E&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:xe,latestFinalSeq:E}),!i&&Se&&n.onFinal(Se),(ce=c.shift())==null||ce()}else if(ae.data.type==="partial"){const Se=ae.data.seq??0,xe=ae.data.text??"",Xe=performance.now()-D;_=!1,Xe>=KS?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Xe),seq:Se})):Xe>=qS&&(j=Math.min(j*2,VS),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Xe),newIntervalMs:j,seq:Se})),O||(O=!0,Xe>V$&&j<500&&(j=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Xe),newIntervalMs:500})));const nt=Se!==S||Se<=E;if(!i&&!nt&&xe){const ut=J(xe);ut&&((ye=n.onPartial)==null||ye.call(n,ut),B===0&&(B=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(B-y)})))}oe()}else if(ae.data.type==="partial-error"){const Se=performance.now()-D;_=!1,Se>=KS?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Se),seq:ae.data.seq})):Se>=qS&&(j=Math.min(j*2,VS),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Se),newIntervalMs:j,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),oe()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(Pe=c.shift())==null||Pe()):ae.data.type==="status"?(i||(de=n.onModelStatus)==null||de.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(qa=!0,cs=!1)):ae.data.type==="progress"&&(i||(Z=n.onProgress)==null||Z.call(n,ae.data.pct))};e.addEventListener("message",q);const ie=ae=>{var ce,ye;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(ce=n.onStatusChange)==null||ce.call(n,"restarting");c.length;)(ye=c.shift())==null||ye();if(p.clear(),ee(),_=!1,ae.respawned){try{e.removeEventListener("message",q)}catch{}e=Eb(),e.addEventListener("message",q)}}};return dw.add(ie),{start:async()=>{if(!i){if(kp){n.onError("Speech recognition disabled — please reload the app.");return}!qa&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:qa,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,ce=n.inputDeviceId||null,ye={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ce&&(ye.deviceId={exact:ce}),ht.info("speech","getUserMedia",{hasDeviceId:!!ce,deviceIdPrefix:ce?ce.slice(0,8):null});const Pe=await navigator.mediaDevices.getUserMedia({audio:ye});s=Pe,a=new AudioContext;for(const de of Pe.getAudioTracks())de.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(de){ht.warn("speech","analyser init failed",{error:de instanceof Error?de.message:String(de)}),l=null,d=null}r=await G$.MicVAD.new({audioContext:a,getStream:async()=>Pe,resumeStream:async()=>Pe,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:_T,negativeSpeechThreshold:wT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(de,Z)=>{var Se;i||((Se=n.onFrame)==null||Se.call(n,de),b&&(V(Z),oe()))},onSpeechStart:()=>{var de;i||(fe(),b=!0,y=performance.now(),(de=n.onSpeechStart)==null||de.call(n))},onSpeechEnd:de=>{var Z;i||((Z=n.onStatusChange)==null||Z.call(n,"transcribing"),fe(),re(de))},onVADMisfire:()=>{var de,Z;i||((de=n.onStatusChange)==null||de.call(n,"idle"),fe(),(Z=n.onMisfire)==null||Z.call(n))}}),r.start()}catch(ae){const ce=ae instanceof Error?ae.message:"Microphone access denied",ye=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:ce,stack:ye}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(Pe=>Pe.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(ce)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(fe();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,ce)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:ce})}catch(ye){ht.warn("speech","setVadThresholds failed",{error:ye instanceof Error?ye.message:String(ye)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,fe(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}dw.delete(ie),e.removeEventListener("message",q)}}}let vg=null;const uw=new Set,hw=new Set;function J$(){for(const n of uw)try{n()}catch{}}function pw(){for(const n of hw)try{n()}catch{}}function Z$(n){return n.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 Q$(n){if(!window.speechSynthesis)return;const e=Z$(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{vg=performance.now(),J$()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vg=null,pw())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vg=null,pw())},window.speechSynthesis.speak(i)}function ET(){window.speechSynthesis&&(window.speechSynthesis.cancel(),vg=null,pw())}function TT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function eP(){return vg}function tP(n){return uw.add(n),()=>{uw.delete(n)}}function nP(n){return hw.add(n),()=>{hw.delete(n)}}function iP(n){TT()&&(n.setVadThresholds(YS,XS),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=tP(()=>{n.setVadThresholds(YS,XS),ht.info("voice","tts.duck.on")}),i=nP(()=>{n.setVadThresholds(_T,wT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const rP=[{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 sP(n){const e=n.trim();return rP.find(i=>i.match.test(e))??null}const oP=4e4;let uu=null;function Cp(){uu&&clearTimeout(uu),uu=setTimeout(()=>{uu=null,kt.getState().stopRecording()},oP)}function dx(){uu&&(clearTimeout(uu),uu=null)}let Xc=null,qc=null;const aP=.04,lP=.3;let Tb=0,fw=0;function cP(n){qc!==null&&cancelAnimationFrame(qc);const e=()=>{if(Xc===null||kt.getState().submitCountdownStartAt===null){qc=null;return}const i=performance.now();if(i-fw<200&&Tb>lP){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Tb.toFixed(2),msIntoCountdown:Math.round(s)}),Gc(),Cp();return}const r=jT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>aP){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Gc(),Cp();return}}qc=requestAnimationFrame(e)};qc=requestAnimationFrame(e)}function ZS(n){Xc&&clearTimeout(Xc);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),Xc=setTimeout(()=>{var s;Xc=null,kt.setState({submitCountdownStartAt:null});const r=bt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=zn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(zn.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),zn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Cp()},e),cP(i)}function Gc(){qc!==null&&(cancelAnimationFrame(qc),qc=null),Xc&&(clearTimeout(Xc),Xc=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Rm=null;function jT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const ux=1e4;let xg=null;function hx(){xg&&(clearTimeout(xg),xg=null)}let ib=null,rb=null;function px(){ib=null,rb&&(rb(),rb=null)}const dP=1500,uP=9e4;let fx=0,sb=null,mw=-1;function mx(){sb&&(clearTimeout(sb),sb=null,mw=-1)}const hP=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=Ti((n,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;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++fx,r=()=>{i===fx&&(mx(),mw=i,sb=setTimeout(()=>{mw===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},uP))};r(),K$((s,a)=>{i===fx&&(s==="ready"?(mx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(mx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===fx&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),mx(),Y$(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!hy()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=CT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Tb=l.isSpeech,fw=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),dx(),Gc(),TT()){const c=eP(),p=c!==null?performance.now()-c:null;ET(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Cp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Cp();const c=l.trim();if(!c||hP.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Rm){Rm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=bt.getState().tabs.find(y=>y.id===i))==null?void 0:b.status)==="dormant"){zn.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&ZS(i);const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:c}),y.__transcripts.length>500&&y.__transcripts.shift());return}const m=sP(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Gc();const y=window;y.__transcripts&&(y.__transcripts.push({tabId:i,text:c}),y.__transcripts.length>500&&y.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&ZS(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Gc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,dx(),xr==null||xr.destroy(),xr=null,Rm=null,Be.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Rm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Cp(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=iP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Be.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(dx(),Gc(),Tb=0,fw=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Rm=null),e().hotkeyState==="stopping"&&(hx(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;dx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await qg(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>h$);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Gc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=jb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),hx(),xg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:ux}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),px(),ib={tabId:a,source:r,mode:s},rb=kt.subscribe((p,m)=>{if(ib&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=ib;if(px(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){px(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),hx(),xg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:ux}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(px(),Gc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(hx(),n({hotkeyState:"destroyed"}))}})),pP=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),jb=n=>hy()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}function N0(n,e,i){return new Promise((r,s)=>{const a=setTimeout(()=>s(new Error(`${i} timed out after ${e}ms`)),e);n.then(d=>{clearTimeout(a),r(d)},d=>{clearTimeout(a),s(d)})})}const fP=5e3,to=Ti(()=>({snapshot:null,loaded:!1}));let QS=!1,ek=!1,Im;async function mP(){var n;if(!QS){QS=!0;try{const e=await N0(window.api.schedule.state(),fP,"schedule.state");to.setState({snapshot:e,loaded:!0}),Im=((n=e.paused)==null?void 0:n.reason)??null}catch(e){if(!ek){ek=!0;const i=e instanceof Error?e.message:String(e);Be.error(`Scheduler state hydrate failed: ${i}`)}Im=null}window.api.schedule.onState(e=>{var r;const i=((r=e.paused)==null?void 0:r.reason)??null;Im!==void 0&&i!==Im&&(i==="auth"?Be.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):i==="network"&&Be.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Im=i,to.setState({snapshot:e,loaded:!0})})}}const gP=6e4,vP=5e3,bg=Ti(()=>({data:null,refreshing:!1}));let tk=!1,ob=null,nk=null,ik=!1;async function A0(){bg.setState({refreshing:!0});let n=gP;try{const e=await N0(window.api.billing.fetch(),vP,"billing.fetch");bg.setState({data:e,refreshing:!1}),e.kind==="transient"?n=nk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),nk=e.kind}catch(e){if(bg.setState({refreshing:!1}),!ik){ik=!0;const i=e instanceof Error?e.message:String(e);Be.warn(`Billing usage fetch failed: ${i}`)}}ob=setTimeout(A0,n)}function xP(){tk||(tk=!0,A0())}function DT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function bP(){ob!==null&&(clearTimeout(ob),ob=null),A0()}function Yg(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const gx=new Map,yP=3e4;function $0(n){const[e,i]=M.useState(()=>{var r;return n?((r=gx.get(n))==null?void 0:r.value)??null:null});return M.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=gx.get(n);if(a&&Date.now()-a.ts<yP){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;gx.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;gx.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function Za(n){return n==="overview"?"home":"project"}function _P(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const gw="sm.almanac.sidebarWidth",NT=180,AT=480,vw=252;function wP(){try{const n=parseInt(localStorage.getItem(gw)??"",10);if(Number.isFinite(n))return Math.min(AT,Math.max(NT,n))}catch{}return vw}const SP=52,$T="sm.almanac.sidebarCollapsed";function kP(){try{return localStorage.getItem($T)==="1"}catch{}return!1}const PT="sm.almanac.collapsedGroups";function CP(){try{const n=localStorage.getItem(PT);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function EP(){const n=bt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function TP({active:n,onNavigate:e,onNewSession:i}){const[r,s]=M.useState(()=>CP()),a=M.useCallback(P=>{s(R=>{const O=new Set(R);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(PT,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=M.useState(()=>kP()),c=M.useCallback(()=>{l(P=>{const R=!P;try{localStorage.setItem($T,R?"1":"0")}catch{}return R})},[]),p=bt(P=>P.tabs),m=bt(P=>P.activeTabId),f=p.find(P=>P.id===m)??null,b=EP(),y=Za(n),_=_$(y),k=_.filter(P=>P.group==="Workspace"),x=_.filter(P=>P.group==="Configure"),w=_P(_),[S,E]=M.useState(()=>wP()),j=M.useRef(S);j.current=S;const D=M.useCallback(P=>{P.preventDefault();const R=P.clientX,O=j.current;let B=O;const U=Q=>{B=Math.min(AT,Math.max(NT,O+(Q.clientX-R))),E(B)},J=()=>{window.removeEventListener("pointermove",U),window.removeEventListener("pointerup",J),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(gw,String(B))}catch{}};window.addEventListener("pointermove",U),window.addEventListener("pointerup",J),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),$=M.useCallback(()=>{E(vw);try{localStorage.setItem(gw,String(vw))}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:d?SP:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(jP,{tab:f,navFace:y,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(i_,{label:"Workspace",desc:Jy.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(rk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(i_,{label:"Configure",desc:Jy.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(rk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(i_,{label:"Tools",desc:Jy.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(DP,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(NP,{rail:d,navFace:y}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:D,onDoubleClick:$,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 jP({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=$0((n==null?void 0:n.cwd)??null);return r?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:i,"data-testid":"tour-new-session",title:"Open / Start Project",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(an,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,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(an,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?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:"Session Manager"}),o.jsx("button",{onClick:s,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(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):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:s,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(an,{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:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function i_({label:n,desc:e,collapsed:i,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":!i,title:i?`Expand ${n}`:`Collapse ${n}`,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:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&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 rk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.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(an,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&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 DP({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.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(an,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function NP({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=bt(c=>c.tabs),s=bt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=M.useState(null);return M.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return nT(a.presetId).then(p=>{c||l((p==null?void 0:p.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?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 ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"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 ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${Yg(d)}`:"Claude Code"})]})}function AP(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function $P(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const ab=Ti((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:$P(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await qg(async()=>{const{toast:f}=await Promise.resolve().then(()=>oT);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],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||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const y of["command","file_path","pattern","url","query","subagent_type","description"])f&&y in f&&(b[y]=f[y]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const y=m.input,_=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(y==null?void 0:y.file_path)=="string"?y.file_path:void 0,x=typeof(y==null?void 0:y.command)=="string"?y.command:void 0,w=k?k.split("/").pop()??k:x?p(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),_&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${p(k.split("/").pop()??k,34)}`,target:k,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:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,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,y=m.output_tokens??m.outputTokens??0,_=f+b+y;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+y,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(_/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(_/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=AP(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function PP(n){const e=ab(s=>s.subscribe),i=ab(s=>s.unsubscribe),r=ab(s=>n?s.tabs[n.id]:void 0);return M.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function RP({onNavigate:n}){const e=bt(E=>E.tabs),i=bt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=PP(r),a=(s==null?void 0:s.lastEventAt)??0,d=bg(E=>E.data),l=to(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),c=$0((r==null?void 0:r.cwd)??null),[,p]=M.useState(0);M.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=M.useState(!1),y=M.useRef(null);M.useEffect(()=>{if(!f)return;const E=j=>{y.current&&!y.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),M.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const _=DT(d),k=(_==null?void 0:_.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?OP(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:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("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,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(IP,{ref:y,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.45.1"]})]})}const IP=M.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.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 ",i?"▾":"▴"]})]}),i&&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((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(MP,{status:d.status}),o.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},l))})})]})});function MP({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="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 OP(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function LP({onClose:n,onSent:e}){const i=bt(P=>P.tabs),[r,s]=M.useState(""),[a,d]=M.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=M.useState(!1),[p,m]=M.useState({}),f=M.useRef(null),b=M.useRef(e);M.useEffect(()=>{b.current=e},[e]),M.useEffect(()=>{d(P=>{const R={};for(const O of i)R[O.id]=P[O.id]??!0;return R})},[i]),M.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),M.useEffect(()=>window.api.pty.onWriteError(R=>{m(O=>R.tabId in O?{...O,[R.tabId]:"skipped"}:O)}),[]),M.useEffect(()=>{if(Object.keys(p).length===0)return;const P=Object.values(p).filter(O=>O==="sent").length,R=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(R)},[p]);const y=i.filter(P=>a[P.id]).map(P=>P.id),_=y.length,k=Object.keys(p).length>0,x=r.length>0&&_>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=bt.getState().tabs,R=new Set(P.map(B=>B.id)),O={};for(const B of y)R.has(B)?(window.api.pty.write({tabId:B,data:r+"\r"}),O[B]="sent"):O[B]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},E=i.length>0&&i.every(P=>a[P.id]),j=()=>{const P=!E;d(Object.fromEntries(i.map(R=>[R.id,P])))},D=Object.values(p).some(P=>P==="skipped"),$=k?D?"Sent (some skipped)":"Sent":`Send to ${_} tab${_===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:S,"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:P=>s(P.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 (",_,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>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[P.id],onChange:R=>d(O=>({...O,[P.id]:R.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),p[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,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:w,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 zP({tabId:n,cwd:e,onClose:i}){const r=gg(_=>_.watchersForTab(n)),s=gg(_=>_.add),a=gg(_=>_.remove),d=M.useRef(null),[l,c]=M.useState(""),[p,m]=M.useState(""),[f,b]=M.useState(!1);M.useEffect(()=>{const _=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[i]),M.useEffect(()=>{const _=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[i]);const y=async()=>{const _=p.trim();if(!_||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:_,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,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:i,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:_=>c(_.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:_=>m(_.target.value),onKeyDown:_=>{_.key==="Enter"&&y()},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:y,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(_=>{const k=_.lines[_.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:_.label}),o.jsxs("span",{className:"text-fg-faint",children:[_.lineCount," line",_.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(_.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${_.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:_.command,children:_.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},_.watcherId)})})]})}/**
2898
2898
  * dockview-core
2899
2899
  * @version 6.6.1
2900
2900
  * @link https://github.com/mathuo/dockview
@@ -3055,7 +3055,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3055
3055
 
3056
3056
  ${i}`}const dg={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},Rz=["popover","review","diff"],aD=["popover","review"];function Iz(n,e){switch(e.type){case"SELECT":return{...dg,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...dg,editCount:n.editCount};case"LISTEN":return aD.includes(n.phase)?{...n,phase:"listening",transcript:"",modelStatus:null}:n;case"HEARD":return n.phase!=="listening"?n:{...n,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return Rz.includes(n.phase)?{...n,phase:"thinking",instruction:e.recordInstruction?e.instruction:n.instruction}:n;case"RUN_OK":return n.phase!=="thinking"?n:{...n,phase:"diff",diff:e.diff};case"RUN_ERR":return n.phase!=="thinking"?n:{...n,phase:"popover",transcript:"",diff:null};case"ACCEPT":return n.phase!=="diff"?n:{...dg,editCount:n.editCount+1};case"RESET_FILE":return{...dg,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function Mz(n,e){let i=null;for(const r of e){const s=r.cwd;!s||!(n===s||n.startsWith(s.endsWith("/")?s:`${s}/`))||(i===null||s.length>i.length)&&(i=s)}return i}function Oz(n,e,i){var a;let r=null,s=-1/0;for(const d of e){if(d.cwd!==n||d.status!=="dormant")continue;const l=((a=i[d.id])==null?void 0:a.lastEventAt)??0;(r===null||l>s)&&(r=d,s=l)}return r}const Lz="sonnet";function zz(n,e){const[i,r]=M.useReducer(Iz,dg),s=M.useRef(0),a=M.useRef(null),d=M.useRef(n),l=M.useRef(new Map);M.useEffect(()=>window.api.docEdit.onSessionResult(E=>{const j=l.current.get(E.requestId);j&&(l.current.delete(E.requestId),j(E))}),[]),M.useEffect(()=>{d.current!==n&&(d.current=n,s.current+=1,c(),r({type:"RESET_FILE"}))},[n]);function c(){const E=a.current;E&&(a.current=null,E.stop().catch(()=>{}),E.destroy(),kt.setState({externalRecording:!1}))}const p=M.useCallback(E=>{s.current+=1,c(),r({type:"SELECT",selection:E})},[]),m=M.useCallback(()=>{s.current+=1,c(),r({type:"CANCEL"})},[]),f=M.useCallback(()=>{if(!aD.includes(i.phase))return;if(kt.getState().isRecording){Be.error("Microphone is already in use");return}if(!hy()){Be.error("Microphone or Web Worker not available");return}const E=++s.current;r({type:"LISTEN"}),kt.setState({externalRecording:!0});const j=()=>{a.current===D&&(a.current=null),kt.setState({externalRecording:!1})},D=CT({onFinal:$=>{if(s.current!==E)return;D.stop().catch(()=>{}),D.destroy(),j();const P=$.trim();if(!P){r({type:"CANCEL"});return}r({type:"HEARD",transcript:P})},onError:$=>{s.current===E&&(D.destroy(),j(),Be.error(`Microphone error: ${$}`),r({type:"CANCEL"}))},onModelStatus:($,P)=>{s.current===E&&r({type:"MODEL_STATUS",status:$,message:P})},onProgress:$=>{s.current===E&&r({type:"MODEL_STATUS",status:"loading",message:`${$}%`})}});a.current=D,D.start().catch($=>{s.current===E&&(D.destroy(),j(),Be.error(`Could not start mic: ${$ instanceof Error?$.message:String($)}`),r({type:"CANCEL"}))})},[i.phase]),b=M.useCallback(()=>{const E=Mz(n,bt.getState().tabs);if(!E)return null;const j=Oz(E,bt.getState().tabs,ab.getState().tabs);return!j||zn.getState().get(j.id).running?null:j},[n]),y=M.useCallback((E,j,D,$,P,R)=>{const O=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(B=>{l.current.set(O,B),window.api.docEdit.runInSession({tabId:E,sessionId:j,cwd:D,before:$,instruction:P,documentText:R,requestId:O})})},[]),_=M.useCallback(async(E,j)=>{const D=i.selection;if(!D)return;const $=++s.current;r({type:"RUN",instruction:E,recordInstruction:j});const P=Pz(e);try{const R=b(),O=R?await y(R.id,R.sessionId,R.cwd,D.text,E,P):await window.api.docEdit.run({path:n,before:D.text,instruction:E,documentText:P});if(s.current!==$)return;if(!O.ok){Be.error(O.error||"Edit failed"),r({type:"RUN_ERR"});return}r({type:"RUN_OK",diff:{before:D.text,after:O.after??""}})}catch(R){if(s.current!==$)return;Be.error(R instanceof Error?R.message:"Edit failed"),r({type:"RUN_ERR"})}},[n,i.selection,e,b,y]),k=M.useCallback(E=>{_(E,!0)},[_]),x=M.useCallback(()=>{i.phase==="review"&&_(i.transcript,!0)},[_,i.phase,i.transcript]),w=M.useCallback(()=>{const E=i.instruction;E&&_(`${E}
3057
3057
 
3058
- (Give a different rewrite than the last one.)`,!1)},[_,i.instruction]),S=M.useCallback(E=>{const j=i.diff;if(!j)return{ok:!1,reason:"not-found"};const D=Az(E,j.before,j.after);return D.ok?(s.current+=1,r({type:"ACCEPT"})):Be.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},[i.diff]);return{state:i,select:p,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const Bz=[{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."}],NC=320,Vm=8;function Fz(){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 Gz(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,Vm),Math.max(Vm,e-NC-Vm)),r=Math.max(n.top-Vm,Vm);return{position:"fixed",left:i,top:r,width:NC,transform:"translateY(-100%)",zIndex:50}}function Uz({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[y,_]=M.useState(""),k=()=>{const x=y.trim();x&&(d(x),_(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:Gz(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="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"}),Bz.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:y,onChange:x=>_(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():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"})]}),n==="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(Fz,{}),"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"})]}),n==="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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="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"})]}),n==="diff"&&i&&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:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.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 Hz(){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 AC({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,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:Yg(Lz)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="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"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(Hz,{}),"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"})]}),n==="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:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&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:i.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:i.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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function $C(n){return n.split("/").filter(Boolean).pop()||n}function Wz({path:n,onRenamed:e,onDeleted:i}){const[r,s]=M.useState(!1),[a,d]=M.useState(!1),[l,c]=M.useState(""),[p,m]=M.useState(!1),f=$n(B=>B.buffers[n]),b=$n(B=>B.openFile),y=$n(B=>B.renameOpenFile),_=$n(B=>B.closeFile),k=id(),x=$C(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},E=async()=>{const B=l.trim();if(!B||B===x){d(!1);return}try{const U=await window.api.files.rename(n,B);if(U.ok){const J=n.slice(0,n.lastIndexOf("/")),Q=U.newPath??`${J}/${B}`;y(n,Q),e==null||e(n,Q),Be.info(`Renamed to ${B}`)}else Be.error(U.error??`Couldn't rename ${x}`)}catch(U){Be.error(U instanceof Error?U.message:`Couldn't rename ${x}`)}d(!1)},j=async()=>{w();try{const B=await window.api.files.duplicate(n);B.ok&&B.path?(b(B.path),Be.info(`Duplicated as ${$C(B.path)}`)):Be.error(B.error??`Couldn't duplicate ${x}`)}catch(B){Be.error(B instanceof Error?B.message:`Couldn't duplicate ${x}`)}},D=async()=>{try{const B=await window.api.files.delete(n);B.ok?(_(n),i==null||i(n),Be.info(`Deleted ${x}`)):Be.error(B.error??`Couldn't delete ${x}`)}catch(B){Be.error(B instanceof Error?B.message:`Couldn't delete ${x}`)}m(!1)},$=async()=>{w();const B=f??"";try{await navigator.clipboard.writeText(B),Be.info(`Copied ${B.length} chars`)}catch(U){Be.error(U instanceof Error?U.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Be.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Be.info(`Added ${x} to Claude context`)},R=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(B=>{B.ok||Be.error(B.error??`Couldn't open ${x}`)}).catch(B=>Be.error(B instanceof Error?B.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(B=>{B.ok||Be.error(B.error??`Couldn't reveal ${x}`)}).catch(B=>Be.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:w}),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(k_,{children:"Edit"}),o.jsx(iu,{label:"Rename",onClick:S}),o.jsx(iu,{label:"Duplicate",onClick:j}),o.jsx(iu,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(PC,{}),o.jsx(k_,{children:"Open"}),o.jsx(iu,{label:"Open in default app",onClick:R}),o.jsx(iu,{label:"Reveal in OS",onClick:O}),o.jsx(PC,{}),o.jsx(k_,{children:"Export"}),o.jsx(iu,{label:"Copy as Markdown",onClick:$}),o.jsx(iu,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(Vz,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void E()}),p&&o.jsx(qz,{name:x,onCancel:()=>m(!1),onConfirm:()=>void D()})]})}function k_({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function iu({label:n,onClick:e,danger:i,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 ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function PC(){return o.jsx("div",{className:"my-1 border-t border-line"})}function Vz({value:n,onChange:e,onCancel:i,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&&i()},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:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},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:i,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 qz({name:n,onCancel:e,onConfirm:i}){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 ",n,"? 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:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function Kz(){const[n,e]=M.useState(!1),i=wp();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 ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&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(fp,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.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:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(fp,{label:"Word wrap",children:o.jsx(Px,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(fp,{label:"Minimap",children:o.jsx(Px,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(fp,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(fp,{label:"Autosave",children:o.jsx(Px,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(fp,{label:"Wide measure",children:o.jsx(Px,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function fp({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Px({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const Yz=M.lazy(()=>qg(()=>import("./TiptapBody-Pv4sVeQ8.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Rx(n){return n.split("/").filter(Boolean).pop()||n}function Ix(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Mx(n){return zj(n)||Bj(n)}function Fb(){const n=nv(),e=$n(Je=>Je.openFiles),i=$n(Je=>Je.activeFilePath),r=$n(Je=>Je.dirty),s=$n(Je=>Je.viewMode),a=$n(Je=>Je.buffers),d=$n(Je=>Je.setActive),l=$n(Je=>Je.closeFile),c=$n(Je=>Je.closeOthers),p=$n(Je=>Je.closeToTheRight),m=$n(Je=>Je.closeAll),f=$n(Je=>Je.loadBuffer),b=$n(Je=>Je.setBuffer),y=$n(Je=>Je.markSaved),_=$n(Je=>Je.setViewMode),k=wp(),[x,w]=M.useState({}),[S,E]=M.useState({}),[j,D]=M.useState(null),[$,P]=M.useState(null),[R,O]=M.useState(!1),[B,U]=M.useState(!1),[J,Q]=M.useState(!0),Y=M.useRef(null),V=M.useRef(null),ee=M.useRef(void 0),fe=M.useRef(null),oe=M.useRef(null),W=zz(i??"",a[i??""]??""),re=M.useCallback(Je=>{Y.current=Je},[]),q=M.useCallback(()=>Y.current,[]);M.useEffect(()=>{const Je=i;if(!Je||Mx(Je))return;if($n.getState().hasBuffer(Je)){w(vt=>vt[Je]==="ready"?vt:{...vt,[Je]:"ready"});return}let Ct=!1;return w(vt=>({...vt,[Je]:"loading"})),window.api.files.read(Je).then(vt=>{Ct||(vt.binary?w(hn=>({...hn,[Je]:{binary:!0,size:vt.size??0,mime:vt.mime??"application/octet-stream",reason:vt.error??"Binary file"}})):vt.ok?(f(Je,vt.text),w(hn=>({...hn,[Je]:"ready"}))):w(hn=>({...hn,[Je]:{error:vt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),M.useEffect(()=>{P(null)},[i]);const ie=M.useCallback(async(Je,Ct=!1)=>{const vt=$n.getState().buffers[Je];if(vt==null)return;Ct&&O(!0);const hn=await window.api.files.write(Je,vt);hn.ok?(y(Je),E(An=>({...An,[Je]:(An[Je]??0)+1})),Ct||Be.info(`Saved ${Rx(Je)}`)):Be.error(hn.error??`Couldn't save ${Rx(Je)}`),Ct&&O(!1)},[y]);M.useEffect(()=>{if(!k.autosave)return;const Je=i;if(!(!Je||Mx(Je)||!r[Je]))return window.clearTimeout(ee.current),ee.current=window.setTimeout(()=>{ie(Je,!0)},1200),()=>window.clearTimeout(ee.current)},[k.autosave,i,r,a,ie]);const ae=M.useCallback(Je=>{Je.length&&(w(Ct=>Ix(Ct,Je)),E(Ct=>Ix(Ct,Je)))},[]),ce=M.useCallback((Je,Ct)=>{w(vt=>Je in vt?{...Ix(vt,[Je]),[Ct]:vt[Je]}:vt),E(vt=>Je in vt?{...Ix(vt,[Je]),[Ct]:vt[Je]}:vt)},[]),ye=M.useCallback(Je=>{r[Je]?D({kind:"one",path:Je}):(l(Je),ae([Je]))},[r,l,ae]),Pe=M.useCallback(Je=>{e.some(vt=>vt.path!==Je&&r[vt.path])?D({kind:"others",path:Je}):(c(Je),ae(e.filter(vt=>vt.path!==Je).map(vt=>vt.path)))},[e,r,c,ae]),de=M.useCallback(Je=>{const Ct=e.findIndex(hn=>hn.path===Je);Ct!==-1&&e.slice(Ct+1).some(hn=>r[hn.path])?D({kind:"right",path:Je}):(p(Je),ae(Ct!==-1?e.slice(Ct+1).map(hn=>hn.path):[]))},[e,r,p,ae]);M.useEffect(()=>{const Je=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const vt=$n.getState().activeFilePath;vt&&!Mx(vt)&&(Ct.preventDefault(),ie(vt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),U(vt=>!vt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const vt=$n.getState().activeFilePath;vt&&$n.getState().openFiles.length>1&&(Ct.preventDefault(),Pe(vt))}else Ct.key==="Escape"&&W.state.phase!=="idle"?W.cancel():Ct.key==="Escape"&&B&&U(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ie,B,Pe,W.state.phase,W.cancel]),M.useEffect(()=>{if(W.state.phase==="idle")return;const Je=Ct=>{var hn,An;const vt=Ct.target;(hn=oe.current)!=null&&hn.contains(vt)||(An=fe.current)!=null&&An.contains(vt)||W.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[W.state.phase,W.cancel]),M.useEffect(()=>{W.cancel()},[i,W.cancel]);const Z=M.useCallback(()=>{e.some(Ct=>r[Ct.path])?D({kind:"all",path:""}):(m(),w({}),E({}))},[e,r,m]),Se=()=>{if(j){if(j.kind==="one")l(j.path),ae([j.path]);else if(j.kind==="others"){const Je=e.filter(Ct=>Ct.path!==j.path).map(Ct=>Ct.path);c(j.path),ae(Je)}else if(j.kind==="right"){const Je=e.findIndex(vt=>vt.path===j.path),Ct=Je!==-1?e.slice(Je+1).map(vt=>vt.path):[];p(j.path),ae(Ct)}else m(),w({}),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 xe=i,Xe=xe?Rx(xe):"",nt=xe?x[xe]:void 0,ut=xe?Uj(xe):!1,Xt=xe?HL(xe):!1,pt=xe&&ut?s[xe]??WL(xe):"edit",it=!!xe&&!Mx(xe)&&nt==="ready",ot=it,Nt=Xt?["edit","wysiwyg","preview","split"]:ut?["edit","preview"]:[],rn=xe&&o.jsx(QL,{path:xe,name:Xe,value:a[xe]??"",onChange:Je=>b(xe,Je),onSave:()=>void ie(xe),onReady:re,onCursor:P}),fn=R?"Saving…":xe&&r[xe]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!B&&o.jsx(YL,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:ye,onCloseOthers:Pe,onCloseToTheRight:de,onCloseAll:Z}),xe&&!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:Xe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:xe}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",fn]}),Ol(xe)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Q(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${J?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ol(xe)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Nt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Nt.map(Je=>o.jsx("button",{onClick:()=>_(xe,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),o.jsx("div",{className:"flex-1"}),o.jsx(Wz,{path:xe,onRenamed:ce,onDeleted:Je=>ae([Je])}),it&&o.jsx(Kz,{}),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:xe?zj(xe)?o.jsx(wz,{path:xe,name:Xe}):Bj(xe)?o.jsx(Sz,{path:xe}):nt&&typeof nt=="object"&&"binary"in nt?o.jsx(Nz,{path:xe,name:Xe,size:nt.size,mime:nt.mime,reason:nt.reason}):nt&&typeof nt=="object"&&"error"in nt?o.jsx("div",{className:"p-6 text-xs text-red-400",children:nt.error}):nt!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ol(xe)?o.jsx(M.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(Yz,{value:a[xe]??"",onChange:Je=>b(xe,Je)},xe)}):pt==="split"&&Ol(xe)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(TC,{text:a[xe]??"",scrollRef:V}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(EC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:rn})]}),o.jsx("div",{ref:fe,className:"flex-1 min-w-0",children:o.jsx(Mw,{ref:V,text:a[xe]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!B&&k.assistantRail&&o.jsx(AC,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):pt==="preview"&&Ol(xe)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(TC,{text:a[xe]??"",scrollRef:V}),o.jsx("div",{ref:fe,className:"flex-1 min-w-0",children:o.jsx(Mw,{ref:V,text:a[xe]??"",wideMeasure:k.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!B&&k.assistantRail&&o.jsx(AC,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):pt==="preview"&&Lj(xe)?o.jsx(yz,{path:xe,dirty:!!r[xe],reloadToken:S[xe]??0}):pt==="preview"&&Fj(xe)?o.jsx(Cz,{path:xe,text:a[xe]??""}):pt==="preview"&&Gj(xe)?o.jsx(jz,{path:xe,text:a[xe]??""}):Ol(xe)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(EC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:rn})]}):rn:null}),ot&&o.jsx(bz,{text:a[xe]??"",cursor:$,language:no(xe)||void 0}),xe&&Ol(xe)&&(pt==="preview"||pt==="split")&&W.state.phase!=="idle"&&W.state.selection&&o.jsx("div",{ref:oe,children:o.jsx(Uz,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)}})}),j&&o.jsx(Xz,{message:j.kind==="one"?`Discard unsaved changes to ${Rx(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:Se})]})}function Xz({message:n,onCancel:e,onConfirm:i}){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:n}),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:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const RC={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"},Jz={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 C_(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function Zz({open:n,onClose:e,variant:i="overlay"}){const r=bt(D=>D.tabs.find($=>$.id===D.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=M.useState(null),[l,c]=M.useState(!1),[p,m]=M.useState(null),f=M.useRef(null),b=M.useCallback(async D=>{c(!0),m(null);try{const $=await window.api.repo.analyze(D);$.ok?d($):(m($.error||"Analysis failed"),d(null))}catch($){m($ instanceof Error?$.message:String($)),d(null)}finally{c(!1)}},[]);M.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),M.useEffect(()=>{var $;if(!n)return;const D=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",D),($=f.current)==null||$.focus(),()=>window.removeEventListener("keydown",D)},[n,e]);const y=M.useCallback(()=>{s&&b(s)},[s,b]),_=M.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([$,P])=>[$,P.files,P.lines]).sort(($,P)=>P[1]-$[1]).slice(0,12):[],[a]),k=M.useMemo(()=>_.length===0?1:_[0][1],[_]),x=M.useMemo(()=>{if(!a)return[];const D=a.topDirectories;if(D.length===0)return[];const $=D.map(R=>Math.sqrt(Math.max(1,R.fileCount))),P=$.reduce((R,O)=>R+O,0)||1;return D.map((R,O)=>({path:R.path,fileCount:R.fileCount,totalLines:R.totalLines,basis:$[O]/P*100}))},[a]);if(!n)return null;const w=D=>{D.target===D.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=i==="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:w,"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:[S,(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:y,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(E_,{label:"Files",value:C_(a.totalFiles)}),o.jsx(E_,{label:"Lines of code",value:C_(a.totalLines)}),o.jsx(E_,{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"}),_.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:_.map(([D,$,P])=>{const R=RC[D]??RC.other,O=Jz[D]??D,B=$/k*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:O,children:O}),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:R}})}),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:[C_(P)," 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?Cu.createPortal(j,document.body):j}function E_({label:n,value:e,tone:i="neutral"}){const r=i==="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:n})]})}function rd({options:n,active:e,onChange:i}){return o.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:n.map(({key:r,label:s})=>o.jsx("button",{onClick:()=>i(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 IC=n=>/[/\\\-_.\s]/.test(n),MC=n=>n>="A"&&n<="Z";function Qz(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||IC(l[p-1])||MC(d[p])?650:600,matched:Array.from({length:n.length},(S,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,y=-1,_=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,y===w-1?(b++,f+=b*8):b=0,(w===0||IC(s[w-1])||MC(e[w]))&&(_++,f+=15,w===0&&(f+=10)),y=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,_>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function T_(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function OC(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const LC="session-manager.quickopen.recent",e4=8;function t4({open:n,onClose:e,variant:i="overlay"}){const r=bt(O=>O.tabs.find(B=>B.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=M.useState(""),[l,c]=M.useState([]),[p,m]=M.useState(!1),[f,b]=M.useState(0),[y,_]=M.useState([]),k=M.useRef(null),x=M.useRef(null);M.useEffect(()=>{if(n)try{const O=localStorage.getItem(LC);O&&_(JSON.parse(O))}catch{}},[n]),M.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var B;return(B=k.current)==null?void 0:B.focus()},0);return()=>clearTimeout(O)},[n]),M.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(B=>{if(!O){if(!B.ok){Be.error(`File search failed: ${B.error??"unknown error"}`),c([]);return}c(B.files)}}).catch(B=>{const U=B instanceof Error?B.message:String(B);ht.error("quick-open","search.files threw",{error:U},{cwd:s,tabId:r==null?void 0:r.id}),Be.error(`File search failed: ${U}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=M.useMemo(()=>{if(!a.trim())return[...l].sort((J,Q)=>J.name.localeCompare(Q.name)).slice(0,100).map(J=>({file:J,score:0,matched:[]}));const O=a.trim(),B=[];for(const U of l){const J=Qz(O,U.name,U.path);J.match&&B.push({file:U,score:J.score,matched:J.matched})}return B.sort((U,J)=>J.score-U.score),B.slice(0,100)},[l,a]),S=M.useMemo(()=>a.trim()?[]:y.map(O=>l.find(B=>B.path===O)||null).filter(O=>O!==null).slice(0,5),[y,l,a]);M.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),M.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const E=M.useCallback(O=>{try{const Q=[O,...y.filter(Y=>Y!==O)].slice(0,e4);_(Q),localStorage.setItem(LC,JSON.stringify(Q))}catch{}const B=r==null?void 0:r.id;if(!B){Be.error("No active tab to receive file path");return}const J=(s?T_(O,s):O)||O;try{window.api.pty.write({tabId:B,data:J})}catch(Q){const Y=Q instanceof Error?Q.message:String(Q);ht.error("quick-open","pty.write failed",{error:Y},{cwd:s,tabId:B}),Be.error(`Failed to write to terminal: ${Y}`);return}e()},[r==null?void 0:r.id,s,y,e]),j=M.useCallback(O=>{const B=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),B===0)return;b(U=>Math.min(B-1,U+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),B===0)return;b(U=>Math.max(0,U-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Q=S[f];Q&&E(Q.path);return}const U=f-S.length,J=w[U];J&&E(J.file.path)}},[f,w,S,E,e]);if(!n)return null;const D=(O,B)=>{if(B.length===0)return O;const U=new Set(B);return O.split("").map((J,Q)=>o.jsx("span",{className:U.has(Q)?"text-accent font-semibold":"",children:J},Q))};let $=-1;const P=i==="page",R=o.jsx("div",{className:P?"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:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"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:k,type:"text",value:a,onChange:O=>{d(O.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?S.length===0&&w.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:[S.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"}),S.map(O=>{$++;const B=$,U=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":U,onClick:()=>E(O.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:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:T_(OC(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.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"}),w.map(({file:O,matched:B})=>{$++;const U=$,J=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":J,onClick:()=>E(O.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${J?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:D(O.name,B)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:T_(OC(O.path),s)})]},O.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:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Cu.createPortal(R,document.body):R}function zC(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function n4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function i4({open:n,onClose:e,variant:i="overlay"}){const r=bt(Q=>Q.tabs.find(Y=>Y.id===Q.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=M.useState(""),[l,c]=M.useState(!1),[p,m]=M.useState([]),[f,b]=M.useState(!1),[y,_]=M.useState(null),[k,x]=M.useState(0),[w,S]=M.useState(null),E=M.useRef(null),j=M.useRef(null),D=M.useRef(0);M.useEffect(()=>{if(!n){d(""),m([]),_(null),x(0);return}const Q=setTimeout(()=>{var Y;return(Y=E.current)==null?void 0:Y.focus()},0);return()=>clearTimeout(Q)},[n]),M.useEffect(()=>{if(!n||!s)return;const Q=a.trim();if(!Q){m([]),_(null),b(!1);return}const Y=++D.current;b(!0);const V=setTimeout(()=>{window.api.search.text(s,Q,{caseSensitive:l,limit:500}).then(ee=>{Y===D.current&&(ee.ok?(m(ee.matches),_(null)):(_(ee.error??"unknown error"),m([])),S(ee.usedRipgrep))}).catch(ee=>{if(Y!==D.current)return;const fe=ee instanceof Error?ee.message:String(ee);ht.error("global-search","search.text threw",{error:fe},{cwd:s,tabId:r==null?void 0:r.id}),_(fe),m([])}).finally(()=>{Y===D.current&&b(!1)})},250);return()=>clearTimeout(V)},[n,s,a,l]);const $=M.useMemo(()=>{const Q=new Map;for(const V of p){const ee=Q.get(V.path);ee?ee.push(V):Q.set(V.path,[V])}const Y=[];for(const[V,ee]of Q)Y.push({path:V,matches:ee});return Y.sort((V,ee)=>ee.matches.length-V.matches.length||V.path.localeCompare(ee.path)),Y},[p]),P=M.useMemo(()=>p,[p]);M.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),M.useEffect(()=>{if(!j.current)return;const Q=j.current.querySelector(`[data-match="${k}"]`);Q&&Q.scrollIntoView({block:"nearest"})},[k]);const R=M.useCallback(Q=>{const Y=r==null?void 0:r.id;if(!Y){Be.error("No active tab to receive path");return}const ee=`${(s?zC(Q.path,s):Q.path)||Q.path}:${Q.line}`;try{window.api.pty.write({tabId:Y,data:ee})}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);ht.error("global-search","pty.write failed",{error:oe},{cwd:s,tabId:Y}),Be.error(`Failed to write to terminal: ${oe}`);return}e()},[r==null?void 0:r.id,s,e]),O=M.useCallback(Q=>{if(Q.key==="Escape"){Q.preventDefault(),e();return}if(Q.key==="ArrowDown"){if(Q.preventDefault(),P.length===0)return;x(Y=>Math.min(P.length-1,Y+1));return}if(Q.key==="ArrowUp"){if(Q.preventDefault(),P.length===0)return;x(Y=>Math.max(0,Y-1));return}if(Q.key==="Enter"){Q.preventDefault();const Y=P[k];Y&&R(Y)}},[P,k,R,e]);if(!n)return null;const B=i==="page";let U=-1;const J=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:Q=>{Q.target===Q.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:O,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:Q=>{d(Q.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:()=>c(Q=>!Q),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…"}):y?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:y}):P.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(Q=>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:[zC(Q.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Q.matches.length,")"]})]}),Q.matches.map(Y=>{U++;const V=U,ee=V===k;return o.jsxs("button",{"data-match":V,role:"option","aria-selected":ee,onClick:()=>R(Y),onMouseEnter:()=>x(V),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ee?"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:Y.line}),o.jsx("span",{className:"truncate",children:n4(Y.text,a,l)})]},`${Y.path}:${Y.line}:${Y.column}:${V}`)})]},Q.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:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!B&&typeof document<"u"&&document.body?Cu.createPortal(J,document.body):J}const r4=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function s4({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=M.useState(r);return M.useEffect(()=>{a(r)},[r]),n?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(rd,{options:r4,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(t4,{open:!0,onClose:e,variant:"page"}):o.jsx(i4,{open:!0,onClose:e,variant:"page"})})]}):null}const o4={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},BC='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Up({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?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 ${d?"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 ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=M.useRef(null),p=M.useRef(null),m=M.useRef(e);if(m.current=e,M.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const _=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(BC);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(BC)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const E=S[0],j=S[S.length-1],D=document.activeElement;x.shiftKey?(D===E||!w.contains(D))&&(x.preventDefault(),j.focus()):(D===j||!w.contains(D))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(_),document.removeEventListener("keydown",k);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[n]),!n)return null;const f=y=>{y.target===y.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:c,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 ${o4[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"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:i}):i]})});return typeof document<"u"&&document.body?Cu.createPortal(b,document.body):b}class lD extends M.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,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 a4({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(Up,{open:n,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:i}),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(lD,{children:r})})]})}function cD(n,e={}){switch(n){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 FC=n=>Symbol.iterator in n,GC=n=>"entries"in n,UC=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},l4=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function c4(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:FC(n)&&FC(e)?GC(n)&&GC(e)?UC(n,e):l4(n,e):UC({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function p1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return c4(e.current,r)?e.current:e.current=r}}let HC=0;const d4=1e3;function u4(n){const e=performance.now();e-HC<d4||(HC=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function dD(){const n=kt(p=>p.isRecording),e=kt(p=>p.error),i=kt(p=>p.loadingProgress),r=kt(p1(jb)),s=()=>{const p=kt.getState(),{canRecord:m,reason:f}=jb(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 u4(f);const b=bt.getState().activeTabId;b&&p.startRecording(b)},a=cD(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=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":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,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 h4(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"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"}),n?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 p4(n){return/^monitor of /i.test(n.trim())}function WC(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function VC(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=WC(e),a=i.filter(d=>d.label&&WC(d.label)===s);return a.length===1?a[0]:null}async function qC(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&p4(r.label))):[]}const KC=!1;function uD(){const n=kt(p=>p.isRecording);kt(p=>p.startRecording),kt(p=>p.stopRecording);const[e,i]=M.useState([]),[r,s]=M.useState(null),[a,d]=M.useState(null);M.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await qC(KC);if(p)return;i(f),d(m.selectedLabel);const b=VC(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.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}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=M.useCallback(async()=>{try{const p=await qC(KC);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=VC(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){ht.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);M.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const c=async p=>{var y;const m=p.target.value,f=m===""?null:m,b=f?((y=e.find(_=>_.deviceId===f))==null?void 0:y.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(_){ht.warn("voice","setDevicePref failed",{error:_ instanceof Error?_.message:String(_)})}if(n)try{await kt.getState().restartWithDevice()}catch(_){ht.warn("voice","device-picker restart failed",{error:_ instanceof Error?_.message:String(_)})}};return o.jsxs("select",{value:r??"",onChange:c,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 f4(){const n=kt(y=>y.isRecording),e=kt(y=>y.levelMeterEnabled),[i,r]=M.useState(0),[s,a]=M.useState(0),d=M.useRef(0);d.current=s;const[l,c]=M.useState(0),[p,m]=M.useState(!1),f=M.useRef(null);if(M.useEffect(()=>{if(!n||!e){r(0),a(0);return}let y=0,_=!1,k=null,x=null;const w=()=>{if(_)return;const E=x??jT();if(!E){y=requestAnimationFrame(w);return}x!==E&&(x=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=k;E.getByteTimeDomainData(j);let D=0;for(let O=0;O<j.length;O++){const B=j[O]-128;D+=B*B}const $=Math.sqrt(D/j.length)/128,P=$>0?20*Math.log10($):-60,R=Math.max(0,Math.min(1,(P+60)/60));a($),r(R),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),y=requestAnimationFrame(w)};y=requestAnimationFrame(w);const S=setInterval(()=>{_||c(Math.round(d.current*100))},250);return()=>{_=!0,cancelAnimationFrame(y),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!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:`${i*100}%`}})})}function hD(){const n=kt(p=>p.submitCountdownStartAt),e=kt(p=>p.submitDelayMs),[i,r]=M.useState(()=>performance.now());if(M.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,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:`${d}%`}})})})}function m4({open:n,onClose:e,variant:i="overlay"}){return o.jsx(a4,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(b4,{}),o.jsx(hD,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(dD,{}),o.jsx(uD,{}),o.jsx(h4,{})]}),o.jsx(g4,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(x4,{})]}),o.jsx(f4,{})]})})}function g4(){const n=kt(a=>a.isRecording),[e,i]=M.useState(null);if(M.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=v4(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 v4(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.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 x4(){const[n,e]=M.useState(null);if(M.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.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:n.mode==="toggle",onChange:()=>i("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:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function b4(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?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 j_=null;function y4(){return j_||(j_=qg(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(X0.config({monaco:n}),n))),j_}function pD({value:n,onChange:e,path:i,readOnly:r}){const s=M.useRef(null),a=d=>{s.current=d};return o.jsx(J0,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),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 YC=!1;async function _4(n){if(YC)return;const e=await y4(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),YC=!0}function f1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=M.useState(""),[l,c]=M.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.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:br[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:y=>c(y.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:y=>d(y.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(fD,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function fD(n){return n.node.kind==="object"?o.jsx(w4,{...n,node:n.node}):n.node.kind==="array"?o.jsx(S4,{...n,node:n.node}):o.jsx(k4,{...n,node:n.node})}function XC(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Ip(n,e,i){return!!(!i.trim()||n.some(r=>XC(r,i))||e!=null&&e.description&&XC(e.description,i))}function w4({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:p}){const[m,f]=M.useState(p??d<2),b=(l==null?void 0:l.at(e))??null,y=new Set(Object.keys(n.children)),_=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([...y,..._])).sort(),x=M.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Ip([...e,S],E,a)?!0:y.has(S)?mD(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Ip(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});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:d*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:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",y.size,_.length>y.size?`/${new Set([...y,..._]).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(S=>w(S))]});function w(S){if(y.has(S))return o.jsx(fD,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(C4,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function mD(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Ip(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(mD(n.children[a],[...e,a],i,r))return!0;return!1}function S4({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=M.useState(!0),c=(a==null?void 0:a.at(e))??null;return Ip(e,c,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(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(Lg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.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:Gb(p.value)}),o.jsx(zw,{scope:p.fromScope})]},m))]}):null}function k4({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,p]=M.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Ip(e,m,a))return null;const f=n.winner!==r,b=n.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:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Gb(n.value)}),o.jsx(zw,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(Lg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&E4(n.value,m.default)&&o.jsx(Lg,{tone:"dim",children:"= default"}),n.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(gD,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.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 ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((y,_)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Gb(y.value)}),o.jsx(zw,{scope:y.scope,dim:!0})]},_))]})}function C4({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Ip(n,i,d))return null;const l=i.default!==void 0?i.default:T4(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.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(Lg,{tone:"dim",children:c}),i.required&&o.jsx(Lg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Gb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(gD,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,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 ${br[r].label} draft`,children:"set"})]})}function E4(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function T4(n){switch(Array.isArray(n)?n[0]:n){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 Gb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function zw({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="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 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function Lg({children:n,tone:e="default"}){const i={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 ${i}`,children:n})}function gD({values:n}){const e=n.map(i=>String(i)).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 j4=[{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"]}],D4={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function vD(n){return n.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=D4[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function xD(n){const e=new Set,i=[];for(const s of j4){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function N4(n,e){return xD(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const A4={};function bD(n,e){if(e)return{text:e,authored:!1};const i=A4[n];return i?{text:i,authored:!0}:null}const $4={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"},P4=["user","project","local","default"],R4={user:"user",project:"project",local:"local",default:"default"};function I4({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=M.useState(""),[d,l]=M.useState(!1),[c,p]=M.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),y=new Set([...f,...b]),_=M.useMemo(()=>xD(y),[Array.from(y).sort().join(",")]),k=M.useMemo(()=>N4(y,new Set(f)),[Array.from(y).sort().join(","),f.join(",")]),[x,w]=M.useState(null),S=j=>{const D=_.find($=>$.id===j);D!=null&&D.advanced&&!d&&l(!0),w(j)};M.useEffect(()=>{if(!x)return;const j=document.getElementById(`settings-group-${x}`);j&&(j.scrollIntoView({behavior:"smooth",block:"start"}),w(null))});const E=M.useMemo(()=>_.filter(j=>d||!j.advanced).map(j=>({...j,keys:j.keys.filter(D=>{const $=(m==null?void 0:m.children[D])!==void 0;if(!c&&!$)return!1;if(!s.trim())return!0;const P=r.at([D]);return[D,vD(D),(P==null?void 0:P.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(j=>j.keys.length>0),[_,s,d,c,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:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,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:d,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(M4,{groups:k,onJump:S}),o.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[E.map(j=>o.jsx(O4,{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],P=r.at([D]);return o.jsx(L4,{keyName:D,node:$,info:P,targetScope:e,onOverride:(R,O)=>i([D],R,O)},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 M4({groups:n,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:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(an,{name:$4[i.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:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function O4({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=M.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,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:()=>d(!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:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function L4({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=M.useState(!1),[l,c]=M.useState(!1),p=vD(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,y=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",_=i==null?void 0:i.default,k=b&&_!==void 0&&_D(b.value,_),x=V4({isSet:m,leafNode:b,defaultVal:_,isDefault:!!k,node:e}),w=z4(b,_),S=w.length>=2,E=!!b&&!k,j=bD(n,i==null?void 0:i.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:()=>d(!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(q4,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:D=>{D.stopPropagation(),a||d(!0),c($=>!$)},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 · ",w.map(D=>R4[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 ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.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"}),(i==null?void 0:i.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:K4(j.text)}),a&&l&&b&&o.jsx(B4,{leaf:b,defaultVal:_,onReset:D=>s(void 0,D)}),a&&o.jsx(F4,{keyName:n,node:e,info:i,targetScope:r,onOverride:D=>s(D)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(W4,{node:e,info:i,onSet:D=>{s(D)},disabled:y&&m})})]})})}function z4(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),P4.filter(r=>i.has(r))}function B4({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.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],d=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:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?jp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(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 ${br[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?jp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function F4({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=bD(n,i==null?void 0:i.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:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:jp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&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:jp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[jp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.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(G4,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function G4({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=yD(e==null?void 0:e.type);if(d==="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:c,label:p})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"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:["→ ",br[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 c=_D(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"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:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(U4,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(H4,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function U4({value:n,integer:e,onCommit:i,target:r}){const[s,a]=M.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(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:d,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:d,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 H4({value:n,onCommit:e,target:i}){const[r,s]=M.useState(n);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 → ",i]})]})}function W4({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=yD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"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:d?"on":"off"})}return null}function V4({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(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 · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${jp(i)}`}:{kind:"unset",label:"not configured"}}function q4({kind:n,label:e}){const i={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"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function yD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function _D(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function K4(n){const e=n.trim().split(`
3058
+ (Give a different rewrite than the last one.)`,!1)},[_,i.instruction]),S=M.useCallback(E=>{const j=i.diff;if(!j)return{ok:!1,reason:"not-found"};const D=Az(E,j.before,j.after);return D.ok?(s.current+=1,r({type:"ACCEPT"})):Be.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},[i.diff]);return{state:i,select:p,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const Bz=[{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."}],NC=320,Vm=8;function Fz(){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 Gz(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,Vm),Math.max(Vm,e-NC-Vm)),r=Math.max(n.top-Vm,Vm);return{position:"fixed",left:i,top:r,width:NC,transform:"translateY(-100%)",zIndex:50}}function Uz({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[y,_]=M.useState(""),k=()=>{const x=y.trim();x&&(d(x),_(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:Gz(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="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"}),Bz.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:y,onChange:x=>_(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():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"})]}),n==="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(Fz,{}),"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"})]}),n==="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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="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"})]}),n==="diff"&&i&&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:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.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 Hz(){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 AC({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,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:Yg(Lz)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="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"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(Hz,{}),"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"})]}),n==="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:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&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:i.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:i.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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function $C(n){return n.split("/").filter(Boolean).pop()||n}function Wz({path:n,onRenamed:e,onDeleted:i}){const[r,s]=M.useState(!1),[a,d]=M.useState(!1),[l,c]=M.useState(""),[p,m]=M.useState(!1),f=$n(B=>B.buffers[n]),b=$n(B=>B.openFile),y=$n(B=>B.renameOpenFile),_=$n(B=>B.closeFile),k=id(),x=$C(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},E=async()=>{const B=l.trim();if(!B||B===x){d(!1);return}try{const U=await window.api.files.rename(n,B);if(U.ok){const J=n.slice(0,n.lastIndexOf("/")),Q=U.newPath??`${J}/${B}`;y(n,Q),e==null||e(n,Q),Be.info(`Renamed to ${B}`)}else Be.error(U.error??`Couldn't rename ${x}`)}catch(U){Be.error(U instanceof Error?U.message:`Couldn't rename ${x}`)}d(!1)},j=async()=>{w();try{const B=await window.api.files.duplicate(n);B.ok&&B.path?(b(B.path),Be.info(`Duplicated as ${$C(B.path)}`)):Be.error(B.error??`Couldn't duplicate ${x}`)}catch(B){Be.error(B instanceof Error?B.message:`Couldn't duplicate ${x}`)}},D=async()=>{try{const B=await window.api.files.delete(n);B.ok?(_(n),i==null||i(n),Be.info(`Deleted ${x}`)):Be.error(B.error??`Couldn't delete ${x}`)}catch(B){Be.error(B instanceof Error?B.message:`Couldn't delete ${x}`)}m(!1)},$=async()=>{w();const B=f??"";try{await navigator.clipboard.writeText(B),Be.info(`Copied ${B.length} chars`)}catch(U){Be.error(U instanceof Error?U.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Be.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Be.info(`Added ${x} to Claude context`)},R=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(B=>{B.ok||Be.error(B.error??`Couldn't open ${x}`)}).catch(B=>Be.error(B instanceof Error?B.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(B=>{B.ok||Be.error(B.error??`Couldn't reveal ${x}`)}).catch(B=>Be.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:w}),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(k_,{children:"Edit"}),o.jsx(iu,{label:"Rename",onClick:S}),o.jsx(iu,{label:"Duplicate",onClick:j}),o.jsx(iu,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(PC,{}),o.jsx(k_,{children:"Open"}),o.jsx(iu,{label:"Open in default app",onClick:R}),o.jsx(iu,{label:"Reveal in OS",onClick:O}),o.jsx(PC,{}),o.jsx(k_,{children:"Export"}),o.jsx(iu,{label:"Copy as Markdown",onClick:$}),o.jsx(iu,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx(Vz,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void E()}),p&&o.jsx(qz,{name:x,onCancel:()=>m(!1),onConfirm:()=>void D()})]})}function k_({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function iu({label:n,onClick:e,danger:i,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 ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function PC(){return o.jsx("div",{className:"my-1 border-t border-line"})}function Vz({value:n,onChange:e,onCancel:i,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&&i()},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:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},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:i,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 qz({name:n,onCancel:e,onConfirm:i}){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 ",n,"? 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:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function Kz(){const[n,e]=M.useState(!1),i=wp();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 ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&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(fp,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.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:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(fp,{label:"Word wrap",children:o.jsx(Px,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(fp,{label:"Minimap",children:o.jsx(Px,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(fp,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(fp,{label:"Autosave",children:o.jsx(Px,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(fp,{label:"Wide measure",children:o.jsx(Px,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function fp({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Px({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const Yz=M.lazy(()=>qg(()=>import("./TiptapBody-CFlF9v--.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Rx(n){return n.split("/").filter(Boolean).pop()||n}function Ix(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Mx(n){return zj(n)||Bj(n)}function Fb(){const n=nv(),e=$n(Je=>Je.openFiles),i=$n(Je=>Je.activeFilePath),r=$n(Je=>Je.dirty),s=$n(Je=>Je.viewMode),a=$n(Je=>Je.buffers),d=$n(Je=>Je.setActive),l=$n(Je=>Je.closeFile),c=$n(Je=>Je.closeOthers),p=$n(Je=>Je.closeToTheRight),m=$n(Je=>Je.closeAll),f=$n(Je=>Je.loadBuffer),b=$n(Je=>Je.setBuffer),y=$n(Je=>Je.markSaved),_=$n(Je=>Je.setViewMode),k=wp(),[x,w]=M.useState({}),[S,E]=M.useState({}),[j,D]=M.useState(null),[$,P]=M.useState(null),[R,O]=M.useState(!1),[B,U]=M.useState(!1),[J,Q]=M.useState(!0),Y=M.useRef(null),V=M.useRef(null),ee=M.useRef(void 0),fe=M.useRef(null),oe=M.useRef(null),W=zz(i??"",a[i??""]??""),re=M.useCallback(Je=>{Y.current=Je},[]),q=M.useCallback(()=>Y.current,[]);M.useEffect(()=>{const Je=i;if(!Je||Mx(Je))return;if($n.getState().hasBuffer(Je)){w(vt=>vt[Je]==="ready"?vt:{...vt,[Je]:"ready"});return}let Ct=!1;return w(vt=>({...vt,[Je]:"loading"})),window.api.files.read(Je).then(vt=>{Ct||(vt.binary?w(hn=>({...hn,[Je]:{binary:!0,size:vt.size??0,mime:vt.mime??"application/octet-stream",reason:vt.error??"Binary file"}})):vt.ok?(f(Je,vt.text),w(hn=>({...hn,[Je]:"ready"}))):w(hn=>({...hn,[Je]:{error:vt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),M.useEffect(()=>{P(null)},[i]);const ie=M.useCallback(async(Je,Ct=!1)=>{const vt=$n.getState().buffers[Je];if(vt==null)return;Ct&&O(!0);const hn=await window.api.files.write(Je,vt);hn.ok?(y(Je),E(An=>({...An,[Je]:(An[Je]??0)+1})),Ct||Be.info(`Saved ${Rx(Je)}`)):Be.error(hn.error??`Couldn't save ${Rx(Je)}`),Ct&&O(!1)},[y]);M.useEffect(()=>{if(!k.autosave)return;const Je=i;if(!(!Je||Mx(Je)||!r[Je]))return window.clearTimeout(ee.current),ee.current=window.setTimeout(()=>{ie(Je,!0)},1200),()=>window.clearTimeout(ee.current)},[k.autosave,i,r,a,ie]);const ae=M.useCallback(Je=>{Je.length&&(w(Ct=>Ix(Ct,Je)),E(Ct=>Ix(Ct,Je)))},[]),ce=M.useCallback((Je,Ct)=>{w(vt=>Je in vt?{...Ix(vt,[Je]),[Ct]:vt[Je]}:vt),E(vt=>Je in vt?{...Ix(vt,[Je]),[Ct]:vt[Je]}:vt)},[]),ye=M.useCallback(Je=>{r[Je]?D({kind:"one",path:Je}):(l(Je),ae([Je]))},[r,l,ae]),Pe=M.useCallback(Je=>{e.some(vt=>vt.path!==Je&&r[vt.path])?D({kind:"others",path:Je}):(c(Je),ae(e.filter(vt=>vt.path!==Je).map(vt=>vt.path)))},[e,r,c,ae]),de=M.useCallback(Je=>{const Ct=e.findIndex(hn=>hn.path===Je);Ct!==-1&&e.slice(Ct+1).some(hn=>r[hn.path])?D({kind:"right",path:Je}):(p(Je),ae(Ct!==-1?e.slice(Ct+1).map(hn=>hn.path):[]))},[e,r,p,ae]);M.useEffect(()=>{const Je=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const vt=$n.getState().activeFilePath;vt&&!Mx(vt)&&(Ct.preventDefault(),ie(vt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),U(vt=>!vt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const vt=$n.getState().activeFilePath;vt&&$n.getState().openFiles.length>1&&(Ct.preventDefault(),Pe(vt))}else Ct.key==="Escape"&&W.state.phase!=="idle"?W.cancel():Ct.key==="Escape"&&B&&U(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ie,B,Pe,W.state.phase,W.cancel]),M.useEffect(()=>{if(W.state.phase==="idle")return;const Je=Ct=>{var hn,An;const vt=Ct.target;(hn=oe.current)!=null&&hn.contains(vt)||(An=fe.current)!=null&&An.contains(vt)||W.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[W.state.phase,W.cancel]),M.useEffect(()=>{W.cancel()},[i,W.cancel]);const Z=M.useCallback(()=>{e.some(Ct=>r[Ct.path])?D({kind:"all",path:""}):(m(),w({}),E({}))},[e,r,m]),Se=()=>{if(j){if(j.kind==="one")l(j.path),ae([j.path]);else if(j.kind==="others"){const Je=e.filter(Ct=>Ct.path!==j.path).map(Ct=>Ct.path);c(j.path),ae(Je)}else if(j.kind==="right"){const Je=e.findIndex(vt=>vt.path===j.path),Ct=Je!==-1?e.slice(Je+1).map(vt=>vt.path):[];p(j.path),ae(Ct)}else m(),w({}),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 xe=i,Xe=xe?Rx(xe):"",nt=xe?x[xe]:void 0,ut=xe?Uj(xe):!1,Xt=xe?HL(xe):!1,pt=xe&&ut?s[xe]??WL(xe):"edit",it=!!xe&&!Mx(xe)&&nt==="ready",ot=it,Nt=Xt?["edit","wysiwyg","preview","split"]:ut?["edit","preview"]:[],rn=xe&&o.jsx(QL,{path:xe,name:Xe,value:a[xe]??"",onChange:Je=>b(xe,Je),onSave:()=>void ie(xe),onReady:re,onCursor:P}),fn=R?"Saving…":xe&&r[xe]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!B&&o.jsx(YL,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:ye,onCloseOthers:Pe,onCloseToTheRight:de,onCloseAll:Z}),xe&&!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:Xe}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:xe}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",fn]}),Ol(xe)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Q(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${J?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ol(xe)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Nt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Nt.map(Je=>o.jsx("button",{onClick:()=>_(xe,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),o.jsx("div",{className:"flex-1"}),o.jsx(Wz,{path:xe,onRenamed:ce,onDeleted:Je=>ae([Je])}),it&&o.jsx(Kz,{}),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:xe?zj(xe)?o.jsx(wz,{path:xe,name:Xe}):Bj(xe)?o.jsx(Sz,{path:xe}):nt&&typeof nt=="object"&&"binary"in nt?o.jsx(Nz,{path:xe,name:Xe,size:nt.size,mime:nt.mime,reason:nt.reason}):nt&&typeof nt=="object"&&"error"in nt?o.jsx("div",{className:"p-6 text-xs text-red-400",children:nt.error}):nt!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ol(xe)?o.jsx(M.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(Yz,{value:a[xe]??"",onChange:Je=>b(xe,Je)},xe)}):pt==="split"&&Ol(xe)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(TC,{text:a[xe]??"",scrollRef:V}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(EC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:rn})]}),o.jsx("div",{ref:fe,className:"flex-1 min-w-0",children:o.jsx(Mw,{ref:V,text:a[xe]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!B&&k.assistantRail&&o.jsx(AC,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):pt==="preview"&&Ol(xe)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(TC,{text:a[xe]??"",scrollRef:V}),o.jsx("div",{ref:fe,className:"flex-1 min-w-0",children:o.jsx(Mw,{ref:V,text:a[xe]??"",wideMeasure:k.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!B&&k.assistantRail&&o.jsx(AC,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):pt==="preview"&&Lj(xe)?o.jsx(yz,{path:xe,dirty:!!r[xe],reloadToken:S[xe]??0}):pt==="preview"&&Fj(xe)?o.jsx(Cz,{path:xe,text:a[xe]??""}):pt==="preview"&&Gj(xe)?o.jsx(jz,{path:xe,text:a[xe]??""}):Ol(xe)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(EC,{getEditor:q}),o.jsx("div",{className:"flex-1 min-h-0",children:rn})]}):rn:null}),ot&&o.jsx(bz,{text:a[xe]??"",cursor:$,language:no(xe)||void 0}),xe&&Ol(xe)&&(pt==="preview"||pt==="split")&&W.state.phase!=="idle"&&W.state.selection&&o.jsx("div",{ref:oe,children:o.jsx(Uz,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Je=W.accept(a[xe]??"");Je.ok&&b(xe,Je.next)}})}),j&&o.jsx(Xz,{message:j.kind==="one"?`Discard unsaved changes to ${Rx(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:Se})]})}function Xz({message:n,onCancel:e,onConfirm:i}){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:n}),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:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const RC={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"},Jz={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 C_(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function Zz({open:n,onClose:e,variant:i="overlay"}){const r=bt(D=>D.tabs.find($=>$.id===D.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=M.useState(null),[l,c]=M.useState(!1),[p,m]=M.useState(null),f=M.useRef(null),b=M.useCallback(async D=>{c(!0),m(null);try{const $=await window.api.repo.analyze(D);$.ok?d($):(m($.error||"Analysis failed"),d(null))}catch($){m($ instanceof Error?$.message:String($)),d(null)}finally{c(!1)}},[]);M.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),M.useEffect(()=>{var $;if(!n)return;const D=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",D),($=f.current)==null||$.focus(),()=>window.removeEventListener("keydown",D)},[n,e]);const y=M.useCallback(()=>{s&&b(s)},[s,b]),_=M.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([$,P])=>[$,P.files,P.lines]).sort(($,P)=>P[1]-$[1]).slice(0,12):[],[a]),k=M.useMemo(()=>_.length===0?1:_[0][1],[_]),x=M.useMemo(()=>{if(!a)return[];const D=a.topDirectories;if(D.length===0)return[];const $=D.map(R=>Math.sqrt(Math.max(1,R.fileCount))),P=$.reduce((R,O)=>R+O,0)||1;return D.map((R,O)=>({path:R.path,fileCount:R.fileCount,totalLines:R.totalLines,basis:$[O]/P*100}))},[a]);if(!n)return null;const w=D=>{D.target===D.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=i==="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:w,"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:[S,(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:y,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(E_,{label:"Files",value:C_(a.totalFiles)}),o.jsx(E_,{label:"Lines of code",value:C_(a.totalLines)}),o.jsx(E_,{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"}),_.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:_.map(([D,$,P])=>{const R=RC[D]??RC.other,O=Jz[D]??D,B=$/k*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:O,children:O}),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:R}})}),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:[C_(P)," 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?Cu.createPortal(j,document.body):j}function E_({label:n,value:e,tone:i="neutral"}){const r=i==="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:n})]})}function rd({options:n,active:e,onChange:i}){return o.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:n.map(({key:r,label:s})=>o.jsx("button",{onClick:()=>i(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 IC=n=>/[/\\\-_.\s]/.test(n),MC=n=>n>="A"&&n<="Z";function Qz(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||IC(l[p-1])||MC(d[p])?650:600,matched:Array.from({length:n.length},(S,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,y=-1,_=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,y===w-1?(b++,f+=b*8):b=0,(w===0||IC(s[w-1])||MC(e[w]))&&(_++,f+=15,w===0&&(f+=10)),y=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,_>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function T_(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function OC(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const LC="session-manager.quickopen.recent",e4=8;function t4({open:n,onClose:e,variant:i="overlay"}){const r=bt(O=>O.tabs.find(B=>B.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=M.useState(""),[l,c]=M.useState([]),[p,m]=M.useState(!1),[f,b]=M.useState(0),[y,_]=M.useState([]),k=M.useRef(null),x=M.useRef(null);M.useEffect(()=>{if(n)try{const O=localStorage.getItem(LC);O&&_(JSON.parse(O))}catch{}},[n]),M.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var B;return(B=k.current)==null?void 0:B.focus()},0);return()=>clearTimeout(O)},[n]),M.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(B=>{if(!O){if(!B.ok){Be.error(`File search failed: ${B.error??"unknown error"}`),c([]);return}c(B.files)}}).catch(B=>{const U=B instanceof Error?B.message:String(B);ht.error("quick-open","search.files threw",{error:U},{cwd:s,tabId:r==null?void 0:r.id}),Be.error(`File search failed: ${U}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=M.useMemo(()=>{if(!a.trim())return[...l].sort((J,Q)=>J.name.localeCompare(Q.name)).slice(0,100).map(J=>({file:J,score:0,matched:[]}));const O=a.trim(),B=[];for(const U of l){const J=Qz(O,U.name,U.path);J.match&&B.push({file:U,score:J.score,matched:J.matched})}return B.sort((U,J)=>J.score-U.score),B.slice(0,100)},[l,a]),S=M.useMemo(()=>a.trim()?[]:y.map(O=>l.find(B=>B.path===O)||null).filter(O=>O!==null).slice(0,5),[y,l,a]);M.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),M.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const E=M.useCallback(O=>{try{const Q=[O,...y.filter(Y=>Y!==O)].slice(0,e4);_(Q),localStorage.setItem(LC,JSON.stringify(Q))}catch{}const B=r==null?void 0:r.id;if(!B){Be.error("No active tab to receive file path");return}const J=(s?T_(O,s):O)||O;try{window.api.pty.write({tabId:B,data:J})}catch(Q){const Y=Q instanceof Error?Q.message:String(Q);ht.error("quick-open","pty.write failed",{error:Y},{cwd:s,tabId:B}),Be.error(`Failed to write to terminal: ${Y}`);return}e()},[r==null?void 0:r.id,s,y,e]),j=M.useCallback(O=>{const B=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),B===0)return;b(U=>Math.min(B-1,U+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),B===0)return;b(U=>Math.max(0,U-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Q=S[f];Q&&E(Q.path);return}const U=f-S.length,J=w[U];J&&E(J.file.path)}},[f,w,S,E,e]);if(!n)return null;const D=(O,B)=>{if(B.length===0)return O;const U=new Set(B);return O.split("").map((J,Q)=>o.jsx("span",{className:U.has(Q)?"text-accent font-semibold":"",children:J},Q))};let $=-1;const P=i==="page",R=o.jsx("div",{className:P?"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:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"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:k,type:"text",value:a,onChange:O=>{d(O.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?S.length===0&&w.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:[S.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"}),S.map(O=>{$++;const B=$,U=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":U,onClick:()=>E(O.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:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:T_(OC(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.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"}),w.map(({file:O,matched:B})=>{$++;const U=$,J=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":J,onClick:()=>E(O.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${J?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:D(O.name,B)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:T_(OC(O.path),s)})]},O.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:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Cu.createPortal(R,document.body):R}function zC(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function n4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function i4({open:n,onClose:e,variant:i="overlay"}){const r=bt(Q=>Q.tabs.find(Y=>Y.id===Q.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=M.useState(""),[l,c]=M.useState(!1),[p,m]=M.useState([]),[f,b]=M.useState(!1),[y,_]=M.useState(null),[k,x]=M.useState(0),[w,S]=M.useState(null),E=M.useRef(null),j=M.useRef(null),D=M.useRef(0);M.useEffect(()=>{if(!n){d(""),m([]),_(null),x(0);return}const Q=setTimeout(()=>{var Y;return(Y=E.current)==null?void 0:Y.focus()},0);return()=>clearTimeout(Q)},[n]),M.useEffect(()=>{if(!n||!s)return;const Q=a.trim();if(!Q){m([]),_(null),b(!1);return}const Y=++D.current;b(!0);const V=setTimeout(()=>{window.api.search.text(s,Q,{caseSensitive:l,limit:500}).then(ee=>{Y===D.current&&(ee.ok?(m(ee.matches),_(null)):(_(ee.error??"unknown error"),m([])),S(ee.usedRipgrep))}).catch(ee=>{if(Y!==D.current)return;const fe=ee instanceof Error?ee.message:String(ee);ht.error("global-search","search.text threw",{error:fe},{cwd:s,tabId:r==null?void 0:r.id}),_(fe),m([])}).finally(()=>{Y===D.current&&b(!1)})},250);return()=>clearTimeout(V)},[n,s,a,l]);const $=M.useMemo(()=>{const Q=new Map;for(const V of p){const ee=Q.get(V.path);ee?ee.push(V):Q.set(V.path,[V])}const Y=[];for(const[V,ee]of Q)Y.push({path:V,matches:ee});return Y.sort((V,ee)=>ee.matches.length-V.matches.length||V.path.localeCompare(ee.path)),Y},[p]),P=M.useMemo(()=>p,[p]);M.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),M.useEffect(()=>{if(!j.current)return;const Q=j.current.querySelector(`[data-match="${k}"]`);Q&&Q.scrollIntoView({block:"nearest"})},[k]);const R=M.useCallback(Q=>{const Y=r==null?void 0:r.id;if(!Y){Be.error("No active tab to receive path");return}const ee=`${(s?zC(Q.path,s):Q.path)||Q.path}:${Q.line}`;try{window.api.pty.write({tabId:Y,data:ee})}catch(fe){const oe=fe instanceof Error?fe.message:String(fe);ht.error("global-search","pty.write failed",{error:oe},{cwd:s,tabId:Y}),Be.error(`Failed to write to terminal: ${oe}`);return}e()},[r==null?void 0:r.id,s,e]),O=M.useCallback(Q=>{if(Q.key==="Escape"){Q.preventDefault(),e();return}if(Q.key==="ArrowDown"){if(Q.preventDefault(),P.length===0)return;x(Y=>Math.min(P.length-1,Y+1));return}if(Q.key==="ArrowUp"){if(Q.preventDefault(),P.length===0)return;x(Y=>Math.max(0,Y-1));return}if(Q.key==="Enter"){Q.preventDefault();const Y=P[k];Y&&R(Y)}},[P,k,R,e]);if(!n)return null;const B=i==="page";let U=-1;const J=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:Q=>{Q.target===Q.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:O,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:Q=>{d(Q.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:()=>c(Q=>!Q),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…"}):y?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:y}):P.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(Q=>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:[zC(Q.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Q.matches.length,")"]})]}),Q.matches.map(Y=>{U++;const V=U,ee=V===k;return o.jsxs("button",{"data-match":V,role:"option","aria-selected":ee,onClick:()=>R(Y),onMouseEnter:()=>x(V),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ee?"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:Y.line}),o.jsx("span",{className:"truncate",children:n4(Y.text,a,l)})]},`${Y.path}:${Y.line}:${Y.column}:${V}`)})]},Q.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:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!B&&typeof document<"u"&&document.body?Cu.createPortal(J,document.body):J}const r4=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function s4({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=M.useState(r);return M.useEffect(()=>{a(r)},[r]),n?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(rd,{options:r4,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(t4,{open:!0,onClose:e,variant:"page"}):o.jsx(i4,{open:!0,onClose:e,variant:"page"})})]}):null}const o4={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},BC='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Up({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?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 ${d?"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 ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=M.useRef(null),p=M.useRef(null),m=M.useRef(e);if(m.current=e,M.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const _=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(BC);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(BC)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const E=S[0],j=S[S.length-1],D=document.activeElement;x.shiftKey?(D===E||!w.contains(D))&&(x.preventDefault(),j.focus()):(D===j||!w.contains(D))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(_),document.removeEventListener("keydown",k);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[n]),!n)return null;const f=y=>{y.target===y.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:c,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 ${o4[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"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:i}):i]})});return typeof document<"u"&&document.body?Cu.createPortal(b,document.body):b}class lD extends M.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,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 a4({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(Up,{open:n,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:i}),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(lD,{children:r})})]})}function cD(n,e={}){switch(n){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 FC=n=>Symbol.iterator in n,GC=n=>"entries"in n,UC=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},l4=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function c4(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:FC(n)&&FC(e)?GC(n)&&GC(e)?UC(n,e):l4(n,e):UC({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function p1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return c4(e.current,r)?e.current:e.current=r}}let HC=0;const d4=1e3;function u4(n){const e=performance.now();e-HC<d4||(HC=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function dD(){const n=kt(p=>p.isRecording),e=kt(p=>p.error),i=kt(p=>p.loadingProgress),r=kt(p1(jb)),s=()=>{const p=kt.getState(),{canRecord:m,reason:f}=jb(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 u4(f);const b=bt.getState().activeTabId;b&&p.startRecording(b)},a=cD(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=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":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,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 h4(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"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"}),n?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 p4(n){return/^monitor of /i.test(n.trim())}function WC(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function VC(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=WC(e),a=i.filter(d=>d.label&&WC(d.label)===s);return a.length===1?a[0]:null}async function qC(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&p4(r.label))):[]}const KC=!1;function uD(){const n=kt(p=>p.isRecording);kt(p=>p.startRecording),kt(p=>p.stopRecording);const[e,i]=M.useState([]),[r,s]=M.useState(null),[a,d]=M.useState(null);M.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await qC(KC);if(p)return;i(f),d(m.selectedLabel);const b=VC(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.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}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=M.useCallback(async()=>{try{const p=await qC(KC);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=VC(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){ht.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);M.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const c=async p=>{var y;const m=p.target.value,f=m===""?null:m,b=f?((y=e.find(_=>_.deviceId===f))==null?void 0:y.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(_){ht.warn("voice","setDevicePref failed",{error:_ instanceof Error?_.message:String(_)})}if(n)try{await kt.getState().restartWithDevice()}catch(_){ht.warn("voice","device-picker restart failed",{error:_ instanceof Error?_.message:String(_)})}};return o.jsxs("select",{value:r??"",onChange:c,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 f4(){const n=kt(y=>y.isRecording),e=kt(y=>y.levelMeterEnabled),[i,r]=M.useState(0),[s,a]=M.useState(0),d=M.useRef(0);d.current=s;const[l,c]=M.useState(0),[p,m]=M.useState(!1),f=M.useRef(null);if(M.useEffect(()=>{if(!n||!e){r(0),a(0);return}let y=0,_=!1,k=null,x=null;const w=()=>{if(_)return;const E=x??jT();if(!E){y=requestAnimationFrame(w);return}x!==E&&(x=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=k;E.getByteTimeDomainData(j);let D=0;for(let O=0;O<j.length;O++){const B=j[O]-128;D+=B*B}const $=Math.sqrt(D/j.length)/128,P=$>0?20*Math.log10($):-60,R=Math.max(0,Math.min(1,(P+60)/60));a($),r(R),$>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),y=requestAnimationFrame(w)};y=requestAnimationFrame(w);const S=setInterval(()=>{_||c(Math.round(d.current*100))},250);return()=>{_=!0,cancelAnimationFrame(y),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!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:`${i*100}%`}})})}function hD(){const n=kt(p=>p.submitCountdownStartAt),e=kt(p=>p.submitDelayMs),[i,r]=M.useState(()=>performance.now());if(M.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,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:`${d}%`}})})})}function m4({open:n,onClose:e,variant:i="overlay"}){return o.jsx(a4,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(b4,{}),o.jsx(hD,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(dD,{}),o.jsx(uD,{}),o.jsx(h4,{})]}),o.jsx(g4,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(x4,{})]}),o.jsx(f4,{})]})})}function g4(){const n=kt(a=>a.isRecording),[e,i]=M.useState(null);if(M.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=v4(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 v4(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.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 x4(){const[n,e]=M.useState(null);if(M.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.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:n.mode==="toggle",onChange:()=>i("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:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function b4(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?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 j_=null;function y4(){return j_||(j_=qg(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(X0.config({monaco:n}),n))),j_}function pD({value:n,onChange:e,path:i,readOnly:r}){const s=M.useRef(null),a=d=>{s.current=d};return o.jsx(J0,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),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 YC=!1;async function _4(n){if(YC)return;const e=await y4(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),YC=!0}function f1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=M.useState(""),[l,c]=M.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.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:br[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:y=>c(y.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:y=>d(y.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(fD,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function fD(n){return n.node.kind==="object"?o.jsx(w4,{...n,node:n.node}):n.node.kind==="array"?o.jsx(S4,{...n,node:n.node}):o.jsx(k4,{...n,node:n.node})}function XC(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Ip(n,e,i){return!!(!i.trim()||n.some(r=>XC(r,i))||e!=null&&e.description&&XC(e.description,i))}function w4({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:p}){const[m,f]=M.useState(p??d<2),b=(l==null?void 0:l.at(e))??null,y=new Set(Object.keys(n.children)),_=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([...y,..._])).sort(),x=M.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Ip([...e,S],E,a)?!0:y.has(S)?mD(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Ip(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});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:d*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:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",y.size,_.length>y.size?`/${new Set([...y,..._]).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(S=>w(S))]});function w(S){if(y.has(S))return o.jsx(fD,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(C4,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function mD(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Ip(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(mD(n.children[a],[...e,a],i,r))return!0;return!1}function S4({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=M.useState(!0),c=(a==null?void 0:a.at(e))??null;return Ip(e,c,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(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(Lg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.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:Gb(p.value)}),o.jsx(zw,{scope:p.fromScope})]},m))]}):null}function k4({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,p]=M.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Ip(e,m,a))return null;const f=n.winner!==r,b=n.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:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Gb(n.value)}),o.jsx(zw,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(Lg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&E4(n.value,m.default)&&o.jsx(Lg,{tone:"dim",children:"= default"}),n.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(gD,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.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 ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((y,_)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Gb(y.value)}),o.jsx(zw,{scope:y.scope,dim:!0})]},_))]})}function C4({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Ip(n,i,d))return null;const l=i.default!==void 0?i.default:T4(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.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(Lg,{tone:"dim",children:c}),i.required&&o.jsx(Lg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Gb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(gD,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,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 ${br[r].label} draft`,children:"set"})]})}function E4(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function T4(n){switch(Array.isArray(n)?n[0]:n){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 Gb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function zw({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="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 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function Lg({children:n,tone:e="default"}){const i={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 ${i}`,children:n})}function gD({values:n}){const e=n.map(i=>String(i)).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 j4=[{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"]}],D4={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function vD(n){return n.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=D4[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function xD(n){const e=new Set,i=[];for(const s of j4){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function N4(n,e){return xD(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const A4={};function bD(n,e){if(e)return{text:e,authored:!1};const i=A4[n];return i?{text:i,authored:!0}:null}const $4={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"},P4=["user","project","local","default"],R4={user:"user",project:"project",local:"local",default:"default"};function I4({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=M.useState(""),[d,l]=M.useState(!1),[c,p]=M.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),y=new Set([...f,...b]),_=M.useMemo(()=>xD(y),[Array.from(y).sort().join(",")]),k=M.useMemo(()=>N4(y,new Set(f)),[Array.from(y).sort().join(","),f.join(",")]),[x,w]=M.useState(null),S=j=>{const D=_.find($=>$.id===j);D!=null&&D.advanced&&!d&&l(!0),w(j)};M.useEffect(()=>{if(!x)return;const j=document.getElementById(`settings-group-${x}`);j&&(j.scrollIntoView({behavior:"smooth",block:"start"}),w(null))});const E=M.useMemo(()=>_.filter(j=>d||!j.advanced).map(j=>({...j,keys:j.keys.filter(D=>{const $=(m==null?void 0:m.children[D])!==void 0;if(!c&&!$)return!1;if(!s.trim())return!0;const P=r.at([D]);return[D,vD(D),(P==null?void 0:P.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(j=>j.keys.length>0),[_,s,d,c,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:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,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:d,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(M4,{groups:k,onJump:S}),o.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[E.map(j=>o.jsx(O4,{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],P=r.at([D]);return o.jsx(L4,{keyName:D,node:$,info:P,targetScope:e,onOverride:(R,O)=>i([D],R,O)},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 M4({groups:n,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:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(an,{name:$4[i.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:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function O4({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=M.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,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:()=>d(!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:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function L4({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=M.useState(!1),[l,c]=M.useState(!1),p=vD(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,y=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",_=i==null?void 0:i.default,k=b&&_!==void 0&&_D(b.value,_),x=V4({isSet:m,leafNode:b,defaultVal:_,isDefault:!!k,node:e}),w=z4(b,_),S=w.length>=2,E=!!b&&!k,j=bD(n,i==null?void 0:i.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:()=>d(!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(q4,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:D=>{D.stopPropagation(),a||d(!0),c($=>!$)},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 · ",w.map(D=>R4[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 ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.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"}),(i==null?void 0:i.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:K4(j.text)}),a&&l&&b&&o.jsx(B4,{leaf:b,defaultVal:_,onReset:D=>s(void 0,D)}),a&&o.jsx(F4,{keyName:n,node:e,info:i,targetScope:r,onOverride:D=>s(D)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(W4,{node:e,info:i,onSet:D=>{s(D)},disabled:y&&m})})]})})}function z4(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),P4.filter(r=>i.has(r))}function B4({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.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],d=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:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?jp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(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 ${br[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?jp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function F4({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=bD(n,i==null?void 0:i.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:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:jp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&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:jp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[jp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.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(G4,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function G4({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=yD(e==null?void 0:e.type);if(d==="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:c,label:p})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"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:["→ ",br[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 c=_D(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"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:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(U4,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(H4,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function U4({value:n,integer:e,onCommit:i,target:r}){const[s,a]=M.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(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:d,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:d,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 H4({value:n,onCommit:e,target:i}){const[r,s]=M.useState(n);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 → ",i]})]})}function W4({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=yD(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"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:d?"on":"off"})}return null}function V4({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(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 · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${jp(i)}`}:{kind:"unset",label:"not configured"}}function q4({kind:n,label:e}){const i={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"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function yD(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function _D(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function K4(n){const e=n.trim().split(`
3059
3059
  `)[0],i=e.match(/^([^.!?]+[.!?])/);return i?i[1]:e.length>120?e.slice(0,120)+"…":e}function jp(n){if(typeof n=="string")return n===""?'""':JSON.stringify(n);if(n===null)return"null";if(n===void 0)return"—";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>60?e.slice(0,60)+"…":e}return String(n)}function m1(n,e,i){const r=ln(c=>c.files),s=ln(c=>c.loadJson),a=ln(c=>c.watchFile),d=ln(c=>c.unwatchFile),l=M.useMemo(()=>{const c={};for(const p of n.scopes){const m=n.resolve(p,e??"",i);m&&(c[p]=m)}return c},[n,e,i]);return M.useEffect(()=>{const c=Object.values(l).filter(Boolean);return c.forEach(p=>{r[p]||s(p),a(p)}),()=>{c.forEach(p=>d(p))}},[JSON.stringify(l)]),l}const Y4=[];function Ox(n){return Array.isArray(n)?"array":n!==null&&typeof n=="object"?"object":"scalar"}function g1(n){const e=n.filter(i=>i.data!==void 0);return e.length===0?{kind:"object",children:{}}:wD(e,[])}function wD(n,e){const i=Y4.includes(e.join(".")),r=n.every(m=>Ox(m.data)==="object"),s=n.every(m=>Ox(m.data)==="array");if(r){const m=new Set;for(const b of n)for(const y of Object.keys(b.data))m.add(y);const f={};for(const b of m){const y=n.filter(_=>b in _.data).map(_=>({scope:_.scope,data:_.data[b]}));f[b]=wD(y,[...e,b])}return{kind:"object",children:f}}if(s&&!i){const m=[];for(const f of[...n].reverse())for(const b of f.data)m.push({value:b,fromScope:f.scope,index:m.length});return{kind:"array",items:m}}const a=[...n].reverse(),d=a[0],l=a.slice(1).map(m=>({scope:m.scope,value:m.data})),c=Ox(d.data),p=l.some(m=>Ox(m.value)!==c);return{kind:"leaf",value:d.data,winner:d.scope,shadowed:l,...p?{typeMismatch:!0}:{}}}function v1(n,e){if(e.length===0)return n;if(n.kind!=="object")return null;const[i,...r]=e,s=n.children[i];return s?v1(s,r):null}function Sy(n,e,i){if(e.length===0)return i;const[r,...s]=e,a=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};return a[r]=Sy(a[r],s,i),a}const X4=["user","project","local"];function x1(n,e){const i=[];for(const r of X4){const s=e[r];if(!s)continue;const a=n[s];if(!a||!a.exists)continue;const d=a.draftRaw??"";if(d.trim())try{i.push({scope:r,data:JSON.parse(d)})}catch{}}return i}const J4="http://json-schema.org/draft-07/schema#",Z4="https://json.schemastore.org/claude-code-settings.json",Q4={permissionRule:{type:"string",description:`Tool permission rule.
3060
3060
  See https://code.claude.com/docs/en/settings#permission-rule-syntax
3061
3061
  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"}}}}},eB="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",tB=!0,nB=!0,iB="object",rB=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"]}]}}}`),sB="Claude Code Settings",oB={$schema:J4,$id:Z4,$defs:Q4,description:eB,allowTrailingCommas:tB,additionalProperties:nB,type:iB,properties:rB,title:sB};function aB(n){const e=n??{},i={...e.$defs??{},...e.definitions??{}},r=y=>{if(!y)return{};if(!y.$ref)return d(y);const _=/^#\/(\$defs|definitions)\/(.+)$/.exec(y.$ref);if(!_)return d(y);const k=i[_[2]];return k?r({...k,...l(y)}):d(y)},s=new Set(["__proto__","constructor","prototype"]),a=y=>{if(!y)return{};const _={};for(const[k,x]of Object.entries(y))s.has(k)||(_[k]=x);return _},d=y=>{if(!y.allOf||y.allOf.length===0)return y;const _={...y};delete _.allOf;for(const k of y.allOf){const x=r(k);Object.assign(_,{properties:{...a(_.properties),...a(x.properties)},required:lB([..._.required??[],...x.required??[]])}),!_.description&&x.description&&(_.description=x.description),_.default===void 0&&x.default!==void 0&&(_.default=x.default),!_.type&&x.type&&(_.type=x.type)}return _},l=y=>{const{$ref:_,...k}=y;return k},c=(y,_)=>{let k=r(y);for(const x of _){if(!k)return null;if(/^\d+$/.test(x)){const E=Array.isArray(k.items)?k.items[Number(x)]:k.items;k=E?r(E):null;continue}const w=k.properties;if(w&&!s.has(x)&&x in w){k=r(w[x]);continue}const S=k.additionalProperties;if(S&&typeof S=="object"){k=r(S);continue}return null}return k},p=(y,_,k)=>{if(!y)return null;const x={};if(y.description&&(x.description=y.description),y.type&&(x.type=y.type),y.default!==void 0&&(x.default=y.default),y.enum&&(x.enum=y.enum),y.const!==void 0&&(x.const=y.const),y.deprecated&&(x.deprecated=!0),y.examples&&(x.examples=y.examples),y.properties&&(x.knownChildren=Object.keys(y.properties)),k&&(_!=null&&_.includes(k))&&(x.required=!0),y.items&&!Array.isArray(y.items)){const w=r(y.items),S=p(w,void 0,null);S&&(x.itemsInfo=S)}return(y.additionalProperties===!0||typeof y.additionalProperties=="object")&&(x.open=!0),x},m=y=>_=>{if(_.length===0)return p(r(y),void 0,null);const k=c(y,_.slice(0,-1));if(!k)return null;const x=_[_.length-1],w=c(k,[x]);return p(w,k.required,x)},f=y=>{const _=r(y);return Object.keys(_.properties??{})},b=y=>({at:m(y),rootKeys:()=>f(y),rootedAt:_=>{const k=c(y,_);return b(k??{})}});return b(e)}function lB(n){return Array.from(new Set(n))}let D_=null;function Ub(){return D_||(D_=aB(oB)),D_}function cB(){const[n,e]=M.useState(null),[i,r]=M.useState(null),[s,a]=M.useState(null),[d,l]=M.useState(null),[c,p]=M.useState(!1),[m,f]=M.useState(null),[b,y]=M.useState(null);if(M.useEffect(()=>{let S=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([E,j,D])=>{S||(e(E),a(E),r(j),l(D))}).catch(E=>{console.warn("[telemetry] load failed:",E==null?void 0:E.message)}),()=>{S=!0}},[]),!s||!n)return o.jsx(Vt,{title:"loading…"});const _=JSON.stringify(s)!==JSON.stringify(n),k=(S,E)=>{f(null),a({...s,[S]:E})},x=async()=>{p(!0),f(null);try{const S=await window.api.otel.setConfig(s);!S.ok&&S.error&&f(S.error),e(S.config),a(S.config),r(S.status),y(Date.now())}catch(S){f(S instanceof Error?S.message:String(S))}finally{p(!1)}},w=()=>{f(null),a(n)};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."}),d&&o.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",o.jsx("span",{className:"font-mono",children:d})]})]}),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(Mg,{checked:s.enabled,onChange:S=>k("enabled",S),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:S=>k("endpoint",S.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:S=>k("headers",S.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:S=>k("serviceName",S.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(Mg,{checked:s.includeContent,onChange:S=>k("includeContent",S),label:s.includeContent?"on":"off"})]})]}),i&&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:i.enabled?"text-accent":"text-fg-dim",children:String(i.enabled)})]}),i.error&&o.jsxs("div",{className:"text-red-400 break-words",children:[o.jsx("span",{className:"text-fg-faint",children:"error:"})," ",i.error]}),!i.error&&i.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:!_||c,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:c?"saving…":"Save"}),o.jsx("button",{onClick:w,disabled:!_||c,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&&!_&&o.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function dB(){const{model:n,setModel:e}=JA();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:n,onChange:i=>e(i.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:rT.map(i=>o.jsx("option",{value:i,children:i.charAt(0).toUpperCase()+i.slice(1)},i))}),o.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function uB(){const n=Mi(),e=bt(B=>B.tabs),i=bt(B=>B.activeTabId),r=e.find(B=>B.id===i)??null,s=(r==null?void 0:r.cwd)??null,a=bn(B=>B.focusedPanelId),d=Za(a),l=M.useRef(!1),c=M.useRef(d),[p,m]=M.useState(()=>d==="project"&&s?"project":"user"),[f,b]=M.useState("effective");M.useEffect(()=>{if(c.current!==d){if(c.current=d,l.current){l.current=!1;return}m(d==="project"&&s?"project":"user")}},[d,s]);const y=B=>{l.current=!0,m(B)},_=m1(Ig,n,s),k=_[p]??null,x=ln(B=>B.files),w=ln(B=>B.setDraft),S=ln(B=>B.saveJson),E=ln(B=>B.revert),[j,D]=M.useState(null),$=M.useMemo(()=>g1(x1(x,_)),[x,_]),P=(B,U,J)=>{var oe;const Y=_[J??p];if(!Y)return;D(null);const V=((oe=x[Y])==null?void 0:oe.draftRaw)??"";let ee={};if(V.trim())try{ee=JSON.parse(V)}catch{ee={}}const fe=Sy(ee,B,U);w(Y,JSON.stringify(fe,null,2)+`