claude-code-session-manager 0.78.0 → 0.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentLibrary-13pfo8uY.js → AgentLibrary-zS3jw_1e.js} +1 -1
- package/dist/assets/{DataModel-SUyQbFlg.js → DataModel-Cy_vxTpi.js} +1 -1
- package/dist/assets/{History-2GJMS703.js → History-C6JRuqfT.js} +1 -1
- package/dist/assets/{Hooks-DM2nS3RT.js → Hooks-BafPy9mB.js} +1 -1
- package/dist/assets/{HostBilko-BLeC-lpp.js → HostBilko-BZwhQOFt.js} +1 -1
- package/dist/assets/{Library-BaRkU9m0.js → Library-C8JDDliz.js} +1 -1
- package/dist/assets/{ListDetail-D5scjSKq.js → ListDetail-CqiOdwLc.js} +1 -1
- package/dist/assets/{MarkdownEditor-B1lgAo9T.js → MarkdownEditor-CyLyP67L.js} +1 -1
- package/dist/assets/{McpServers-BzyThQSM.js → McpServers-BzMv-_84.js} +1 -1
- package/dist/assets/{Memory-7UdaOTtl.js → Memory-DSBYQdJR.js} +1 -1
- package/dist/assets/{Panel-JbTMaOPq.js → Panel-CLUhkNNA.js} +1 -1
- package/dist/assets/{Permissions-UBam0bJG.js → Permissions-BfC2-HN4.js} +1 -1
- package/dist/assets/{Plugins-B3gUDkeb.js → Plugins-BKi40jT5.js} +2 -2
- package/dist/assets/{ProvenanceBadge-CeHOub7m.js → ProvenanceBadge-BzFw4KhD.js} +1 -1
- package/dist/assets/{SaveBar-BcvQEq6h.js → SaveBar-avk2p9jv.js} +1 -1
- package/dist/assets/{Scheduler-Dc5qiP24.js → Scheduler-Bf_6MdJo.js} +7 -7
- package/dist/assets/{ScopeSwitcher-BvGQmw4Y.js → ScopeSwitcher-C-RwYUVZ.js} +1 -1
- package/dist/assets/{Settings-C2dEFb-v.js → Settings-Djd8OoBA.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-CIwlosBc.js → SkillReferenceGraph-DuogY6s7.js} +1 -1
- package/dist/assets/{Skills-C0GzzVrQ.js → Skills-D_qAqxZ_.js} +1 -1
- package/dist/assets/{SystemPrompt-mtGPK8zo.js → SystemPrompt-DbHFLQV3.js} +1 -1
- package/dist/assets/{TagLibrary-DX54-mpd.js → TagLibrary-C2y91BT0.js} +1 -1
- package/dist/assets/{TiptapBody-yADC2RWE.js → TiptapBody-D9iz4xQx.js} +1 -1
- package/dist/assets/{Toggle-CRxaCYLI.js → Toggle-BGnFL2E5.js} +1 -1
- package/dist/assets/{index-D6ymGESc.js → index-_2ARyFDj.js} +4 -4
- package/dist/assets/{settingsSchema-TtMvT5Sx.js → settingsSchema-JK15eJU8.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/builder/3-publish/SKILL.md +10 -0
- package/scripts/project-pages-logic/dist/logic.cjs +12 -12
- package/scripts/render-project-pages/dist/renderer.cjs +22 -22
- package/src/main/__tests__/computeDepHistorySatisfaction.test.cjs +66 -0
- package/src/main/__tests__/prdCreate.test.cjs +133 -8
- package/src/main/__tests__/prdFrontmatterDependsOn.test.cjs +136 -0
- package/src/main/__tests__/prdUpdateDependsOn.test.cjs +160 -0
- package/src/main/__tests__/queueHistory.test.cjs +33 -0
- package/src/main/__tests__/runLogRetention.test.cjs +59 -0
- package/src/main/__tests__/scheduleJobTransitions.test.cjs +1 -0
- package/src/main/__tests__/scheduler-autofix-outcome.test.cjs +73 -1
- package/src/main/__tests__/scheduler-autofix-select.test.cjs +17 -0
- package/src/main/__tests__/scheduler-commit-guard-noop.test.cjs +20 -0
- package/src/main/__tests__/scheduler-leftover-quarantine.test.cjs +199 -0
- package/src/main/__tests__/scheduler-mechanical-recovery.test.cjs +222 -0
- package/src/main/__tests__/scheduler-never-stop.test.cjs +157 -0
- package/src/main/__tests__/scheduler-no-orphan-run-dir.test.cjs +81 -0
- package/src/main/__tests__/scheduler-rate-limit-cooldown-freshness.test.cjs +123 -0
- package/src/main/__tests__/scheduler-rate-limit-spin-guard.test.cjs +158 -0
- package/src/main/__tests__/scheduler-reap-dead-running-jobs.test.cjs +30 -0
- package/src/main/__tests__/scheduler-reconcile-quarantine.test.cjs +51 -0
- package/src/main/__tests__/scheduler-resume-recovery.test.cjs +254 -0
- package/src/main/__tests__/schedulerBatchRootBlocker.test.cjs +117 -0
- package/src/main/__tests__/uniquePrdNumbers.test.cjs +14 -2
- package/src/main/ipcSchemas.cjs +15 -1
- package/src/main/lib/__tests__/gitWorktree.test.cjs +129 -10
- package/src/main/lib/__tests__/reaperHelpers.test.cjs +90 -1
- package/src/main/lib/__tests__/schedulerBatchDepends.test.cjs +59 -7
- package/src/main/lib/depSlugResolve.cjs +72 -0
- package/src/main/lib/epicWorktreeMerge.cjs +3 -3
- package/src/main/lib/epicWorktreeMint.cjs +17 -5
- package/src/main/lib/fixPlanSlug.cjs +62 -0
- package/src/main/lib/gitWorktree.cjs +97 -12
- package/src/main/lib/jobDirtFilter.cjs +54 -0
- package/src/main/lib/mcpToolCatalog.cjs +4 -1
- package/src/main/lib/prdCreate.cjs +84 -5
- package/src/main/lib/prdFrontmatter.cjs +56 -8
- package/src/main/lib/queueHistory.cjs +50 -5
- package/src/main/lib/rateLimitDetect.cjs +35 -0
- package/src/main/lib/reaperHelpers.cjs +31 -6
- package/src/main/lib/runLogRetention.cjs +82 -4
- package/src/main/lib/scheduleJobTransitions.cjs +12 -2
- package/src/main/lib/schedulerBatch.cjs +181 -23
- package/src/main/scheduler/prdParser.cjs +7 -0
- package/src/main/scheduler.cjs +1165 -70
- package/src/preload/api.d.ts +8 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-D9iz4xQx.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-D_qAqxZ_.js","./Panel-CLUhkNNA.js","./ListDetail-CqiOdwLc.js","./MarkdownEditor-CyLyP67L.js","./SaveBar-avk2p9jv.js","./ScopeSwitcher-C-RwYUVZ.js","./Toggle-BGnFL2E5.js","./ProvenanceBadge-BzFw4KhD.js","./Library-C8JDDliz.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-C6JRuqfT.js","./Scheduler-Bf_6MdJo.js","./Settings-Djd8OoBA.js","./settingsSchema-JK15eJU8.js","./Permissions-BfC2-HN4.js","./SystemPrompt-DbHFLQV3.js","./Memory-DSBYQdJR.js","./Plugins-BKi40jT5.js","./McpServers-BzMv-_84.js","./Hooks-BafPy9mB.js","./AgentLibrary-zS3jw_1e.js","./TagLibrary-C2y91BT0.js","./HostBilko-BZwhQOFt.js","./DataModel-Cy_vxTpi.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var Pk=Object.defineProperty;var Rk=(i,e,t)=>e in i?Pk(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Fi=(i,e,t)=>Rk(i,typeof e!="symbol"?e+"":e,t);import{_ as qn}from"./monaco-editor-BW5C4Iv1.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const l of r)if(l.type==="childList")for(const p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&n(p)}).observe(document,{childList:!0,subtree:!0});function t(r){const l={};return r.integrity&&(l.integrity=r.integrity),r.referrerPolicy&&(l.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?l.credentials="include":r.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(r){if(r.ep)return;r.ep=!0;const l=t(r);fetch(r.href,l)}})();function Lb(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Bv={exports:{}},Yp={},Gv={exports:{}},mi={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -40,7 +40,7 @@ var Pk=Object.defineProperty;var Rk=(i,e,t)=>e in i?Pk(i,e,{enumerable:!0,config
|
|
|
40
40
|
Error generating stack: `+F.message+`
|
|
41
41
|
`+F.stack}return{value:o,source:u,stack:O,digest:null}}function du(o,u,_){return{value:o,source:null,stack:_??null,digest:u??null}}function uu(o,u){try{console.error(u.value)}catch(_){setTimeout(function(){throw _})}}var $m=typeof WeakMap=="function"?WeakMap:Map;function gp(o,u,_){_=Yr(-1,_),_.tag=3,_.payload={element:null};var $=u.value;return _.callback=function(){Gc||(Gc=!0,Pu=$),uu(o,u)},_}function vp(o,u,_){_=Yr(-1,_),_.tag=3;var $=o.type.getDerivedStateFromError;if(typeof $=="function"){var O=u.value;_.payload=function(){return $(O)},_.callback=function(){uu(o,u)}}var F=o.stateNode;return F!==null&&typeof F.componentDidCatch=="function"&&(_.callback=function(){uu(o,u),typeof $!="function"&&(Co===null?Co=new Set([this]):Co.add(this));var ee=u.stack;this.componentDidCatch(u.value,{componentStack:ee!==null?ee:""})}),_}function _p(o,u,_){var $=o.pingCache;if($===null){$=o.pingCache=new $m;var O=new Set;$.set(u,O)}else O=$.get(u),O===void 0&&(O=new Set,$.set(u,O));O.has(_)||(O.add(_),o=Fm.bind(null,o,u,_),u.then(o,o))}function Im(o){do{var u;if((u=o.tag===13)&&(u=o.memoizedState,u=u!==null?u.dehydrated!==null:!0),u)return o;o=o.return}while(o!==null);return null}function rs(o,u,_,$,O){return(o.mode&1)===0?(o===u?o.flags|=65536:(o.flags|=128,_.flags|=131072,_.flags&=-52805,_.tag===1&&(_.alternate===null?_.tag=17:(u=Yr(-1,1),u.tag=2,wo(_,u,1))),_.lanes|=1),o):(o.flags|=65536,o.lanes=O,o)}var Pm=A.ReactCurrentOwner,xs=!1;function Wn(o,u,_,$){u.child=o===null?Wd(u,null,_,$):Pa(u,o.child,_,$)}function bp(o,u,_,$,O){_=_.render;var F=u.ref;return Ra(u,O),$=su(o,u,_,$,F,O),_=ru(),o!==null&&!xs?(u.updateQueue=o.updateQueue,u.flags&=-2053,o.lanes&=~O,Jr(o,u,O)):(Xi&&_&&fn(u),u.flags|=1,Wn(o,u,$,O),u.child)}function El(o,u,_,$,O){if(o===null){var F=_.type;return typeof F=="function"&&!zu(F)&&F.defaultProps===void 0&&_.compare===null&&_.defaultProps===void 0?(u.tag=15,u.type=F,wp(o,u,F,$,O)):(o=Vc(_.type,null,$,u,u.mode,O),o.ref=u.ref,o.return=u,u.child=o)}if(F=o.child,(o.lanes&O)===0){var ee=F.memoizedProps;if(_=_.compare,_=_!==null?_:pl,_(ee,$)&&o.ref===u.ref)return Jr(o,u,O)}return u.flags|=1,o=To(F,$),o.ref=u.ref,o.return=u,u.child=o}function wp(o,u,_,$,O){if(o!==null){var F=o.memoizedProps;if(pl(F,$)&&o.ref===u.ref)if(xs=!1,u.pendingProps=$=F,(o.lanes&O)!==0)(o.flags&131072)!==0&&(xs=!0);else return u.lanes=o.lanes,Jr(o,u,O)}return hu(o,u,_,$,O)}function yp(o,u,_){var $=u.pendingProps,O=$.children,F=o!==null?o.memoizedState:null;if($.mode==="hidden")if((u.mode&1)===0)u.memoizedState={baseLanes:0,cachePool:null,transitions:null},Mi(La,Rs),Rs|=_;else{if((_&1073741824)===0)return o=F!==null?F.baseLanes|_:_,u.lanes=u.childLanes=1073741824,u.memoizedState={baseLanes:o,cachePool:null,transitions:null},u.updateQueue=null,Mi(La,Rs),Rs|=o,null;u.memoizedState={baseLanes:0,cachePool:null,transitions:null},$=F!==null?F.baseLanes:_,Mi(La,Rs),Rs|=$}else F!==null?($=F.baseLanes|_,u.memoizedState=null):$=_,Mi(La,Rs),Rs|=$;return Wn(o,u,O,_),u.child}function xp(o,u){var _=u.ref;(o===null&&_!==null||o!==null&&o.ref!==_)&&(u.flags|=512,u.flags|=2097152)}function hu(o,u,_,$,O){var F=vs(_)?Wo:ns.current;return F=ss(u,F),Ra(u,O),_=su(o,u,_,$,F,O),$=ru(),o!==null&&!xs?(u.updateQueue=o.updateQueue,u.flags&=-2053,o.lanes&=~O,Jr(o,u,O)):(Xi&&$&&fn(u),u.flags|=1,Wn(o,u,_,O),u.child)}function Sp(o,u,_,$,O){if(vs(_)){var F=!0;wc(u)}else F=!1;if(Ra(u,O),u.stateNode===null)Nc(o,u),fp(u,_,$),cu(u,_,$,O),$=!0;else if(o===null){var ee=u.stateNode,be=u.memoizedProps;ee.props=be;var Te=ee.context,Ue=_.contextType;typeof Ue=="object"&&Ue!==null?Ue=qs(Ue):(Ue=vs(_)?Wo:ns.current,Ue=ss(u,Ue));var lt=_.getDerivedStateFromProps,ut=typeof lt=="function"||typeof ee.getSnapshotBeforeUpdate=="function";ut||typeof ee.UNSAFE_componentWillReceiveProps!="function"&&typeof ee.componentWillReceiveProps!="function"||(be!==$||Te!==Ue)&&mp(u,ee,$,Ue),Ir=!1;var at=u.memoizedState;ee.state=at,Dc(u,$,ee,O),Te=u.memoizedState,be!==$||at!==Te||gs.current||Ir?(typeof lt=="function"&&(Rr(u,_,lt,$),Te=u.memoizedState),(be=Ir||Qo(u,_,be,$,at,Te,Ue))?(ut||typeof ee.UNSAFE_componentWillMount!="function"&&typeof ee.componentWillMount!="function"||(typeof ee.componentWillMount=="function"&&ee.componentWillMount(),typeof ee.UNSAFE_componentWillMount=="function"&&ee.UNSAFE_componentWillMount()),typeof ee.componentDidMount=="function"&&(u.flags|=4194308)):(typeof ee.componentDidMount=="function"&&(u.flags|=4194308),u.memoizedProps=$,u.memoizedState=Te),ee.props=$,ee.state=Te,ee.context=Ue,$=be):(typeof ee.componentDidMount=="function"&&(u.flags|=4194308),$=!1)}else{ee=u.stateNode,Yd(o,u),be=u.memoizedProps,Ue=u.type===u.elementType?be:gn(u.type,be),ee.props=Ue,ut=u.pendingProps,at=ee.context,Te=_.contextType,typeof Te=="object"&&Te!==null?Te=qs(Te):(Te=vs(_)?Wo:ns.current,Te=ss(u,Te));var Tt=_.getDerivedStateFromProps;(lt=typeof Tt=="function"||typeof ee.getSnapshotBeforeUpdate=="function")||typeof ee.UNSAFE_componentWillReceiveProps!="function"&&typeof ee.componentWillReceiveProps!="function"||(be!==ut||at!==Te)&&mp(u,ee,$,Te),Ir=!1,at=u.memoizedState,ee.state=at,Dc(u,$,ee,O);var Nt=u.memoizedState;be!==ut||at!==Nt||gs.current||Ir?(typeof Tt=="function"&&(Rr(u,_,Tt,$),Nt=u.memoizedState),(Ue=Ir||Qo(u,_,Ue,$,at,Nt,Te)||!1)?(lt||typeof ee.UNSAFE_componentWillUpdate!="function"&&typeof ee.componentWillUpdate!="function"||(typeof ee.componentWillUpdate=="function"&&ee.componentWillUpdate($,Nt,Te),typeof ee.UNSAFE_componentWillUpdate=="function"&&ee.UNSAFE_componentWillUpdate($,Nt,Te)),typeof ee.componentDidUpdate=="function"&&(u.flags|=4),typeof ee.getSnapshotBeforeUpdate=="function"&&(u.flags|=1024)):(typeof ee.componentDidUpdate!="function"||be===o.memoizedProps&&at===o.memoizedState||(u.flags|=4),typeof ee.getSnapshotBeforeUpdate!="function"||be===o.memoizedProps&&at===o.memoizedState||(u.flags|=1024),u.memoizedProps=$,u.memoizedState=Nt),ee.props=$,ee.state=Nt,ee.context=Te,$=Ue):(typeof ee.componentDidUpdate!="function"||be===o.memoizedProps&&at===o.memoizedState||(u.flags|=4),typeof ee.getSnapshotBeforeUpdate!="function"||be===o.memoizedProps&&at===o.memoizedState||(u.flags|=1024),$=!1)}return pu(o,u,_,$,F,O)}function pu(o,u,_,$,O,F){xp(o,u);var ee=(u.flags&128)!==0;if(!$&&!ee)return O&&Fh(u,_,!1),Jr(o,u,F);$=u.stateNode,Pm.current=u;var be=ee&&typeof _.getDerivedStateFromError!="function"?null:$.render();return u.flags|=1,o!==null&&ee?(u.child=Pa(u,o.child,null,F),u.child=Pa(u,null,be,F)):Wn(o,u,be,F),u.memoizedState=$.state,O&&Fh(u,_,!0),u.child}function fu(o){var u=o.stateNode;u.pendingContext?Bh(o,u.pendingContext,u.pendingContext!==u.context):u.context&&Bh(o,u.context,!1),Xd(o,u.containerInfo)}function Cp(o,u,_,$,O){return Vo(),Fd(O),u.flags|=256,Wn(o,u,_,$),u.child}var mu={dehydrated:null,treeContext:null,retryLane:0};function gu(o){return{baseLanes:o,cachePool:null,transitions:null}}function kp(o,u,_){var $=u.pendingProps,O=Qi.current,F=!1,ee=(u.flags&128)!==0,be;if((be=ee)||(be=o!==null&&o.memoizedState===null?!1:(O&2)!==0),be?(F=!0,u.flags&=-129):(o===null||o.memoizedState!==null)&&(O|=1),Mi(Qi,O&1),o===null)return Bd(u),o=u.memoizedState,o!==null&&(o=o.dehydrated,o!==null)?((u.mode&1)===0?u.lanes=1:o.data==="$!"?u.lanes=8:u.lanes=1073741824,null):(ee=$.children,o=$.fallback,F?($=u.mode,F=u.child,ee={mode:"hidden",children:ee},($&1)===0&&F!==null?(F.childLanes=0,F.pendingProps=ee):F=qc(ee,$,0,null),o=Ga(o,$,_,null),F.return=u,o.return=u,F.sibling=o,u.child=F,u.child.memoizedState=gu(_),u.memoizedState=mu,o):Tl(u,ee));if(O=o.memoizedState,O!==null&&(be=O.dehydrated,be!==null))return Rm(o,u,ee,$,be,O,_);if(F){F=$.fallback,ee=u.mode,O=o.child,be=O.sibling;var Te={mode:"hidden",children:$.children};return(ee&1)===0&&u.child!==O?($=u.child,$.childLanes=0,$.pendingProps=Te,u.deletions=null):($=To(O,Te),$.subtreeFlags=O.subtreeFlags&14680064),be!==null?F=To(be,F):(F=Ga(F,ee,_,null),F.flags|=2),F.return=u,$.return=u,$.sibling=F,u.child=$,$=F,F=u.child,ee=o.child.memoizedState,ee=ee===null?gu(_):{baseLanes:ee.baseLanes|_,cachePool:null,transitions:ee.transitions},F.memoizedState=ee,F.childLanes=o.childLanes&~_,u.memoizedState=mu,$}return F=o.child,o=F.sibling,$=To(F,{mode:"visible",children:$.children}),(u.mode&1)===0&&($.lanes=_),$.return=u,$.sibling=null,o!==null&&(_=u.deletions,_===null?(u.deletions=[o],u.flags|=16):_.push(o)),u.child=$,u.memoizedState=null,$}function Tl(o,u){return u=qc({mode:"visible",children:u},o.mode,0,null),u.return=o,o.child=u}function jc(o,u,_,$){return $!==null&&Fd($),Pa(u,o.child,null,_),o=Tl(u,u.pendingProps.children),o.flags|=2,u.memoizedState=null,o}function Rm(o,u,_,$,O,F,ee){if(_)return u.flags&256?(u.flags&=-257,$=du(Error(t(422))),jc(o,u,ee,$)):u.memoizedState!==null?(u.child=o.child,u.flags|=128,null):(F=$.fallback,O=u.mode,$=qc({mode:"visible",children:$.children},O,0,null),F=Ga(F,O,ee,null),F.flags|=2,$.return=u,F.return=u,$.sibling=F,u.child=$,(u.mode&1)!==0&&Pa(u,o.child,null,ee),u.child.memoizedState=gu(ee),u.memoizedState=mu,F);if((u.mode&1)===0)return jc(o,u,ee,null);if(O.data==="$!"){if($=O.nextSibling&&O.nextSibling.dataset,$)var be=$.dgst;return $=be,F=Error(t(419)),$=du(F,$,void 0),jc(o,u,ee,$)}if(be=(ee&o.childLanes)!==0,xs||be){if($=vn,$!==null){switch(ee&-ee){case 4:O=2;break;case 16:O=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:O=32;break;case 536870912:O=268435456;break;default:O=0}O=(O&($.suspendedLanes|ee))!==0?0:O,O!==0&&O!==F.retryLane&&(F.retryLane=O,Kr(o,O),fr($,o,O,-1))}return Lu(),$=du(Error(t(421))),jc(o,u,ee,$)}return O.data==="$?"?(u.flags|=128,u.child=o.child,u=Wm.bind(null,o),O._reactRetry=u,null):(o=F.treeContext,Ps=go(O.nextSibling),ws=u,Xi=!0,ys=null,o!==null&&(Us[dr++]=_s,Us[dr++]=bs,Us[dr++]=Vs,_s=o.id,bs=o.overflow,Vs=u),u=Tl(u,$.children),u.flags|=4096,u)}function Ep(o,u,_){o.lanes|=u;var $=o.alternate;$!==null&&($.lanes|=u),Vh(o.return,u,_)}function vu(o,u,_,$,O){var F=o.memoizedState;F===null?o.memoizedState={isBackwards:u,rendering:null,renderingStartTime:0,last:$,tail:_,tailMode:O}:(F.isBackwards=u,F.rendering=null,F.renderingStartTime=0,F.last=$,F.tail=_,F.tailMode=O)}function _u(o,u,_){var $=u.pendingProps,O=$.revealOrder,F=$.tail;if(Wn(o,u,$.children,_),$=Qi.current,($&2)!==0)$=$&1|2,u.flags|=128;else{if(o!==null&&(o.flags&128)!==0)e:for(o=u.child;o!==null;){if(o.tag===13)o.memoizedState!==null&&Ep(o,_,u);else if(o.tag===19)Ep(o,_,u);else if(o.child!==null){o.child.return=o,o=o.child;continue}if(o===u)break e;for(;o.sibling===null;){if(o.return===null||o.return===u)break e;o=o.return}o.sibling.return=o.return,o=o.sibling}$&=1}if(Mi(Qi,$),(u.mode&1)===0)u.memoizedState=null;else switch(O){case"forwards":for(_=u.child,O=null;_!==null;)o=_.alternate,o!==null&&Ac(o)===null&&(O=_),_=_.sibling;_=O,_===null?(O=u.child,u.child=null):(O=_.sibling,_.sibling=null),vu(u,!1,O,_,F);break;case"backwards":for(_=null,O=u.child,u.child=null;O!==null;){if(o=O.alternate,o!==null&&Ac(o)===null){u.child=O;break}o=O.sibling,O.sibling=_,_=O,O=o}vu(u,!0,_,null,F);break;case"together":vu(u,!1,null,null,void 0);break;default:u.memoizedState=null}return u.child}function Nc(o,u){(u.mode&1)===0&&o!==null&&(o.alternate=null,u.alternate=null,u.flags|=2)}function Jr(o,u,_){if(o!==null&&(u.dependencies=o.dependencies),ea|=u.lanes,(_&u.childLanes)===0)return null;if(o!==null&&u.child!==o.child)throw Error(t(153));if(u.child!==null){for(o=u.child,_=To(o,o.pendingProps),u.child=_,_.return=u;o.sibling!==null;)o=o.sibling,_=_.sibling=To(o,o.pendingProps),_.return=u;_.sibling=null}return u.child}function Rv(o,u,_){switch(u.tag){case 3:fu(u),Vo();break;case 5:qh(u);break;case 1:vs(u.type)&&wc(u);break;case 4:Xd(u,u.stateNode.containerInfo);break;case 10:var $=u.type._context,O=u.memoizedProps.value;Mi(qo,$._currentValue),$._currentValue=O;break;case 13:if($=u.memoizedState,$!==null)return $.dehydrated!==null?(Mi(Qi,Qi.current&1),u.flags|=128,null):(_&u.child.childLanes)!==0?kp(o,u,_):(Mi(Qi,Qi.current&1),o=Jr(o,u,_),o!==null?o.sibling:null);Mi(Qi,Qi.current&1);break;case 19:if($=(_&u.childLanes)!==0,(o.flags&128)!==0){if($)return _u(o,u,_);u.flags|=128}if(O=u.memoizedState,O!==null&&(O.rendering=null,O.tail=null,O.lastEffect=null),Mi(Qi,Qi.current),$)break;return null;case 22:case 23:return u.lanes=0,yp(o,u,_)}return Jr(o,u,_)}var bu,wu,Tp,Dp;bu=function(o,u){for(var _=u.child;_!==null;){if(_.tag===5||_.tag===6)o.appendChild(_.stateNode);else if(_.tag!==4&&_.child!==null){_.child.return=_,_=_.child;continue}if(_===u)break;for(;_.sibling===null;){if(_.return===null||_.return===u)return;_=_.return}_.sibling.return=_.return,_=_.sibling}},wu=function(){},Tp=function(o,u,_,$){var O=o.memoizedProps;if(O!==$){o=u.stateNode,Yo(Pr.current);var F=null;switch(_){case"input":O=Pt(o,O),$=Pt(o,$),F=[];break;case"select":O=ie({},O,{value:void 0}),$=ie({},$,{value:void 0}),F=[];break;case"textarea":O=ft(o,O),$=ft(o,$),F=[];break;default:typeof O.onClick!="function"&&typeof $.onClick=="function"&&(o.onclick=vc)}pn(_,$);var ee;_=null;for(Ue in O)if(!$.hasOwnProperty(Ue)&&O.hasOwnProperty(Ue)&&O[Ue]!=null)if(Ue==="style"){var be=O[Ue];for(ee in be)be.hasOwnProperty(ee)&&(_||(_={}),_[ee]="")}else Ue!=="dangerouslySetInnerHTML"&&Ue!=="children"&&Ue!=="suppressContentEditableWarning"&&Ue!=="suppressHydrationWarning"&&Ue!=="autoFocus"&&(r.hasOwnProperty(Ue)?F||(F=[]):(F=F||[]).push(Ue,null));for(Ue in $){var Te=$[Ue];if(be=O!=null?O[Ue]:void 0,$.hasOwnProperty(Ue)&&Te!==be&&(Te!=null||be!=null))if(Ue==="style")if(be){for(ee in be)!be.hasOwnProperty(ee)||Te&&Te.hasOwnProperty(ee)||(_||(_={}),_[ee]="");for(ee in Te)Te.hasOwnProperty(ee)&&be[ee]!==Te[ee]&&(_||(_={}),_[ee]=Te[ee])}else _||(F||(F=[]),F.push(Ue,_)),_=Te;else Ue==="dangerouslySetInnerHTML"?(Te=Te?Te.__html:void 0,be=be?be.__html:void 0,Te!=null&&be!==Te&&(F=F||[]).push(Ue,Te)):Ue==="children"?typeof Te!="string"&&typeof Te!="number"||(F=F||[]).push(Ue,""+Te):Ue!=="suppressContentEditableWarning"&&Ue!=="suppressHydrationWarning"&&(r.hasOwnProperty(Ue)?(Te!=null&&Ue==="onScroll"&&Bi("scroll",o),F||be===Te||(F=[])):(F=F||[]).push(Ue,Te))}_&&(F=F||[]).push("style",_);var Ue=F;(u.updateQueue=Ue)&&(u.flags|=4)}},Dp=function(o,u,_,$){_!==$&&(u.flags|=4)};function Mc(o,u){if(!Xi)switch(o.tailMode){case"hidden":u=o.tail;for(var _=null;u!==null;)u.alternate!==null&&(_=u),u=u.sibling;_===null?o.tail=null:_.sibling=null;break;case"collapsed":_=o.tail;for(var $=null;_!==null;)_.alternate!==null&&($=_),_=_.sibling;$===null?u||o.tail===null?o.tail=null:o.tail.sibling=null:$.sibling=null}}function Un(o){var u=o.alternate!==null&&o.alternate.child===o.child,_=0,$=0;if(u)for(var O=o.child;O!==null;)_|=O.lanes|O.childLanes,$|=O.subtreeFlags&14680064,$|=O.flags&14680064,O.return=o,O=O.sibling;else for(O=o.child;O!==null;)_|=O.lanes|O.childLanes,$|=O.subtreeFlags,$|=O.flags,O.return=o,O=O.sibling;return o.subtreeFlags|=$,o.childLanes=_,u}function jm(o,u,_){var $=u.pendingProps;switch(Md(u),u.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Un(u),null;case 1:return vs(u.type)&&bc(),Un(u),null;case 3:return $=u.stateNode,Xo(),Gi(gs),Gi(ns),Qd(),$.pendingContext&&($.context=$.pendingContext,$.pendingContext=null),(o===null||o.child===null)&&(yl(u)?u.flags|=4:o===null||o.memoizedState.isDehydrated&&(u.flags&256)===0||(u.flags|=1024,ys!==null&&(Nu(ys),ys=null))),wu(o,u),Un(u),null;case 5:Jd(u);var O=Yo(Na.current);if(_=u.type,o!==null&&u.stateNode!=null)Tp(o,u,_,$,O),o.ref!==u.ref&&(u.flags|=512,u.flags|=2097152);else{if(!$){if(u.stateNode===null)throw Error(t(166));return Un(u),null}if(o=Yo(Pr.current),yl(u)){$=u.stateNode,_=u.type;var F=u.memoizedProps;switch($[Ar]=u,$[bl]=F,o=(u.mode&1)!==0,_){case"dialog":Bi("cancel",$),Bi("close",$);break;case"iframe":case"object":case"embed":Bi("load",$);break;case"video":case"audio":for(O=0;O<gl.length;O++)Bi(gl[O],$);break;case"source":Bi("error",$);break;case"img":case"image":case"link":Bi("error",$),Bi("load",$);break;case"details":Bi("toggle",$);break;case"input":dt($,F),Bi("invalid",$);break;case"select":$._wrapperState={wasMultiple:!!F.multiple},Bi("invalid",$);break;case"textarea":ct($,F),Bi("invalid",$)}pn(_,F),O=null;for(var ee in F)if(F.hasOwnProperty(ee)){var be=F[ee];ee==="children"?typeof be=="string"?$.textContent!==be&&(F.suppressHydrationWarning!==!0&&gc($.textContent,be,o),O=["children",be]):typeof be=="number"&&$.textContent!==""+be&&(F.suppressHydrationWarning!==!0&&gc($.textContent,be,o),O=["children",""+be]):r.hasOwnProperty(ee)&&be!=null&&ee==="onScroll"&&Bi("scroll",$)}switch(_){case"input":Pe($),Ct($,F,!0);break;case"textarea":Pe($),ai($);break;case"select":case"option":break;default:typeof F.onClick=="function"&&($.onclick=vc)}$=O,u.updateQueue=$,$!==null&&(u.flags|=4)}else{ee=O.nodeType===9?O:O.ownerDocument,o==="http://www.w3.org/1999/xhtml"&&(o=Zi(_)),o==="http://www.w3.org/1999/xhtml"?_==="script"?(o=ee.createElement("div"),o.innerHTML="<script><\/script>",o=o.removeChild(o.firstChild)):typeof $.is=="string"?o=ee.createElement(_,{is:$.is}):(o=ee.createElement(_),_==="select"&&(ee=o,$.multiple?ee.multiple=!0:$.size&&(ee.size=$.size))):o=ee.createElementNS(o,_),o[Ar]=u,o[bl]=$,bu(o,u,!1,!1),u.stateNode=o;e:{switch(ee=pi(_,$),_){case"dialog":Bi("cancel",o),Bi("close",o),O=$;break;case"iframe":case"object":case"embed":Bi("load",o),O=$;break;case"video":case"audio":for(O=0;O<gl.length;O++)Bi(gl[O],o);O=$;break;case"source":Bi("error",o),O=$;break;case"img":case"image":case"link":Bi("error",o),Bi("load",o),O=$;break;case"details":Bi("toggle",o),O=$;break;case"input":dt(o,$),O=Pt(o,$),Bi("invalid",o);break;case"option":O=$;break;case"select":o._wrapperState={wasMultiple:!!$.multiple},O=ie({},$,{value:void 0}),Bi("invalid",o);break;case"textarea":ct(o,$),O=ft(o,$),Bi("invalid",o);break;default:O=$}pn(_,O),be=O;for(F in be)if(be.hasOwnProperty(F)){var Te=be[F];F==="style"?ri(o,Te):F==="dangerouslySetInnerHTML"?(Te=Te?Te.__html:void 0,Te!=null&&hn(o,Te)):F==="children"?typeof Te=="string"?(_!=="textarea"||Te!=="")&&Ai(o,Te):typeof Te=="number"&&Ai(o,""+Te):F!=="suppressContentEditableWarning"&&F!=="suppressHydrationWarning"&&F!=="autoFocus"&&(r.hasOwnProperty(F)?Te!=null&&F==="onScroll"&&Bi("scroll",o):Te!=null&&x(o,F,Te,ee))}switch(_){case"input":Pe(o),Ct(o,$,!1);break;case"textarea":Pe(o),ai(o);break;case"option":$.value!=null&&o.setAttribute("value",""+X($.value));break;case"select":o.multiple=!!$.multiple,F=$.value,F!=null?ze(o,!!$.multiple,F,!1):$.defaultValue!=null&&ze(o,!!$.multiple,$.defaultValue,!0);break;default:typeof O.onClick=="function"&&(o.onclick=vc)}switch(_){case"button":case"input":case"select":case"textarea":$=!!$.autoFocus;break e;case"img":$=!0;break e;default:$=!1}}$&&(u.flags|=4)}u.ref!==null&&(u.flags|=512,u.flags|=2097152)}return Un(u),null;case 6:if(o&&u.stateNode!=null)Dp(o,u,o.memoizedProps,$);else{if(typeof $!="string"&&u.stateNode===null)throw Error(t(166));if(_=Yo(Na.current),Yo(Pr.current),yl(u)){if($=u.stateNode,_=u.memoizedProps,$[Ar]=u,(F=$.nodeValue!==_)&&(o=ws,o!==null))switch(o.tag){case 3:gc($.nodeValue,_,(o.mode&1)!==0);break;case 5:o.memoizedProps.suppressHydrationWarning!==!0&&gc($.nodeValue,_,(o.mode&1)!==0)}F&&(u.flags|=4)}else $=(_.nodeType===9?_:_.ownerDocument).createTextNode($),$[Ar]=u,u.stateNode=$}return Un(u),null;case 13:if(Gi(Qi),$=u.memoizedState,o===null||o.memoizedState!==null&&o.memoizedState.dehydrated!==null){if(Xi&&Ps!==null&&(u.mode&1)!==0&&(u.flags&128)===0)Wh(),Vo(),u.flags|=98560,F=!1;else if(F=yl(u),$!==null&&$.dehydrated!==null){if(o===null){if(!F)throw Error(t(318));if(F=u.memoizedState,F=F!==null?F.dehydrated:null,!F)throw Error(t(317));F[Ar]=u}else Vo(),(u.flags&128)===0&&(u.memoizedState=null),u.flags|=4;Un(u),F=!1}else ys!==null&&(Nu(ys),ys=null),F=!0;if(!F)return u.flags&65536?u:null}return(u.flags&128)!==0?(u.lanes=_,u):($=$!==null,$!==(o!==null&&o.memoizedState!==null)&&$&&(u.child.flags|=8192,(u.mode&1)!==0&&(o===null||(Qi.current&1)!==0?Cn===0&&(Cn=3):Lu())),u.updateQueue!==null&&(u.flags|=4),Un(u),null);case 4:return Xo(),wu(o,u),o===null&&vl(u.stateNode.containerInfo),Un(u),null;case 10:return qd(u.type._context),Un(u),null;case 17:return vs(u.type)&&bc(),Un(u),null;case 19:if(Gi(Qi),F=u.memoizedState,F===null)return Un(u),null;if($=(u.flags&128)!==0,ee=F.rendering,ee===null)if($)Mc(F,!1);else{if(Cn!==0||o!==null&&(o.flags&128)!==0)for(o=u.child;o!==null;){if(ee=Ac(o),ee!==null){for(u.flags|=128,Mc(F,!1),$=ee.updateQueue,$!==null&&(u.updateQueue=$,u.flags|=4),u.subtreeFlags=0,$=_,_=u.child;_!==null;)F=_,o=$,F.flags&=14680066,ee=F.alternate,ee===null?(F.childLanes=0,F.lanes=o,F.child=null,F.subtreeFlags=0,F.memoizedProps=null,F.memoizedState=null,F.updateQueue=null,F.dependencies=null,F.stateNode=null):(F.childLanes=ee.childLanes,F.lanes=ee.lanes,F.child=ee.child,F.subtreeFlags=0,F.deletions=null,F.memoizedProps=ee.memoizedProps,F.memoizedState=ee.memoizedState,F.updateQueue=ee.updateQueue,F.type=ee.type,o=ee.dependencies,F.dependencies=o===null?null:{lanes:o.lanes,firstContext:o.firstContext}),_=_.sibling;return Mi(Qi,Qi.current&1|2),u.child}o=o.sibling}F.tail!==null&&Ci()>za&&(u.flags|=128,$=!0,Mc(F,!1),u.lanes=4194304)}else{if(!$)if(o=Ac(ee),o!==null){if(u.flags|=128,$=!0,_=o.updateQueue,_!==null&&(u.updateQueue=_,u.flags|=4),Mc(F,!0),F.tail===null&&F.tailMode==="hidden"&&!ee.alternate&&!Xi)return Un(u),null}else 2*Ci()-F.renderingStartTime>za&&_!==1073741824&&(u.flags|=128,$=!0,Mc(F,!1),u.lanes=4194304);F.isBackwards?(ee.sibling=u.child,u.child=ee):(_=F.last,_!==null?_.sibling=ee:u.child=ee,F.last=ee)}return F.tail!==null?(u=F.tail,F.rendering=u,F.tail=u.sibling,F.renderingStartTime=Ci(),u.sibling=null,_=Qi.current,Mi(Qi,$?_&1|2:_&1),u):(Un(u),null);case 22:case 23:return Ou(),$=u.memoizedState!==null,o!==null&&o.memoizedState!==null!==$&&(u.flags|=8192),$&&(u.mode&1)!==0?(Rs&1073741824)!==0&&(Un(u),u.subtreeFlags&6&&(u.flags|=8192)):Un(u),null;case 24:return null;case 25:return null}throw Error(t(156,u.tag))}function Nm(o,u){switch(Md(u),u.tag){case 1:return vs(u.type)&&bc(),o=u.flags,o&65536?(u.flags=o&-65537|128,u):null;case 3:return Xo(),Gi(gs),Gi(ns),Qd(),o=u.flags,(o&65536)!==0&&(o&128)===0?(u.flags=o&-65537|128,u):null;case 5:return Jd(u),null;case 13:if(Gi(Qi),o=u.memoizedState,o!==null&&o.dehydrated!==null){if(u.alternate===null)throw Error(t(340));Vo()}return o=u.flags,o&65536?(u.flags=o&-65537|128,u):null;case 19:return Gi(Qi),null;case 4:return Xo(),null;case 10:return qd(u.type._context),null;case 22:case 23:return Ou(),null;case 24:return null;default:return null}}var yu=!1,Vn=!1,Mm=typeof WeakSet=="function"?WeakSet:Set,jt=null;function Oa(o,u){var _=o.ref;if(_!==null)if(typeof _=="function")try{_(null)}catch($){en(o,u,$)}else _.current=null}function xu(o,u,_){try{_()}catch($){en(o,u,$)}}var Ap=!1;function Om(o,u){if(Dd=fo,o=wd(),yd(o)){if("selectionStart"in o)var _={start:o.selectionStart,end:o.selectionEnd};else e:{_=(_=o.ownerDocument)&&_.defaultView||window;var $=_.getSelection&&_.getSelection();if($&&$.rangeCount!==0){_=$.anchorNode;var O=$.anchorOffset,F=$.focusNode;$=$.focusOffset;try{_.nodeType,F.nodeType}catch{_=null;break e}var ee=0,be=-1,Te=-1,Ue=0,lt=0,ut=o,at=null;t:for(;;){for(var Tt;ut!==_||O!==0&&ut.nodeType!==3||(be=ee+O),ut!==F||$!==0&&ut.nodeType!==3||(Te=ee+$),ut.nodeType===3&&(ee+=ut.nodeValue.length),(Tt=ut.firstChild)!==null;)at=ut,ut=Tt;for(;;){if(ut===o)break t;if(at===_&&++Ue===O&&(be=ee),at===F&&++lt===$&&(Te=ee),(Tt=ut.nextSibling)!==null)break;ut=at,at=ut.parentNode}ut=Tt}_=be===-1||Te===-1?null:{start:be,end:Te}}else _=null}_=_||{start:0,end:0}}else _=null;for(Ad={focusedElem:o,selectionRange:_},fo=!1,jt=u;jt!==null;)if(u=jt,o=u.child,(u.subtreeFlags&1028)!==0&&o!==null)o.return=u,jt=o;else for(;jt!==null;){u=jt;try{var Nt=u.alternate;if((u.flags&1024)!==0)switch(u.tag){case 0:case 11:case 15:break;case 1:if(Nt!==null){var Mt=Nt.memoizedProps,Oi=Nt.memoizedState,Ge=u.stateNode,Re=Ge.getSnapshotBeforeUpdate(u.elementType===u.type?Mt:gn(u.type,Mt),Oi);Ge.__reactInternalSnapshotBeforeUpdate=Re}break;case 3:var Ve=u.stateNode.containerInfo;Ve.nodeType===1?Ve.textContent="":Ve.nodeType===9&&Ve.documentElement&&Ve.removeChild(Ve.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(t(163))}}catch(mt){en(u,u.return,mt)}if(o=u.sibling,o!==null){o.return=u.return,jt=o;break}jt=u.return}return Nt=Ap,Ap=!1,Nt}function Dl(o,u,_){var $=u.updateQueue;if($=$!==null?$.lastEffect:null,$!==null){var O=$=$.next;do{if((O.tag&o)===o){var F=O.destroy;O.destroy=void 0,F!==void 0&&xu(u,_,F)}O=O.next}while(O!==$)}}function Su(o,u){if(u=u.updateQueue,u=u!==null?u.lastEffect:null,u!==null){var _=u=u.next;do{if((_.tag&o)===o){var $=_.create;_.destroy=$()}_=_.next}while(_!==u)}}function Cu(o){var u=o.ref;if(u!==null){var _=o.stateNode;switch(o.tag){case 5:o=_;break;default:o=_}typeof u=="function"?u(o):u.current=o}}function $p(o){var u=o.alternate;u!==null&&(o.alternate=null,$p(u)),o.child=null,o.deletions=null,o.sibling=null,o.tag===5&&(u=o.stateNode,u!==null&&(delete u[Ar],delete u[bl],delete u[Rd],delete u[Lh],delete u[zh])),o.stateNode=null,o.return=null,o.dependencies=null,o.memoizedProps=null,o.memoizedState=null,o.pendingProps=null,o.stateNode=null,o.updateQueue=null}function Ip(o){return o.tag===5||o.tag===3||o.tag===4}function Pp(o){e:for(;;){for(;o.sibling===null;){if(o.return===null||Ip(o.return))return null;o=o.return}for(o.sibling.return=o.return,o=o.sibling;o.tag!==5&&o.tag!==6&&o.tag!==18;){if(o.flags&2||o.child===null||o.tag===4)continue e;o.child.return=o,o=o.child}if(!(o.flags&2))return o.stateNode}}function ku(o,u,_){var $=o.tag;if($===5||$===6)o=o.stateNode,u?_.nodeType===8?_.parentNode.insertBefore(o,u):_.insertBefore(o,u):(_.nodeType===8?(u=_.parentNode,u.insertBefore(o,_)):(u=_,u.appendChild(o)),_=_._reactRootContainer,_!=null||u.onclick!==null||(u.onclick=vc));else if($!==4&&(o=o.child,o!==null))for(ku(o,u,_),o=o.sibling;o!==null;)ku(o,u,_),o=o.sibling}function Eu(o,u,_){var $=o.tag;if($===5||$===6)o=o.stateNode,u?_.insertBefore(o,u):_.appendChild(o);else if($!==4&&(o=o.child,o!==null))for(Eu(o,u,_),o=o.sibling;o!==null;)Eu(o,u,_),o=o.sibling}var Pn=null,hr=!1;function xo(o,u,_){for(_=_.child;_!==null;)Lm(o,u,_),_=_.sibling}function Lm(o,u,_){if(wn&&typeof wn.onCommitFiberUnmount=="function")try{wn.onCommitFiberUnmount(ps,_)}catch{}switch(_.tag){case 5:Vn||Oa(_,u);case 6:var $=Pn,O=hr;Pn=null,xo(o,u,_),Pn=$,hr=O,Pn!==null&&(hr?(o=Pn,_=_.stateNode,o.nodeType===8?o.parentNode.removeChild(_):o.removeChild(_)):Pn.removeChild(_.stateNode));break;case 18:Pn!==null&&(hr?(o=Pn,_=_.stateNode,o.nodeType===8?Pd(o.parentNode,_):o.nodeType===1&&Pd(o,_),Wr(o)):Pd(Pn,_.stateNode));break;case 4:$=Pn,O=hr,Pn=_.stateNode.containerInfo,hr=!0,xo(o,u,_),Pn=$,hr=O;break;case 0:case 11:case 14:case 15:if(!Vn&&($=_.updateQueue,$!==null&&($=$.lastEffect,$!==null))){O=$=$.next;do{var F=O,ee=F.destroy;F=F.tag,ee!==void 0&&((F&2)!==0||(F&4)!==0)&&xu(_,u,ee),O=O.next}while(O!==$)}xo(o,u,_);break;case 1:if(!Vn&&(Oa(_,u),$=_.stateNode,typeof $.componentWillUnmount=="function"))try{$.props=_.memoizedProps,$.state=_.memoizedState,$.componentWillUnmount()}catch(be){en(_,u,be)}xo(o,u,_);break;case 21:xo(o,u,_);break;case 22:_.mode&1?(Vn=($=Vn)||_.memoizedState!==null,xo(o,u,_),Vn=$):xo(o,u,_);break;default:xo(o,u,_)}}function Al(o){var u=o.updateQueue;if(u!==null){o.updateQueue=null;var _=o.stateNode;_===null&&(_=o.stateNode=new Mm),u.forEach(function($){var O=Um.bind(null,o,$);_.has($)||(_.add($),$.then(O,O))})}}function Ys(o,u){var _=u.deletions;if(_!==null)for(var $=0;$<_.length;$++){var O=_[$];try{var F=o,ee=u,be=ee;e:for(;be!==null;){switch(be.tag){case 5:Pn=be.stateNode,hr=!1;break e;case 3:Pn=be.stateNode.containerInfo,hr=!0;break e;case 4:Pn=be.stateNode.containerInfo,hr=!0;break e}be=be.return}if(Pn===null)throw Error(t(160));Lm(F,ee,O),Pn=null,hr=!1;var Te=O.alternate;Te!==null&&(Te.return=null),O.return=null}catch(Ue){en(O,u,Ue)}}if(u.subtreeFlags&12854)for(u=u.child;u!==null;)Tu(u,o),u=u.sibling}function Tu(o,u){var _=o.alternate,$=o.flags;switch(o.tag){case 0:case 11:case 14:case 15:if(Ys(u,o),pr(o),$&4){try{Dl(3,o,o.return),Su(3,o)}catch(Mt){en(o,o.return,Mt)}try{Dl(5,o,o.return)}catch(Mt){en(o,o.return,Mt)}}break;case 1:Ys(u,o),pr(o),$&512&&_!==null&&Oa(_,_.return);break;case 5:if(Ys(u,o),pr(o),$&512&&_!==null&&Oa(_,_.return),o.flags&32){var O=o.stateNode;try{Ai(O,"")}catch(Mt){en(o,o.return,Mt)}}if($&4&&(O=o.stateNode,O!=null)){var F=o.memoizedProps,ee=_!==null?_.memoizedProps:F,be=o.type,Te=o.updateQueue;if(o.updateQueue=null,Te!==null)try{be==="input"&&F.type==="radio"&&F.name!=null&&Yt(O,F),pi(be,ee);var Ue=pi(be,F);for(ee=0;ee<Te.length;ee+=2){var lt=Te[ee],ut=Te[ee+1];lt==="style"?ri(O,ut):lt==="dangerouslySetInnerHTML"?hn(O,ut):lt==="children"?Ai(O,ut):x(O,lt,ut,Ue)}switch(be){case"input":Fe(O,F);break;case"textarea":Zt(O,F);break;case"select":var at=O._wrapperState.wasMultiple;O._wrapperState.wasMultiple=!!F.multiple;var Tt=F.value;Tt!=null?ze(O,!!F.multiple,Tt,!1):at!==!!F.multiple&&(F.defaultValue!=null?ze(O,!!F.multiple,F.defaultValue,!0):ze(O,!!F.multiple,F.multiple?[]:"",!1))}O[bl]=F}catch(Mt){en(o,o.return,Mt)}}break;case 6:if(Ys(u,o),pr(o),$&4){if(o.stateNode===null)throw Error(t(162));O=o.stateNode,F=o.memoizedProps;try{O.nodeValue=F}catch(Mt){en(o,o.return,Mt)}}break;case 3:if(Ys(u,o),pr(o),$&4&&_!==null&&_.memoizedState.isDehydrated)try{Wr(u.containerInfo)}catch(Mt){en(o,o.return,Mt)}break;case 4:Ys(u,o),pr(o);break;case 13:Ys(u,o),pr(o),O=o.child,O.flags&8192&&(F=O.memoizedState!==null,O.stateNode.isHidden=F,!F||O.alternate!==null&&O.alternate.memoizedState!==null||(Iu=Ci())),$&4&&Al(o);break;case 22:if(lt=_!==null&&_.memoizedState!==null,o.mode&1?(Vn=(Ue=Vn)||lt,Ys(u,o),Vn=Ue):Ys(u,o),pr(o),$&8192){if(Ue=o.memoizedState!==null,(o.stateNode.isHidden=Ue)&&!lt&&(o.mode&1)!==0)for(jt=o,lt=o.child;lt!==null;){for(ut=jt=lt;jt!==null;){switch(at=jt,Tt=at.child,at.tag){case 0:case 11:case 14:case 15:Dl(4,at,at.return);break;case 1:Oa(at,at.return);var Nt=at.stateNode;if(typeof Nt.componentWillUnmount=="function"){$=at,_=at.return;try{u=$,Nt.props=u.memoizedProps,Nt.state=u.memoizedState,Nt.componentWillUnmount()}catch(Mt){en($,_,Mt)}}break;case 5:Oa(at,at.return);break;case 22:if(at.memoizedState!==null){Du(ut);continue}}Tt!==null?(Tt.return=at,jt=Tt):Du(ut)}lt=lt.sibling}e:for(lt=null,ut=o;;){if(ut.tag===5){if(lt===null){lt=ut;try{O=ut.stateNode,Ue?(F=O.style,typeof F.setProperty=="function"?F.setProperty("display","none","important"):F.display="none"):(be=ut.stateNode,Te=ut.memoizedProps.style,ee=Te!=null&&Te.hasOwnProperty("display")?Te.display:null,be.style.display=it("display",ee))}catch(Mt){en(o,o.return,Mt)}}}else if(ut.tag===6){if(lt===null)try{ut.stateNode.nodeValue=Ue?"":ut.memoizedProps}catch(Mt){en(o,o.return,Mt)}}else if((ut.tag!==22&&ut.tag!==23||ut.memoizedState===null||ut===o)&&ut.child!==null){ut.child.return=ut,ut=ut.child;continue}if(ut===o)break e;for(;ut.sibling===null;){if(ut.return===null||ut.return===o)break e;lt===ut&&(lt=null),ut=ut.return}lt===ut&&(lt=null),ut.sibling.return=ut.return,ut=ut.sibling}}break;case 19:Ys(u,o),pr(o),$&4&&Al(o);break;case 21:break;default:Ys(u,o),pr(o)}}function pr(o){var u=o.flags;if(u&2){try{e:{for(var _=o.return;_!==null;){if(Ip(_)){var $=_;break e}_=_.return}throw Error(t(160))}switch($.tag){case 5:var O=$.stateNode;$.flags&32&&(Ai(O,""),$.flags&=-33);var F=Pp(o);Eu(o,F,O);break;case 3:case 4:var ee=$.stateNode.containerInfo,be=Pp(o);ku(o,be,ee);break;default:throw Error(t(161))}}catch(Te){en(o,o.return,Te)}o.flags&=-3}u&4096&&(o.flags&=-4097)}function Rp(o,u,_){jt=o,jp(o)}function jp(o,u,_){for(var $=(o.mode&1)!==0;jt!==null;){var O=jt,F=O.child;if(O.tag===22&&$){var ee=O.memoizedState!==null||yu;if(!ee){var be=O.alternate,Te=be!==null&&be.memoizedState!==null||Vn;be=yu;var Ue=Vn;if(yu=ee,(Vn=Te)&&!Ue)for(jt=O;jt!==null;)ee=jt,Te=ee.child,ee.tag===22&&ee.memoizedState!==null?Au(O):Te!==null?(Te.return=ee,jt=Te):Au(O);for(;F!==null;)jt=F,jp(F),F=F.sibling;jt=O,yu=be,Vn=Ue}Np(o)}else(O.subtreeFlags&8772)!==0&&F!==null?(F.return=O,jt=F):Np(o)}}function Np(o){for(;jt!==null;){var u=jt;if((u.flags&8772)!==0){var _=u.alternate;try{if((u.flags&8772)!==0)switch(u.tag){case 0:case 11:case 15:Vn||Su(5,u);break;case 1:var $=u.stateNode;if(u.flags&4&&!Vn)if(_===null)$.componentDidMount();else{var O=u.elementType===u.type?_.memoizedProps:gn(u.type,_.memoizedProps);$.componentDidUpdate(O,_.memoizedState,$.__reactInternalSnapshotBeforeUpdate)}var F=u.updateQueue;F!==null&&xm(u,F,$);break;case 3:var ee=u.updateQueue;if(ee!==null){if(_=null,u.child!==null)switch(u.child.tag){case 5:_=u.child.stateNode;break;case 1:_=u.child.stateNode}xm(u,ee,_)}break;case 5:var be=u.stateNode;if(_===null&&u.flags&4){_=be;var Te=u.memoizedProps;switch(u.type){case"button":case"input":case"select":case"textarea":Te.autoFocus&&_.focus();break;case"img":Te.src&&(_.src=Te.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(u.memoizedState===null){var Ue=u.alternate;if(Ue!==null){var lt=Ue.memoizedState;if(lt!==null){var ut=lt.dehydrated;ut!==null&&Wr(ut)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(t(163))}Vn||u.flags&512&&Cu(u)}catch(at){en(u,u.return,at)}}if(u===o){jt=null;break}if(_=u.sibling,_!==null){_.return=u.return,jt=_;break}jt=u.return}}function Du(o){for(;jt!==null;){var u=jt;if(u===o){jt=null;break}var _=u.sibling;if(_!==null){_.return=u.return,jt=_;break}jt=u.return}}function Au(o){for(;jt!==null;){var u=jt;try{switch(u.tag){case 0:case 11:case 15:var _=u.return;try{Su(4,u)}catch(Te){en(u,_,Te)}break;case 1:var $=u.stateNode;if(typeof $.componentDidMount=="function"){var O=u.return;try{$.componentDidMount()}catch(Te){en(u,O,Te)}}var F=u.return;try{Cu(u)}catch(Te){en(u,F,Te)}break;case 5:var ee=u.return;try{Cu(u)}catch(Te){en(u,ee,Te)}}}catch(Te){en(u,u.return,Te)}if(u===o){jt=null;break}var be=u.sibling;if(be!==null){be.return=u.return,jt=be;break}jt=u.return}}var zm=Math.ceil,Oc=A.ReactCurrentDispatcher,Lc=A.ReactCurrentOwner,Xs=A.ReactCurrentBatchConfig,_i=0,vn=null,un=null,Rn=0,Rs=0,La=Vr(0),Cn=0,$l=null,ea=0,zc=0,$u=0,Bc=null,Ss=null,Iu=0,za=1/0,So=null,Gc=!1,Pu=null,Co=null,Fc=!1,ta=null,Hc=0,Il=0,Ru=null,Pl=-1,Wc=0;function os(){return(_i&6)!==0?Ci():Pl!==-1?Pl:Pl=Ci()}function ko(o){return(o.mode&1)===0?1:(_i&2)!==0&&Rn!==0?Rn&-Rn:Hd.transition!==null?(Wc===0&&(Wc=Is()),Wc):(o=je,o!==0||(o=window.event,o=o===void 0?16:se(o.type)),o)}function fr(o,u,_,$){if(50<Il)throw Il=0,Ru=null,Error(t(185));Jn(o,_,$),((_i&2)===0||o!==vn)&&(o===vn&&((_i&2)===0&&(zc|=_),Cn===4&&Eo(o,Rn)),Cs(o,$),_===1&&_i===0&&(u.mode&1)===0&&(za=Ci()+500,yc&&_o()))}function Cs(o,u){var _=o.callbackNode;ms(o,u);var $=Cr(o,o===vn?Rn:0);if($===0)_!==null&&In(_),o.callbackNode=null,o.callbackPriority=0;else if(u=$&-$,o.callbackPriority!==u){if(_!=null&&In(_),u===1)o.tag===0?$v(Lp.bind(null,o)):Hh(Lp.bind(null,o)),_m(function(){(_i&6)===0&&_o()}),_=null;else{switch(Je($)){case 1:_=Ki;break;case 4:_=Gn;break;case 16:_=nr;break;case 536870912:_=yr;break;default:_=nr}_=Wp(_,Mp.bind(null,o))}o.callbackPriority=u,o.callbackNode=_}}function Mp(o,u){if(Pl=-1,Wc=0,(_i&6)!==0)throw Error(t(327));var _=o.callbackNode;if(Ba()&&o.callbackNode!==_)return null;var $=Cr(o,o===vn?Rn:0);if($===0)return null;if(($&30)!==0||($&o.expiredLanes)!==0||u)u=Uc(o,$);else{u=$;var O=_i;_i|=2;var F=Bm();(vn!==o||Rn!==u)&&(So=null,za=Ci()+500,na(o,u));do try{jv();break}catch(be){zp(o,be)}while(!0);Vd(),Oc.current=F,_i=O,un!==null?u=0:(vn=null,Rn=0,u=Cn)}if(u!==0){if(u===2&&(O=Fr(o),O!==0&&($=O,u=ju(o,O))),u===1)throw _=$l,na(o,0),Eo(o,$),Cs(o,Ci()),_;if(u===6)Eo(o,$);else{if(O=o.current.alternate,($&30)===0&&!Op(O)&&(u=Uc(o,$),u===2&&(F=Fr(o),F!==0&&($=F,u=ju(o,F))),u===1))throw _=$l,na(o,0),Eo(o,$),Cs(o,Ci()),_;switch(o.finishedWork=O,o.finishedLanes=$,u){case 0:case 1:throw Error(t(345));case 2:sa(o,Ss,So);break;case 3:if(Eo(o,$),($&130023424)===$&&(u=Iu+500-Ci(),10<u)){if(Cr(o,0)!==0)break;if(O=o.suspendedLanes,(O&$)!==$){os(),o.pingedLanes|=o.suspendedLanes&O;break}o.timeoutHandle=Id(sa.bind(null,o,Ss,So),u);break}sa(o,Ss,So);break;case 4:if(Eo(o,$),($&4194240)===$)break;for(u=o.eventTimes,O=-1;0<$;){var ee=31-Yi($);F=1<<ee,ee=u[ee],ee>O&&(O=ee),$&=~F}if($=O,$=Ci()-$,$=(120>$?120:480>$?480:1080>$?1080:1920>$?1920:3e3>$?3e3:4320>$?4320:1960*zm($/1960))-$,10<$){o.timeoutHandle=Id(sa.bind(null,o,Ss,So),$);break}sa(o,Ss,So);break;case 5:sa(o,Ss,So);break;default:throw Error(t(329))}}}return Cs(o,Ci()),o.callbackNode===_?Mp.bind(null,o):null}function ju(o,u){var _=Bc;return o.current.memoizedState.isDehydrated&&(na(o,u).flags|=256),o=Uc(o,u),o!==2&&(u=Ss,Ss=_,u!==null&&Nu(u)),o}function Nu(o){Ss===null?Ss=o:Ss.push.apply(Ss,o)}function Op(o){for(var u=o;;){if(u.flags&16384){var _=u.updateQueue;if(_!==null&&(_=_.stores,_!==null))for(var $=0;$<_.length;$++){var O=_[$],F=O.getSnapshot;O=O.value;try{if(!cr(F(),O))return!1}catch{return!1}}}if(_=u.child,u.subtreeFlags&16384&&_!==null)_.return=u,u=_;else{if(u===o)break;for(;u.sibling===null;){if(u.return===null||u.return===o)return!0;u=u.return}u.sibling.return=u.return,u=u.sibling}}return!0}function Eo(o,u){for(u&=~$u,u&=~zc,o.suspendedLanes|=u,o.pingedLanes&=~u,o=o.expirationTimes;0<u;){var _=31-Yi(u),$=1<<_;o[_]=-1,u&=~$}}function Lp(o){if((_i&6)!==0)throw Error(t(327));Ba();var u=Cr(o,0);if((u&1)===0)return Cs(o,Ci()),null;var _=Uc(o,u);if(o.tag!==0&&_===2){var $=Fr(o);$!==0&&(u=$,_=ju(o,$))}if(_===1)throw _=$l,na(o,0),Eo(o,u),Cs(o,Ci()),_;if(_===6)throw Error(t(345));return o.finishedWork=o.current.alternate,o.finishedLanes=u,sa(o,Ss,So),Cs(o,Ci()),null}function Mu(o,u){var _=_i;_i|=1;try{return o(u)}finally{_i=_,_i===0&&(za=Ci()+500,yc&&_o())}}function ia(o){ta!==null&&ta.tag===0&&(_i&6)===0&&Ba();var u=_i;_i|=1;var _=Xs.transition,$=je;try{if(Xs.transition=null,je=1,o)return o()}finally{je=$,Xs.transition=_,_i=u,(_i&6)===0&&_o()}}function Ou(){Rs=La.current,Gi(La)}function na(o,u){o.finishedWork=null,o.finishedLanes=0;var _=o.timeoutHandle;if(_!==-1&&(o.timeoutHandle=-1,vm(_)),un!==null)for(_=un.return;_!==null;){var $=_;switch(Md($),$.tag){case 1:$=$.type.childContextTypes,$!=null&&bc();break;case 3:Xo(),Gi(gs),Gi(ns),Qd();break;case 5:Jd($);break;case 4:Xo();break;case 13:Gi(Qi);break;case 19:Gi(Qi);break;case 10:qd($.type._context);break;case 22:case 23:Ou()}_=_.return}if(vn=o,un=o=To(o.current,null),Rn=Rs=u,Cn=0,$l=null,$u=zc=ea=0,Ss=Bc=null,ja!==null){for(u=0;u<ja.length;u++)if(_=ja[u],$=_.interleaved,$!==null){_.interleaved=null;var O=$.next,F=_.pending;if(F!==null){var ee=F.next;F.next=O,$.next=ee}_.pending=$}ja=null}return o}function zp(o,u){do{var _=un;try{if(Vd(),eu.current=Rc,iu){for(var $=Ji.memoizedState;$!==null;){var O=$.queue;O!==null&&(O.pending=null),$=$.next}iu=!1}if(Jo=0,Sn=mn=Ji=null,Zo=!1,yo=0,Lc.current=null,_===null||_.return===null){Cn=1,$l=u,un=null;break}e:{var F=o,ee=_.return,be=_,Te=u;if(u=Rn,be.flags|=32768,Te!==null&&typeof Te=="object"&&typeof Te.then=="function"){var Ue=Te,lt=be,ut=lt.tag;if((lt.mode&1)===0&&(ut===0||ut===11||ut===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=Im(ee);if(Tt!==null){Tt.flags&=-257,rs(Tt,ee,be,F,u),Tt.mode&1&&_p(F,Ue,u),u=Tt,Te=Ue;var Nt=u.updateQueue;if(Nt===null){var Mt=new Set;Mt.add(Te),u.updateQueue=Mt}else Nt.add(Te);break e}else{if((u&1)===0){_p(F,Ue,u),Lu();break e}Te=Error(t(426))}}else if(Xi&&be.mode&1){var Oi=Im(ee);if(Oi!==null){(Oi.flags&65536)===0&&(Oi.flags|=256),rs(Oi,ee,be,F,u),Fd(Ma(Te,be));break e}}F=Te=Ma(Te,be),Cn!==4&&(Cn=2),Bc===null?Bc=[F]:Bc.push(F),F=ee;do{switch(F.tag){case 3:F.flags|=65536,u&=-u,F.lanes|=u;var Ge=gp(F,Te,u);ym(F,Ge);break e;case 1:be=Te;var Re=F.type,Ve=F.stateNode;if((F.flags&128)===0&&(typeof Re.getDerivedStateFromError=="function"||Ve!==null&&typeof Ve.componentDidCatch=="function"&&(Co===null||!Co.has(Ve)))){F.flags|=65536,u&=-u,F.lanes|=u;var mt=vp(F,be,u);ym(F,mt);break e}}F=F.return}while(F!==null)}Rl(_)}catch(Gt){u=Gt,un===_&&_!==null&&(un=_=_.return);continue}break}while(!0)}function Bm(){var o=Oc.current;return Oc.current=Rc,o===null?Rc:o}function Lu(){(Cn===0||Cn===3||Cn===2)&&(Cn=4),vn===null||(ea&268435455)===0&&(zc&268435455)===0||Eo(vn,Rn)}function Uc(o,u){var _=_i;_i|=2;var $=Bm();(vn!==o||Rn!==u)&&(So=null,na(o,u));do try{Gm();break}catch(O){zp(o,O)}while(!0);if(Vd(),_i=_,Oc.current=$,un!==null)throw Error(t(261));return vn=null,Rn=0,Cn}function Gm(){for(;un!==null;)Bp(un)}function jv(){for(;un!==null&&!ya();)Bp(un)}function Bp(o){var u=Hp(o.alternate,o,Rs);o.memoizedProps=o.pendingProps,u===null?Rl(o):un=u,Lc.current=null}function Rl(o){var u=o;do{var _=u.alternate;if(o=u.return,(u.flags&32768)===0){if(_=jm(_,u,Rs),_!==null){un=_;return}}else{if(_=Nm(_,u),_!==null){_.flags&=32767,un=_;return}if(o!==null)o.flags|=32768,o.subtreeFlags=0,o.deletions=null;else{Cn=6,un=null;return}}if(u=u.sibling,u!==null){un=u;return}un=u=o}while(u!==null);Cn===0&&(Cn=5)}function sa(o,u,_){var $=je,O=Xs.transition;try{Xs.transition=null,je=1,Gp(o,u,_,$)}finally{Xs.transition=O,je=$}return null}function Gp(o,u,_,$){do Ba();while(ta!==null);if((_i&6)!==0)throw Error(t(327));_=o.finishedWork;var O=o.finishedLanes;if(_===null)return null;if(o.finishedWork=null,o.finishedLanes=0,_===o.current)throw Error(t(177));o.callbackNode=null,o.callbackPriority=0;var F=_.lanes|_.childLanes;if(vt(o,F),o===vn&&(un=vn=null,Rn=0),(_.subtreeFlags&2064)===0&&(_.flags&2064)===0||Fc||(Fc=!0,Wp(nr,function(){return Ba(),null})),F=(_.flags&15990)!==0,(_.subtreeFlags&15990)!==0||F){F=Xs.transition,Xs.transition=null;var ee=je;je=1;var be=_i;_i|=4,Lc.current=null,Om(o,_),Tu(_,o),hm(Ad),fo=!!Dd,Ad=Dd=null,o.current=_,Rp(_),xa(),_i=be,je=ee,Xs.transition=F}else o.current=_;if(Fc&&(Fc=!1,ta=o,Hc=O),F=o.pendingLanes,F===0&&(Co=null),Bt(_.stateNode),Cs(o,Ci()),u!==null)for($=o.onRecoverableError,_=0;_<u.length;_++)O=u[_],$(O.value,{componentStack:O.stack,digest:O.digest});if(Gc)throw Gc=!1,o=Pu,Pu=null,o;return(Hc&1)!==0&&o.tag!==0&&Ba(),F=o.pendingLanes,(F&1)!==0?o===Ru?Il++:(Il=0,Ru=o):Il=0,_o(),null}function Ba(){if(ta!==null){var o=Je(Hc),u=Xs.transition,_=je;try{if(Xs.transition=null,je=16>o?16:o,ta===null)var $=!1;else{if(o=ta,ta=null,Hc=0,(_i&6)!==0)throw Error(t(331));var O=_i;for(_i|=4,jt=o.current;jt!==null;){var F=jt,ee=F.child;if((jt.flags&16)!==0){var be=F.deletions;if(be!==null){for(var Te=0;Te<be.length;Te++){var Ue=be[Te];for(jt=Ue;jt!==null;){var lt=jt;switch(lt.tag){case 0:case 11:case 15:Dl(8,lt,F)}var ut=lt.child;if(ut!==null)ut.return=lt,jt=ut;else for(;jt!==null;){lt=jt;var at=lt.sibling,Tt=lt.return;if($p(lt),lt===Ue){jt=null;break}if(at!==null){at.return=Tt,jt=at;break}jt=Tt}}}var Nt=F.alternate;if(Nt!==null){var Mt=Nt.child;if(Mt!==null){Nt.child=null;do{var Oi=Mt.sibling;Mt.sibling=null,Mt=Oi}while(Mt!==null)}}jt=F}}if((F.subtreeFlags&2064)!==0&&ee!==null)ee.return=F,jt=ee;else e:for(;jt!==null;){if(F=jt,(F.flags&2048)!==0)switch(F.tag){case 0:case 11:case 15:Dl(9,F,F.return)}var Ge=F.sibling;if(Ge!==null){Ge.return=F.return,jt=Ge;break e}jt=F.return}}var Re=o.current;for(jt=Re;jt!==null;){ee=jt;var Ve=ee.child;if((ee.subtreeFlags&2064)!==0&&Ve!==null)Ve.return=ee,jt=Ve;else e:for(ee=Re;jt!==null;){if(be=jt,(be.flags&2048)!==0)try{switch(be.tag){case 0:case 11:case 15:Su(9,be)}}catch(Gt){en(be,be.return,Gt)}if(be===ee){jt=null;break e}var mt=be.sibling;if(mt!==null){mt.return=be.return,jt=mt;break e}jt=be.return}}if(_i=O,_o(),wn&&typeof wn.onPostCommitFiberRoot=="function")try{wn.onPostCommitFiberRoot(ps,o)}catch{}$=!0}return $}finally{je=_,Xs.transition=u}}return!1}function Fp(o,u,_){u=Ma(_,u),u=gp(o,u,1),o=wo(o,u,1),u=os(),o!==null&&(Jn(o,1,u),Cs(o,u))}function en(o,u,_){if(o.tag===3)Fp(o,o,_);else for(;u!==null;){if(u.tag===3){Fp(u,o,_);break}else if(u.tag===1){var $=u.stateNode;if(typeof u.type.getDerivedStateFromError=="function"||typeof $.componentDidCatch=="function"&&(Co===null||!Co.has($))){o=Ma(_,o),o=vp(u,o,1),u=wo(u,o,1),o=os(),u!==null&&(Jn(u,1,o),Cs(u,o));break}}u=u.return}}function Fm(o,u,_){var $=o.pingCache;$!==null&&$.delete(u),u=os(),o.pingedLanes|=o.suspendedLanes&_,vn===o&&(Rn&_)===_&&(Cn===4||Cn===3&&(Rn&130023424)===Rn&&500>Ci()-Iu?na(o,0):$u|=_),Cs(o,u)}function Hm(o,u){u===0&&((o.mode&1)===0?u=1:(u=Xn,Xn<<=1,(Xn&130023424)===0&&(Xn=4194304)));var _=os();o=Kr(o,u),o!==null&&(Jn(o,u,_),Cs(o,_))}function Wm(o){var u=o.memoizedState,_=0;u!==null&&(_=u.retryLane),Hm(o,_)}function Um(o,u){var _=0;switch(o.tag){case 13:var $=o.stateNode,O=o.memoizedState;O!==null&&(_=O.retryLane);break;case 19:$=o.stateNode;break;default:throw Error(t(314))}$!==null&&$.delete(u),Hm(o,_)}var Hp;Hp=function(o,u,_){if(o!==null)if(o.memoizedProps!==u.pendingProps||gs.current)xs=!0;else{if((o.lanes&_)===0&&(u.flags&128)===0)return xs=!1,Rv(o,u,_);xs=(o.flags&131072)!==0}else xs=!1,Xi&&(u.flags&1048576)!==0&&Uo(u,Sc,u.index);switch(u.lanes=0,u.tag){case 2:var $=u.type;Nc(o,u),o=u.pendingProps;var O=ss(u,ns.current);Ra(u,_),O=su(null,u,$,o,O,_);var F=ru();return u.flags|=1,typeof O=="object"&&O!==null&&typeof O.render=="function"&&O.$$typeof===void 0?(u.tag=1,u.memoizedState=null,u.updateQueue=null,vs($)?(F=!0,wc(u)):F=!1,u.memoizedState=O.state!==null&&O.state!==void 0?O.state:null,Tc(u),O.updater=Xr,u.stateNode=O,O._reactInternals=u,cu(u,$,o,_),u=pu(null,u,$,!0,F,_)):(u.tag=0,Xi&&F&&fn(u),Wn(null,u,O,_),u=u.child),u;case 16:$=u.elementType;e:{switch(Nc(o,u),o=u.pendingProps,O=$._init,$=O($._payload),u.type=$,O=u.tag=Vm($),o=gn($,o),O){case 0:u=hu(null,u,$,o,_);break e;case 1:u=Sp(null,u,$,o,_);break e;case 11:u=bp(null,u,$,o,_);break e;case 14:u=El(null,u,$,gn($.type,o),_);break e}throw Error(t(306,$,""))}return u;case 0:return $=u.type,O=u.pendingProps,O=u.elementType===$?O:gn($,O),hu(o,u,$,O,_);case 1:return $=u.type,O=u.pendingProps,O=u.elementType===$?O:gn($,O),Sp(o,u,$,O,_);case 3:e:{if(fu(u),o===null)throw Error(t(387));$=u.pendingProps,F=u.memoizedState,O=F.element,Yd(o,u),Dc(u,$,null,_);var ee=u.memoizedState;if($=ee.element,F.isDehydrated)if(F={element:$,isDehydrated:!1,cache:ee.cache,pendingSuspenseBoundaries:ee.pendingSuspenseBoundaries,transitions:ee.transitions},u.updateQueue.baseState=F,u.memoizedState=F,u.flags&256){O=Ma(Error(t(423)),u),u=Cp(o,u,$,_,O);break e}else if($!==O){O=Ma(Error(t(424)),u),u=Cp(o,u,$,_,O);break e}else for(Ps=go(u.stateNode.containerInfo.firstChild),ws=u,Xi=!0,ys=null,_=Wd(u,null,$,_),u.child=_;_;)_.flags=_.flags&-3|4096,_=_.sibling;else{if(Vo(),$===O){u=Jr(o,u,_);break e}Wn(o,u,$,_)}u=u.child}return u;case 5:return qh(u),o===null&&Bd(u),$=u.type,O=u.pendingProps,F=o!==null?o.memoizedProps:null,ee=O.children,$d($,O)?ee=null:F!==null&&$d($,F)&&(u.flags|=32),xp(o,u),Wn(o,u,ee,_),u.child;case 6:return o===null&&Bd(u),null;case 13:return kp(o,u,_);case 4:return Xd(u,u.stateNode.containerInfo),$=u.pendingProps,o===null?u.child=Pa(u,null,$,_):Wn(o,u,$,_),u.child;case 11:return $=u.type,O=u.pendingProps,O=u.elementType===$?O:gn($,O),bp(o,u,$,O,_);case 7:return Wn(o,u,u.pendingProps,_),u.child;case 8:return Wn(o,u,u.pendingProps.children,_),u.child;case 12:return Wn(o,u,u.pendingProps.children,_),u.child;case 10:e:{if($=u.type._context,O=u.pendingProps,F=u.memoizedProps,ee=O.value,Mi(qo,$._currentValue),$._currentValue=ee,F!==null)if(cr(F.value,ee)){if(F.children===O.children&&!gs.current){u=Jr(o,u,_);break e}}else for(F=u.child,F!==null&&(F.return=u);F!==null;){var be=F.dependencies;if(be!==null){ee=F.child;for(var Te=be.firstContext;Te!==null;){if(Te.context===$){if(F.tag===1){Te=Yr(-1,_&-_),Te.tag=2;var Ue=F.updateQueue;if(Ue!==null){Ue=Ue.shared;var lt=Ue.pending;lt===null?Te.next=Te:(Te.next=lt.next,lt.next=Te),Ue.pending=Te}}F.lanes|=_,Te=F.alternate,Te!==null&&(Te.lanes|=_),Vh(F.return,_,u),be.lanes|=_;break}Te=Te.next}}else if(F.tag===10)ee=F.type===u.type?null:F.child;else if(F.tag===18){if(ee=F.return,ee===null)throw Error(t(341));ee.lanes|=_,be=ee.alternate,be!==null&&(be.lanes|=_),Vh(ee,_,u),ee=F.sibling}else ee=F.child;if(ee!==null)ee.return=F;else for(ee=F;ee!==null;){if(ee===u){ee=null;break}if(F=ee.sibling,F!==null){F.return=ee.return,ee=F;break}ee=ee.return}F=ee}Wn(o,u,O.children,_),u=u.child}return u;case 9:return O=u.type,$=u.pendingProps.children,Ra(u,_),O=qs(O),$=$(O),u.flags|=1,Wn(o,u,$,_),u.child;case 14:return $=u.type,O=gn($,u.pendingProps),O=gn($.type,O),El(o,u,$,O,_);case 15:return wp(o,u,u.type,u.pendingProps,_);case 17:return $=u.type,O=u.pendingProps,O=u.elementType===$?O:gn($,O),Nc(o,u),u.tag=1,vs($)?(o=!0,wc(u)):o=!1,Ra(u,_),fp(u,$,O),cu(u,$,O,_),pu(null,u,$,!0,o,_);case 19:return _u(o,u,_);case 22:return yp(o,u,_)}throw Error(t(156,u.tag))};function Wp(o,u){return zo(o,u)}function Nv(o,u,_,$){this.tag=o,this.key=_,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=u,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=$,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function js(o,u,_,$){return new Nv(o,u,_,$)}function zu(o){return o=o.prototype,!(!o||!o.isReactComponent)}function Vm(o){if(typeof o=="function")return zu(o)?1:0;if(o!=null){if(o=o.$$typeof,o===de)return 11;if(o===te)return 14}return 2}function To(o,u){var _=o.alternate;return _===null?(_=js(o.tag,u,o.key,o.mode),_.elementType=o.elementType,_.type=o.type,_.stateNode=o.stateNode,_.alternate=o,o.alternate=_):(_.pendingProps=u,_.type=o.type,_.flags=0,_.subtreeFlags=0,_.deletions=null),_.flags=o.flags&14680064,_.childLanes=o.childLanes,_.lanes=o.lanes,_.child=o.child,_.memoizedProps=o.memoizedProps,_.memoizedState=o.memoizedState,_.updateQueue=o.updateQueue,u=o.dependencies,_.dependencies=u===null?null:{lanes:u.lanes,firstContext:u.firstContext},_.sibling=o.sibling,_.index=o.index,_.ref=o.ref,_}function Vc(o,u,_,$,O,F){var ee=2;if($=o,typeof o=="function")zu(o)&&(ee=1);else if(typeof o=="string")ee=5;else e:switch(o){case L:return Ga(_.children,O,F,u);case j:ee=8,O|=8;break;case H:return o=js(12,_,u,O|2),o.elementType=H,o.lanes=F,o;case Z:return o=js(13,_,u,O),o.elementType=Z,o.lanes=F,o;case me:return o=js(19,_,u,O),o.elementType=me,o.lanes=F,o;case _e:return qc(_,O,F,u);default:if(typeof o=="object"&&o!==null)switch(o.$$typeof){case W:ee=10;break e;case re:ee=9;break e;case de:ee=11;break e;case te:ee=14;break e;case pe:ee=16,$=null;break e}throw Error(t(130,o==null?o:typeof o,""))}return u=js(ee,_,u,O),u.elementType=o,u.type=$,u.lanes=F,u}function Ga(o,u,_,$){return o=js(7,o,$,u),o.lanes=_,o}function qc(o,u,_,$){return o=js(22,o,$,u),o.elementType=_e,o.lanes=_,o.stateNode={isHidden:!1},o}function Bu(o,u,_){return o=js(6,o,null,u),o.lanes=_,o}function Gu(o,u,_){return u=js(4,o.children!==null?o.children:[],o.key,u),u.lanes=_,u.stateNode={containerInfo:o.containerInfo,pendingChildren:null,implementation:o.implementation},u}function Mv(o,u,_,$,O){this.tag=u,this.containerInfo=o,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ye(0),this.expirationTimes=Ye(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ye(0),this.identifierPrefix=$,this.onRecoverableError=O,this.mutableSourceEagerHydrationData=null}function Fu(o,u,_,$,O,F,ee,be,Te){return o=new Mv(o,u,_,be,Te),u===1?(u=1,F===!0&&(u|=8)):u=0,F=js(3,null,null,u),o.current=F,F.stateNode=o,F.memoizedState={element:$,isDehydrated:_,cache:null,transitions:null,pendingSuspenseBoundaries:null},Tc(F),o}function Ov(o,u,_){var $=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:N,key:$==null?null:""+$,children:o,containerInfo:u,implementation:_}}function Up(o){if(!o)return vo;o=o._reactInternals;e:{if(Et(o)!==o||o.tag!==1)throw Error(t(170));var u=o;do{switch(u.tag){case 3:u=u.stateNode.context;break e;case 1:if(vs(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break e}}u=u.return}while(u!==null);throw Error(t(171))}if(o.tag===1){var _=o.type;if(vs(_))return Gh(o,_,u)}return u}function qm(o,u,_,$,O,F,ee,be,Te){return o=Fu(_,$,!0,o,O,F,ee,be,Te),o.context=Up(null),_=o.current,$=os(),O=ko(_),F=Yr($,O),F.callback=u??null,wo(_,F,O),o.current.lanes=O,Jn(o,O,$),Cs(o,$),o}function Kc(o,u,_,$){var O=u.current,F=os(),ee=ko(O);return _=Up(_),u.context===null?u.context=_:u.pendingContext=_,u=Yr(F,ee),u.payload={element:o},$=$===void 0?null:$,$!==null&&(u.callback=$),o=wo(O,u,ee),o!==null&&(fr(o,O,ee,F),xl(o,O,ee)),ee}function Yc(o){if(o=o.current,!o.child)return null;switch(o.child.tag){case 5:return o.child.stateNode;default:return o.child.stateNode}}function Vp(o,u){if(o=o.memoizedState,o!==null&&o.dehydrated!==null){var _=o.retryLane;o.retryLane=_!==0&&_<u?_:u}}function Hu(o,u){Vp(o,u),(o=o.alternate)&&Vp(o,u)}function Km(){return null}var Ym=typeof reportError=="function"?reportError:function(o){console.error(o)};function Wu(o){this._internalRoot=o}Fa.prototype.render=Wu.prototype.render=function(o){var u=this._internalRoot;if(u===null)throw Error(t(409));Kc(o,u,null,null)},Fa.prototype.unmount=Wu.prototype.unmount=function(){var o=this._internalRoot;if(o!==null){this._internalRoot=null;var u=o.containerInfo;ia(function(){Kc(null,o,null,null)}),u[$r]=null}};function Fa(o){this._internalRoot=o}Fa.prototype.unstable_scheduleHydration=function(o){if(o){var u=ji();o={blockedOn:null,target:o,priority:u};for(var _=0;_<sr.length&&u!==0&&u<sr[_].priority;_++);sr.splice(_,0,o),_===0&&rl(o)}};function Uu(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11)}function Xc(o){return!(!o||o.nodeType!==1&&o.nodeType!==9&&o.nodeType!==11&&(o.nodeType!==8||o.nodeValue!==" react-mount-point-unstable "))}function Xm(){}function Jm(o,u,_,$,O){if(O){if(typeof $=="function"){var F=$;$=function(){var Ue=Yc(ee);F.call(Ue)}}var ee=qm(u,$,o,0,null,!1,!1,"",Xm);return o._reactRootContainer=ee,o[$r]=ee.current,vl(o.nodeType===8?o.parentNode:o),ia(),ee}for(;O=o.lastChild;)o.removeChild(O);if(typeof $=="function"){var be=$;$=function(){var Ue=Yc(Te);be.call(Ue)}}var Te=Fu(o,0,!1,null,null,!1,!1,"",Xm);return o._reactRootContainer=Te,o[$r]=Te.current,vl(o.nodeType===8?o.parentNode:o),ia(function(){Kc(u,Te,_,$)}),Te}function jl(o,u,_,$,O){var F=_._reactRootContainer;if(F){var ee=F;if(typeof O=="function"){var be=O;O=function(){var Te=Yc(ee);be.call(Te)}}Kc(u,ee,o,O)}else ee=Jm(_,u,o,O,$);return Yc(ee)}Dt=function(o){switch(o.tag){case 3:var u=o.stateNode;if(u.current.memoizedState.isDehydrated){var _=Bs(u.pendingLanes);_!==0&&(fe(u,_|1),Cs(u,Ci()),(_i&6)===0&&(za=Ci()+500,_o()))}break;case 13:ia(function(){var $=Kr(o,1);if($!==null){var O=os();fr($,o,1,O)}}),Hu(o,1)}},ii=function(o){if(o.tag===13){var u=Kr(o,134217728);if(u!==null){var _=os();fr(u,o,134217728,_)}Hu(o,134217728)}},oi=function(o){if(o.tag===13){var u=ko(o),_=Kr(o,u);if(_!==null){var $=os();fr(_,o,u,$)}Hu(o,u)}},ji=function(){return je},$i=function(o,u){var _=je;try{return je=o,u()}finally{je=_}},Os=function(o,u,_){switch(u){case"input":if(Fe(o,_),u=_.name,_.type==="radio"&&u!=null){for(_=o;_.parentNode;)_=_.parentNode;for(_=_.querySelectorAll("input[name="+JSON.stringify(""+u)+'][type="radio"]'),u=0;u<_.length;u++){var $=_[u];if($!==o&&$.form===o.form){var O=_c($);if(!O)throw Error(t(90));Qe($),Fe($,O)}}}break;case"textarea":Zt(o,_);break;case"select":u=_.value,u!=null&&ze(o,!!_.multiple,u,!1)}},zs=Mu,Ln=ia;var qp={usingClientEntryPoint:!1,Events:[wl,Ta,_c,br,wr,Mu]},mr={findFiberByHostInstance:Ho,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},Zm={bundleType:mr.bundleType,version:mr.version,rendererPackageName:mr.rendererPackageName,rendererConfig:mr.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:A.ReactCurrentDispatcher,findHostInstanceByFiber:function(o){return o=ao(o),o===null?null:o.stateNode},findFiberByHostInstance:mr.findFiberByHostInstance||Km,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 Nl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Nl.isDisabled&&Nl.supportsFiber)try{ps=Nl.inject(Zm),wn=Nl}catch{}}return gr.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=qp,gr.createPortal=function(o,u){var _=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Uu(u))throw Error(t(200));return Ov(o,u,null,_)},gr.createRoot=function(o,u){if(!Uu(o))throw Error(t(299));var _=!1,$="",O=Ym;return u!=null&&(u.unstable_strictMode===!0&&(_=!0),u.identifierPrefix!==void 0&&($=u.identifierPrefix),u.onRecoverableError!==void 0&&(O=u.onRecoverableError)),u=Fu(o,1,!1,null,null,_,!1,$,O),o[$r]=u.current,vl(o.nodeType===8?o.parentNode:o),new Wu(u)},gr.findDOMNode=function(o){if(o==null)return null;if(o.nodeType===1)return o;var u=o._reactInternals;if(u===void 0)throw typeof o.render=="function"?Error(t(188)):(o=Object.keys(o).join(","),Error(t(268,o)));return o=ao(u),o=o===null?null:o.stateNode,o},gr.flushSync=function(o){return ia(o)},gr.hydrate=function(o,u,_){if(!Xc(u))throw Error(t(200));return jl(null,o,u,!0,_)},gr.hydrateRoot=function(o,u,_){if(!Uu(o))throw Error(t(405));var $=_!=null&&_.hydratedSources||null,O=!1,F="",ee=Ym;if(_!=null&&(_.unstable_strictMode===!0&&(O=!0),_.identifierPrefix!==void 0&&(F=_.identifierPrefix),_.onRecoverableError!==void 0&&(ee=_.onRecoverableError)),u=qm(u,null,o,1,_??null,O,!1,F,ee),o[$r]=u.current,vl(o),$)for(o=0;o<$.length;o++)_=$[o],O=_._getVersion,O=O(_._source),u.mutableSourceEagerHydrationData==null?u.mutableSourceEagerHydrationData=[_,O]:u.mutableSourceEagerHydrationData.push(_,O);return new Fa(u)},gr.render=function(o,u,_){if(!Xc(u))throw Error(t(200));return jl(null,o,u,!1,_)},gr.unmountComponentAtNode=function(o){if(!Xc(o))throw Error(t(40));return o._reactRootContainer?(ia(function(){jl(null,null,o,!1,function(){o._reactRootContainer=null,o[$r]=null})}),!0):!1},gr.unstable_batchedUpdates=Mu,gr.unstable_renderSubtreeIntoContainer=function(o,u,_,$){if(!Xc(_))throw Error(t(200));if(o==null||o._reactInternals===void 0)throw Error(t(38));return jl(o,u,_,!1,$)},gr.version="18.3.1-next-f1338f8080-20240426",gr}var Kw;function vS(){if(Kw)return Fv.exports;Kw=1;function i(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(i)}catch(e){console.error(e)}}return i(),Fv.exports=zk(),Fv.exports}var Yw;function Bk(){if(Yw)return eg;Yw=1;var i=vS();return eg.createRoot=i.createRoot,eg.hydrateRoot=i.hydrateRoot,eg}var Gk=Bk();const Fk=Lb(Gk);var B=zb();const Rt=Lb(B),Xw=i=>{let e;const t=new Set,n=(f,g)=>{const m=typeof f=="function"?f(e):f;if(!Object.is(m,e)){const w=e;e=g??(typeof m!="object"||m===null)?m:Object.assign({},e,m),t.forEach(D=>D(e,w))}},r=()=>e,a={setState:n,getState:r,getInitialState:()=>d,subscribe:f=>(t.add(f),()=>t.delete(f))},d=e=i(n,r,a);return a},Hk=(i=>i?Xw(i):Xw),Wk=i=>i;function Uk(i,e=Wk){const t=Rt.useSyncExternalStore(i.subscribe,Rt.useCallback(()=>e(i.getState()),[i,e]),Rt.useCallback(()=>e(i.getInitialState()),[i,e]));return Rt.useDebugValue(t),t}const Jw=i=>{const e=Hk(i),t=n=>Uk(e,n);return Object.assign(t,e),t},On=(i=>i?Jw(i):Jw);function No(i){return"'"+i.replace(/'/g,"'\\''")+"'"}function Bb(i){return!i||i==="inherit"?"":` --model ${No(i)}`}const Uv=({sessionId:i,model:e})=>`claude --dangerously-skip-permissions --session-id ${No(i)}${Bb(e)}`,Zw=({sessionId:i,model:e})=>`claude --session-id ${No(i)}${Bb(e)}`,Vk=()=>"claude --resume",_S=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:Uv},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:Zw},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:Uv},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:Uv},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:Zw},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:Vk},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let Qr=null;async function qk(){if(Qr)return Qr;try{const i=await window.api.app.engageRulesPath();if(!i)return Qr=[],Qr;const e=await window.api.config.readJson(i);if(!e.exists||e.parseError||!e.data)return Qr=[],Qr;const t=e.data;if(!t.presets||!Array.isArray(t.presets))return Qr=[],Qr;const n=t.projectPath;return Qr=t.presets.map(r=>({id:r.id,label:r.label,description:r.description,category:"engage",cwd:n,platform:r.platform,pipeline:r.pipeline,rules:r.rules,command:()=>`cd ${No(n)} && ${r.cliEntry}`})),Qr}catch(i){return console.warn("[presets] Failed to load engage presets:",i),Qr=[],Qr}}async function bS(i){const e=_S.find(n=>n.id===i);return e||((await qk()).find(n=>n.id===i)??null)}async function Qw(i){return i.cwd==="app-cwd"?window.api.app.cwd():i.cwd==="home"?window.api.app.homeDir():i.cwd==="pick"?window.api.app.pickDirectory():i.cwd}function wS(i,e){return i.command?i.command(e):null}const Kk=["opus","sonnet","haiku"],yS="sm.rawSessionModel",Yk="opus";function Xk(i){return Kk.includes(i)}function Jk(){try{const i=localStorage.getItem(yS);if(i&&Xk(i))return i}catch{}return Yk}let sh=Jk();const M_=new Set;function Kg(){return sh}function Zk(i){if(i!==sh){sh=i;try{localStorage.setItem(yS,i)}catch{}M_.forEach(e=>e(i))}}function tz(){const[i,e]=B.useState(sh);B.useEffect(()=>{const n=r=>e(r);return M_.add(n),sh!==i&&e(sh),()=>{M_.delete(n)}},[]);const t=B.useCallback(n=>Zk(n),[]);return{model:i,setModel:t}}async function gv(i,e){const t=await window.api.transcripts.pathFor(i,e);return window.api.config.exists(t)}const Qk=5,ey=100,eE=5e3,O_=new Map;function ty(i){const e=O_.get(i);e!==void 0&&(clearTimeout(e),O_.delete(i))}function tE(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const da=On((i,e)=>({toasts:[],history:[],unreadCount:0,show:(t,n)=>{const r=tE(),l=Date.now();i(a=>{const d=[...a.toasts,{id:r,kind:t,message:n,createdAt:l}];for(;d.length>Qk;){const m=d.shift();m&&ty(m.id)}const g=[{id:r,kind:t,message:n,createdAt:l,read:!1},...a.history];return g.length>ey&&(g.length=ey),{toasts:d,history:g,unreadCount:a.unreadCount+1}});const p=setTimeout(()=>e().dismiss(r),eE);return O_.set(r,p),r},dismiss:t=>{ty(t),i(n=>({toasts:n.toasts.filter(r=>r.id!==t)}))},markAllRead:()=>{i(t=>t.unreadCount===0?t:{history:t.history.map(n=>n.read?n:{...n,read:!0}),unreadCount:0})},clearHistory:()=>{i({history:[],unreadCount:0})},dismissHistoryEntry:t=>{i(n=>{const r=n.history.filter(p=>p.id!==t);if(r.length===n.history.length)return n;const l=n.history.find(p=>p.id===t&&!p.read);return{history:r,unreadCount:l?Math.max(0,n.unreadCount-1):n.unreadCount}})}})),st={info:i=>da.getState().show("info",i),warn:i=>da.getState().show("warn",i),error:i=>da.getState().show("error",i),fromOutcome:i=>da.getState().show(i.kind??(i.ok?"info":"warn"),i.message)},xS=Object.freeze(Object.defineProperty({__proto__:null,toast:st,useToast:da},Symbol.toStringTag,{value:"Module"}));async function iE(i){var e,t;if(typeof window>"u"||typeof((t=(e=window.api)==null?void 0:e.chat)==null?void 0:t.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:i})==="develop"?"develop":"inline"}catch{return"inline"}}const nE={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"},build:{bg:"bg-hive-teal/20",text:"text-hive-teal",border:!0,label:"Build"},"project-home-builder":{bg:"bg-honey/20",text:"text-honey-dark",border:!0,label:"Project Home Builder"},"bilko-host-publisher":{bg:"bg-sage/15",text:"text-sage-dark",border:!0,label:"Bilko Host Publisher"}};function sE(i){return nE[i]}function rE(i){return i==="discussion"}function Gb(i,e,t){return new Promise((n,r)=>{const l=setTimeout(()=>r(new Error(`${t} timed out after ${e}ms`)),e);i.then(p=>{clearTimeout(l),n(p)},p=>{clearTimeout(l),r(p)})})}const oE=5e3,Or=On(()=>({snapshot:null,loaded:!1}));let iy=!1,ny=!1,Xp;async function aE(){var i;if(!iy){iy=!0;try{const e=await Gb(window.api.schedule.state(),oE,"schedule.state");Or.setState({snapshot:e,loaded:!0}),Xp=((i=e.paused)==null?void 0:i.reason)??null}catch(e){if(!ny){ny=!0;const t=e instanceof Error?e.message:String(e);st.error(`Scheduler state hydrate failed: ${t}`)}Xp=null}window.api.schedule.onState(e=>{var n;const t=((n=e.paused)==null?void 0:n.reason)??null;Xp!==void 0&&t!==Xp&&(t==="auth"?st.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):t==="network"&&st.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Xp=t,Or.setState({snapshot:e,loaded:!0})}),window.api.schedule.onStall(e=>{st.error(e.message)})}}const el=On((i,e)=>({modes:{},attached:{},setMode:(t,n)=>i(r=>({modes:{...r.modes,[t]:n}})),setAttached:(t,n)=>i(r=>({attached:{...r.attached,[t]:n}})),isAttached:t=>!!e().attached[t]})),lE={epicId:null,label:null,known:!1};function SS(i){if(!i)return[];const e=[];for(const t of[i.epicId,i.sourcePromptId,i.sourceTabId])typeof t=="string"&&t&&!e.includes(t)&&e.push(t);return e}function iz(i,e){const t=SS(i);if(t.length===0)return lE;for(const n of t){const r=e[n];if(r)return{epicId:n,label:r.goalText||n,known:!0}}return{epicId:t[0],label:null,known:!1}}function cE(i){return i.length>12?`${i.slice(0,12)}…`:i}function dE(i,e={}){const{suffixCase:t="lower",kDecimals:n=0}=e,r=t==="upper"?{k:"K",m:"M"}:{k:"k",m:"M"};return i>=1e6?`${(i/1e6).toFixed(1)}${r.m}`:i>=1e3?`${(i/1e3).toFixed(n)}${r.k}`:i.toFixed(0)}function ad(i){const e=i.indexOf(`
|
|
42
42
|
|
|
43
|
-
`);return e===-1?{title:i,goal:""}:{title:i.slice(0,e),goal:i.slice(e+2)}}function tl(i,e){var D;const t=e.sessions[i];if((t==null?void 0:t.status)==="completed")return"completed";if((t==null?void 0:t.status)==="proposed")return"proposed";const n=e.chats[i];if(((n==null?void 0:n.ticketHistory)??[]).some(k=>k.status==="needs-input"))return"needs";if((((D=e.events)==null?void 0:D[i])??[]).some(k=>k.kind==="response"&&k.validation==="refuted"))return"refuted";const a=e.jobs.filter(k=>k.sourcePromptId===i);if(a.some(k=>k.status==="failed"))return"failed";if(a.some(k=>k.status==="needs_review"))return"attention";const d=(n==null?void 0:n.queuedPosition)??0,f=(n==null?void 0:n.running)===!0&&d===0,g=a.some(k=>k.status==="running");if(f||g)return"running";const m=(n==null?void 0:n.running)===!0&&d>0,w=a.some(k=>k.status==="pending");return m||w?"queued":"active"}function uE(i,e){const t=e.jobs.filter(a=>a.sourcePromptId===i),n=t.find(a=>a.status==="failed");if(n)return`failed — PRD ${n.slug} did not complete`;const r=t.find(a=>a.status==="needs_review");if(r)return`needs review — PRD ${r.slug} is asking a question`;const l=e.chats[i],p=(l==null?void 0:l.queuedPosition)??0;if((l==null?void 0:l.running)===!0&&p>0)return`queued — waiting on a session slot (position ${p})`;if(t.some(a=>a.status==="pending"))return"queued — waiting for the scheduler"}function Fb(i,e){const t=new Map(e.jobs.filter(n=>n.sourcePromptId===i).map(n=>[n.slug,n]));return e.prds.filter(n=>n.sourcePromptId===i).map(n=>{const r=t.get(n.slug)??null,l=n.archived===!0,p=(r==null?void 0:r.status)??(l?n.archivedStatus??"completed":"draft");return{slug:n.slug,title:n.title,cwd:n.cwd,mtimeMs:n.mtimeMs,estimateMinutes:n.estimateMinutes,parallelGroup:n.parallelGroup,status:p,archived:l,job:r}})}function Hb(i,e){var d;const t=e.chats[i];if(!t)return null;const n=t.turns,r=n.reduce((f,g)=>{var m;return f+(((m=g.toolUses)==null?void 0:m.length)??0)},0),l=(d=e.usage)==null?void 0:d[i],p=l?l.inputTokens+l.outputTokens:0,a=p>0?dE(p):null;return{turns:n.length,toolCalls:r,tokens:a}}function hE(i,e){return`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/${e}.json`}function Wb(i){return`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/active-index.json`}function sy(i,e){const t=Date.parse(i.at),n=Date.parse(e.at),r=!Number.isNaN(t),l=!Number.isNaN(n);return r&&l&&t!==n?t-n:e.causedByEventId===i.id?-1:i.causedByEventId===e.id?1:r&&l?0:r?-1:l?1:0}let ry=0;function oy(i){return ry+=1,`${i}-${Date.now().toString(36)}-${ry}`}function Vu(i,e){var t,n;typeof window>"u"||!((n=(t=window.api)==null?void 0:t.auditLog)!=null&&n.append)||window.api.auditLog.append(i,e).catch(r=>{console.warn(`[auditLog] failed to append ${i}`,r)})}const xf=new Map;function pE(i){return(xf.get(i)??0)>0}async function ay(i,e=!1){var n,r;const t=i.worktree;if(!t)return{worktree:t};if(t.status!=="active"&&!(e&&t.status==="needs_merge_resolution"))return{worktree:t};if(typeof window>"u"||!((r=(n=window.api)==null?void 0:n.promptSessions)!=null&&r.mergeToMain))return{worktree:t};try{const l=await window.api.promptSessions.mergeToMain({cwd:i.cwd,epicId:i.id,branch:t.branch,dir:t.dir});return{worktree:{...t,status:l.ok?"merged":"needs_merge_resolution",conflictReason:l.ok?void 0:l.reason},reason:l.ok?void 0:l.reason}}catch{return{worktree:t}}}const ly=new Set;function $o(i,e,t,n=[]){var f,g;if(typeof window>"u"||!((g=(f=window.api)==null?void 0:f.promptSessions)!=null&&g.mergeActiveIndex))return Promise.resolve();const r=window.api,l=Object.fromEntries(Object.entries(e).filter(([,m])=>m.cwd===i&&(m.status==="active"||m.status==="proposed"))),p={};for(const m of Object.keys(l))p[m]=t[m]??[];const a=Wb(i);return xf.set(a,(xf.get(a)??0)+1),r.promptSessions.mergeActiveIndex({cwd:i,sessions:l,events:p,removedIds:n,source:"epics"}).then(()=>{},m=>{var D;const w=m instanceof Error?m.message:String(m);throw(D=r==null?void 0:r.logs)==null||D.write("promptSessions","warn",`persistActiveIndex failed for ${i}: ${w}`),m instanceof Error?m:new Error(w)}).finally(()=>{xf.set(a,Math.max(0,(xf.get(a)??1)-1))})}const Kt=On((i,e)=>({sessions:{},events:{},focusedEpicId:null,setFocusedEpicId:t=>i({focusedEpicId:t}),createPromptSession:async(t,n,r,l,p,a,d)=>{const g=(await window.api.promptSessions.create({cwd:t,goalText:n,tag:r,agentType:p,openingPrompt:a,sections:d})).session,m={id:oy("pevt"),promptSessionId:g.id,kind:"prompt",causedByEventId:null,at:g.createdAt,text:n},w={...e().sessions,[g.id]:g},D={...e().events,[g.id]:[m]};return i({sessions:w,events:D}),$o(t,w,D).catch(()=>{}),Vu("epic_create",{cwd:t,epicId:g.id,source:l??"unknown"}),g},approveProposed:(t,n)=>{var d,f;const r=e().sessions[t];if(!r||r.status!=="proposed")return null;const l={...r,status:"active"},p={...e().sessions,[t]:l};i({sessions:p});const{title:a}=ad(r.goalText);return $o(r.cwd,p,e().events).catch(g=>{const m=e().sessions[t];m&&m.status==="active"&&i({sessions:{...e().sessions,[t]:{...m,status:"proposed"}}});const w=g instanceof Error?g.message:String(g);st.error(`Could not start "${a}" — ${w}. Reopened for review.`)}),Vu("epic_approve",{cwd:r.cwd,epicId:t,source:n??"unknown"}),typeof window<"u"&&((f=(d=window.api)==null?void 0:d.promptSessions)!=null&&f.createWorktree)&&window.api.promptSessions.createWorktree({cwd:r.cwd,epicId:t}).then(g=>{if(!g)return;const m=e().sessions[t];if(!m||m.status!=="active")return;const w={...m,worktree:g};i({sessions:{...e().sessions,[t]:w}}),$o(r.cwd,e().sessions,e().events).catch(()=>{})}).catch(()=>{}),l},appendPromptSessionEvent:(t,n)=>{if(!e().sessions[t])throw new Error(`appendPromptSessionEvent: no PromptSession with id "${t}"`);const r=e().events[t]??[],l=r[r.length-1]??null;if(n.causedByEventId!==null){if(!l||n.causedByEventId!==l.id)throw new Error(`appendPromptSessionEvent: causedByEventId "${n.causedByEventId}" does not reference the current tail event of promptSession "${t}"`)}else if(r.length>0)throw new Error(`appendPromptSessionEvent: causedByEventId may only be null for a session's first event (promptSession "${t}" already has ${r.length})`);if(n.kind==="prd_created"&&!n.prdSlug)throw new Error("appendPromptSessionEvent: kind 'prd_created' requires prdSlug");const p={...n,id:oy("pevt"),promptSessionId:t,at:new Date().toISOString()},a={...e().events,[t]:[...r,p]};i({events:a});const d=e().sessions[t];return $o(d.cwd,e().sessions,a).catch(()=>{}),p},markCompleted:async(t,n)=>{const r=e().sessions[t];if(!r)throw new Error(`markCompleted: no PromptSession with id "${t}"`);if(r.status==="completed")return;await window.api.chat.cancel(t),window.api.pty.kill(r.claudeSessionId);const{worktree:l}=await ay(r),p=r,a=e().events[t]??[],{title:d}=ad(r.goalText),f=a.slice(-1)[0]??null;f&&e().appendPromptSessionEvent(t,{kind:"closed",causedByEventId:f.id});const g=e().events[t]??a,m={...e().events,[t]:g},w=new Date().toISOString(),D={...r,worktree:l,status:"completed",completedAt:w},k={...e().sessions,[t]:D};i({sessions:k});const E=x=>{i({sessions:{...e().sessions,[t]:p},events:{...e().events,[t]:a}}),st.error(`Could not mark "${d}" completed — ${x}`)};try{await $o(r.cwd,k,m,[t])}catch(x){throw E(x instanceof Error?x.message:String(x)),x}Vu("epic_complete",{cwd:r.cwd,epicId:t,source:n??"unknown"});let b="";try{const x=await window.api.transcripts.pathFor(r.cwd,r.claudeSessionId),A=await window.api.config.readText(x);b=A.exists?A.text:""}catch{b=""}let C;if(!b)try{const{turns:x}=await window.api.promptSessionTranscript.read(r.cwd,t);x.length>0&&(C=x.map(A=>({role:A.role,text:A.text,at:A.at})))}catch{C=void 0}const y={session:D,events:e().events[t]??g,transcript:b,archivedAt:w,status:D.status,cwd:D.cwd,indexedAt:w,...C?{durableTurns:C}:{}};try{await window.api.config.writeJson(hE(r.cwd,t),y,"epics")}catch(x){throw E(x instanceof Error?x.message:String(x)),$o(p.cwd,e().sessions,e().events).catch(()=>{}),x}},mergeEpicToMain:async t=>{const n=e().sessions[t];if(!n)throw new Error(`mergeEpicToMain: no PromptSession with id "${t}"`);const{worktree:r,reason:l}=await ay(n,!0),p=e().sessions[t];if(p&&p.worktree===n.worktree){const a={...p,worktree:r};i({sessions:{...e().sessions,[t]:a}}),$o(n.cwd,e().sessions,e().events).catch(()=>{})}return{ok:(r==null?void 0:r.status)==="merged",reason:l}},resumeArchived:async(t,n)=>{const r=e().sessions[t];if(!r)throw new Error(`resumeArchived: no PromptSession with id "${t}"`);const l=n??"unknown",p=await e().createPromptSession(r.cwd,r.goalText,void 0,l),a={...p,resumedFromId:t},d={...e().sessions,[p.id]:a};i({sessions:d}),$o(a.cwd,d,e().events).catch(()=>{});const f=e().approveProposed(a.id,l);return Vu("epic_resume",{cwd:a.cwd,epicId:a.id,source:l}),f??a},renameEpic:async(t,n,r)=>{const l=e().sessions[t];if(!l)throw new Error(`renameEpic: no PromptSession with id "${t}"`);const p=n.trim().replace(/\s*\n+\s*/g," ");if(!p)throw new Error("renameEpic: title must not be empty");const a=`${p}
|
|
43
|
+
`);return e===-1?{title:i,goal:""}:{title:i.slice(0,e),goal:i.slice(e+2)}}function tl(i,e){var D;const t=e.sessions[i];if((t==null?void 0:t.status)==="completed")return"completed";if((t==null?void 0:t.status)==="proposed")return"proposed";const n=e.chats[i];if(((n==null?void 0:n.ticketHistory)??[]).some(k=>k.status==="needs-input"))return"needs";if((((D=e.events)==null?void 0:D[i])??[]).some(k=>k.kind==="response"&&k.validation==="refuted"))return"refuted";const a=e.jobs.filter(k=>k.sourcePromptId===i);if(a.some(k=>k.status==="failed"))return"failed";if(a.some(k=>k.status==="needs_review"))return"attention";const d=(n==null?void 0:n.queuedPosition)??0,f=(n==null?void 0:n.running)===!0&&d===0,g=a.some(k=>k.status==="running");if(f||g)return"running";const m=(n==null?void 0:n.running)===!0&&d>0,w=a.some(k=>k.status==="pending");return m||w?"queued":"active"}function uE(i,e){const t=e.jobs.filter(a=>a.sourcePromptId===i),n=t.find(a=>a.status==="failed");if(n)return`failed — PRD ${n.slug} did not complete`;const r=t.find(a=>a.status==="needs_review");if(r)return`needs review — PRD ${r.slug} is asking a question`;const l=e.chats[i],p=(l==null?void 0:l.queuedPosition)??0;if((l==null?void 0:l.running)===!0&&p>0)return`queued — waiting on a session slot (position ${p})`;if(t.some(a=>a.status==="pending"))return"queued — waiting for the scheduler"}function Fb(i,e){const t=new Map(e.jobs.filter(n=>n.sourcePromptId===i).map(n=>[n.slug,n]));return e.prds.filter(n=>n.sourcePromptId===i).map(n=>{const r=t.get(n.slug)??null,l=n.archived===!0,p=(r==null?void 0:r.status)??(l?n.archivedStatus??"completed":"draft");return{slug:n.slug,title:n.title,cwd:n.cwd,mtimeMs:n.mtimeMs,estimateMinutes:n.estimateMinutes,parallelGroup:n.parallelGroup,status:p,archived:l,job:r}})}function Hb(i,e){var d;const t=e.chats[i];if(!t)return null;const n=t.turns,r=n.reduce((f,g)=>{var m;return f+(((m=g.toolUses)==null?void 0:m.length)??0)},0),l=(d=e.usage)==null?void 0:d[i],p=l?l.inputTokens+l.outputTokens:0,a=p>0?dE(p):null;return{turns:n.length,toolCalls:r,tokens:a}}function hE(i,e){return`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/${e}.json`}function Wb(i){return`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions/active-index.json`}function sy(i,e){const t=Date.parse(i.at),n=Date.parse(e.at),r=!Number.isNaN(t),l=!Number.isNaN(n);return r&&l&&t!==n?t-n:e.causedByEventId===i.id?-1:i.causedByEventId===e.id?1:r&&l?0:r?-1:l?1:0}let ry=0;function oy(i){return ry+=1,`${i}-${Date.now().toString(36)}-${ry}`}function Vu(i,e){var t,n;typeof window>"u"||!((n=(t=window.api)==null?void 0:t.auditLog)!=null&&n.append)||window.api.auditLog.append(i,e).catch(r=>{console.warn(`[auditLog] failed to append ${i}`,r)})}const xf=new Map;function pE(i){return(xf.get(i)??0)>0}async function ay(i,e=!1){var n,r;const t=i.worktree;if(!t)return{worktree:t};if(t.status!=="active"&&!(e&&t.status==="needs_merge_resolution"))return{worktree:t};if(typeof window>"u"||!((r=(n=window.api)==null?void 0:n.promptSessions)!=null&&r.mergeToMain))return{worktree:t};try{const l=await window.api.promptSessions.mergeToMain({cwd:i.cwd,epicId:i.id,branch:t.branch,dir:t.dir,carriedPaths:t.carriedPaths});return{worktree:{...t,status:l.ok?"merged":"needs_merge_resolution",conflictReason:l.ok?void 0:l.reason},reason:l.ok?void 0:l.reason}}catch{return{worktree:t}}}const ly=new Set;function $o(i,e,t,n=[]){var f,g;if(typeof window>"u"||!((g=(f=window.api)==null?void 0:f.promptSessions)!=null&&g.mergeActiveIndex))return Promise.resolve();const r=window.api,l=Object.fromEntries(Object.entries(e).filter(([,m])=>m.cwd===i&&(m.status==="active"||m.status==="proposed"))),p={};for(const m of Object.keys(l))p[m]=t[m]??[];const a=Wb(i);return xf.set(a,(xf.get(a)??0)+1),r.promptSessions.mergeActiveIndex({cwd:i,sessions:l,events:p,removedIds:n,source:"epics"}).then(()=>{},m=>{var D;const w=m instanceof Error?m.message:String(m);throw(D=r==null?void 0:r.logs)==null||D.write("promptSessions","warn",`persistActiveIndex failed for ${i}: ${w}`),m instanceof Error?m:new Error(w)}).finally(()=>{xf.set(a,Math.max(0,(xf.get(a)??1)-1))})}const Kt=On((i,e)=>({sessions:{},events:{},focusedEpicId:null,setFocusedEpicId:t=>i({focusedEpicId:t}),createPromptSession:async(t,n,r,l,p,a,d)=>{const g=(await window.api.promptSessions.create({cwd:t,goalText:n,tag:r,agentType:p,openingPrompt:a,sections:d})).session,m={id:oy("pevt"),promptSessionId:g.id,kind:"prompt",causedByEventId:null,at:g.createdAt,text:n},w={...e().sessions,[g.id]:g},D={...e().events,[g.id]:[m]};return i({sessions:w,events:D}),$o(t,w,D).catch(()=>{}),Vu("epic_create",{cwd:t,epicId:g.id,source:l??"unknown"}),g},approveProposed:(t,n)=>{var d,f;const r=e().sessions[t];if(!r||r.status!=="proposed")return null;const l={...r,status:"active"},p={...e().sessions,[t]:l};i({sessions:p});const{title:a}=ad(r.goalText);return $o(r.cwd,p,e().events).catch(g=>{const m=e().sessions[t];m&&m.status==="active"&&i({sessions:{...e().sessions,[t]:{...m,status:"proposed"}}});const w=g instanceof Error?g.message:String(g);st.error(`Could not start "${a}" — ${w}. Reopened for review.`)}),Vu("epic_approve",{cwd:r.cwd,epicId:t,source:n??"unknown"}),typeof window<"u"&&((f=(d=window.api)==null?void 0:d.promptSessions)!=null&&f.createWorktree)&&window.api.promptSessions.createWorktree({cwd:r.cwd,epicId:t}).then(g=>{if(!g)return;const m=e().sessions[t];if(!m||m.status!=="active")return;const w={...m,worktree:g};i({sessions:{...e().sessions,[t]:w}}),$o(r.cwd,e().sessions,e().events).catch(()=>{})}).catch(()=>{}),l},appendPromptSessionEvent:(t,n)=>{if(!e().sessions[t])throw new Error(`appendPromptSessionEvent: no PromptSession with id "${t}"`);const r=e().events[t]??[],l=r[r.length-1]??null;if(n.causedByEventId!==null){if(!l||n.causedByEventId!==l.id)throw new Error(`appendPromptSessionEvent: causedByEventId "${n.causedByEventId}" does not reference the current tail event of promptSession "${t}"`)}else if(r.length>0)throw new Error(`appendPromptSessionEvent: causedByEventId may only be null for a session's first event (promptSession "${t}" already has ${r.length})`);if(n.kind==="prd_created"&&!n.prdSlug)throw new Error("appendPromptSessionEvent: kind 'prd_created' requires prdSlug");const p={...n,id:oy("pevt"),promptSessionId:t,at:new Date().toISOString()},a={...e().events,[t]:[...r,p]};i({events:a});const d=e().sessions[t];return $o(d.cwd,e().sessions,a).catch(()=>{}),p},markCompleted:async(t,n)=>{const r=e().sessions[t];if(!r)throw new Error(`markCompleted: no PromptSession with id "${t}"`);if(r.status==="completed")return;await window.api.chat.cancel(t),window.api.pty.kill(r.claudeSessionId);const{worktree:l}=await ay(r),p=r,a=e().events[t]??[],{title:d}=ad(r.goalText),f=a.slice(-1)[0]??null;f&&e().appendPromptSessionEvent(t,{kind:"closed",causedByEventId:f.id});const g=e().events[t]??a,m={...e().events,[t]:g},w=new Date().toISOString(),D={...r,worktree:l,status:"completed",completedAt:w},k={...e().sessions,[t]:D};i({sessions:k});const E=x=>{i({sessions:{...e().sessions,[t]:p},events:{...e().events,[t]:a}}),st.error(`Could not mark "${d}" completed — ${x}`)};try{await $o(r.cwd,k,m,[t])}catch(x){throw E(x instanceof Error?x.message:String(x)),x}Vu("epic_complete",{cwd:r.cwd,epicId:t,source:n??"unknown"});let b="";try{const x=await window.api.transcripts.pathFor(r.cwd,r.claudeSessionId),A=await window.api.config.readText(x);b=A.exists?A.text:""}catch{b=""}let C;if(!b)try{const{turns:x}=await window.api.promptSessionTranscript.read(r.cwd,t);x.length>0&&(C=x.map(A=>({role:A.role,text:A.text,at:A.at})))}catch{C=void 0}const y={session:D,events:e().events[t]??g,transcript:b,archivedAt:w,status:D.status,cwd:D.cwd,indexedAt:w,...C?{durableTurns:C}:{}};try{await window.api.config.writeJson(hE(r.cwd,t),y,"epics")}catch(x){throw E(x instanceof Error?x.message:String(x)),$o(p.cwd,e().sessions,e().events).catch(()=>{}),x}},mergeEpicToMain:async t=>{const n=e().sessions[t];if(!n)throw new Error(`mergeEpicToMain: no PromptSession with id "${t}"`);const{worktree:r,reason:l}=await ay(n,!0),p=e().sessions[t];if(p&&p.worktree===n.worktree){const a={...p,worktree:r};i({sessions:{...e().sessions,[t]:a}}),$o(n.cwd,e().sessions,e().events).catch(()=>{})}return{ok:(r==null?void 0:r.status)==="merged",reason:l}},resumeArchived:async(t,n)=>{const r=e().sessions[t];if(!r)throw new Error(`resumeArchived: no PromptSession with id "${t}"`);const l=n??"unknown",p=await e().createPromptSession(r.cwd,r.goalText,void 0,l),a={...p,resumedFromId:t},d={...e().sessions,[p.id]:a};i({sessions:d}),$o(a.cwd,d,e().events).catch(()=>{});const f=e().approveProposed(a.id,l);return Vu("epic_resume",{cwd:a.cwd,epicId:a.id,source:l}),f??a},renameEpic:async(t,n,r)=>{const l=e().sessions[t];if(!l)throw new Error(`renameEpic: no PromptSession with id "${t}"`);const p=n.trim().replace(/\s*\n+\s*/g," ");if(!p)throw new Error("renameEpic: title must not be empty");const a=`${p}
|
|
44
44
|
|
|
45
45
|
${r}`,d={...l,goalText:a},f={...e().sessions,[t]:d};i({sessions:f});try{await $o(l.cwd,f,e().events)}catch(g){throw i({sessions:{...e().sessions,[t]:l}}),g}},duplicateEpic:async(t,n)=>{const r=e().sessions[t];if(!r)throw new Error(`duplicateEpic: no PromptSession with id "${t}"`);const l=n??"unknown",p=await e().createPromptSession(r.cwd,r.goalText,r.tag,l),a=e().approveProposed(p.id,l)??p;return Vu("epic_duplicate",{cwd:r.cwd,epicId:a.id,source:l}),a},deleteEpic:async(t,n)=>{var m;const r=e().sessions[t];if(!r)throw new Error(`deleteEpic: no PromptSession with id "${t}"`);if((((m=Or.getState().snapshot)==null?void 0:m.jobs)??[]).some(w=>(w.status==="running"||w.status==="pending")&&SS(w).includes(t)))throw new Error("deleteEpic: this Epic has a running or queued scheduler job — cancel it first");const p=hi.getState().chats[t];if(p&&(p.running||p.queuedPosition>0))throw new Error("deleteEpic: this Epic has a chat run in flight — wait for it to finish first");if(el.getState().isAttached(t))throw new Error("deleteEpic: this Epic has a live Terminal session attached — detach it first");const a=e().sessions,d=e().events,f={...a},g={...d};delete f[t],delete g[t],i({sessions:f,events:g});try{await $o(r.cwd,f,g,[t])}catch(w){throw i({sessions:a,events:d}),w}Vu("epic_delete",{cwd:r.cwd,epicId:t,source:n??"unknown"})},hydrate:async t=>{var n,r,l,p;if(!(typeof window>"u"||!((r=(n=window.api)==null?void 0:n.config)!=null&&r.readJson)))try{const a=Wb(t),d=await window.api.config.readJson(a),f=d.exists&&d.data?d.data:{},g=f.sessions??{},m=f.events??{},w=e().sessions,D=Object.keys(g).filter(y=>!w[y]),k=pE(a)?[]:Object.keys(w).filter(y=>w[y].cwd===t&&(w[y].status==="active"||w[y].status==="proposed")&&!g[y]),E={...w},b={...e().events};let C=!1;for(const y of D)E[y]=g[y],b[y]=m[y]??[],ly.add(y),C=!0;for(const y of k)delete E[y],delete b[y],C=!0;for(const y of Object.keys(m)){if(!w[y]||D.includes(y))continue;const x=m[y]??[],A=b[y]??[],P=new Set(A.map(L=>L.id)),N=x.filter(L=>!P.has(L.id));N.length>0&&(b[y]=[...A,...N].sort(sy),C=!0)}if(!C)return;i({sessions:E,events:b})}catch(a){const d=a instanceof Error?a.message:String(a);(p=(l=window.api)==null?void 0:l.logs)==null||p.write("promptSessions","warn",`hydrate failed for ${t}: ${d}`)}},hydrateArchived:async t=>{var n,r,l,p,a,d;if(!(typeof window>"u"||!((r=(n=window.api)==null?void 0:n.config)!=null&&r.listDir)||!((p=(l=window.api)==null?void 0:l.config)!=null&&p.readJson)))try{const f=`${t.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions`,g=await window.api.config.listDir(f,{filesOnly:!0});if(!g.ok)return;const w={...e().sessions},D={...e().events};let k=!1;const E=[];for(const b of g.entries){if(!b.name.endsWith(".json")||b.name==="active-index.json")continue;const C=b.name.slice(0,-5),y=w[C],x=!!y&&y.status!=="completed"&&ly.has(C);if(y&&!x)continue;const A=await window.api.config.readJson(b.path);if(!A.exists||!A.data)continue;const P=A.data;!P.session||P.session.id!==C||(w[C]={...P.session,status:"completed"},D[C]=P.events??[],k=!0,x&&E.push(C))}if(!k)return;i({sessions:w,events:D}),E.length>0&&$o(t,w,D,E).catch(()=>{})}catch(f){const g=f instanceof Error?f.message:String(f);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("promptSessions","warn",`hydrateArchived failed for ${t}: ${g}`)}},mergeAppendedEvent:(t,n,r)=>{const l=e().sessions[n];if(!l||l.cwd!==t)return;const p=e().events[n]??[];if(p.some(d=>d.id===r.id))return;const a={...e().events,[n]:[...p,r].sort(sy)};if(i({events:a}),r.kind==="response"&&n!==e().focusedEpicId){const{title:d}=ad(l.goalText),f=r.text?/^PRD (\S+) finished/.exec(r.text):null,g=f?`PRD ${f[1]} finished`:"Epic updated";st.info(`${g} — ${d}`)}}}));var mS;typeof window<"u"&&((mS=window.api)!=null&&mS.promptSessions)&&window.api.promptSessions.onEventAppended(({cwd:i,promptSessionId:e,event:t})=>{Kt.getState().mergeAppendedEvent(i,e,t)});const cy=2e3,fE=300;function Ll(i){return typeof i!="string"||i.length===0?{}:i.length<=cy?{text:i}:{text:i.slice(0,cy)+"…",textTruncated:!0}}function zl(i){return!Array.isArray(i)||i.length===0?{}:{names:i.filter(t=>typeof t=="string").slice(0,fE),count:i.length}}function Ts(i){return i&&typeof i=="object"&&!Array.isArray(i)?i:null}function Ri(i){return typeof i=="string"?i:void 0}function mE(i){if(i.startsWith("mcp__")){const e=i.split("__");return{kind:"mcp",label:e[e.length-1]||i}}return i==="Skill"?{kind:"skill",label:"Skill"}:{kind:"tool",label:i}}function gE(i){for(const e of i.split(`
|
|
46
46
|
`)){const t=e.trim();if(t)return t.length>200?t.slice(0,200)+"…":t}return""}function CS(i){let e="",t=!1;const n=Ts(i.message),r=n==null?void 0:n.content;if(Array.isArray(r))for(const l of r){const p=Ts(l);if(!(!p||p.type!=="tool_result")){if(p.is_error===!0&&(t=!0),typeof p.content=="string")e=e?e+`
|
|
@@ -2907,7 +2907,7 @@ ${I}`,M=v.createShaderModule({code:R,label:s.name});si("verbose",()=>`[WebGPU] $
|
|
|
2907
2907
|
* ONNX Runtime Web v1.26.0
|
|
2908
2908
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2909
2909
|
* Licensed under the MIT License.
|
|
2910
|
-
*/var Oy;function nT(){return Oy||(Oy=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof io<"u"?io:typeof Proxy<"u"?new Proxy(Y,{get:(se,ue)=>(typeof io<"u"?io:se)[ue]}):Y)(function(Y){if(typeof io<"u")return io.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),d=(Y,se)=>()=>(Y&&(se=Y(Y=0)),se),f=(Y,se)=>{for(var ue in se)n(Y,ue,{get:se[ue],enumerable:!0})},g=(Y,se,ue,Ee)=>{if(se&&typeof se=="object"||typeof se=="function")for(let ye of l(se))!p.call(Y,ye)&&ye!==ue&&n(Y,ye,{get:()=>se[ye],enumerable:!(Ee=r(se,ye))||Ee.enumerable});return Y},m=Y=>g(n({},"__esModule",{value:!0}),Y),w,D,k,E,b,C=d(()=>{w=new Map,D=[],k=(Y,se,ue)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Ee=w.get(Y);if(Ee===void 0)w.set(Y,{backend:se,priority:ue});else{if(Ee.priority>ue)return;if(Ee.priority===ue&&Ee.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${ue}`)}if(ue>=0){let ye=D.indexOf(Y);ye!==-1&&D.splice(ye,1);for(let Le=0;Le<D.length;Le++)if(w.get(D[Le]).priority<=ue){D.splice(Le,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},E=async Y=>{let se=w.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let ue=!!se.initPromise;try{return ue||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Ee){return ue||(se.error=`${Ee}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],ue=se.map(Be=>typeof Be=="string"?Be:Be.name),Ee=ue.length===0?D:ue,ye,Le=[],De=new Set;for(let Be of Ee){let et=await E(Be);typeof et=="string"?Le.push({name:Be,err:et}):(ye||(ye=et),ye===et&&De.add(Be))}if(!ye)throw new Error(`no available backend found. ERR: ${Le.map(Be=>`[${Be.name}] ${Be.err}`).join(", ")}`);for(let{name:Be,err:et}of Le)ue.includes(Be)&&console.warn(`removing requested execution provider "${Be}" from session options because it is not available: ${et}`);let Ae=se.filter(Be=>De.has(typeof Be=="string"?Be:Be.name));return[ye,new Proxy(Y,{get:(Be,et)=>et==="executionProviders"?Ae:Reflect.get(Be,et)})]}}),y=d(()=>{C()}),x,A=d(()=>{x="1.26.0"}),P,N,L=d(()=>{A(),P="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);P=Y}},get logLevel(){return P}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,H=d(()=>{L(),j=N}),W,re,de=d(()=>{W=(Y,se)=>{let ue=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ue.width=Y.dims[3],ue.height=Y.dims[2];let Ee=ue.getContext("2d");if(Ee!=null){let ye,Le;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(ye=Y.dims[2],Le=Y.dims[3]):(ye=Y.dims[3],Le=Y.dims[2]);let De=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Be,et;Ae===void 0||Ae.mean===void 0?Be=[255,255,255,255]:typeof Ae.mean=="number"?Be=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Be=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Be[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?et=[0,0,0,0]:typeof Ae.bias=="number"?et=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(et=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(et[3]=Ae.bias[3]));let rt=Le*ye,tt=0,Xe=rt,It=rt*2,Oe=-1;De==="RGBA"?(tt=0,Xe=rt,It=rt*2,Oe=rt*3):De==="RGB"?(tt=0,Xe=rt,It=rt*2):De==="RBG"&&(tt=0,It=rt,Xe=rt*2);for(let ht=0;ht<Le;ht++)for(let Ei=0;Ei<ye;Ei++){let Qt=(Y.data[tt++]-et[0])*Be[0],ei=(Y.data[Xe++]-et[1])*Be[1],Ti=(Y.data[It++]-et[2])*Be[2],Ot=Oe===-1?255:(Y.data[Oe++]-et[3])*Be[3];Ee.fillStyle="rgba("+Qt+","+ei+","+Ti+","+Ot+")",Ee.fillRect(Ei,ht,1,1)}if("toDataURL"in ue)return ue.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},re=(Y,se)=>{let ue=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Ee;if(ue!=null){let ye,Le,De;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(ye=Y.dims[2],Le=Y.dims[1],De=Y.dims[3]):(ye=Y.dims[3],Le=Y.dims[2],De=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Be=se==null?void 0:se.norm,et,rt;Be===void 0||Be.mean===void 0?et=[255,255,255,255]:typeof Be.mean=="number"?et=[Be.mean,Be.mean,Be.mean,Be.mean]:(et=[Be.mean[0],Be.mean[1],Be.mean[2],255],Be.mean[3]!==void 0&&(et[3]=Be.mean[3])),Be===void 0||Be.bias===void 0?rt=[0,0,0,0]:typeof Be.bias=="number"?rt=[Be.bias,Be.bias,Be.bias,Be.bias]:(rt=[Be.bias[0],Be.bias[1],Be.bias[2],0],Be.bias[3]!==void 0&&(rt[3]=Be.bias[3]));let tt=Le*ye;if(se!==void 0&&(se.format!==void 0&&De===4&&se.format!=="RGBA"||De===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,It=0,Oe=1,ht=2,Ei=3,Qt=0,ei=tt,Ti=tt*2,Ot=-1;Ae==="RGBA"?(Qt=0,ei=tt,Ti=tt*2,Ot=tt*3):Ae==="RGB"?(Qt=0,ei=tt,Ti=tt*2):Ae==="RBG"&&(Qt=0,Ti=tt,ei=tt*2),Ee=ue.createImageData(ye,Le);for(let Ni=0;Ni<Le*ye;It+=Xe,Oe+=Xe,ht+=Xe,Ei+=Xe,Ni++)Ee.data[It]=(Y.data[Qt++]-rt[0])*et[0],Ee.data[Oe]=(Y.data[ei++]-rt[1])*et[1],Ee.data[ht]=(Y.data[Ti++]-rt[2])*et[2],Ee.data[Ei]=Ot===-1?255:(Y.data[Ot++]-rt[3])*et[3]}else throw new Error("Can not access image data");return Ee}}),Z,me,te,pe,_e,Ce,U=d(()=>{Ie(),Z=(Y,se)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(se.height===void 0||se.width===void 0)throw new Error("Image height and width must be defined");if(se.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ue,width:Ee}=se,ye=se.norm??{mean:255,bias:0},Le,De;typeof ye.mean=="number"?Le=[ye.mean,ye.mean,ye.mean,ye.mean]:Le=[ye.mean[0],ye.mean[1],ye.mean[2],ye.mean[3]??255],typeof ye.bias=="number"?De=[ye.bias,ye.bias,ye.bias,ye.bias]:De=[ye.bias[0],ye.bias[1],ye.bias[2],ye.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Be=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",et=ue*Ee,rt=Be==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,It=1,Oe=2,ht=3,Ei=0,Qt=et,ei=et*2,Ti=-1;Ae==="RGB"&&(tt=3,Xe=0,It=1,Oe=2,ht=-1),Be==="RGBA"?Ti=et*3:Be==="RBG"?(Ei=0,ei=et,Qt=et*2):Be==="BGR"&&(ei=0,Qt=et,Ei=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,Oe+=tt,It+=tt,ht+=tt)rt[Ei++]=(Y[Xe]+De[0])/Le[0],rt[Qt++]=(Y[It]+De[1])/Le[1],rt[ei++]=(Y[Oe]+De[2])/Le[2],Ti!==-1&&ht!==-1&&(rt[Ti++]=(Y[ht]+De[3])/Le[3]);return Be==="RGBA"?new X("float32",rt,[1,4,ue,Ee]):new X("float32",rt,[1,3,ue,Ee])},me=async(Y,se)=>{let ue=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Ee=typeof ImageData<"u"&&Y instanceof ImageData,ye=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Le=typeof Y=="string",De,Ae=se??{},Be=()=>{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=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(ue){let rt=Be();rt.width=Y.width,rt.height=Y.height;let tt=et(rt);if(tt!=null){let Xe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(Xe=se.resizedHeight,It=se.resizedWidth),se!==void 0){if(Ae=se,se.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=Xe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=Xe,Ae.width=It;tt.drawImage(Y,0,0),De=tt.getImageData(0,0,It,Xe).data}else throw new Error("Can not access image data")}else if(Ee){let rt,tt;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,tt=se.resizedWidth):(rt=Y.height,tt=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=tt,se!==void 0){let Xe=Be();Xe.width=tt,Xe.height=rt;let It=et(Xe);if(It!=null)It.putImageData(Y,0,0),De=It.getImageData(0,0,tt,rt).data;else throw new Error("Can not access image data")}else De=Y.data}else if(ye){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Be();rt.width=Y.width,rt.height=Y.height;let tt=et(rt);if(tt!=null){let Xe=Y.height,It=Y.width;return tt.drawImage(Y,0,0,It,Xe),De=tt.getImageData(0,0,It,Xe).data,Ae.height=Xe,Ae.width=It,Z(De,Ae)}else throw new Error("Can not access image data")}else{if(Le)return new Promise((rt,tt)=>{let Xe=Be(),It=et(Xe);if(!Y||!It)return tt();let Oe=new Image;Oe.crossOrigin="Anonymous",Oe.src=Y,Oe.onload=()=>{Xe.width=Oe.width,Xe.height=Oe.height,It.drawImage(Oe,0,0,Xe.width,Xe.height);let ht=It.getImageData(0,0,Xe.width,Xe.height);Ae.height=Xe.height,Ae.width=Xe.width,rt(Z(ht.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(De!==void 0)return Z(De,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(Y,se)=>{let{width:ue,height:Ee,download:ye,dispose:Le}=se,De=[1,Ee,ue,4];return new X({location:"texture",type:"float32",texture:Y,dims:De,download:ye,dispose:Le})},pe=(Y,se)=>{let{dataType:ue,dims:Ee,download:ye,dispose:Le}=se;return new X({location:"gpu-buffer",type:ue??"float32",gpuBuffer:Y,dims:Ee,download:ye,dispose:Le})},_e=(Y,se)=>{let{dataType:ue,dims:Ee,download:ye,dispose:Le}=se;return new X({location:"ml-tensor",type:ue??"float32",mlTensor:Y,dims:Ee,download:ye,dispose:Le})},Ce=(Y,se,ue)=>new X({location:"cpu-pinned",type:Y,data:se,dims:ue??[se.length]})}),ie,q,oe,ge,ke=d(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),oe=!1,ge=()=>{if(!oe){oe=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,ue=globalThis.Float16Array,Ee=typeof ue<"u"&&ue.from;Y&&(ie.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),se&&(ie.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),Ee?(ie.set("float16",ue),q.set(ue,"float16")):ie.set("float16",Uint16Array)}}}),$e,He,ve=d(()=>{Ie(),$e=Y=>{let se=1;for(let ue=0;ue<Y.length;ue++){let Ee=Y[ue];if(typeof Ee!="number"||!Number.isSafeInteger(Ee))throw new TypeError(`dims[${ue}] must be an integer, got: ${Ee}`);if(Ee<0)throw new RangeError(`dims[${ue}] must be a non-negative integer, got: ${Ee}`);se*=Ee}return se},He=(Y,se)=>{switch(Y.location){case"cpu":return new X(Y.type,Y.data,se);case"cpu-pinned":return new X({location:"cpu-pinned",data:Y.data,type:Y.type,dims:se});case"texture":return new X({location:"texture",texture:Y.texture,type:Y.type,dims:se});case"gpu-buffer":return new X({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:se});case"ml-tensor":return new X({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:se});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),X,Ie=d(()=>{de(),U(),ke(),ve(),X=class{constructor(Y,se,ue){ge();let Ee,ye;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Ee=Y.type,ye=Y.dims,Y.location){case"cpu-pinned":{let De=ie.get(Ee);if(!De)throw new TypeError(`unsupported type "${Ee}" to create tensor from pinned buffer`);if(!(Y.data instanceof De))throw new TypeError(`buffer should be of type ${De.name}`);this.cpuData=Y.data;break}case"texture":{if(Ee!=="float32")throw new TypeError(`unsupported type "${Ee}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Ee!=="float32"&&Ee!=="float16"&&Ee!=="int32"&&Ee!=="int64"&&Ee!=="uint32"&&Ee!=="uint8"&&Ee!=="bool"&&Ee!=="uint4"&&Ee!=="int4")throw new TypeError(`unsupported type "${Ee}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Ee!=="float32"&&Ee!=="float16"&&Ee!=="int32"&&Ee!=="int64"&&Ee!=="uint32"&&Ee!=="uint64"&&Ee!=="int8"&&Ee!=="uint8"&&Ee!=="bool"&&Ee!=="uint4"&&Ee!=="int4")throw new TypeError(`unsupported type "${Ee}" to create tensor from MLTensor`);this.mlTensorData=Y.mlTensor,this.downloader=Y.download,this.disposer=Y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let De,Ae;if(typeof Y=="string")if(Ee=Y,Ae=ue,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");De=se}else{let Be=ie.get(Y);if(Be===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Be===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Be.name} as data.`);Y==="uint64"||Y==="int64"?De=Be.from(se,BigInt):De=Be.from(se)}else if(se instanceof Be)De=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")De=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Be!==Uint16Array)De=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Ee} tensor's data must be type of ${Be}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Be=typeof Y[0];if(Be==="string")Ee="string",De=Y;else if(Be==="boolean")Ee="bool",De=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Be}.`)}else if(Y instanceof Uint8ClampedArray)Ee="uint8",De=Uint8Array.from(Y);else{let Be=q.get(Y.constructor);if(Be===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Ee=Be,De=Y}if(Ae===void 0)Ae=[De.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");ye=Ae,this.cpuData=De,this.dataLocation="cpu"}let Le=$e(ye);if(this.cpuData&&Le!==this.cpuData.length&&!((Ee==="uint4"||Ee==="int4")&&Math.ceil(Le/2)===this.cpuData.length))throw new Error(`Tensor's size(${Le}) does not match data length(${this.cpuData.length}).`);this.type=Ee,this.dims=ye,this.size=Le}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return te(Y,se)}static fromGpuBuffer(Y,se){return pe(Y,se)}static fromMLTensor(Y,se){return _e(Y,se)}static fromPinnedBuffer(Y,se,ue){return Ce(Y,se,ue)}toDataURL(Y){return W(this,Y)}toImageData(Y){return re(this,Y)}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(Y){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 se=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=se,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),se}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(Y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return He(this,Y)}}}),he,Pe=d(()=>{Ie(),he=X}),Qe,pt,Pt,dt,Yt,Fe,Ct=d(()=>{L(),Qe=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},pt=(Y,se)=>{var ye;let ue=((ye=new Error().stack)==null?void 0:ye.split(/\r\n|\r|\n/g))||[],Ee=!1;for(let Le=0;Le<ue.length;Le++){if(Ee&&!ue[Le].includes("TRACE_FUNC")){let De=`FUNC_${Y}::${ue[Le].trim().split(" ")[1]}`;se&&(De+=`::${se}`),Qe("CPU",De);return}ue[Le].includes("TRACE_FUNC")&&(Ee=!0)}},Pt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||pt("BEGIN",Y)},dt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||pt("END",Y)},Yt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Fe=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),Me,ot=d(()=>{C(),Pe(),Ct(),Me=class GS{constructor(se){this.handler=se}async run(se,ue,Ee){Pt(),Yt("InferenceSession.run");let ye={},Le={};if(typeof se!="object"||se===null||se instanceof he||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let De=!0;if(typeof ue=="object"){if(ue===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ue instanceof he)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ue)){if(ue.length===0)throw new TypeError("'fetches' cannot be an empty array.");De=!1;for(let et of ue){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}.`);ye[et]=null}if(typeof Ee=="object"&&Ee!==null)Le=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,rt=Object.getOwnPropertyNames(ue);for(let tt of this.outputNames)if(rt.indexOf(tt)!==-1){let Xe=ue[tt];(Xe===null||Xe instanceof he)&&(et=!0,De=!1,ye[tt]=Xe)}if(et){if(typeof Ee=="object"&&Ee!==null)Le=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else Le=ue}}else if(typeof ue<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof se[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(De)for(let et of this.outputNames)ye[et]=null;let Ae=await this.handler.run(se,ye,Le),Be={};for(let et in Ae)if(Object.hasOwnProperty.call(Ae,et)){let rt=Ae[et];rt instanceof he?Be[et]=rt:Be[et]=new he(rt.type,rt.data,rt.dims)}return Fe("InferenceSession.run"),dt(),Be}async release(){return this.handler.dispose()}static async create(se,ue,Ee,ye){Pt(),Yt("InferenceSession.create");let Le,De={};if(typeof se=="string"){if(Le=se,typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Le=se,typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,tt=0,Xe=se.byteLength;if(typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue=="number"){if(tt=ue,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(Xe=se.byteLength-tt,typeof Ee=="number"){if(Xe=Ee,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-tt}].`);if(typeof ye=="object"&&ye!==null)De=ye;else if(typeof ye<"u")throw new TypeError("'options' must be an object.")}else if(typeof Ee<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ue<"u")throw new TypeError("'options' must be an object.");Le=new Uint8Array(rt,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Be]=await b(De),et=await Ae.createInferenceSessionHandler(Le,Be);return Fe("InferenceSession.create"),dt(),new GS(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}}}),ze,ft=d(()=>{ot(),ze=Me}),ct=d(()=>{}),Zt=d(()=>{}),ai=d(()=>{}),Zi=d(()=>{}),$n={};f($n,{InferenceSession:()=>ze,TRACE:()=>Qe,TRACE_EVENT_BEGIN:()=>Yt,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>Pt,TRACE_FUNC_END:()=>dt,Tensor:()=>he,env:()=>j,registerBackend:()=>k});var ci=d(()=>{y(),H(),ft(),Pe(),ct(),Zt(),Ct(),ai(),Zi()}),hn=d(()=>{}),Ai={};f(Ai,{default:()=>it});var Wi,di,it,ri=d(()=>{var Y;fe(),Yn(),Kn(),Wi="ort-wasm-proxy-worker",di=((Y=globalThis.self)==null?void 0:Y.name)===Wi,di&&(self.onmessage=se=>{let{type:ue,in:Ee}=se.data;try{switch(ue){case"init-wasm":ir(Ee.wasm).then(()=>{Bo(Ee).then(()=>{postMessage({type:ue})},ye=>{postMessage({type:ue,err:ye})})},ye=>{postMessage({type:ue,err:ye})});break;case"init-ep":{let{epName:ye,env:Le}=Ee;Sr(Le,ye).then(()=>{postMessage({type:ue})},De=>{postMessage({type:ue,err:De})});break}case"copy-from":{let{buffer:ye}=Ee,Le=si(ye);postMessage({type:ue,out:Le});break}case"create":{let{model:ye,options:Le}=Ee;ms(ye,Le).then(De=>{postMessage({type:ue,out:De})},De=>{postMessage({type:ue,err:De})});break}case"release":Fr(Ee),postMessage({type:ue});break;case"run":{let{sessionId:ye,inputIndices:Le,inputs:De,outputIndices:Ae,options:Be}=Ee;Ye(ye,Le,De,Ae,new Array(Ae.length).fill(null),Be).then(et=>{et.some(rt=>rt[3]!=="cpu")?postMessage({type:ue,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ue,out:et},vt([...De,...et]))},et=>{postMessage({type:ue,err:et})});break}case"end-profiling":Jn(Ee),postMessage({type:ue});break;default:}}catch(ye){postMessage({type:ue,err:ye})}}),it=di?null:se=>new Worker(se??pi,{type:"classic",name:Wi})}),gi,pn,pi,an,Ui,Os,Ls,us,zr,br,wr,zs,Ln,Kn=d(()=>{hn(),gi=typeof location>"u"?void 0:location.origin,pn=()=>{var Y,se;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(se=self.location)==null?void 0:se.href:void 0},pi=pn(),an=()=>{if(pi&&!pi.startsWith("blob:"))return pi.substring(0,pi.lastIndexOf("/")+1)},Ui=(Y,se)=>{try{let ue=se??pi;return(ue?new URL(Y,ue):new URL(Y)).origin===gi}catch{return!1}},Os=(Y,se)=>{let ue=se??pi;try{return(ue?new URL(Y,ue):new URL(Y)).href}catch{return}},Ls=(Y,se)=>`${se??"./"}${Y}`,us=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},zr=async Y=>(await import(Y)).default,br=(ri(),m(Ai)).default,wr=async()=>{if(!pi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ui(pi))return[void 0,br()];let Y=await us(pi);return[Y,br(Y)]},zs=void 0,Ln=async(Y,se,ue,Ee)=>{let ye=zs&&!(Y||se);if(ye)if(pi)ye=Ui(pi)||Ee&&!ue;else if(Ee&&!ue)ye=!0;else throw new Error("cannot determine the script source URL.");if(ye)return[void 0,zs];{let Le="ort-wasm-simd-threaded.mjs",De=Y??Os(Le,se),Ae=ue&&De&&!Ui(De,se),Be=Ae?await us(De):De??Ls(Le,se);return[Ae?Be:void 0,await zr(Be)]}}}),Qs,zn,hs,$s,ro,er,tr,ir,zt,Yn=d(()=>{Kn(),zn=!1,hs=!1,$s=!1,ro=()=>{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}},er=()=>{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}},tr=()=>{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}},ir=async Y=>{if(zn)return Promise.resolve();if(hs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if($s)throw new Error("previous call to 'initializeWebAssembly()' failed.");hs=!0;let se=Y.initTimeout,ue=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!tr())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!er())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Ee=ro();ue>1&&!Ee&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ue+", 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."),Y.numThreads=ue=1);let ye=Y.wasmPaths,Le=typeof ye=="string"?ye:void 0,De=ye==null?void 0:ye.mjs,Ae=(De==null?void 0:De.href)??De,Be=ye==null?void 0:ye.wasm,et=(Be==null?void 0:Be.href)??Be,rt=Y.wasmBinary,[tt,Xe]=await Ln(Ae,Le,ue>1,!!rt||!!et),It=!1,Oe=[];if(se>0&&Oe.push(new Promise(ht=>{setTimeout(()=>{It=!0,ht()},se)})),Oe.push(new Promise((ht,Ei)=>{let Qt={numThreads:ue};if(rt)Qt.wasmBinary=rt,Qt.locateFile=ei=>ei;else if(et||Le)Qt.locateFile=ei=>et??Le+ei;else if(Ae&&Ae.indexOf("blob:")!==0)Qt.locateFile=ei=>new URL(ei,Ae).href;else if(tt){let ei=an();ei&&(Qt.locateFile=Ti=>ei+Ti)}Xe(Qt).then(ei=>{hs=!1,zn=!0,Qs=ei,ht(),tt&&URL.revokeObjectURL(tt)},ei=>{hs=!1,$s=!0,Ei(ei)})})),await Promise.race(Oe),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(zn&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Vi,Si,Et,Br=d(()=>{Yn(),Vi=(Y,se)=>{let ue=zt(),Ee=ue.lengthBytesUTF8(Y)+1,ye=ue._malloc(Ee);return ue.stringToUTF8(Y,ye,Ee),se.push(ye),ye},Si=(Y,se,ue,Ee)=>{if(typeof Y=="object"&&Y!==null){if(ue.has(Y))throw new Error("Circular reference in options");ue.add(Y)}Object.entries(Y).forEach(([ye,Le])=>{let De=se?se+ye:ye;if(typeof Le=="object")Si(Le,De+".",ue,Ee);else if(typeof Le=="string"||typeof Le=="number")Ee(De,Le.toString());else if(typeof Le=="boolean")Ee(De,Le?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Le}`)})},Et=Y=>{let se=zt(),ue=se.stackSave();try{let Ee=se.PTR_SIZE,ye=se.stackAlloc(2*Ee);se._OrtGetLastError(ye,ye+Ee);let Le=Number(se.getValue(ye,Ee===4?"i32":"i64")),De=se.getValue(ye+Ee,"*"),Ae=De?se.UTF8ToString(De):"";throw new Error(`${Y} ERROR_CODE: ${Le}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(ue)}}}),oo,wa=d(()=>{Yn(),Br(),oo=Y=>{let se=zt(),ue=0,Ee=[],ye=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)ye.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)ye.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(ye.terminate=!1);let Le=0;return(Y==null?void 0:Y.tag)!==void 0&&(Le=Vi(Y.tag,Ee)),ue=se._OrtCreateRunOptions(ye.logSeverityLevel,ye.logVerbosityLevel,!!ye.terminate,Le),ue===0&&Et("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&Si(Y.extra,"",new WeakSet,(De,Ae)=>{let Be=Vi(De,Ee),et=Vi(Ae,Ee);se._OrtAddRunConfigEntry(ue,Be,et)!==0&&Et(`Can't set a run config entry: ${De} - ${Ae}.`)}),[ue,Ee]}catch(Le){throw ue!==0&&se._OrtReleaseRunOptions(ue),Ee.forEach(De=>se._free(De)),Le}}}),ao,lo,zo,In,ya,xa,Ci=d(()=>{Yn(),Br(),ao=Y=>{switch(Y){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: ${Y}`)}},lo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},zo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let se=Y.extra.session;se.use_ort_model_bytes_directly||(se.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(ue=>(typeof ue=="string"?ue:ue.name)==="webgpu")&&(Y.enableMemPattern=!1)},In=(Y,se,ue,Ee)=>{let ye=Vi(se,Ee),Le=Vi(ue,Ee);zt()._OrtAddSessionConfigEntry(Y,ye,Le)!==0&&Et(`Can't set a session config entry: ${se} - ${ue}.`)},ya=async(Y,se,ue)=>{let Ee=se.executionProviders;for(let ye of Ee){let Le=typeof ye=="string"?ye:ye.name,De=[];switch(Le){case"webnn":if(Le="WEBNN",In(Y,"session.disable_quant_qdq","1",ue),In(Y,"session.disable_qdq_constant_folding","1",ue),typeof ye!="string"){let tt=ye==null?void 0:ye.deviceType;tt&&In(Y,"deviceType",tt,ue)}break;case"webgpu":if(Le="JS",typeof ye!="string"){let tt=ye;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);In(Y,"preferredLayout",tt.preferredLayout,ue)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Le}`)}let Ae=Vi(Le,ue),Be=De.length,et=0,rt=0;if(Be>0){et=zt()._malloc(Be*zt().PTR_SIZE),ue.push(et),rt=zt()._malloc(Be*zt().PTR_SIZE),ue.push(rt);for(let tt=0;tt<Be;tt++)zt().setValue(et+tt*zt().PTR_SIZE,De[tt][0],"*"),zt().setValue(rt+tt*zt().PTR_SIZE,De[tt][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,et,rt,Be)!==0&&Et(`Can't append execution provider: ${Le}.`)}},xa=async Y=>{let se=zt(),ue=0,Ee=[],ye=Y||{};zo(ye);try{let Le=ao(ye.graphOptimizationLevel??"all"),De=lo(ye.executionMode??"sequential"),Ae=typeof ye.logId=="string"?Vi(ye.logId,Ee):0,Be=ye.logSeverityLevel??2;if(!Number.isInteger(Be)||Be<0||Be>4)throw new Error(`log severity level is not valid: ${Be}`);let et=ye.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let rt=typeof ye.optimizedModelFilePath=="string"?Vi(ye.optimizedModelFilePath,Ee):0;if(ue=se._OrtCreateSessionOptions(Le,!!ye.enableCpuMemArena,!!ye.enableMemPattern,De,!!ye.enableProfiling,0,Ae,Be,et,rt),ue===0&&Et("Can't create session options."),ye.executionProviders&&await ya(ue,ye,Ee),ye.enableGraphCapture!==void 0){if(typeof ye.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ye.enableGraphCapture}`);In(ue,"enableGraphCapture",ye.enableGraphCapture.toString(),Ee)}if(ye.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(ye.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let It=Vi(tt,Ee);se._OrtAddFreeDimensionOverride(ue,It,Xe)!==0&&Et(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return ye.extra!==void 0&&Si(ye.extra,"",new WeakSet,(tt,Xe)=>{In(ue,tt,Xe,Ee)}),[ue,Ee]}catch(Le){throw ue!==0&&se._OrtReleaseSessionOptions(ue)!==0&&Et("Can't release session options."),Ee.forEach(De=>se._free(De)),Le}}}),Bn,Ki,Gn,nr,Gr,yr,ps,wn,Bt=d(()=>{Bn=Y=>{switch(Y){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: ${Y}`)}},Ki=Y=>{switch(Y){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: ${Y}`)}},Gn=(Y,se)=>{let ue=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Y],Ee=typeof se=="number"?se:se.reduce((ye,Le)=>ye*Le,1);return ue>0?Math.ceil(Ee*ue):void 0},nr=Y=>{switch(Y){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: ${Y}`)}},Gr=Y=>{switch(Y){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: ${Y}`)}},yr=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",ps=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",wn=Y=>{switch(Y){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: ${Y}`)}}}),Yi,xr=d(()=>{hn(),Yi=async Y=>{if(typeof Y=="string"){let se=await fetch(Y);if(!se.ok)throw new Error(`failed to load external data file: ${Y}`);let ue=se.headers.get("Content-Length"),Ee=ue?parseInt(ue,10):0;if(Ee<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let ye=se.body.getReader(),Le;try{Le=new ArrayBuffer(Ee)}catch(Ae){if(Ae instanceof RangeError){let Be=Math.ceil(Ee/65536);Le=new WebAssembly.Memory({initial:Be,maximum:Be}).buffer}else throw Ae}let De=0;for(;;){let{done:Ae,value:Be}=await ye.read();if(Ae)break;let et=Be.byteLength;new Uint8Array(Le,De,et).set(Be),De+=et}return new Uint8Array(Le,0,Ee)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),fs,Bo,Sr,Xn,Bs,Cr,si,ms,Fr,Is,Ye,Jn,vt,fe=d(()=>{ci(),wa(),Ci(),Bt(),Yn(),Br(),xr(),fs=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&Et("Can't initialize onnxruntime.")},Bo=async Y=>{fs(Y.wasm.numThreads,Gr(Y.logLevel))},Sr=async(Y,se)=>{var Ee,ye;(ye=(Ee=zt()).asyncInit)==null||ye.call(Ee);let ue=Y.webgpu.adapter;if(se==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ue){if(typeof ue.limits!="object"||typeof ue.features!="object"||typeof ue.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Le=Y.webgpu.powerPreference;if(Le!==void 0&&Le!=="low-power"&&Le!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Le}"`);let De=Y.webgpu.forceFallbackAdapter;if(De!==void 0&&typeof De!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${De}"`);if(ue=await navigator.gpu.requestAdapter({powerPreference:Le,forceFallbackAdapter:De}),!ue)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(se==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Xn=new Map,Bs=Y=>{let se=zt(),ue=se.stackSave();try{let Ee=se.PTR_SIZE,ye=se.stackAlloc(2*Ee);se._OrtGetInputOutputCount(Y,ye,ye+Ee)!==0&&Et("Can't get session input/output count.");let Le=Ee===4?"i32":"i64";return[Number(se.getValue(ye,Le)),Number(se.getValue(ye+Ee,Le))]}finally{se.stackRestore(ue)}},Cr=(Y,se)=>{let ue=zt(),Ee=ue.stackSave(),ye=0;try{let Le=ue.PTR_SIZE,De=ue.stackAlloc(2*Le);ue._OrtGetInputOutputMetadata(Y,se,De,De+Le)!==0&&Et("Can't get session input/output metadata.");let Ae=Number(ue.getValue(De,"*"));ye=Number(ue.getValue(De+Le,"*"));let Be=ue.HEAP32[ye/4];if(Be===0)return[Ae,0];let et=ue.HEAPU32[ye/4+1],rt=[];for(let tt=0;tt<et;tt++){let Xe=Number(ue.getValue(ye+8+tt*Le,"*"));rt.push(Xe!==0?ue.UTF8ToString(Xe):Number(ue.getValue(ye+8+(tt+et)*Le,"*")))}return[Ae,Be,rt]}finally{ue.stackRestore(Ee),ye!==0&&ue._OrtFree(ye)}},si=Y=>{let se=zt(),ue=se._malloc(Y.byteLength);if(ue===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,ue),[ue,Y.byteLength]},ms=async(Y,se)=>{var rt,tt,Xe;let ue,Ee,ye=zt();Array.isArray(Y)?[ue,Ee]=Y:Y.buffer===ye.HEAPU8.buffer?[ue,Ee]=[Y.byteOffset,Y.byteLength]:[ue,Ee]=si(Y);let Le=0,De=0,Ae=[],Be=[],et=[];try{if([De,Ae]=await xa(se),(se==null?void 0:se.externalData)&&ye.mountExternalData){let Ni=[];for(let ui of se.externalData){let yn=typeof ui=="string"?ui:ui.path;Ni.push(Yi(typeof ui=="string"?ui:ui.data).then(Fn=>{ye.mountExternalData(yn,Fn)}))}await Promise.all(Ni)}for(let Ni of(se==null?void 0:se.executionProviders)??[])if((typeof Ni=="string"?Ni:Ni.name)==="webnn"){if(ye.shouldTransferToMLTensor=!1,typeof Ni!="string"){let ui=Ni,yn=ui==null?void 0:ui.context,Fn=ui==null?void 0:ui.gpuDevice,Zn=ui==null?void 0:ui.deviceType,Ca=ui==null?void 0:ui.powerPreference;yn?ye.currentContext=yn:Fn?ye.currentContext=await ye.webnnCreateMLContext(Fn):ye.currentContext=await ye.webnnCreateMLContext({deviceType:Zn,powerPreference:Ca})}else ye.currentContext=await ye.webnnCreateMLContext();break}Le=await ye._OrtCreateSession(ue,Ee,De),(rt=ye.webgpuOnCreateSession)==null||rt.call(ye,Le),Le===0&&Et("Can't create a session."),(tt=ye.jsepOnCreateSession)==null||tt.call(ye),ye.currentContext&&(ye.webnnRegisterMLContext(Le,ye.currentContext),ye.currentContext=void 0,ye.shouldTransferToMLTensor=!0);let[It,Oe]=Bs(Le),ht=!!(se!=null&&se.enableGraphCapture),Ei=[],Qt=[],ei=[],Ti=[],Ot=[];for(let Ni=0;Ni<It;Ni++){let[ui,yn,Fn]=Cr(Le,Ni);ui===0&&Et("Can't get an input name."),Be.push(ui);let Zn=ye.UTF8ToString(ui);Ei.push(Zn),ei.push(yn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ki(yn),shape:Fn})}for(let Ni=0;Ni<Oe;Ni++){let[ui,yn,Fn]=Cr(Le,Ni+It);ui===0&&Et("Can't get an output name."),et.push(ui);let Zn=ye.UTF8ToString(ui);Qt.push(Zn),Ti.push(yn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ki(yn),shape:Fn})}return Xn.set(Le,[Le,Be,et,null,ht,!1]),[Le,Ei,Qt,ei,Ti]}catch(It){throw Be.forEach(Oe=>ye._OrtFree(Oe)),et.forEach(Oe=>ye._OrtFree(Oe)),Le!==0&&ye._OrtReleaseSession(Le)!==0&&Et("Can't release session."),It}finally{ye._free(ue),De!==0&&ye._OrtReleaseSessionOptions(De)!==0&&Et("Can't release session options."),Ae.forEach(It=>ye._free(It)),(Xe=ye.unmountExternalData)==null||Xe.call(ye)}},Fr=Y=>{var Be,et,rt;let se=zt(),ue=Xn.get(Y);if(!ue)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Ee,ye,Le,De,Ae]=ue;De&&(Ae&&se._OrtClearBoundOutputs(De.handle)!==0&&Et("Can't clear bound outputs."),se._OrtReleaseBinding(De.handle)!==0&&Et("Can't release IO binding.")),(Be=se.jsepOnReleaseSession)==null||Be.call(se,Y),(et=se.webnnOnReleaseSession)==null||et.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),ye.forEach(tt=>se._OrtFree(tt)),Le.forEach(tt=>se._OrtFree(tt)),se._OrtReleaseSession(Ee)!==0&&Et("Can't release session."),Xn.delete(Y)},Is=async(Y,se,ue,Ee,ye,Le,De=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Be=Ae.PTR_SIZE,et=Y[0],rt=Y[1],tt=Y[3],Xe=tt,It,Oe;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(De&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Le} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Qt=Y[2].gpuBuffer;Oe=Gn(Bn(et),rt);{let ei=Ae.jsepRegisterBuffer;if(!ei)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=ei(Ee,Le,Qt,Oe)}}else if(tt==="ml-tensor"){let Qt=Y[2].mlTensor;Oe=Gn(Bn(et),rt);let ei=Ae.webnnRegisterMLTensor;if(!ei)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=ei(Ee,Qt,Bn(et),rt)}else{let Qt=Y[2];if(Array.isArray(Qt)){Oe=Be*Qt.length,It=Ae._malloc(Oe),ue.push(It);for(let ei=0;ei<Qt.length;ei++){if(typeof Qt[ei]!="string")throw new TypeError(`tensor data at index ${ei} is not a string`);Ae.setValue(It+ei*Be,Vi(Qt[ei],ue),"*")}}else{let ei=Ae.webnnIsGraphInput,Ti=Ae.webnnIsGraphOutput;if(et!=="string"&&ei&&Ti){let Ot=Ae.UTF8ToString(ye);if(ei(Ee,Ot)||Ti(Ee,Ot)){let Ni=Bn(et);Oe=Gn(Ni,rt),Xe="ml-tensor";let ui=Ae.webnnCreateTemporaryTensor,yn=Ae.webnnUploadTensor;if(!ui||!yn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Fn=await ui(Ee,Ni,rt);yn(Fn,new Uint8Array(Qt.buffer,Qt.byteOffset,Qt.byteLength)),It=Fn}else Oe=Qt.byteLength,It=Ae._malloc(Oe),ue.push(It),Ae.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Oe),It)}else Oe=Qt.byteLength,It=Ae._malloc(Oe),ue.push(It),Ae.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Oe),It)}}let ht=Ae.stackSave(),Ei=Ae.stackAlloc(4*rt.length);try{rt.forEach((ei,Ti)=>Ae.setValue(Ei+Ti*Be,ei,Be===4?"i32":"i64"));let Qt=Ae._OrtCreateTensor(Bn(et),It,Oe,Ei,rt.length,wn(Xe));Qt===0&&Et(`Can't create tensor for input/output. session=${Ee}, index=${Le}.`),se.push(Qt)}finally{Ae.stackRestore(ht)}},Ye=async(Y,se,ue,Ee,ye,Le)=>{var Qn,cl,rc;let De=zt(),Ae=De.PTR_SIZE,Be=Xn.get(Y);if(!Be)throw new Error(`cannot run inference. invalid session id: ${Y}`);let et=Be[0],rt=Be[1],tt=Be[2],Xe=Be[3],It=Be[4];Be[5];let Oe=se.length,ht=Ee.length,Ei=0,Qt=[],ei=[],Ti=[],Ot=[],Ni=[],ui=De.stackSave(),yn=De.stackAlloc(Oe*Ae),Fn=De.stackAlloc(Oe*Ae),Zn=De.stackAlloc(ht*Ae),Ca=De.stackAlloc(ht*Ae);try{[Ei,Qt]=oo(Le),Yt("wasm prepareInputOutputTensor");for(let li=0;li<Oe;li++)await Is(ue[li],ei,Ot,Y,rt[se[li]],se[li],It);for(let li=0;li<ht;li++)await Is(ye[li],Ti,Ot,Y,tt[Ee[li]],Oe+Ee[li],It);Fe("wasm prepareInputOutputTensor");for(let li=0;li<Oe;li++)De.setValue(yn+li*Ae,ei[li],"*"),De.setValue(Fn+li*Ae,rt[se[li]],"*");for(let li=0;li<ht;li++)De.setValue(Zn+li*Ae,Ti[li],"*"),De.setValue(Ca+li*Ae,tt[Ee[li]],"*");(Qn=De.jsepOnRunStart)==null||Qn.call(De,et),(cl=De.webnnOnRunStart)==null||cl.call(De,et);let xn;xn=await De._OrtRun(et,Fn,yn,Oe,Ca,ht,Zn,Ei),xn!==0&&Et("failed to call OrtRun().");let rr=[],oc=[];Yt("wasm ProcessOutputTensor");for(let li=0;li<ht;li++){let Fs=Number(De.getValue(Zn+li*Ae,"*"));if(Fs===Ti[li]||Ni.includes(Ti[li])){rr.push(ye[li]),Fs!==Ti[li]&&De._OrtReleaseTensor(Fs)!==0&&Et("Can't release tensor.");continue}let fd=De.stackSave(),Tr=De.stackAlloc(4*Ae),Go=!1,cn,es=0;try{De._OrtGetTensorData(Fs,Tr,Tr+Ae,Tr+2*Ae,Tr+3*Ae)!==0&&Et(`Can't access output tensor data on index ${li}.`);let dl=Ae===4?"i32":"i64",ts=Number(De.getValue(Tr,dl));es=De.getValue(Tr+Ae,"*");let ac=De.getValue(Tr+Ae*2,"*"),md=Number(De.getValue(Tr+Ae*3,dl)),Dr=[];for(let dn=0;dn<md;dn++)Dr.push(Number(De.getValue(ac+dn*Ae,dl)));De._OrtFree(ac)!==0&&Et("Can't free memory for tensor dims.");let Hs=Dr.reduce((dn,qi)=>dn*qi,1);cn=Ki(ts);let or=Xe==null?void 0:Xe.outputPreferredLocations[Ee[li]];if(cn==="string"){if(or==="gpu-buffer"||or==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let dn=[];for(let qi=0;qi<Hs;qi++){let Ws=De.getValue(es+qi*Ae,"*"),lc=De.getValue(es+(qi+1)*Ae,"*"),cc=qi===Hs-1?void 0:lc-Ws;dn.push(De.UTF8ToString(Ws,cc))}rr.push([cn,Dr,dn,"cpu"])}else if(or==="gpu-buffer"&&Hs>0){let dn=De.jsepGetBuffer;if(!dn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let qi=dn(es),Ws=Gn(ts,Hs);if(Ws===void 0||!yr(cn))throw new Error(`Unsupported data type: ${cn}`);Go=!0,rr.push([cn,Dr,{gpuBuffer:qi,download:De.jsepCreateDownloader(qi,Ws,cn),dispose:()=>{De._OrtReleaseTensor(Fs)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(or==="ml-tensor"&&Hs>0){let dn=De.webnnEnsureTensor,qi=De.webnnIsGraphInputOutputTypeSupported;if(!dn||!qi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Gn(ts,Hs)===void 0||!ps(cn))throw new Error(`Unsupported data type: ${cn}`);if(!qi(Y,cn,!1))throw new Error(`preferredLocation "ml-tensor" for ${cn} output is not supported by current WebNN Context.`);let Ws=await dn(Y,es,ts,Dr,!1);Go=!0,rr.push([cn,Dr,{mlTensor:Ws,download:De.webnnCreateMLTensorDownloader(es,cn),dispose:()=>{De.webnnReleaseTensorId(es),De._OrtReleaseTensor(Fs)}},"ml-tensor"])}else if(or==="ml-tensor-cpu-output"&&Hs>0){let dn=De.webnnCreateMLTensorDownloader(es,cn)(),qi=rr.length;Go=!0,oc.push((async()=>{let Ws=[qi,await dn];return De.webnnReleaseTensorId(es),De._OrtReleaseTensor(Fs),Ws})()),rr.push([cn,Dr,[],"cpu"])}else{let dn=nr(cn),qi=new dn(Hs);new Uint8Array(qi.buffer,qi.byteOffset,qi.byteLength).set(De.HEAPU8.subarray(es,es+qi.byteLength)),rr.push([cn,Dr,qi,"cpu"])}}finally{De.stackRestore(fd),cn==="string"&&es&&De._free(es),Go||De._OrtReleaseTensor(Fs)}}Xe&&!It&&(De._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),Xn.set(Y,[et,rt,tt,Xe,It,!1]));for(let[li,Fs]of await Promise.all(oc))rr[li][2]=Fs;return Fe("wasm ProcessOutputTensor"),rr}finally{(rc=De.webnnOnRunEnd)==null||rc.call(De,et),De.stackRestore(ui),ei.forEach(xn=>De._OrtReleaseTensor(xn)),Ti.forEach(xn=>De._OrtReleaseTensor(xn)),Ot.forEach(xn=>De._free(xn)),Ei!==0&&De._OrtReleaseRunOptions(Ei),Qt.forEach(xn=>De._free(xn))}},Jn=Y=>{let se=zt(),ue=Xn.get(Y);if(!ue)throw new Error("invalid session id");let Ee=ue[0],ye=se._OrtEndProfiling(Ee);ye===0&&Et("Can't get an profile file name."),se._OrtFree(ye)},vt=Y=>{let se=[];for(let ue of Y){let Ee=ue[2];!Array.isArray(Ee)&&"buffer"in Ee&&se.push(Ee.buffer)}return se}}),je,Je,Dt,ii,oi,ji,$i,rn,zi,ln,Ii,Gs,Hr,co,sr,pd,uo,ho,ic=d(()=>{ci(),fe(),Yn(),Kn(),je=()=>!!j.wasm.proxy&&typeof document<"u",Dt=!1,ii=!1,oi=!1,rn=new Map,zi=(Y,se)=>{let ue=rn.get(Y);ue?ue.push(se):rn.set(Y,[se])},ln=()=>{if(Dt||!ii||oi||!Je)throw new Error("worker not ready")},Ii=Y=>{switch(Y.data.type){case"init-wasm":Dt=!1,Y.data.err?(oi=!0,$i[1](Y.data.err)):(ii=!0,$i[0]()),ji&&(URL.revokeObjectURL(ji),ji=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=rn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Gs=async()=>{if(!ii){if(Dt)throw new Error("multiple calls to 'initWasm()' detected.");if(oi)throw new Error("previous call to 'initWasm()' failed.");if(Dt=!0,je())return new Promise((Y,se)=>{Je==null||Je.terminate(),wr().then(([ue,Ee])=>{try{Je=Ee,Je.onerror=Le=>se(Le),Je.onmessage=Ii,$i=[Y,se];let ye={type:"init-wasm",in:j};if(!ye.in.wasm.wasmPaths&&ue){let Le=an();Le&&(ye.in.wasm.wasmPaths=Le)}Je.postMessage(ye),ji=ue}catch(ye){se(ye)}},se)});try{await ir(j.wasm),await Bo(j),ii=!0}catch(Y){throw oi=!0,Y}finally{Dt=!1}}},Hr=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("init-ep",[se,ue]);let Ee={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Ee)});await Sr(j,Y)},co=async Y=>je()?(ln(),new Promise((se,ue)=>{zi("copy-from",[se,ue]);let Ee={type:"copy-from",in:{buffer:Y}};Je.postMessage(Ee,[Y.buffer])})):si(Y),sr=async(Y,se)=>{if(je()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ln(),new Promise((ue,Ee)=>{zi("create",[ue,Ee]);let ye={type:"create",in:{model:Y,options:{...se}}},Le=[];Y instanceof Uint8Array&&Le.push(Y.buffer),Je.postMessage(ye,Le)})}else return ms(Y,se)},pd=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("release",[se,ue]);let Ee={type:"release",in:Y};Je.postMessage(Ee)});Fr(Y)},uo=async(Y,se,ue,Ee,ye,Le)=>{if(je()){if(ue.some(De=>De[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ye.some(De=>De))throw new Error("pre-allocated output tensor is not supported for proxy.");return ln(),new Promise((De,Ae)=>{zi("run",[De,Ae]);let Be=ue,et={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Be,outputIndices:Ee,options:Le}};Je.postMessage(et,vt(Be))})}else return Ye(Y,se,ue,Ee,ye,Le)},ho=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("end-profiling",[se,ue]);let Ee={type:"end-profiling",in:Y};Je.postMessage(Ee)});Jn(Y)}}),rl,po,Sa,ol=d(()=>{ci(),ic(),Bt(),hn(),xr(),rl=(Y,se)=>{switch(Y.location){case"cpu":return[Y.type,Y.dims,Y.data,"cpu"];case"gpu-buffer":return[Y.type,Y.dims,{gpuBuffer:Y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Y.type,Y.dims,{mlTensor:Y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Y.location} for ${se()}`)}},po=Y=>{switch(Y[3]){case"cpu":return new he(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!yr(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:ue,download:Ee,dispose:ye}=Y[2];return he.fromGpuBuffer(ue,{dataType:se,dims:Y[1],download:Ee,dispose:ye})}case"ml-tensor":{let se=Y[0];if(!ps(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:ue,download:Ee,dispose:ye}=Y[2];return he.fromMLTensor(ue,{dataType:se,dims:Y[1],download:Ee,dispose:ye})}default:throw new Error(`invalid data location: ${Y[3]}`)}},Sa=class{async fetchModelAndCopyToWasmMemory(Y){return co(await Yi(Y))}async loadModel(Y,se){Pt();let ue;typeof Y=="string"?ue=await this.fetchModelAndCopyToWasmMemory(Y):ue=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await sr(ue,se),dt()}async dispose(){return pd(this.sessionId)}async run(Y,se,ue){Pt();let Ee=[],ye=[];Object.entries(Y).forEach(tt=>{let Xe=tt[0],It=tt[1],Oe=this.inputNames.indexOf(Xe);if(Oe===-1)throw new Error(`invalid input '${Xe}'`);Ee.push(It),ye.push(Oe)});let Le=[],De=[];Object.entries(se).forEach(tt=>{let Xe=tt[0],It=tt[1],Oe=this.outputNames.indexOf(Xe);if(Oe===-1)throw new Error(`invalid output '${Xe}'`);Le.push(It),De.push(Oe)});let Ae=Ee.map((tt,Xe)=>rl(tt,()=>`input "${this.inputNames[ye[Xe]]}"`)),Be=Le.map((tt,Xe)=>tt?rl(tt,()=>`output "${this.outputNames[De[Xe]]}"`):null),et=await uo(this.sessionId,ye,Ae,De,Be,ue),rt={};for(let tt=0;tt<et.length;tt++)rt[this.outputNames[De[tt]]]=Le[tt]??po(et[tt]);return dt(),rt}startProfiling(){}endProfiling(){ho(this.sessionId)}}}),kr={};f(kr,{OnnxruntimeWebAssemblyBackend:()=>Er,initializeFlags:()=>Wr,wasmBackend:()=>fo});var Wr,Er,fo,nc=d(()=>{ci(),ic(),ol(),Wr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let Y=j.wasm.simd;if(typeof Y!="boolean"&&Y!==void 0&&Y!=="fixed"&&Y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Y}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let se=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((se||1)/2))}},Er=class{async init(Y){Wr(),await Gs(),await Hr(Y)}async createInferenceSessionHandler(Y,se){let ue=new Sa;return await ue.loadModel(Y,se),ue}},fo=new Er}),sc={};f(sc,{InferenceSession:()=>ze,TRACE:()=>Qe,TRACE_EVENT_BEGIN:()=>Yt,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>Pt,TRACE_FUNC_END:()=>dt,Tensor:()=>he,default:()=>ll,env:()=>j,registerBackend:()=>k}),ci(),ci(),ci();var al="1.26.0",ll=$n;{let Y=(nc(),m(kr)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:al,enumerable:!0}),m(sc)})();i.exports=t})(Xv)),Xv.exports}var Ly;function sT(){return Ly||(Ly=1,(function(i){var e=qa&&qa.__createBinding||(Object.create?(function(x,A,P,N){N===void 0&&(N=P);var L=Object.getOwnPropertyDescriptor(A,P);(!L||("get"in L?!A.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return A[P]}}),Object.defineProperty(x,N,L)}):(function(x,A,P,N){N===void 0&&(N=P),x[N]=A[P]})),t=qa&&qa.__setModuleDefault||(Object.create?(function(x,A){Object.defineProperty(x,"default",{enumerable:!0,value:A})}):function(x,A){x.default=A}),n=qa&&qa.__importStar||function(x){if(x&&x.__esModule)return x;var A={};if(x!=null)for(var P in x)P!=="default"&&Object.prototype.hasOwnProperty.call(x,P)&&e(A,x,P);return t(A,x),A};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(nT()),l=qb(),p=Kb(),a=Yf(),d=vv(),f=zS(),g=BS();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",w="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",k=x=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async A=>{A.getTracks().forEach(P=>{P.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:A=>{A.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const E=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,A,P,N,L){await P.audioWorklet.addModule(x),A.processorOptions={...A.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(P,"vad-helper-worklet",A);return j.port.onmessage=async H=>{const W=H.data;if(!(typeof W=="object"&&W&&"message"in W)){console.error("Invalid message event",W);return}switch(W.message){case d.Message.AudioFrame:{if(!("data"in W&&W.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const re=new Float32Array(W.data);await L(re);break}}},j}async function C(x,A,P){const N=new g.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:A});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async W=>{if(!H){H=!0;try{const re=W.inputBuffer.getChannelData(0);W.outputBuffer.getChannelData(0).fill(0);const Z=N.process(re);for(const me of Z)await P(me)}catch(re){console.error("Error processing audio:",re)}finally{H=!1}}},j.connect(x.destination),j}class y{constructor(A,P,N,L,j=!1,H=null,W=null,re=null,de=null,Z=null,me=null,te="uninitialized",pe=!1){this.options=A,this.frameProcessor=P,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=W,this._audioContext=re,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=te,this.ownsAudioContext=pe,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=_e=>{this.initializationState="errored",this.errored=_e},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(_e){throw _e instanceof Error?this.setErrored(_e.message):this.setErrored(String(_e)),_e}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"?E(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await C(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),a.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{a.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:_e,audioContext:Ce,vadNode:U}=this.getAudioInstances();this._stream=await this.options.resumeStream(_e);const ie=new MediaStreamAudioSourceNode(Ce,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ie,ie.connect(U);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:_e,mediaStreamAudioSourceNode:Ce}=this.getAudioInstances();await this.options.pauseStream(_e),Ce.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ce;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:_e}=this.getAudioInstances();_e instanceof AudioWorkletNode&&_e.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ce=this._audioContext)==null?void 0:Ce.close())},this.setOptions=_e=>{this.frameProcessor.setOptions(_e)},this.processFrame=async _e=>{await this.frameProcessor.process(_e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=_e=>{switch(_e.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(_e.probs,_e.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(_e.audio);break}}}static async new(A={}){const P={...(0,i.getDefaultRealTimeVADOptions)(A.model??i.DEFAULT_MODEL),...A};(0,p.validateOptions)(P),i.ort.env.wasm.wasmPaths=P.onnxWASMBasePath,P.ortConfig!==void 0&&P.ortConfig(i.ort);const N=P.model==="v5"?w:D,L=P.baseAssetPath+N,j=P.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let H;try{H=await j(i.ort,()=>(0,l.defaultModelFetcher)(L))}catch(me){throw console.error(`Encountered an error while loading model file ${L}`),me}const W=P.model==="v5"?512:1536,re=W/16,de=new p.FrameProcessor(H.process,H.reset_state,{positiveSpeechThreshold:P.positiveSpeechThreshold,negativeSpeechThreshold:P.negativeSpeechThreshold,redemptionMs:P.redemptionMs,preSpeechPadMs:P.preSpeechPadMs,minSpeechMs:P.minSpeechMs,submitUserSpeechOnPause:P.submitUserSpeechOnPause},re),Z=new y(P,de,H,W);if(P.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=y})(qa)),qa}var zy;function rT(){return zy||(zy=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=MS();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=qb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Kb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=vv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=tT();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=iT();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=sT();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return a.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return a.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return a.getDefaultRealTimeVADOptions}})})(qv)),qv}var oT=rT();function ng(i,e,t,n,r){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,r)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const gt={debug:(i,e,t)=>ng(i,"debug",e,t),info:(i,e,t)=>ng(i,"info",e,t),warn:(i,e,t)=>ng(i,"warn",e,t),error:(i,e,t,n)=>ng(i,"error",e,t,n)},FS=16e3,aT=6,Ku=FS*aT,lT=400,cT=FS*lT/1e3,By=300,Gy=2e3,Fy=1500,Hy=3e3,dT=600,HS=.5,WS=.35,Wy=.85,Uy=.7;let _r=null,ga=!1,Zs=!1;const G_=new Set;function sg(i){for(const e of Array.from(G_))try{e(i)}catch(t){gt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Jv=0;const Vy=2;let rh=!1,US=!1;function VS(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";gt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{gt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),uT(`error:${e.message||"unknown"}`)})}function ev(){return _r||(_r=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),VS(_r),gt.info("speech","worker spawned"),_r)}let rg=!1;function uT(i){if(!rh){if(rg){gt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(rg=!0,Jv+=1,US=!0,gt.warn("speech","respawnWorker: starting",{reason:i,attempt:Jv}),sg({reason:i,respawned:!1,finalOnly:!0}),Jv>Vy){if(rh=!0,gt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Vy}),_r)try{_r.terminate()}catch{}_r=null,ga=!1,Zs=!1,sg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),rg=!1;return}if(_r)try{_r.terminate()}catch{}_r=null,ga=!1,Zs=!1;try{_r=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),VS(_r),Zs=!0,_r.postMessage({type:"load"}),gt.info("speech","respawnWorker: new worker spawned, load posted"),sg({reason:i,respawned:!0,finalOnly:!0})}catch(e){rh=!0,gt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),sg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{rg=!1}}}function hT(i,e){if(ga||Zs)return;Zs=!0;const t=ev();gt.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(i==null||i(r.data.status,r.data.message),r.data.status==="ready"&&(ga=!0,Zs=!1,gt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(Zs=!1,gt.error("speech","preloadModel: worker reported error",{error:r.data.error}),i==null||i("error",r.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function pT(){gt.info("speech","resetModel: clearing load flags"),ga=!1,Zs=!1}function _v(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function fT(i){const e=ev();return!ga&&!Zs&&(Zs=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const r=l=>{var p,a,d;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",r),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(l.data.error??"Transcription failed")))):((d=l.data)==null?void 0:d.type)==="status"&&l.data.status==="ready"&&(ga=!0,Zs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function qS(i){let e=ev(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let g=null,m=0,w=!1,D=0,k=!1,E=!1,b=0,C=0,y=0,x=-1,A=By,P=0,N=null,L="",j="",H=!1,W=0;function re(ge,ke){const $e=Math.min(ge.length,ke.length);let He=0;for(;He<$e&&ge.charCodeAt(He)===ke.charCodeAt(He);)He++;return He}function de(ge){const ke=re(L,ge);return L=ge,ke>j.length&&(j=ge.slice(0,ke)),j.length>ge.length&&(j=ge),j}const Z=()=>(g||(g=new Float32Array(Ku)),g),me=()=>{m=0},te=ge=>{const ke=Z(),$e=ge.length;if($e>=Ku){ke.set(ge.subarray($e-Ku)),m=Ku;return}if(m+$e<=Ku){ke.set(ge,m),m+=$e;return}const He=m+$e-Ku;ke.copyWithin(0,He,m),m-=He,ke.set(ge,m),m+=$e},pe=()=>{N&&(clearTimeout(N),N=null)},_e=()=>{pe(),w=!1,k=!1,E=!1,A=By,L="",j="",H=!1,W=0,me()},Ce=()=>{if(t||!w||E||k||N)return;if(m<cT){N=setTimeout(()=>{N=null,Ce()},A);return}const ge=performance.now()-b;if(ge<A&&b!==0){N=setTimeout(()=>{N=null,Ce()},A-ge);return}if(US||rh||i.partialsEnabled&&!i.partialsEnabled())return;const ke=Z(),$e=new Float32Array(m);$e.set(ke.subarray(0,m)),C+=1,y=C,k=!0,P=performance.now(),b=P,e.postMessage({type:"transcribe-partial",audio:$e,seq:C},[$e.buffer])},U=ge=>ge.length===0?Promise.resolve():rh?(gt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ke=>{d.push(ke),C+=1;const $e=C;x=$e,e.postMessage({type:"transcribe",audio:ge,seq:$e},[ge.buffer])}),ie=ge=>{const ke=U(ge);return f.add(ke),ke.finally(()=>{f.delete(ke)}),ke},q=ge=>{var ke,$e,He,ve,X;if(ge.data.type==="result"){const Ie=ge.data.text,he=ge.data.seq??0;he&&he<x&>.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:he,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(ke=d.shift())==null||ke()}else if(ge.data.type==="partial"){const Ie=ge.data.seq??0,he=ge.data.text??"",Pe=performance.now()-P;k=!1,Pe>=Hy?(E=!0,gt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Pe),seq:Ie})):Pe>=Fy&&(A=Math.min(A*2,Gy),gt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Pe),newIntervalMs:A,seq:Ie})),H||(H=!0,Pe>dT&&A<500&&(A=500,gt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Pe),newIntervalMs:500})));const Qe=Ie!==y||Ie<=x;if(!t&&!Qe&&he){const pt=de(he);pt&&(($e=i.onPartial)==null||$e.call(i,pt),W===0&&(W=performance.now(),gt.info("speech","partial.first",{msSinceSpeechStart:Math.round(W-D)})))}Ce()}else if(ge.data.type==="partial-error"){const Ie=performance.now()-P;k=!1,Ie>=Hy?(E=!0,gt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ge.data.seq})):Ie>=Fy&&(A=Math.min(A*2,Gy),gt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:A,seq:ge.data.seq})),gt.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),Ce()}else ge.data.type==="error"?(t||i.onError(ge.data.error),(He=d.shift())==null||He()):ge.data.type==="status"?(t||(ve=i.onModelStatus)==null||ve.call(i,ge.data.status,ge.data.message),ge.data.status==="ready"&&(ga=!0,Zs=!1)):ge.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ge.data.pct))};e.addEventListener("message",q);const oe=ge=>{var ke,$e;if(!t){for(gt.warn("speech","createRecognition: worker death event",ge),(ke=i.onStatusChange)==null||ke.call(i,"restarting");d.length;)($e=d.shift())==null||$e();if(f.clear(),pe(),k=!1,ge.respawned){try{e.removeEventListener("message",q)}catch{}e=ev(),e.addEventListener("message",q)}}};return G_.add(oe),{start:async()=>{if(!t){if(rh){i.onError("Speech recognition disabled — please reload the app.");return}!ga&&!Zs&&(Zs=!0,gt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),gt.info("speech","createRecognition.start: initializing VAD",{modelReady:ga,modelLoading:Zs});try{const ge=new URL("vad/",document.baseURI).href,ke=i.inputDeviceId||null,$e={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ke&&($e.deviceId={exact:ke}),gt.info("speech","getUserMedia",{hasDeviceId:!!ke,deviceIdPrefix:ke?ke.slice(0,8):null});const He=await navigator.mediaDevices.getUserMedia({audio:$e});r=He,l=new AudioContext;for(const ve of He.getAudioTracks())ve.addEventListener("ended",()=>{t||(gt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(r),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ve){gt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),a=null,p=null}n=await oT.MicVAD.new({audioContext:l,getStream:async()=>He,resumeStream:async()=>He,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:HS,negativeSpeechThreshold:WS,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,ve),w&&(te(X),Ce()))},onSpeechStart:()=>{var ve;t||(_e(),w=!0,D=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),_e(),ie(ve))},onVADMisfire:()=>{var ve,X;t||((ve=i.onStatusChange)==null||ve.call(i,"idle"),_e(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ge){const ke=ge instanceof Error?ge.message:"Microphone access denied",$e=ge instanceof Error?ge.stack:"";if(gt.error("speech","createRecognition.start: VAD init failed",{error:ke,stack:$e}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(He=>He.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(ke)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(_e();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ge,ke)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:ke})}catch($e){gt.warn("speech","setVadThresholds failed",{error:$e instanceof Error?$e.message:String($e)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,_e(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}G_.delete(oe),e.removeEventListener("message",q)}}}let $f=null;const F_=new Set,H_=new Set;function mT(){for(const i of F_)try{i()}catch{}}function W_(){for(const i of H_)try{i()}catch{}}function gT(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function vT(i){if(!window.speechSynthesis)return;const e=gT(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{$f=performance.now(),mT()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&($f=null,W_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&($f=null,W_())},window.speechSynthesis.speak(t)}function KS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),$f=null,W_())}function YS(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function _T(){return $f}function bT(i){return F_.add(i),()=>{F_.delete(i)}}function wT(i){return H_.add(i),()=>{H_.delete(i)}}function yT(i){YS()&&(i.setVadThresholds(Wy,Uy),gt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bT(()=>{i.setVadThresholds(Wy,Uy),gt.info("voice","tts.duck.on")}),t=wT(()=>{i.setVadThresholds(HS,WS),gt.info("voice","tts.duck.off")});return()=>{e(),t()}}const xT=[{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 ST(i){const e=i.trim();return xT.find(t=>t.match.test(e))??null}const CT=4e4;let od=null;function oh(){od&&clearTimeout(od),od=setTimeout(()=>{od=null,kt.getState().stopRecording()},CT)}function og(){od&&(clearTimeout(od),od=null)}let Zl=null,Kl=null;const kT=.04,ET=.3;let tv=0,U_=0;function TT(i){Kl!==null&&cancelAnimationFrame(Kl);const e=()=>{if(Zl===null||kt.getState().submitCountdownStartAt===null){Kl=null;return}const t=performance.now();if(t-U_<200&&tv>ET){const r=t-i;gt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:tv.toFixed(2),msIntoCountdown:Math.round(r)}),Vl(),oh();return}const n=XS();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let l=0;for(let a=0;a<r.length;a++){const d=(r[a]-128)/128;l+=d*d}const p=Math.sqrt(l/r.length);if(p>kT){const a=t-i;gt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Vl(),oh();return}}Kl=requestAnimationFrame(e)};Kl=requestAnimationFrame(e)}function qy(i){Zl&&clearTimeout(Zl);const e=kt.getState().submitDelayMs,t=performance.now();kt.setState({submitCountdownStartAt:t}),Zl=setTimeout(()=>{var r;Zl=null,kt.setState({submitCountdownStartAt:null});const n=St.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=hi.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(hi.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),hi.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){gt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}oh()},e),TT(t)}function Vl(){Kl!==null&&(cancelAnimationFrame(Kl),Kl=null),Zl&&(clearTimeout(Zl),Zl=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let ds=null,Ns=null,of=null;function XS(){var i;return((i=ds==null?void 0:ds.getAnalyser)==null?void 0:i.call(ds))??null}const ag=1e4;let If=null;function lg(){If&&(clearTimeout(If),If=null)}let zg=null,Bg=null;function cg(){zg=null,Bg&&(Bg(),Bg=null)}const DT=1500,AT=9e4;let dg=0,Gg=null,V_=-1;function ug(){Gg&&(clearTimeout(Gg),Gg=null,V_=-1)}const $T=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=On((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;gt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++dg,n=()=>{t===dg&&(ug(),V_=t,Gg=setTimeout(()=>{V_===t&&e().modelStatus==="loading"&&(gt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},AT))};n(),hT((r,l)=>{t===dg&&(r==="ready"?(ug(),gt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(ug(),gt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===dg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{gt.info("voice","mic.gate.retry"),ug(),pT(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ds){gt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!_v()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=qS({inputDeviceId:l,onStatusChange:a=>{i(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&i({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{tv=a.isSpeech,U_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),og(),Vl(),YS()){const d=_T(),f=d!==null?performance.now()-d:null;KS(),i({lastBargeInAt:performance.now()}),gt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else gt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),oh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&>.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var w;oh();const d=a.trim();if(!d||$T.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(of){of(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((w=St.getState().tabs.find(D=>D.id===t))==null?void 0:w.status)==="dormant"){hi.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&qy(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const g=ST(d);if(g){gt.info("voice","voice-command",{tabId:t,label:g.label,transcript:d}),window.api.pty.write({tabId:t,data:g.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vl();const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&qy(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{gt.error("voice","recognition error",{err:a}),Vl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Ns==null||Ns(),Ns=null,og(),ds==null||ds.destroy(),ds=null,of=null,st.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?i({modelStatus:"ready",loadingProgress:100}):a==="loading"&&i({modelStatus:"loading"})},onProgress:a=>i({loadingProgress:Math.round(a)})});ds=p,of=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),oh(),p.start().then(()=>{ds===p&&(Ns==null||Ns(),Ns=yT(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);gt.error("voice","handle.start() failed",{error:d}),st.error(`Could not start mic: ${d}`)})}catch(p){i({error:p instanceof Error?p.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,p,a;return((a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.getDevicePref)==null?void 0:a.call(p))??Promise.resolve(null)}).then(l=>r((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{gt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=ds;t&&(og(),Vl(),tv=0,U_=0,Ns==null||Ns(),Ns=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ds===t&&(ds=null,of=null),e().hotkeyState==="stopping"&&(lg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ds;if(!t)return;og(),Ns==null||Ns(),Ns=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){gt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),ds===t&&(ds=null);const{useSessions:n}=await qn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>RE);return{useSessions:l}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},setExternalRecording:t=>i({externalRecording:t}),toggleTTS:()=>i(t=>({ttsEnabled:!t.ttsEnabled})),setAutoSubmit:t=>i({autoSubmit:t}),setSubmitDelayMs:t=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(t)))}),cancelSubmit:()=>Vl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(gt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:t}),i({permissionState:t}))},setLevelMeterEnabled:t=>{e().levelMeterEnabled!==t&&i({levelMeterEnabled:t})},setTurnDetectorRuntimeState:t=>{e().turnDetectorState!==t&&(i({turnDetectorState:t}),t==="load_failed"?gt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?gt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&>.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:t=>{e().wizardArmed!==t&&i({wizardArmed:t})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:t,source:n,mode:r,tabId:l})=>{const p=e(),{canRecord:a,reason:d}=iv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),gt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){gt.warn("voice-hotkey","miss-model-loading",{modelStatus:p.modelStatus,reason:d});return}if(p.hotkeyState==="recording"||p.isRecording){(r==="toggle"||n==="global")&&(i({hotkeyState:"stopping"}),lg(),If=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:ag}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},ag),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),gt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),cg(),zg={tabId:l,source:n,mode:r},Bg=kt.subscribe((f,g)=>{if(zg&&f.modelStatus==="ready"&&g.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=zg;if(cg(),!m.tabId){gt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}gt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),kt.getState().startRecording(m.tabId)}});return}if(!l){gt.warn("voice-hotkey","no-active-tab",{source:n});return}gt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(gt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){cg(),gt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),lg(),If=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:ag}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},ag),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(cg(),Vl(),t.hotkeyState==="recording"){gt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(lg(),i({hotkeyState:"destroyed"}))}})),IT=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),iv=i=>_v()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=kt,i.__transcripts=[]}const PT=6e4,RT=5e3,Pf=On(()=>({data:null,refreshing:!1}));let Ky=!1,Fg=null,Yy=null,Xy=!1;async function Yb(){Pf.setState({refreshing:!0});let i=PT;try{const e=await Gb(window.api.billing.fetch(),RT,"billing.fetch");Pf.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Yy==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Yy=e.kind}catch(e){if(Pf.setState({refreshing:!1}),!Xy){Xy=!0;const t=e instanceof Error?e.message:String(e);st.warn(`Billing usage fetch failed: ${t}`)}}Fg=setTimeout(Yb,i)}function jT(){Ky||(Ky=!0,Yb())}function JS(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function NT(){Fg!==null&&(clearTimeout(Fg),Fg=null),Yb()}function Xb(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),r=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${r} ${e[1]}`:`${n} ${r}`}const hg=new Map,MT=3e4;function Jb(i){const[e,t]=B.useState(()=>{var n;return i?((n=hg.get(i))==null?void 0:n.value)??null:null});return B.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=hg.get(i);if(l&&Date.now()-l.ts<MT){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;hg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;hg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function OT(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:r})=>({key:e,label:t,icon:n,hint:r}))}const q_="sm.almanac.sidebarWidth",ZS=180,QS=480,K_=252;function LT(){try{const i=parseInt(localStorage.getItem(q_)??"",10);if(Number.isFinite(i))return Math.min(QS,Math.max(ZS,i))}catch{}return K_}const zT=52,e1="sm.almanac.sidebarCollapsed";function BT(){try{return localStorage.getItem(e1)==="1"}catch{}return!1}const t1="sm.almanac.collapsedGroups";function GT(){try{const i=localStorage.getItem(t1);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(t=>t==="Workspace"||t==="Configure"||t==="Tools")):new Set}catch{return new Set}}function FT(){const i=St(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Or(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function HT({active:i,onNavigate:e,onNewSession:t}){const[n,r]=B.useState(()=>GT()),l=B.useCallback(j=>{r(H=>{const W=new Set(H);W.has(j)?W.delete(j):W.add(j);try{localStorage.setItem(t1,JSON.stringify(Array.from(W)))}catch{}return W})},[]),[p,a]=B.useState(()=>BT()),d=B.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(e1,H?"1":"0")}catch{}return H})},[]),f=St(j=>j.tabs),g=St(j=>j.activeTabId),m=f.find(j=>j.id===g)??null,w=FT(),D=Di(j=>j.navFace),k=OE(D),E=k.filter(j=>j.group==="Workspace"),b=k.filter(j=>j.group==="Configure"),C=OT(k),y=D==="home"&&!p,[x,A]=B.useState(()=>LT()),P=B.useRef(x);P.current=x;const N=B.useCallback(j=>{j.preventDefault();const H=j.clientX,W=P.current;let re=W;const de=me=>{re=Math.min(QS,Math.max(ZS,W+(me.clientX-H))),A(re)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(q_,String(re))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=B.useCallback(()=>{A(K_);try{localStorage.setItem(q_,String(K_))}catch{}},[]);return h.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?zT:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx(WT,{tab:m,navFace:D,onNewSession:t,rail:p,onToggleRail:d}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:y?h.jsxs(h.Fragment,{children:[h.jsx(Zv,{label:"Workspace",desc:Vv.Workspace,collapsed:n.has("Workspace"),count:E.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&E.map(j=>h.jsx(Qv,{item:j,active:i===j.key,live:j.liveKind?w[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Zv,{label:"Configure",desc:Vv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Qv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Zv,{label:"Tools",desc:Vv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(Jy,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:k.map(j=>j.group==="Tools"?h.jsx(Jy,{tool:{key:j.key,label:j.label,icon:j.icon,hint:j.hint},active:i===j.key,onClick:()=>e(j.key),rail:p},j.key):h.jsx(Qv,{item:j,active:i===j.key,live:j.liveKind?w[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(UT,{rail:p,navFace:D}),!p&&h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:L,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 WT({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Jb((i==null?void 0:i.cwd)??null);return n?h.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[h.jsx("button",{onClick:t,"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:h.jsx(Dn,{name:"plus",size:15,stroke:1.8})}),h.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:h.jsx(Dn,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),h.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(Dn,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.jsxs("button",{onClick:t,"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:[h.jsx(Dn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),h.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(Dn,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[h.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),h.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),h.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.jsxs("button",{onClick:t,"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:[h.jsx(Dn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Zv({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return h.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[h.jsxs("button",{onClick:r,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[h.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),h.jsx("span",{className:"flex-1",children:i}),t&&h.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&h.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 Qv({item:i,active:e,live:t,onClick:n,rail:r}){return h.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(Dn,{name:i.icon,size:17,stroke:1.6})}),!r&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&h.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 Jy({tool:i,active:e,onClick:t,rail:n}){return h.jsxs("button",{onClick:t,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${n?"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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(Dn,{name:i.icon,size:15,stroke:1.6})}),!n&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function UT({rail:i,navFace:e}){const t=kt(d=>d.isRecording),n=St(d=>d.tabs),r=St(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=B.useState(null);return B.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return bS(l.presetId).then(f=>{d||a((f==null?void 0:f.model)??null)}).catch(()=>{d||a(null)}),()=>{d=!0}},[l==null?void 0:l.presetId]),i?h.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):h.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:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"}),(t||e==="project")&&h.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Xb(p)}`:"Claude Code"})]})}const An={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},VT={dialog:50};function qT(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function KT(i,e,t){return{tabId:i,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function YT(i,e,t){const n=Date.now(),r={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,d)=>a.length>d?a.slice(0,d-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];r.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,d=a.input,f={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])d&&g in d&&(f[g]=d[g]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),w=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,D=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,k=w?w.split("/").pop()??w:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:w??D,toolName:a.name}),m&&w&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(w.split("/").pop()??w,34)}`,target:w,toolName:a.name})}break}case"plan":{const a=e.data,d=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);r.plans=[{at:n,content:d??""},...i.plans].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"plan-revision",at:n,label:"Plan revised"});break}case"agent_spawn":{const a=e.data;r.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,d=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,g=a.output_tokens??a.outputTokens??0,m=d+f+g;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+g,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(d/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const a=e.data;r.agents=qT(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Hg=On((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,r)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:KT(t,n,r)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:r}).then(async a=>{const d=e().tabs[t];if(!d)return;if(!a.ok){const{toast:g}=await qn(async()=>{const{toast:m}=await Promise.resolve().then(()=>xS);return{toast:m}},void 0,import.meta.url);g.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...d,path:null}}});return}i({tabs:{...e().tabs,[t]:{...d,path:a.path}}});const f=await window.api.transcripts.buffer(t);e().ingestBatch(t,f,{replay:!0})}).catch(a=>console.error("[live] transcripts.subscribe failed:",t,a))},unsubscribe:t=>{const n={...e().refs};if(!n[t])return;if(n[t]--,n[t]>0){i({refs:n});return}delete n[t];const r=e().unsubs[t];r==null||r();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,r)=>{e().ingestBatch(t,[n],r)},ingestBatch:(t,n,r)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const d of n){const{next:f,newActivity:g}=YT(p,d,r);p=f,a=a.concat(g)}if(a.length>0){let d=l.activitySeq;const f=a.map(g=>({...g,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function XT(i){const e=Hg(r=>r.subscribe),t=Hg(r=>r.unsubscribe),n=Hg(r=>i?r.tabs[i.id]:void 0);return B.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>t(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,t]),n}function i1(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${r}h`:r>0?`${r}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function Y_(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function Zy(i,e){const t=Y_(e);if(t==null)return`${i} — usage unavailable`;const n=i1((e==null?void 0:e.resets_at)??null),r=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${r} — click to open Home`}function JT({onNavigate:i}){const e=St(P=>P.tabs),t=St(P=>P.activeTabId),n=e.find(P=>P.id===t)??null,r=XT(n),l=(r==null?void 0:r.lastEventAt)??0,p=Pf(P=>P.data),a=Or(P=>{var N;return((N=P.snapshot)==null?void 0:N.paused)??null}),d=Jb((n==null?void 0:n.cwd)??null),[,f]=B.useState(0);B.useEffect(()=>{const P=setInterval(()=>f(N=>N+1),6e4);return()=>clearInterval(P)},[]);const g=(r==null?void 0:r.todos)??[],[m,w]=B.useState(!1),D=B.useRef(null);B.useEffect(()=>{if(!m)return;const P=N=>{D.current&&!D.current.contains(N.target)&&w(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[m]),B.useEffect(()=>{g.length===0&&w(!1)},[g.length]);const k=JS(p),E=(k==null?void 0:k.usage.five_hour)??null,b=(k==null?void 0:k.usage.seven_day)??null,C=Y_(E),y=Y_(b),x=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",A=l>0?e2(Date.now()-l):"—";return h.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:[h.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:x?"Connected to Anthropic":"Disconnected",children:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x?"bg-sage":"bg-fg-faint"}`}),h.jsx("span",{children:x?"connected":"offline"})]}),h.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Zy("Session (5h window)",E),"data-testid":"footer-usage-session",children:["session ",h.jsx("span",{className:"text-fg",children:C!=null?`${C}%`:"—"})]}),h.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Zy("Weekly window (all models)",b),"data-testid":"footer-usage-weekly",children:["weekly ",h.jsx("span",{className:"text-fg",children:y!=null?`${y}%`:"—"})]}),a&&h.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.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:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&h.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&h.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),h.jsxs("span",{className:"text-fg-faint",children:["last activity: ",h.jsx("span",{className:"text-fg-dim",children:A})]}),g.length>0&&h.jsx(ZT,{ref:D,todos:g,open:m,onToggle:()=>w(P=>!P)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.78.0"]})]})}const ZT=B.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return h.jsxs("div",{ref:r,className:"relative",children:[h.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[h.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),h.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),h.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),h.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&h.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 ${An.dialog}`,"data-testid":"footer-todos-popover",children:h.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>h.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[h.jsx(QT,{status:p.status}),h.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function QT({status:i}){return i==="completed"?h.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?h.jsx("span",{className:"w-3 shrink-0",children:h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):h.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function e2(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function t2({onClose:i,onSent:e}){const t=St(L=>L.tabs),[n,r]=B.useState(""),[l,p]=B.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=B.useState(!1),[f,g]=B.useState({}),m=B.useRef(null),w=B.useRef(e);B.useEffect(()=>{w.current=e},[e]),B.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),B.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),B.useEffect(()=>window.api.pty.onWriteError(j=>{g(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),B.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>w.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,E=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!E,C=()=>{if(!b)return;d(!0);const L=St.getState().tabs,j=new Set(L.map(W=>W.id)),H={};for(const W of D)j.has(W)?(window.api.pty.write({tabId:W,data:n+"\r"}),H[W]="sent"):H[W]="skipped";g(H),d(!1)},y=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),C())},x=t.length>0&&t.every(L=>l[L.id]),A=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},P=Object.values(f).some(L=>L==="skipped"),N=E?P?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return h.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:y,"data-testid":"broadcast-bar",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),h.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),h.jsx("textarea",{ref:m,value:n,onChange:L=>r(L.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"}),h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:x,onChange:A,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),h.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>h.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:j=>p(H=>({...H,[L.id]:j.target.checked})),className:"accent-accent"}),h.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&h.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&h.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),h.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[h.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),h.jsx("button",{onClick:C,disabled:!b,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:N})]})]})}function i2({tabId:i,cwd:e,onClose:t}){const n=Af(k=>k.watchersForTab(i)),r=Af(k=>k.add),l=Af(k=>k.remove),p=B.useRef(null),[a,d]=B.useState(""),[f,g]=B.useState(""),[m,w]=B.useState(!1);B.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),B.useEffect(()=>{const k=E=>{p.current&&!p.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||m)return;w(!0);const E=await r({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),E&&(d(""),g(""))};return h.jsxs("div",{ref:p,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:[h.jsxs("div",{className:"flex items-center mb-2",children:[h.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),h.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),h.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[h.jsx("input",{value:a,onChange:k=>d(k.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"}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("input",{value:f,onChange:k=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},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"}),h.jsx("button",{onClick:D,disabled:!f.trim()||m,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"})]}),h.jsxs("span",{className:"text-fg-faint",children:["cwd: ",h.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?h.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):h.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const E=k.lines[k.lines.length-1];return h.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),h.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2910
|
+
*/var Oy;function nT(){return Oy||(Oy=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof io<"u"?io:typeof Proxy<"u"?new Proxy(Y,{get:(se,ue)=>(typeof io<"u"?io:se)[ue]}):Y)(function(Y){if(typeof io<"u")return io.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),d=(Y,se)=>()=>(Y&&(se=Y(Y=0)),se),f=(Y,se)=>{for(var ue in se)n(Y,ue,{get:se[ue],enumerable:!0})},g=(Y,se,ue,Ee)=>{if(se&&typeof se=="object"||typeof se=="function")for(let ye of l(se))!p.call(Y,ye)&&ye!==ue&&n(Y,ye,{get:()=>se[ye],enumerable:!(Ee=r(se,ye))||Ee.enumerable});return Y},m=Y=>g(n({},"__esModule",{value:!0}),Y),w,D,k,E,b,C=d(()=>{w=new Map,D=[],k=(Y,se,ue)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Ee=w.get(Y);if(Ee===void 0)w.set(Y,{backend:se,priority:ue});else{if(Ee.priority>ue)return;if(Ee.priority===ue&&Ee.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${ue}`)}if(ue>=0){let ye=D.indexOf(Y);ye!==-1&&D.splice(ye,1);for(let Le=0;Le<D.length;Le++)if(w.get(D[Le]).priority<=ue){D.splice(Le,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},E=async Y=>{let se=w.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let ue=!!se.initPromise;try{return ue||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Ee){return ue||(se.error=`${Ee}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],ue=se.map(Be=>typeof Be=="string"?Be:Be.name),Ee=ue.length===0?D:ue,ye,Le=[],De=new Set;for(let Be of Ee){let et=await E(Be);typeof et=="string"?Le.push({name:Be,err:et}):(ye||(ye=et),ye===et&&De.add(Be))}if(!ye)throw new Error(`no available backend found. ERR: ${Le.map(Be=>`[${Be.name}] ${Be.err}`).join(", ")}`);for(let{name:Be,err:et}of Le)ue.includes(Be)&&console.warn(`removing requested execution provider "${Be}" from session options because it is not available: ${et}`);let Ae=se.filter(Be=>De.has(typeof Be=="string"?Be:Be.name));return[ye,new Proxy(Y,{get:(Be,et)=>et==="executionProviders"?Ae:Reflect.get(Be,et)})]}}),y=d(()=>{C()}),x,A=d(()=>{x="1.26.0"}),P,N,L=d(()=>{A(),P="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);P=Y}},get logLevel(){return P}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,H=d(()=>{L(),j=N}),W,re,de=d(()=>{W=(Y,se)=>{let ue=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ue.width=Y.dims[3],ue.height=Y.dims[2];let Ee=ue.getContext("2d");if(Ee!=null){let ye,Le;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(ye=Y.dims[2],Le=Y.dims[3]):(ye=Y.dims[3],Le=Y.dims[2]);let De=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Be,et;Ae===void 0||Ae.mean===void 0?Be=[255,255,255,255]:typeof Ae.mean=="number"?Be=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Be=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Be[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?et=[0,0,0,0]:typeof Ae.bias=="number"?et=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(et=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(et[3]=Ae.bias[3]));let rt=Le*ye,tt=0,Xe=rt,It=rt*2,Oe=-1;De==="RGBA"?(tt=0,Xe=rt,It=rt*2,Oe=rt*3):De==="RGB"?(tt=0,Xe=rt,It=rt*2):De==="RBG"&&(tt=0,It=rt,Xe=rt*2);for(let ht=0;ht<Le;ht++)for(let Ei=0;Ei<ye;Ei++){let Qt=(Y.data[tt++]-et[0])*Be[0],ei=(Y.data[Xe++]-et[1])*Be[1],Ti=(Y.data[It++]-et[2])*Be[2],Ot=Oe===-1?255:(Y.data[Oe++]-et[3])*Be[3];Ee.fillStyle="rgba("+Qt+","+ei+","+Ti+","+Ot+")",Ee.fillRect(Ei,ht,1,1)}if("toDataURL"in ue)return ue.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},re=(Y,se)=>{let ue=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Ee;if(ue!=null){let ye,Le,De;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(ye=Y.dims[2],Le=Y.dims[1],De=Y.dims[3]):(ye=Y.dims[3],Le=Y.dims[2],De=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Be=se==null?void 0:se.norm,et,rt;Be===void 0||Be.mean===void 0?et=[255,255,255,255]:typeof Be.mean=="number"?et=[Be.mean,Be.mean,Be.mean,Be.mean]:(et=[Be.mean[0],Be.mean[1],Be.mean[2],255],Be.mean[3]!==void 0&&(et[3]=Be.mean[3])),Be===void 0||Be.bias===void 0?rt=[0,0,0,0]:typeof Be.bias=="number"?rt=[Be.bias,Be.bias,Be.bias,Be.bias]:(rt=[Be.bias[0],Be.bias[1],Be.bias[2],0],Be.bias[3]!==void 0&&(rt[3]=Be.bias[3]));let tt=Le*ye;if(se!==void 0&&(se.format!==void 0&&De===4&&se.format!=="RGBA"||De===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,It=0,Oe=1,ht=2,Ei=3,Qt=0,ei=tt,Ti=tt*2,Ot=-1;Ae==="RGBA"?(Qt=0,ei=tt,Ti=tt*2,Ot=tt*3):Ae==="RGB"?(Qt=0,ei=tt,Ti=tt*2):Ae==="RBG"&&(Qt=0,Ti=tt,ei=tt*2),Ee=ue.createImageData(ye,Le);for(let Ni=0;Ni<Le*ye;It+=Xe,Oe+=Xe,ht+=Xe,Ei+=Xe,Ni++)Ee.data[It]=(Y.data[Qt++]-rt[0])*et[0],Ee.data[Oe]=(Y.data[ei++]-rt[1])*et[1],Ee.data[ht]=(Y.data[Ti++]-rt[2])*et[2],Ee.data[Ei]=Ot===-1?255:(Y.data[Ot++]-rt[3])*et[3]}else throw new Error("Can not access image data");return Ee}}),Z,me,te,pe,_e,Ce,U=d(()=>{Ie(),Z=(Y,se)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(se.height===void 0||se.width===void 0)throw new Error("Image height and width must be defined");if(se.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ue,width:Ee}=se,ye=se.norm??{mean:255,bias:0},Le,De;typeof ye.mean=="number"?Le=[ye.mean,ye.mean,ye.mean,ye.mean]:Le=[ye.mean[0],ye.mean[1],ye.mean[2],ye.mean[3]??255],typeof ye.bias=="number"?De=[ye.bias,ye.bias,ye.bias,ye.bias]:De=[ye.bias[0],ye.bias[1],ye.bias[2],ye.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Be=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",et=ue*Ee,rt=Be==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,It=1,Oe=2,ht=3,Ei=0,Qt=et,ei=et*2,Ti=-1;Ae==="RGB"&&(tt=3,Xe=0,It=1,Oe=2,ht=-1),Be==="RGBA"?Ti=et*3:Be==="RBG"?(Ei=0,ei=et,Qt=et*2):Be==="BGR"&&(ei=0,Qt=et,Ei=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,Oe+=tt,It+=tt,ht+=tt)rt[Ei++]=(Y[Xe]+De[0])/Le[0],rt[Qt++]=(Y[It]+De[1])/Le[1],rt[ei++]=(Y[Oe]+De[2])/Le[2],Ti!==-1&&ht!==-1&&(rt[Ti++]=(Y[ht]+De[3])/Le[3]);return Be==="RGBA"?new X("float32",rt,[1,4,ue,Ee]):new X("float32",rt,[1,3,ue,Ee])},me=async(Y,se)=>{let ue=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Ee=typeof ImageData<"u"&&Y instanceof ImageData,ye=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Le=typeof Y=="string",De,Ae=se??{},Be=()=>{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=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(ue){let rt=Be();rt.width=Y.width,rt.height=Y.height;let tt=et(rt);if(tt!=null){let Xe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(Xe=se.resizedHeight,It=se.resizedWidth),se!==void 0){if(Ae=se,se.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=Xe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=Xe,Ae.width=It;tt.drawImage(Y,0,0),De=tt.getImageData(0,0,It,Xe).data}else throw new Error("Can not access image data")}else if(Ee){let rt,tt;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,tt=se.resizedWidth):(rt=Y.height,tt=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=tt,se!==void 0){let Xe=Be();Xe.width=tt,Xe.height=rt;let It=et(Xe);if(It!=null)It.putImageData(Y,0,0),De=It.getImageData(0,0,tt,rt).data;else throw new Error("Can not access image data")}else De=Y.data}else if(ye){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Be();rt.width=Y.width,rt.height=Y.height;let tt=et(rt);if(tt!=null){let Xe=Y.height,It=Y.width;return tt.drawImage(Y,0,0,It,Xe),De=tt.getImageData(0,0,It,Xe).data,Ae.height=Xe,Ae.width=It,Z(De,Ae)}else throw new Error("Can not access image data")}else{if(Le)return new Promise((rt,tt)=>{let Xe=Be(),It=et(Xe);if(!Y||!It)return tt();let Oe=new Image;Oe.crossOrigin="Anonymous",Oe.src=Y,Oe.onload=()=>{Xe.width=Oe.width,Xe.height=Oe.height,It.drawImage(Oe,0,0,Xe.width,Xe.height);let ht=It.getImageData(0,0,Xe.width,Xe.height);Ae.height=Xe.height,Ae.width=Xe.width,rt(Z(ht.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(De!==void 0)return Z(De,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(Y,se)=>{let{width:ue,height:Ee,download:ye,dispose:Le}=se,De=[1,Ee,ue,4];return new X({location:"texture",type:"float32",texture:Y,dims:De,download:ye,dispose:Le})},pe=(Y,se)=>{let{dataType:ue,dims:Ee,download:ye,dispose:Le}=se;return new X({location:"gpu-buffer",type:ue??"float32",gpuBuffer:Y,dims:Ee,download:ye,dispose:Le})},_e=(Y,se)=>{let{dataType:ue,dims:Ee,download:ye,dispose:Le}=se;return new X({location:"ml-tensor",type:ue??"float32",mlTensor:Y,dims:Ee,download:ye,dispose:Le})},Ce=(Y,se,ue)=>new X({location:"cpu-pinned",type:Y,data:se,dims:ue??[se.length]})}),ie,q,oe,ge,ke=d(()=>{ie=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),oe=!1,ge=()=>{if(!oe){oe=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,ue=globalThis.Float16Array,Ee=typeof ue<"u"&&ue.from;Y&&(ie.set("int64",BigInt64Array),q.set(BigInt64Array,"int64")),se&&(ie.set("uint64",BigUint64Array),q.set(BigUint64Array,"uint64")),Ee?(ie.set("float16",ue),q.set(ue,"float16")):ie.set("float16",Uint16Array)}}}),$e,He,ve=d(()=>{Ie(),$e=Y=>{let se=1;for(let ue=0;ue<Y.length;ue++){let Ee=Y[ue];if(typeof Ee!="number"||!Number.isSafeInteger(Ee))throw new TypeError(`dims[${ue}] must be an integer, got: ${Ee}`);if(Ee<0)throw new RangeError(`dims[${ue}] must be a non-negative integer, got: ${Ee}`);se*=Ee}return se},He=(Y,se)=>{switch(Y.location){case"cpu":return new X(Y.type,Y.data,se);case"cpu-pinned":return new X({location:"cpu-pinned",data:Y.data,type:Y.type,dims:se});case"texture":return new X({location:"texture",texture:Y.texture,type:Y.type,dims:se});case"gpu-buffer":return new X({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:se});case"ml-tensor":return new X({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:se});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),X,Ie=d(()=>{de(),U(),ke(),ve(),X=class{constructor(Y,se,ue){ge();let Ee,ye;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Ee=Y.type,ye=Y.dims,Y.location){case"cpu-pinned":{let De=ie.get(Ee);if(!De)throw new TypeError(`unsupported type "${Ee}" to create tensor from pinned buffer`);if(!(Y.data instanceof De))throw new TypeError(`buffer should be of type ${De.name}`);this.cpuData=Y.data;break}case"texture":{if(Ee!=="float32")throw new TypeError(`unsupported type "${Ee}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Ee!=="float32"&&Ee!=="float16"&&Ee!=="int32"&&Ee!=="int64"&&Ee!=="uint32"&&Ee!=="uint8"&&Ee!=="bool"&&Ee!=="uint4"&&Ee!=="int4")throw new TypeError(`unsupported type "${Ee}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Ee!=="float32"&&Ee!=="float16"&&Ee!=="int32"&&Ee!=="int64"&&Ee!=="uint32"&&Ee!=="uint64"&&Ee!=="int8"&&Ee!=="uint8"&&Ee!=="bool"&&Ee!=="uint4"&&Ee!=="int4")throw new TypeError(`unsupported type "${Ee}" to create tensor from MLTensor`);this.mlTensorData=Y.mlTensor,this.downloader=Y.download,this.disposer=Y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let De,Ae;if(typeof Y=="string")if(Ee=Y,Ae=ue,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");De=se}else{let Be=ie.get(Y);if(Be===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Be===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Be.name} as data.`);Y==="uint64"||Y==="int64"?De=Be.from(se,BigInt):De=Be.from(se)}else if(se instanceof Be)De=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")De=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Be!==Uint16Array)De=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Ee} tensor's data must be type of ${Be}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Be=typeof Y[0];if(Be==="string")Ee="string",De=Y;else if(Be==="boolean")Ee="bool",De=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Be}.`)}else if(Y instanceof Uint8ClampedArray)Ee="uint8",De=Uint8Array.from(Y);else{let Be=q.get(Y.constructor);if(Be===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Ee=Be,De=Y}if(Ae===void 0)Ae=[De.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");ye=Ae,this.cpuData=De,this.dataLocation="cpu"}let Le=$e(ye);if(this.cpuData&&Le!==this.cpuData.length&&!((Ee==="uint4"||Ee==="int4")&&Math.ceil(Le/2)===this.cpuData.length))throw new Error(`Tensor's size(${Le}) does not match data length(${this.cpuData.length}).`);this.type=Ee,this.dims=ye,this.size=Le}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return te(Y,se)}static fromGpuBuffer(Y,se){return pe(Y,se)}static fromMLTensor(Y,se){return _e(Y,se)}static fromPinnedBuffer(Y,se,ue){return Ce(Y,se,ue)}toDataURL(Y){return W(this,Y)}toImageData(Y){return re(this,Y)}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(Y){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 se=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=se,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),se}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(Y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return He(this,Y)}}}),he,Pe=d(()=>{Ie(),he=X}),Qe,pt,Pt,dt,Yt,Fe,Ct=d(()=>{L(),Qe=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},pt=(Y,se)=>{var ye;let ue=((ye=new Error().stack)==null?void 0:ye.split(/\r\n|\r|\n/g))||[],Ee=!1;for(let Le=0;Le<ue.length;Le++){if(Ee&&!ue[Le].includes("TRACE_FUNC")){let De=`FUNC_${Y}::${ue[Le].trim().split(" ")[1]}`;se&&(De+=`::${se}`),Qe("CPU",De);return}ue[Le].includes("TRACE_FUNC")&&(Ee=!0)}},Pt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||pt("BEGIN",Y)},dt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||pt("END",Y)},Yt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Fe=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),Me,ot=d(()=>{C(),Pe(),Ct(),Me=class GS{constructor(se){this.handler=se}async run(se,ue,Ee){Pt(),Yt("InferenceSession.run");let ye={},Le={};if(typeof se!="object"||se===null||se instanceof he||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let De=!0;if(typeof ue=="object"){if(ue===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ue instanceof he)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ue)){if(ue.length===0)throw new TypeError("'fetches' cannot be an empty array.");De=!1;for(let et of ue){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}.`);ye[et]=null}if(typeof Ee=="object"&&Ee!==null)Le=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,rt=Object.getOwnPropertyNames(ue);for(let tt of this.outputNames)if(rt.indexOf(tt)!==-1){let Xe=ue[tt];(Xe===null||Xe instanceof he)&&(et=!0,De=!1,ye[tt]=Xe)}if(et){if(typeof Ee=="object"&&Ee!==null)Le=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else Le=ue}}else if(typeof ue<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof se[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(De)for(let et of this.outputNames)ye[et]=null;let Ae=await this.handler.run(se,ye,Le),Be={};for(let et in Ae)if(Object.hasOwnProperty.call(Ae,et)){let rt=Ae[et];rt instanceof he?Be[et]=rt:Be[et]=new he(rt.type,rt.data,rt.dims)}return Fe("InferenceSession.run"),dt(),Be}async release(){return this.handler.dispose()}static async create(se,ue,Ee,ye){Pt(),Yt("InferenceSession.create");let Le,De={};if(typeof se=="string"){if(Le=se,typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Le=se,typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,tt=0,Xe=se.byteLength;if(typeof ue=="object"&&ue!==null)De=ue;else if(typeof ue=="number"){if(tt=ue,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(Xe=se.byteLength-tt,typeof Ee=="number"){if(Xe=Ee,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-tt}].`);if(typeof ye=="object"&&ye!==null)De=ye;else if(typeof ye<"u")throw new TypeError("'options' must be an object.")}else if(typeof Ee<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ue<"u")throw new TypeError("'options' must be an object.");Le=new Uint8Array(rt,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Be]=await b(De),et=await Ae.createInferenceSessionHandler(Le,Be);return Fe("InferenceSession.create"),dt(),new GS(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}}}),ze,ft=d(()=>{ot(),ze=Me}),ct=d(()=>{}),Zt=d(()=>{}),ai=d(()=>{}),Zi=d(()=>{}),$n={};f($n,{InferenceSession:()=>ze,TRACE:()=>Qe,TRACE_EVENT_BEGIN:()=>Yt,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>Pt,TRACE_FUNC_END:()=>dt,Tensor:()=>he,env:()=>j,registerBackend:()=>k});var ci=d(()=>{y(),H(),ft(),Pe(),ct(),Zt(),Ct(),ai(),Zi()}),hn=d(()=>{}),Ai={};f(Ai,{default:()=>it});var Wi,di,it,ri=d(()=>{var Y;fe(),Yn(),Kn(),Wi="ort-wasm-proxy-worker",di=((Y=globalThis.self)==null?void 0:Y.name)===Wi,di&&(self.onmessage=se=>{let{type:ue,in:Ee}=se.data;try{switch(ue){case"init-wasm":ir(Ee.wasm).then(()=>{Bo(Ee).then(()=>{postMessage({type:ue})},ye=>{postMessage({type:ue,err:ye})})},ye=>{postMessage({type:ue,err:ye})});break;case"init-ep":{let{epName:ye,env:Le}=Ee;Sr(Le,ye).then(()=>{postMessage({type:ue})},De=>{postMessage({type:ue,err:De})});break}case"copy-from":{let{buffer:ye}=Ee,Le=si(ye);postMessage({type:ue,out:Le});break}case"create":{let{model:ye,options:Le}=Ee;ms(ye,Le).then(De=>{postMessage({type:ue,out:De})},De=>{postMessage({type:ue,err:De})});break}case"release":Fr(Ee),postMessage({type:ue});break;case"run":{let{sessionId:ye,inputIndices:Le,inputs:De,outputIndices:Ae,options:Be}=Ee;Ye(ye,Le,De,Ae,new Array(Ae.length).fill(null),Be).then(et=>{et.some(rt=>rt[3]!=="cpu")?postMessage({type:ue,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ue,out:et},vt([...De,...et]))},et=>{postMessage({type:ue,err:et})});break}case"end-profiling":Jn(Ee),postMessage({type:ue});break;default:}}catch(ye){postMessage({type:ue,err:ye})}}),it=di?null:se=>new Worker(se??pi,{type:"classic",name:Wi})}),gi,pn,pi,an,Ui,Os,Ls,us,zr,br,wr,zs,Ln,Kn=d(()=>{hn(),gi=typeof location>"u"?void 0:location.origin,pn=()=>{var Y,se;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(se=self.location)==null?void 0:se.href:void 0},pi=pn(),an=()=>{if(pi&&!pi.startsWith("blob:"))return pi.substring(0,pi.lastIndexOf("/")+1)},Ui=(Y,se)=>{try{let ue=se??pi;return(ue?new URL(Y,ue):new URL(Y)).origin===gi}catch{return!1}},Os=(Y,se)=>{let ue=se??pi;try{return(ue?new URL(Y,ue):new URL(Y)).href}catch{return}},Ls=(Y,se)=>`${se??"./"}${Y}`,us=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},zr=async Y=>(await import(Y)).default,br=(ri(),m(Ai)).default,wr=async()=>{if(!pi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Ui(pi))return[void 0,br()];let Y=await us(pi);return[Y,br(Y)]},zs=void 0,Ln=async(Y,se,ue,Ee)=>{let ye=zs&&!(Y||se);if(ye)if(pi)ye=Ui(pi)||Ee&&!ue;else if(Ee&&!ue)ye=!0;else throw new Error("cannot determine the script source URL.");if(ye)return[void 0,zs];{let Le="ort-wasm-simd-threaded.mjs",De=Y??Os(Le,se),Ae=ue&&De&&!Ui(De,se),Be=Ae?await us(De):De??Ls(Le,se);return[Ae?Be:void 0,await zr(Be)]}}}),Qs,zn,hs,$s,ro,er,tr,ir,zt,Yn=d(()=>{Kn(),zn=!1,hs=!1,$s=!1,ro=()=>{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}},er=()=>{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}},tr=()=>{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}},ir=async Y=>{if(zn)return Promise.resolve();if(hs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if($s)throw new Error("previous call to 'initializeWebAssembly()' failed.");hs=!0;let se=Y.initTimeout,ue=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!tr())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!er())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Ee=ro();ue>1&&!Ee&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ue+", 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."),Y.numThreads=ue=1);let ye=Y.wasmPaths,Le=typeof ye=="string"?ye:void 0,De=ye==null?void 0:ye.mjs,Ae=(De==null?void 0:De.href)??De,Be=ye==null?void 0:ye.wasm,et=(Be==null?void 0:Be.href)??Be,rt=Y.wasmBinary,[tt,Xe]=await Ln(Ae,Le,ue>1,!!rt||!!et),It=!1,Oe=[];if(se>0&&Oe.push(new Promise(ht=>{setTimeout(()=>{It=!0,ht()},se)})),Oe.push(new Promise((ht,Ei)=>{let Qt={numThreads:ue};if(rt)Qt.wasmBinary=rt,Qt.locateFile=ei=>ei;else if(et||Le)Qt.locateFile=ei=>et??Le+ei;else if(Ae&&Ae.indexOf("blob:")!==0)Qt.locateFile=ei=>new URL(ei,Ae).href;else if(tt){let ei=an();ei&&(Qt.locateFile=Ti=>ei+Ti)}Xe(Qt).then(ei=>{hs=!1,zn=!0,Qs=ei,ht(),tt&&URL.revokeObjectURL(tt)},ei=>{hs=!1,$s=!0,Ei(ei)})})),await Promise.race(Oe),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(zn&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Vi,Si,Et,Br=d(()=>{Yn(),Vi=(Y,se)=>{let ue=zt(),Ee=ue.lengthBytesUTF8(Y)+1,ye=ue._malloc(Ee);return ue.stringToUTF8(Y,ye,Ee),se.push(ye),ye},Si=(Y,se,ue,Ee)=>{if(typeof Y=="object"&&Y!==null){if(ue.has(Y))throw new Error("Circular reference in options");ue.add(Y)}Object.entries(Y).forEach(([ye,Le])=>{let De=se?se+ye:ye;if(typeof Le=="object")Si(Le,De+".",ue,Ee);else if(typeof Le=="string"||typeof Le=="number")Ee(De,Le.toString());else if(typeof Le=="boolean")Ee(De,Le?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Le}`)})},Et=Y=>{let se=zt(),ue=se.stackSave();try{let Ee=se.PTR_SIZE,ye=se.stackAlloc(2*Ee);se._OrtGetLastError(ye,ye+Ee);let Le=Number(se.getValue(ye,Ee===4?"i32":"i64")),De=se.getValue(ye+Ee,"*"),Ae=De?se.UTF8ToString(De):"";throw new Error(`${Y} ERROR_CODE: ${Le}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(ue)}}}),oo,wa=d(()=>{Yn(),Br(),oo=Y=>{let se=zt(),ue=0,Ee=[],ye=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)ye.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)ye.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(ye.terminate=!1);let Le=0;return(Y==null?void 0:Y.tag)!==void 0&&(Le=Vi(Y.tag,Ee)),ue=se._OrtCreateRunOptions(ye.logSeverityLevel,ye.logVerbosityLevel,!!ye.terminate,Le),ue===0&&Et("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&Si(Y.extra,"",new WeakSet,(De,Ae)=>{let Be=Vi(De,Ee),et=Vi(Ae,Ee);se._OrtAddRunConfigEntry(ue,Be,et)!==0&&Et(`Can't set a run config entry: ${De} - ${Ae}.`)}),[ue,Ee]}catch(Le){throw ue!==0&&se._OrtReleaseRunOptions(ue),Ee.forEach(De=>se._free(De)),Le}}}),ao,lo,zo,In,ya,xa,Ci=d(()=>{Yn(),Br(),ao=Y=>{switch(Y){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: ${Y}`)}},lo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},zo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let se=Y.extra.session;se.use_ort_model_bytes_directly||(se.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(ue=>(typeof ue=="string"?ue:ue.name)==="webgpu")&&(Y.enableMemPattern=!1)},In=(Y,se,ue,Ee)=>{let ye=Vi(se,Ee),Le=Vi(ue,Ee);zt()._OrtAddSessionConfigEntry(Y,ye,Le)!==0&&Et(`Can't set a session config entry: ${se} - ${ue}.`)},ya=async(Y,se,ue)=>{let Ee=se.executionProviders;for(let ye of Ee){let Le=typeof ye=="string"?ye:ye.name,De=[];switch(Le){case"webnn":if(Le="WEBNN",In(Y,"session.disable_quant_qdq","1",ue),In(Y,"session.disable_qdq_constant_folding","1",ue),typeof ye!="string"){let tt=ye==null?void 0:ye.deviceType;tt&&In(Y,"deviceType",tt,ue)}break;case"webgpu":if(Le="JS",typeof ye!="string"){let tt=ye;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);In(Y,"preferredLayout",tt.preferredLayout,ue)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Le}`)}let Ae=Vi(Le,ue),Be=De.length,et=0,rt=0;if(Be>0){et=zt()._malloc(Be*zt().PTR_SIZE),ue.push(et),rt=zt()._malloc(Be*zt().PTR_SIZE),ue.push(rt);for(let tt=0;tt<Be;tt++)zt().setValue(et+tt*zt().PTR_SIZE,De[tt][0],"*"),zt().setValue(rt+tt*zt().PTR_SIZE,De[tt][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,et,rt,Be)!==0&&Et(`Can't append execution provider: ${Le}.`)}},xa=async Y=>{let se=zt(),ue=0,Ee=[],ye=Y||{};zo(ye);try{let Le=ao(ye.graphOptimizationLevel??"all"),De=lo(ye.executionMode??"sequential"),Ae=typeof ye.logId=="string"?Vi(ye.logId,Ee):0,Be=ye.logSeverityLevel??2;if(!Number.isInteger(Be)||Be<0||Be>4)throw new Error(`log severity level is not valid: ${Be}`);let et=ye.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let rt=typeof ye.optimizedModelFilePath=="string"?Vi(ye.optimizedModelFilePath,Ee):0;if(ue=se._OrtCreateSessionOptions(Le,!!ye.enableCpuMemArena,!!ye.enableMemPattern,De,!!ye.enableProfiling,0,Ae,Be,et,rt),ue===0&&Et("Can't create session options."),ye.executionProviders&&await ya(ue,ye,Ee),ye.enableGraphCapture!==void 0){if(typeof ye.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ye.enableGraphCapture}`);In(ue,"enableGraphCapture",ye.enableGraphCapture.toString(),Ee)}if(ye.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(ye.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let It=Vi(tt,Ee);se._OrtAddFreeDimensionOverride(ue,It,Xe)!==0&&Et(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return ye.extra!==void 0&&Si(ye.extra,"",new WeakSet,(tt,Xe)=>{In(ue,tt,Xe,Ee)}),[ue,Ee]}catch(Le){throw ue!==0&&se._OrtReleaseSessionOptions(ue)!==0&&Et("Can't release session options."),Ee.forEach(De=>se._free(De)),Le}}}),Bn,Ki,Gn,nr,Gr,yr,ps,wn,Bt=d(()=>{Bn=Y=>{switch(Y){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: ${Y}`)}},Ki=Y=>{switch(Y){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: ${Y}`)}},Gn=(Y,se)=>{let ue=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Y],Ee=typeof se=="number"?se:se.reduce((ye,Le)=>ye*Le,1);return ue>0?Math.ceil(Ee*ue):void 0},nr=Y=>{switch(Y){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: ${Y}`)}},Gr=Y=>{switch(Y){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: ${Y}`)}},yr=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",ps=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",wn=Y=>{switch(Y){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: ${Y}`)}}}),Yi,xr=d(()=>{hn(),Yi=async Y=>{if(typeof Y=="string"){let se=await fetch(Y);if(!se.ok)throw new Error(`failed to load external data file: ${Y}`);let ue=se.headers.get("Content-Length"),Ee=ue?parseInt(ue,10):0;if(Ee<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let ye=se.body.getReader(),Le;try{Le=new ArrayBuffer(Ee)}catch(Ae){if(Ae instanceof RangeError){let Be=Math.ceil(Ee/65536);Le=new WebAssembly.Memory({initial:Be,maximum:Be}).buffer}else throw Ae}let De=0;for(;;){let{done:Ae,value:Be}=await ye.read();if(Ae)break;let et=Be.byteLength;new Uint8Array(Le,De,et).set(Be),De+=et}return new Uint8Array(Le,0,Ee)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),fs,Bo,Sr,Xn,Bs,Cr,si,ms,Fr,Is,Ye,Jn,vt,fe=d(()=>{ci(),wa(),Ci(),Bt(),Yn(),Br(),xr(),fs=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&Et("Can't initialize onnxruntime.")},Bo=async Y=>{fs(Y.wasm.numThreads,Gr(Y.logLevel))},Sr=async(Y,se)=>{var Ee,ye;(ye=(Ee=zt()).asyncInit)==null||ye.call(Ee);let ue=Y.webgpu.adapter;if(se==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ue){if(typeof ue.limits!="object"||typeof ue.features!="object"||typeof ue.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Le=Y.webgpu.powerPreference;if(Le!==void 0&&Le!=="low-power"&&Le!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Le}"`);let De=Y.webgpu.forceFallbackAdapter;if(De!==void 0&&typeof De!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${De}"`);if(ue=await navigator.gpu.requestAdapter({powerPreference:Le,forceFallbackAdapter:De}),!ue)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(se==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Xn=new Map,Bs=Y=>{let se=zt(),ue=se.stackSave();try{let Ee=se.PTR_SIZE,ye=se.stackAlloc(2*Ee);se._OrtGetInputOutputCount(Y,ye,ye+Ee)!==0&&Et("Can't get session input/output count.");let Le=Ee===4?"i32":"i64";return[Number(se.getValue(ye,Le)),Number(se.getValue(ye+Ee,Le))]}finally{se.stackRestore(ue)}},Cr=(Y,se)=>{let ue=zt(),Ee=ue.stackSave(),ye=0;try{let Le=ue.PTR_SIZE,De=ue.stackAlloc(2*Le);ue._OrtGetInputOutputMetadata(Y,se,De,De+Le)!==0&&Et("Can't get session input/output metadata.");let Ae=Number(ue.getValue(De,"*"));ye=Number(ue.getValue(De+Le,"*"));let Be=ue.HEAP32[ye/4];if(Be===0)return[Ae,0];let et=ue.HEAPU32[ye/4+1],rt=[];for(let tt=0;tt<et;tt++){let Xe=Number(ue.getValue(ye+8+tt*Le,"*"));rt.push(Xe!==0?ue.UTF8ToString(Xe):Number(ue.getValue(ye+8+(tt+et)*Le,"*")))}return[Ae,Be,rt]}finally{ue.stackRestore(Ee),ye!==0&&ue._OrtFree(ye)}},si=Y=>{let se=zt(),ue=se._malloc(Y.byteLength);if(ue===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,ue),[ue,Y.byteLength]},ms=async(Y,se)=>{var rt,tt,Xe;let ue,Ee,ye=zt();Array.isArray(Y)?[ue,Ee]=Y:Y.buffer===ye.HEAPU8.buffer?[ue,Ee]=[Y.byteOffset,Y.byteLength]:[ue,Ee]=si(Y);let Le=0,De=0,Ae=[],Be=[],et=[];try{if([De,Ae]=await xa(se),(se==null?void 0:se.externalData)&&ye.mountExternalData){let Ni=[];for(let ui of se.externalData){let yn=typeof ui=="string"?ui:ui.path;Ni.push(Yi(typeof ui=="string"?ui:ui.data).then(Fn=>{ye.mountExternalData(yn,Fn)}))}await Promise.all(Ni)}for(let Ni of(se==null?void 0:se.executionProviders)??[])if((typeof Ni=="string"?Ni:Ni.name)==="webnn"){if(ye.shouldTransferToMLTensor=!1,typeof Ni!="string"){let ui=Ni,yn=ui==null?void 0:ui.context,Fn=ui==null?void 0:ui.gpuDevice,Zn=ui==null?void 0:ui.deviceType,Ca=ui==null?void 0:ui.powerPreference;yn?ye.currentContext=yn:Fn?ye.currentContext=await ye.webnnCreateMLContext(Fn):ye.currentContext=await ye.webnnCreateMLContext({deviceType:Zn,powerPreference:Ca})}else ye.currentContext=await ye.webnnCreateMLContext();break}Le=await ye._OrtCreateSession(ue,Ee,De),(rt=ye.webgpuOnCreateSession)==null||rt.call(ye,Le),Le===0&&Et("Can't create a session."),(tt=ye.jsepOnCreateSession)==null||tt.call(ye),ye.currentContext&&(ye.webnnRegisterMLContext(Le,ye.currentContext),ye.currentContext=void 0,ye.shouldTransferToMLTensor=!0);let[It,Oe]=Bs(Le),ht=!!(se!=null&&se.enableGraphCapture),Ei=[],Qt=[],ei=[],Ti=[],Ot=[];for(let Ni=0;Ni<It;Ni++){let[ui,yn,Fn]=Cr(Le,Ni);ui===0&&Et("Can't get an input name."),Be.push(ui);let Zn=ye.UTF8ToString(ui);Ei.push(Zn),ei.push(yn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ki(yn),shape:Fn})}for(let Ni=0;Ni<Oe;Ni++){let[ui,yn,Fn]=Cr(Le,Ni+It);ui===0&&Et("Can't get an output name."),et.push(ui);let Zn=ye.UTF8ToString(ui);Qt.push(Zn),Ti.push(yn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ki(yn),shape:Fn})}return Xn.set(Le,[Le,Be,et,null,ht,!1]),[Le,Ei,Qt,ei,Ti]}catch(It){throw Be.forEach(Oe=>ye._OrtFree(Oe)),et.forEach(Oe=>ye._OrtFree(Oe)),Le!==0&&ye._OrtReleaseSession(Le)!==0&&Et("Can't release session."),It}finally{ye._free(ue),De!==0&&ye._OrtReleaseSessionOptions(De)!==0&&Et("Can't release session options."),Ae.forEach(It=>ye._free(It)),(Xe=ye.unmountExternalData)==null||Xe.call(ye)}},Fr=Y=>{var Be,et,rt;let se=zt(),ue=Xn.get(Y);if(!ue)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Ee,ye,Le,De,Ae]=ue;De&&(Ae&&se._OrtClearBoundOutputs(De.handle)!==0&&Et("Can't clear bound outputs."),se._OrtReleaseBinding(De.handle)!==0&&Et("Can't release IO binding.")),(Be=se.jsepOnReleaseSession)==null||Be.call(se,Y),(et=se.webnnOnReleaseSession)==null||et.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),ye.forEach(tt=>se._OrtFree(tt)),Le.forEach(tt=>se._OrtFree(tt)),se._OrtReleaseSession(Ee)!==0&&Et("Can't release session."),Xn.delete(Y)},Is=async(Y,se,ue,Ee,ye,Le,De=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Be=Ae.PTR_SIZE,et=Y[0],rt=Y[1],tt=Y[3],Xe=tt,It,Oe;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(De&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Le} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Qt=Y[2].gpuBuffer;Oe=Gn(Bn(et),rt);{let ei=Ae.jsepRegisterBuffer;if(!ei)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=ei(Ee,Le,Qt,Oe)}}else if(tt==="ml-tensor"){let Qt=Y[2].mlTensor;Oe=Gn(Bn(et),rt);let ei=Ae.webnnRegisterMLTensor;if(!ei)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=ei(Ee,Qt,Bn(et),rt)}else{let Qt=Y[2];if(Array.isArray(Qt)){Oe=Be*Qt.length,It=Ae._malloc(Oe),ue.push(It);for(let ei=0;ei<Qt.length;ei++){if(typeof Qt[ei]!="string")throw new TypeError(`tensor data at index ${ei} is not a string`);Ae.setValue(It+ei*Be,Vi(Qt[ei],ue),"*")}}else{let ei=Ae.webnnIsGraphInput,Ti=Ae.webnnIsGraphOutput;if(et!=="string"&&ei&&Ti){let Ot=Ae.UTF8ToString(ye);if(ei(Ee,Ot)||Ti(Ee,Ot)){let Ni=Bn(et);Oe=Gn(Ni,rt),Xe="ml-tensor";let ui=Ae.webnnCreateTemporaryTensor,yn=Ae.webnnUploadTensor;if(!ui||!yn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Fn=await ui(Ee,Ni,rt);yn(Fn,new Uint8Array(Qt.buffer,Qt.byteOffset,Qt.byteLength)),It=Fn}else Oe=Qt.byteLength,It=Ae._malloc(Oe),ue.push(It),Ae.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Oe),It)}else Oe=Qt.byteLength,It=Ae._malloc(Oe),ue.push(It),Ae.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Oe),It)}}let ht=Ae.stackSave(),Ei=Ae.stackAlloc(4*rt.length);try{rt.forEach((ei,Ti)=>Ae.setValue(Ei+Ti*Be,ei,Be===4?"i32":"i64"));let Qt=Ae._OrtCreateTensor(Bn(et),It,Oe,Ei,rt.length,wn(Xe));Qt===0&&Et(`Can't create tensor for input/output. session=${Ee}, index=${Le}.`),se.push(Qt)}finally{Ae.stackRestore(ht)}},Ye=async(Y,se,ue,Ee,ye,Le)=>{var Qn,cl,rc;let De=zt(),Ae=De.PTR_SIZE,Be=Xn.get(Y);if(!Be)throw new Error(`cannot run inference. invalid session id: ${Y}`);let et=Be[0],rt=Be[1],tt=Be[2],Xe=Be[3],It=Be[4];Be[5];let Oe=se.length,ht=Ee.length,Ei=0,Qt=[],ei=[],Ti=[],Ot=[],Ni=[],ui=De.stackSave(),yn=De.stackAlloc(Oe*Ae),Fn=De.stackAlloc(Oe*Ae),Zn=De.stackAlloc(ht*Ae),Ca=De.stackAlloc(ht*Ae);try{[Ei,Qt]=oo(Le),Yt("wasm prepareInputOutputTensor");for(let li=0;li<Oe;li++)await Is(ue[li],ei,Ot,Y,rt[se[li]],se[li],It);for(let li=0;li<ht;li++)await Is(ye[li],Ti,Ot,Y,tt[Ee[li]],Oe+Ee[li],It);Fe("wasm prepareInputOutputTensor");for(let li=0;li<Oe;li++)De.setValue(yn+li*Ae,ei[li],"*"),De.setValue(Fn+li*Ae,rt[se[li]],"*");for(let li=0;li<ht;li++)De.setValue(Zn+li*Ae,Ti[li],"*"),De.setValue(Ca+li*Ae,tt[Ee[li]],"*");(Qn=De.jsepOnRunStart)==null||Qn.call(De,et),(cl=De.webnnOnRunStart)==null||cl.call(De,et);let xn;xn=await De._OrtRun(et,Fn,yn,Oe,Ca,ht,Zn,Ei),xn!==0&&Et("failed to call OrtRun().");let rr=[],oc=[];Yt("wasm ProcessOutputTensor");for(let li=0;li<ht;li++){let Fs=Number(De.getValue(Zn+li*Ae,"*"));if(Fs===Ti[li]||Ni.includes(Ti[li])){rr.push(ye[li]),Fs!==Ti[li]&&De._OrtReleaseTensor(Fs)!==0&&Et("Can't release tensor.");continue}let fd=De.stackSave(),Tr=De.stackAlloc(4*Ae),Go=!1,cn,es=0;try{De._OrtGetTensorData(Fs,Tr,Tr+Ae,Tr+2*Ae,Tr+3*Ae)!==0&&Et(`Can't access output tensor data on index ${li}.`);let dl=Ae===4?"i32":"i64",ts=Number(De.getValue(Tr,dl));es=De.getValue(Tr+Ae,"*");let ac=De.getValue(Tr+Ae*2,"*"),md=Number(De.getValue(Tr+Ae*3,dl)),Dr=[];for(let dn=0;dn<md;dn++)Dr.push(Number(De.getValue(ac+dn*Ae,dl)));De._OrtFree(ac)!==0&&Et("Can't free memory for tensor dims.");let Hs=Dr.reduce((dn,qi)=>dn*qi,1);cn=Ki(ts);let or=Xe==null?void 0:Xe.outputPreferredLocations[Ee[li]];if(cn==="string"){if(or==="gpu-buffer"||or==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let dn=[];for(let qi=0;qi<Hs;qi++){let Ws=De.getValue(es+qi*Ae,"*"),lc=De.getValue(es+(qi+1)*Ae,"*"),cc=qi===Hs-1?void 0:lc-Ws;dn.push(De.UTF8ToString(Ws,cc))}rr.push([cn,Dr,dn,"cpu"])}else if(or==="gpu-buffer"&&Hs>0){let dn=De.jsepGetBuffer;if(!dn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let qi=dn(es),Ws=Gn(ts,Hs);if(Ws===void 0||!yr(cn))throw new Error(`Unsupported data type: ${cn}`);Go=!0,rr.push([cn,Dr,{gpuBuffer:qi,download:De.jsepCreateDownloader(qi,Ws,cn),dispose:()=>{De._OrtReleaseTensor(Fs)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(or==="ml-tensor"&&Hs>0){let dn=De.webnnEnsureTensor,qi=De.webnnIsGraphInputOutputTypeSupported;if(!dn||!qi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Gn(ts,Hs)===void 0||!ps(cn))throw new Error(`Unsupported data type: ${cn}`);if(!qi(Y,cn,!1))throw new Error(`preferredLocation "ml-tensor" for ${cn} output is not supported by current WebNN Context.`);let Ws=await dn(Y,es,ts,Dr,!1);Go=!0,rr.push([cn,Dr,{mlTensor:Ws,download:De.webnnCreateMLTensorDownloader(es,cn),dispose:()=>{De.webnnReleaseTensorId(es),De._OrtReleaseTensor(Fs)}},"ml-tensor"])}else if(or==="ml-tensor-cpu-output"&&Hs>0){let dn=De.webnnCreateMLTensorDownloader(es,cn)(),qi=rr.length;Go=!0,oc.push((async()=>{let Ws=[qi,await dn];return De.webnnReleaseTensorId(es),De._OrtReleaseTensor(Fs),Ws})()),rr.push([cn,Dr,[],"cpu"])}else{let dn=nr(cn),qi=new dn(Hs);new Uint8Array(qi.buffer,qi.byteOffset,qi.byteLength).set(De.HEAPU8.subarray(es,es+qi.byteLength)),rr.push([cn,Dr,qi,"cpu"])}}finally{De.stackRestore(fd),cn==="string"&&es&&De._free(es),Go||De._OrtReleaseTensor(Fs)}}Xe&&!It&&(De._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),Xn.set(Y,[et,rt,tt,Xe,It,!1]));for(let[li,Fs]of await Promise.all(oc))rr[li][2]=Fs;return Fe("wasm ProcessOutputTensor"),rr}finally{(rc=De.webnnOnRunEnd)==null||rc.call(De,et),De.stackRestore(ui),ei.forEach(xn=>De._OrtReleaseTensor(xn)),Ti.forEach(xn=>De._OrtReleaseTensor(xn)),Ot.forEach(xn=>De._free(xn)),Ei!==0&&De._OrtReleaseRunOptions(Ei),Qt.forEach(xn=>De._free(xn))}},Jn=Y=>{let se=zt(),ue=Xn.get(Y);if(!ue)throw new Error("invalid session id");let Ee=ue[0],ye=se._OrtEndProfiling(Ee);ye===0&&Et("Can't get an profile file name."),se._OrtFree(ye)},vt=Y=>{let se=[];for(let ue of Y){let Ee=ue[2];!Array.isArray(Ee)&&"buffer"in Ee&&se.push(Ee.buffer)}return se}}),je,Je,Dt,ii,oi,ji,$i,rn,zi,ln,Ii,Gs,Hr,co,sr,pd,uo,ho,ic=d(()=>{ci(),fe(),Yn(),Kn(),je=()=>!!j.wasm.proxy&&typeof document<"u",Dt=!1,ii=!1,oi=!1,rn=new Map,zi=(Y,se)=>{let ue=rn.get(Y);ue?ue.push(se):rn.set(Y,[se])},ln=()=>{if(Dt||!ii||oi||!Je)throw new Error("worker not ready")},Ii=Y=>{switch(Y.data.type){case"init-wasm":Dt=!1,Y.data.err?(oi=!0,$i[1](Y.data.err)):(ii=!0,$i[0]()),ji&&(URL.revokeObjectURL(ji),ji=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=rn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Gs=async()=>{if(!ii){if(Dt)throw new Error("multiple calls to 'initWasm()' detected.");if(oi)throw new Error("previous call to 'initWasm()' failed.");if(Dt=!0,je())return new Promise((Y,se)=>{Je==null||Je.terminate(),wr().then(([ue,Ee])=>{try{Je=Ee,Je.onerror=Le=>se(Le),Je.onmessage=Ii,$i=[Y,se];let ye={type:"init-wasm",in:j};if(!ye.in.wasm.wasmPaths&&ue){let Le=an();Le&&(ye.in.wasm.wasmPaths=Le)}Je.postMessage(ye),ji=ue}catch(ye){se(ye)}},se)});try{await ir(j.wasm),await Bo(j),ii=!0}catch(Y){throw oi=!0,Y}finally{Dt=!1}}},Hr=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("init-ep",[se,ue]);let Ee={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Ee)});await Sr(j,Y)},co=async Y=>je()?(ln(),new Promise((se,ue)=>{zi("copy-from",[se,ue]);let Ee={type:"copy-from",in:{buffer:Y}};Je.postMessage(Ee,[Y.buffer])})):si(Y),sr=async(Y,se)=>{if(je()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return ln(),new Promise((ue,Ee)=>{zi("create",[ue,Ee]);let ye={type:"create",in:{model:Y,options:{...se}}},Le=[];Y instanceof Uint8Array&&Le.push(Y.buffer),Je.postMessage(ye,Le)})}else return ms(Y,se)},pd=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("release",[se,ue]);let Ee={type:"release",in:Y};Je.postMessage(Ee)});Fr(Y)},uo=async(Y,se,ue,Ee,ye,Le)=>{if(je()){if(ue.some(De=>De[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ye.some(De=>De))throw new Error("pre-allocated output tensor is not supported for proxy.");return ln(),new Promise((De,Ae)=>{zi("run",[De,Ae]);let Be=ue,et={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Be,outputIndices:Ee,options:Le}};Je.postMessage(et,vt(Be))})}else return Ye(Y,se,ue,Ee,ye,Le)},ho=async Y=>{if(je())return ln(),new Promise((se,ue)=>{zi("end-profiling",[se,ue]);let Ee={type:"end-profiling",in:Y};Je.postMessage(Ee)});Jn(Y)}}),rl,po,Sa,ol=d(()=>{ci(),ic(),Bt(),hn(),xr(),rl=(Y,se)=>{switch(Y.location){case"cpu":return[Y.type,Y.dims,Y.data,"cpu"];case"gpu-buffer":return[Y.type,Y.dims,{gpuBuffer:Y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Y.type,Y.dims,{mlTensor:Y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Y.location} for ${se()}`)}},po=Y=>{switch(Y[3]){case"cpu":return new he(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!yr(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:ue,download:Ee,dispose:ye}=Y[2];return he.fromGpuBuffer(ue,{dataType:se,dims:Y[1],download:Ee,dispose:ye})}case"ml-tensor":{let se=Y[0];if(!ps(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:ue,download:Ee,dispose:ye}=Y[2];return he.fromMLTensor(ue,{dataType:se,dims:Y[1],download:Ee,dispose:ye})}default:throw new Error(`invalid data location: ${Y[3]}`)}},Sa=class{async fetchModelAndCopyToWasmMemory(Y){return co(await Yi(Y))}async loadModel(Y,se){Pt();let ue;typeof Y=="string"?ue=await this.fetchModelAndCopyToWasmMemory(Y):ue=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await sr(ue,se),dt()}async dispose(){return pd(this.sessionId)}async run(Y,se,ue){Pt();let Ee=[],ye=[];Object.entries(Y).forEach(tt=>{let Xe=tt[0],It=tt[1],Oe=this.inputNames.indexOf(Xe);if(Oe===-1)throw new Error(`invalid input '${Xe}'`);Ee.push(It),ye.push(Oe)});let Le=[],De=[];Object.entries(se).forEach(tt=>{let Xe=tt[0],It=tt[1],Oe=this.outputNames.indexOf(Xe);if(Oe===-1)throw new Error(`invalid output '${Xe}'`);Le.push(It),De.push(Oe)});let Ae=Ee.map((tt,Xe)=>rl(tt,()=>`input "${this.inputNames[ye[Xe]]}"`)),Be=Le.map((tt,Xe)=>tt?rl(tt,()=>`output "${this.outputNames[De[Xe]]}"`):null),et=await uo(this.sessionId,ye,Ae,De,Be,ue),rt={};for(let tt=0;tt<et.length;tt++)rt[this.outputNames[De[tt]]]=Le[tt]??po(et[tt]);return dt(),rt}startProfiling(){}endProfiling(){ho(this.sessionId)}}}),kr={};f(kr,{OnnxruntimeWebAssemblyBackend:()=>Er,initializeFlags:()=>Wr,wasmBackend:()=>fo});var Wr,Er,fo,nc=d(()=>{ci(),ic(),ol(),Wr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let Y=j.wasm.simd;if(typeof Y!="boolean"&&Y!==void 0&&Y!=="fixed"&&Y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Y}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let se=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((se||1)/2))}},Er=class{async init(Y){Wr(),await Gs(),await Hr(Y)}async createInferenceSessionHandler(Y,se){let ue=new Sa;return await ue.loadModel(Y,se),ue}},fo=new Er}),sc={};f(sc,{InferenceSession:()=>ze,TRACE:()=>Qe,TRACE_EVENT_BEGIN:()=>Yt,TRACE_EVENT_END:()=>Fe,TRACE_FUNC_BEGIN:()=>Pt,TRACE_FUNC_END:()=>dt,Tensor:()=>he,default:()=>ll,env:()=>j,registerBackend:()=>k}),ci(),ci(),ci();var al="1.26.0",ll=$n;{let Y=(nc(),m(kr)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:al,enumerable:!0}),m(sc)})();i.exports=t})(Xv)),Xv.exports}var Ly;function sT(){return Ly||(Ly=1,(function(i){var e=qa&&qa.__createBinding||(Object.create?(function(x,A,P,N){N===void 0&&(N=P);var L=Object.getOwnPropertyDescriptor(A,P);(!L||("get"in L?!A.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return A[P]}}),Object.defineProperty(x,N,L)}):(function(x,A,P,N){N===void 0&&(N=P),x[N]=A[P]})),t=qa&&qa.__setModuleDefault||(Object.create?(function(x,A){Object.defineProperty(x,"default",{enumerable:!0,value:A})}):function(x,A){x.default=A}),n=qa&&qa.__importStar||function(x){if(x&&x.__esModule)return x;var A={};if(x!=null)for(var P in x)P!=="default"&&Object.prototype.hasOwnProperty.call(x,P)&&e(A,x,P);return t(A,x),A};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(nT()),l=qb(),p=Kb(),a=Yf(),d=vv(),f=zS(),g=BS();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",w="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",k=x=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async A=>{A.getTracks().forEach(P=>{P.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:A=>{A.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const E=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,A,P,N,L){await P.audioWorklet.addModule(x),A.processorOptions={...A.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(P,"vad-helper-worklet",A);return j.port.onmessage=async H=>{const W=H.data;if(!(typeof W=="object"&&W&&"message"in W)){console.error("Invalid message event",W);return}switch(W.message){case d.Message.AudioFrame:{if(!("data"in W&&W.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const re=new Float32Array(W.data);await L(re);break}}},j}async function C(x,A,P){const N=new g.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:A});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async W=>{if(!H){H=!0;try{const re=W.inputBuffer.getChannelData(0);W.outputBuffer.getChannelData(0).fill(0);const Z=N.process(re);for(const me of Z)await P(me)}catch(re){console.error("Error processing audio:",re)}finally{H=!1}}},j.connect(x.destination),j}class y{constructor(A,P,N,L,j=!1,H=null,W=null,re=null,de=null,Z=null,me=null,te="uninitialized",pe=!1){this.options=A,this.frameProcessor=P,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=W,this._audioContext=re,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=te,this.ownsAudioContext=pe,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=_e=>{this.initializationState="errored",this.errored=_e},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(_e){throw _e instanceof Error?this.setErrored(_e.message):this.setErrored(String(_e)),_e}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"?E(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await C(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),a.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{a.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:_e,audioContext:Ce,vadNode:U}=this.getAudioInstances();this._stream=await this.options.resumeStream(_e);const ie=new MediaStreamAudioSourceNode(Ce,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ie,ie.connect(U);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:_e,mediaStreamAudioSourceNode:Ce}=this.getAudioInstances();await this.options.pauseStream(_e),Ce.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ce;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:_e}=this.getAudioInstances();_e instanceof AudioWorkletNode&&_e.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ce=this._audioContext)==null?void 0:Ce.close())},this.setOptions=_e=>{this.frameProcessor.setOptions(_e)},this.processFrame=async _e=>{await this.frameProcessor.process(_e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=_e=>{switch(_e.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(_e.probs,_e.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(_e.audio);break}}}static async new(A={}){const P={...(0,i.getDefaultRealTimeVADOptions)(A.model??i.DEFAULT_MODEL),...A};(0,p.validateOptions)(P),i.ort.env.wasm.wasmPaths=P.onnxWASMBasePath,P.ortConfig!==void 0&&P.ortConfig(i.ort);const N=P.model==="v5"?w:D,L=P.baseAssetPath+N,j=P.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let H;try{H=await j(i.ort,()=>(0,l.defaultModelFetcher)(L))}catch(me){throw console.error(`Encountered an error while loading model file ${L}`),me}const W=P.model==="v5"?512:1536,re=W/16,de=new p.FrameProcessor(H.process,H.reset_state,{positiveSpeechThreshold:P.positiveSpeechThreshold,negativeSpeechThreshold:P.negativeSpeechThreshold,redemptionMs:P.redemptionMs,preSpeechPadMs:P.preSpeechPadMs,minSpeechMs:P.minSpeechMs,submitUserSpeechOnPause:P.submitUserSpeechOnPause},re),Z=new y(P,de,H,W);if(P.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=y})(qa)),qa}var zy;function rT(){return zy||(zy=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=MS();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=qb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Kb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=vv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=tT();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=iT();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=sT();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return a.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return a.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return a.getDefaultRealTimeVADOptions}})})(qv)),qv}var oT=rT();function ng(i,e,t,n,r){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,r)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const gt={debug:(i,e,t)=>ng(i,"debug",e,t),info:(i,e,t)=>ng(i,"info",e,t),warn:(i,e,t)=>ng(i,"warn",e,t),error:(i,e,t,n)=>ng(i,"error",e,t,n)},FS=16e3,aT=6,Ku=FS*aT,lT=400,cT=FS*lT/1e3,By=300,Gy=2e3,Fy=1500,Hy=3e3,dT=600,HS=.5,WS=.35,Wy=.85,Uy=.7;let _r=null,ga=!1,Zs=!1;const G_=new Set;function sg(i){for(const e of Array.from(G_))try{e(i)}catch(t){gt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Jv=0;const Vy=2;let rh=!1,US=!1;function VS(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";gt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{gt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),uT(`error:${e.message||"unknown"}`)})}function ev(){return _r||(_r=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),VS(_r),gt.info("speech","worker spawned"),_r)}let rg=!1;function uT(i){if(!rh){if(rg){gt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(rg=!0,Jv+=1,US=!0,gt.warn("speech","respawnWorker: starting",{reason:i,attempt:Jv}),sg({reason:i,respawned:!1,finalOnly:!0}),Jv>Vy){if(rh=!0,gt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Vy}),_r)try{_r.terminate()}catch{}_r=null,ga=!1,Zs=!1,sg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),rg=!1;return}if(_r)try{_r.terminate()}catch{}_r=null,ga=!1,Zs=!1;try{_r=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),VS(_r),Zs=!0,_r.postMessage({type:"load"}),gt.info("speech","respawnWorker: new worker spawned, load posted"),sg({reason:i,respawned:!0,finalOnly:!0})}catch(e){rh=!0,gt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),sg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{rg=!1}}}function hT(i,e){if(ga||Zs)return;Zs=!0;const t=ev();gt.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(i==null||i(r.data.status,r.data.message),r.data.status==="ready"&&(ga=!0,Zs=!1,gt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(Zs=!1,gt.error("speech","preloadModel: worker reported error",{error:r.data.error}),i==null||i("error",r.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function pT(){gt.info("speech","resetModel: clearing load flags"),ga=!1,Zs=!1}function _v(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function fT(i){const e=ev();return!ga&&!Zs&&(Zs=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const r=l=>{var p,a,d;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",r),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(l.data.error??"Transcription failed")))):((d=l.data)==null?void 0:d.type)==="status"&&l.data.status==="ready"&&(ga=!0,Zs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function qS(i){let e=ev(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let g=null,m=0,w=!1,D=0,k=!1,E=!1,b=0,C=0,y=0,x=-1,A=By,P=0,N=null,L="",j="",H=!1,W=0;function re(ge,ke){const $e=Math.min(ge.length,ke.length);let He=0;for(;He<$e&&ge.charCodeAt(He)===ke.charCodeAt(He);)He++;return He}function de(ge){const ke=re(L,ge);return L=ge,ke>j.length&&(j=ge.slice(0,ke)),j.length>ge.length&&(j=ge),j}const Z=()=>(g||(g=new Float32Array(Ku)),g),me=()=>{m=0},te=ge=>{const ke=Z(),$e=ge.length;if($e>=Ku){ke.set(ge.subarray($e-Ku)),m=Ku;return}if(m+$e<=Ku){ke.set(ge,m),m+=$e;return}const He=m+$e-Ku;ke.copyWithin(0,He,m),m-=He,ke.set(ge,m),m+=$e},pe=()=>{N&&(clearTimeout(N),N=null)},_e=()=>{pe(),w=!1,k=!1,E=!1,A=By,L="",j="",H=!1,W=0,me()},Ce=()=>{if(t||!w||E||k||N)return;if(m<cT){N=setTimeout(()=>{N=null,Ce()},A);return}const ge=performance.now()-b;if(ge<A&&b!==0){N=setTimeout(()=>{N=null,Ce()},A-ge);return}if(US||rh||i.partialsEnabled&&!i.partialsEnabled())return;const ke=Z(),$e=new Float32Array(m);$e.set(ke.subarray(0,m)),C+=1,y=C,k=!0,P=performance.now(),b=P,e.postMessage({type:"transcribe-partial",audio:$e,seq:C},[$e.buffer])},U=ge=>ge.length===0?Promise.resolve():rh?(gt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ke=>{d.push(ke),C+=1;const $e=C;x=$e,e.postMessage({type:"transcribe",audio:ge,seq:$e},[ge.buffer])}),ie=ge=>{const ke=U(ge);return f.add(ke),ke.finally(()=>{f.delete(ke)}),ke},q=ge=>{var ke,$e,He,ve,X;if(ge.data.type==="result"){const Ie=ge.data.text,he=ge.data.seq??0;he&&he<x&>.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:he,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(ke=d.shift())==null||ke()}else if(ge.data.type==="partial"){const Ie=ge.data.seq??0,he=ge.data.text??"",Pe=performance.now()-P;k=!1,Pe>=Hy?(E=!0,gt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Pe),seq:Ie})):Pe>=Fy&&(A=Math.min(A*2,Gy),gt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Pe),newIntervalMs:A,seq:Ie})),H||(H=!0,Pe>dT&&A<500&&(A=500,gt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Pe),newIntervalMs:500})));const Qe=Ie!==y||Ie<=x;if(!t&&!Qe&&he){const pt=de(he);pt&&(($e=i.onPartial)==null||$e.call(i,pt),W===0&&(W=performance.now(),gt.info("speech","partial.first",{msSinceSpeechStart:Math.round(W-D)})))}Ce()}else if(ge.data.type==="partial-error"){const Ie=performance.now()-P;k=!1,Ie>=Hy?(E=!0,gt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ge.data.seq})):Ie>=Fy&&(A=Math.min(A*2,Gy),gt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:A,seq:ge.data.seq})),gt.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),Ce()}else ge.data.type==="error"?(t||i.onError(ge.data.error),(He=d.shift())==null||He()):ge.data.type==="status"?(t||(ve=i.onModelStatus)==null||ve.call(i,ge.data.status,ge.data.message),ge.data.status==="ready"&&(ga=!0,Zs=!1)):ge.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ge.data.pct))};e.addEventListener("message",q);const oe=ge=>{var ke,$e;if(!t){for(gt.warn("speech","createRecognition: worker death event",ge),(ke=i.onStatusChange)==null||ke.call(i,"restarting");d.length;)($e=d.shift())==null||$e();if(f.clear(),pe(),k=!1,ge.respawned){try{e.removeEventListener("message",q)}catch{}e=ev(),e.addEventListener("message",q)}}};return G_.add(oe),{start:async()=>{if(!t){if(rh){i.onError("Speech recognition disabled — please reload the app.");return}!ga&&!Zs&&(Zs=!0,gt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),gt.info("speech","createRecognition.start: initializing VAD",{modelReady:ga,modelLoading:Zs});try{const ge=new URL("vad/",document.baseURI).href,ke=i.inputDeviceId||null,$e={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ke&&($e.deviceId={exact:ke}),gt.info("speech","getUserMedia",{hasDeviceId:!!ke,deviceIdPrefix:ke?ke.slice(0,8):null});const He=await navigator.mediaDevices.getUserMedia({audio:$e});r=He,l=new AudioContext;for(const ve of He.getAudioTracks())ve.addEventListener("ended",()=>{t||(gt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(r),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ve){gt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),a=null,p=null}n=await oT.MicVAD.new({audioContext:l,getStream:async()=>He,resumeStream:async()=>He,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:HS,negativeSpeechThreshold:WS,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,ve),w&&(te(X),Ce()))},onSpeechStart:()=>{var ve;t||(_e(),w=!0,D=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),_e(),ie(ve))},onVADMisfire:()=>{var ve,X;t||((ve=i.onStatusChange)==null||ve.call(i,"idle"),_e(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ge){const ke=ge instanceof Error?ge.message:"Microphone access denied",$e=ge instanceof Error?ge.stack:"";if(gt.error("speech","createRecognition.start: VAD init failed",{error:ke,stack:$e}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(He=>He.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(ke)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(_e();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ge,ke)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:ke})}catch($e){gt.warn("speech","setVadThresholds failed",{error:$e instanceof Error?$e.message:String($e)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,_e(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}G_.delete(oe),e.removeEventListener("message",q)}}}let $f=null;const F_=new Set,H_=new Set;function mT(){for(const i of F_)try{i()}catch{}}function W_(){for(const i of H_)try{i()}catch{}}function gT(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function vT(i){if(!window.speechSynthesis)return;const e=gT(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{$f=performance.now(),mT()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&($f=null,W_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&($f=null,W_())},window.speechSynthesis.speak(t)}function KS(){window.speechSynthesis&&(window.speechSynthesis.cancel(),$f=null,W_())}function YS(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function _T(){return $f}function bT(i){return F_.add(i),()=>{F_.delete(i)}}function wT(i){return H_.add(i),()=>{H_.delete(i)}}function yT(i){YS()&&(i.setVadThresholds(Wy,Uy),gt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bT(()=>{i.setVadThresholds(Wy,Uy),gt.info("voice","tts.duck.on")}),t=wT(()=>{i.setVadThresholds(HS,WS),gt.info("voice","tts.duck.off")});return()=>{e(),t()}}const xT=[{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 ST(i){const e=i.trim();return xT.find(t=>t.match.test(e))??null}const CT=4e4;let od=null;function oh(){od&&clearTimeout(od),od=setTimeout(()=>{od=null,kt.getState().stopRecording()},CT)}function og(){od&&(clearTimeout(od),od=null)}let Zl=null,Kl=null;const kT=.04,ET=.3;let tv=0,U_=0;function TT(i){Kl!==null&&cancelAnimationFrame(Kl);const e=()=>{if(Zl===null||kt.getState().submitCountdownStartAt===null){Kl=null;return}const t=performance.now();if(t-U_<200&&tv>ET){const r=t-i;gt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:tv.toFixed(2),msIntoCountdown:Math.round(r)}),Vl(),oh();return}const n=XS();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let l=0;for(let a=0;a<r.length;a++){const d=(r[a]-128)/128;l+=d*d}const p=Math.sqrt(l/r.length);if(p>kT){const a=t-i;gt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Vl(),oh();return}}Kl=requestAnimationFrame(e)};Kl=requestAnimationFrame(e)}function qy(i){Zl&&clearTimeout(Zl);const e=kt.getState().submitDelayMs,t=performance.now();kt.setState({submitCountdownStartAt:t}),Zl=setTimeout(()=>{var r;Zl=null,kt.setState({submitCountdownStartAt:null});const n=St.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=hi.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(hi.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),hi.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){gt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}oh()},e),TT(t)}function Vl(){Kl!==null&&(cancelAnimationFrame(Kl),Kl=null),Zl&&(clearTimeout(Zl),Zl=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let ds=null,Ns=null,of=null;function XS(){var i;return((i=ds==null?void 0:ds.getAnalyser)==null?void 0:i.call(ds))??null}const ag=1e4;let If=null;function lg(){If&&(clearTimeout(If),If=null)}let zg=null,Bg=null;function cg(){zg=null,Bg&&(Bg(),Bg=null)}const DT=1500,AT=9e4;let dg=0,Gg=null,V_=-1;function ug(){Gg&&(clearTimeout(Gg),Gg=null,V_=-1)}const $T=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=On((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;gt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++dg,n=()=>{t===dg&&(ug(),V_=t,Gg=setTimeout(()=>{V_===t&&e().modelStatus==="loading"&&(gt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},AT))};n(),hT((r,l)=>{t===dg&&(r==="ready"?(ug(),gt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(ug(),gt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===dg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{gt.info("voice","mic.gate.retry"),ug(),pT(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ds){gt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!_v()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=qS({inputDeviceId:l,onStatusChange:a=>{i(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&i({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{tv=a.isSpeech,U_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),og(),Vl(),YS()){const d=_T(),f=d!==null?performance.now()-d:null;KS(),i({lastBargeInAt:performance.now()}),gt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else gt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),oh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&>.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var w;oh();const d=a.trim();if(!d||$T.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(of){of(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((w=St.getState().tabs.find(D=>D.id===t))==null?void 0:w.status)==="dormant"){hi.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&qy(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const g=ST(d);if(g){gt.info("voice","voice-command",{tabId:t,label:g.label,transcript:d}),window.api.pty.write({tabId:t,data:g.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vl();const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&qy(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{gt.error("voice","recognition error",{err:a}),Vl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Ns==null||Ns(),Ns=null,og(),ds==null||ds.destroy(),ds=null,of=null,st.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?i({modelStatus:"ready",loadingProgress:100}):a==="loading"&&i({modelStatus:"loading"})},onProgress:a=>i({loadingProgress:Math.round(a)})});ds=p,of=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),oh(),p.start().then(()=>{ds===p&&(Ns==null||Ns(),Ns=yT(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);gt.error("voice","handle.start() failed",{error:d}),st.error(`Could not start mic: ${d}`)})}catch(p){i({error:p instanceof Error?p.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,p,a;return((a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.getDevicePref)==null?void 0:a.call(p))??Promise.resolve(null)}).then(l=>r((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{gt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=ds;t&&(og(),Vl(),tv=0,U_=0,Ns==null||Ns(),Ns=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ds===t&&(ds=null,of=null),e().hotkeyState==="stopping"&&(lg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ds;if(!t)return;og(),Ns==null||Ns(),Ns=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){gt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),ds===t&&(ds=null);const{useSessions:n}=await qn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>RE);return{useSessions:l}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},setExternalRecording:t=>i({externalRecording:t}),toggleTTS:()=>i(t=>({ttsEnabled:!t.ttsEnabled})),setAutoSubmit:t=>i({autoSubmit:t}),setSubmitDelayMs:t=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(t)))}),cancelSubmit:()=>Vl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(gt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:t}),i({permissionState:t}))},setLevelMeterEnabled:t=>{e().levelMeterEnabled!==t&&i({levelMeterEnabled:t})},setTurnDetectorRuntimeState:t=>{e().turnDetectorState!==t&&(i({turnDetectorState:t}),t==="load_failed"?gt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?gt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&>.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:t=>{e().wizardArmed!==t&&i({wizardArmed:t})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:t,source:n,mode:r,tabId:l})=>{const p=e(),{canRecord:a,reason:d}=iv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),gt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){gt.warn("voice-hotkey","miss-model-loading",{modelStatus:p.modelStatus,reason:d});return}if(p.hotkeyState==="recording"||p.isRecording){(r==="toggle"||n==="global")&&(i({hotkeyState:"stopping"}),lg(),If=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:ag}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},ag),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),gt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),cg(),zg={tabId:l,source:n,mode:r},Bg=kt.subscribe((f,g)=>{if(zg&&f.modelStatus==="ready"&&g.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=zg;if(cg(),!m.tabId){gt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}gt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),kt.getState().startRecording(m.tabId)}});return}if(!l){gt.warn("voice-hotkey","no-active-tab",{source:n});return}gt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(gt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){cg(),gt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),lg(),If=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:ag}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},ag),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(cg(),Vl(),t.hotkeyState==="recording"){gt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(lg(),i({hotkeyState:"destroyed"}))}})),IT=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),iv=i=>_v()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=kt,i.__transcripts=[]}const PT=6e4,RT=5e3,Pf=On(()=>({data:null,refreshing:!1}));let Ky=!1,Fg=null,Yy=null,Xy=!1;async function Yb(){Pf.setState({refreshing:!0});let i=PT;try{const e=await Gb(window.api.billing.fetch(),RT,"billing.fetch");Pf.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Yy==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Yy=e.kind}catch(e){if(Pf.setState({refreshing:!1}),!Xy){Xy=!0;const t=e instanceof Error?e.message:String(e);st.warn(`Billing usage fetch failed: ${t}`)}}Fg=setTimeout(Yb,i)}function jT(){Ky||(Ky=!0,Yb())}function JS(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function NT(){Fg!==null&&(clearTimeout(Fg),Fg=null),Yb()}function Xb(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),r=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${r} ${e[1]}`:`${n} ${r}`}const hg=new Map,MT=3e4;function Jb(i){const[e,t]=B.useState(()=>{var n;return i?((n=hg.get(i))==null?void 0:n.value)??null:null});return B.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=hg.get(i);if(l&&Date.now()-l.ts<MT){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;hg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;hg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function OT(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:r})=>({key:e,label:t,icon:n,hint:r}))}const q_="sm.almanac.sidebarWidth",ZS=180,QS=480,K_=252;function LT(){try{const i=parseInt(localStorage.getItem(q_)??"",10);if(Number.isFinite(i))return Math.min(QS,Math.max(ZS,i))}catch{}return K_}const zT=52,e1="sm.almanac.sidebarCollapsed";function BT(){try{return localStorage.getItem(e1)==="1"}catch{}return!1}const t1="sm.almanac.collapsedGroups";function GT(){try{const i=localStorage.getItem(t1);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(t=>t==="Workspace"||t==="Configure"||t==="Tools")):new Set}catch{return new Set}}function FT(){const i=St(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Or(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function HT({active:i,onNavigate:e,onNewSession:t}){const[n,r]=B.useState(()=>GT()),l=B.useCallback(j=>{r(H=>{const W=new Set(H);W.has(j)?W.delete(j):W.add(j);try{localStorage.setItem(t1,JSON.stringify(Array.from(W)))}catch{}return W})},[]),[p,a]=B.useState(()=>BT()),d=B.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(e1,H?"1":"0")}catch{}return H})},[]),f=St(j=>j.tabs),g=St(j=>j.activeTabId),m=f.find(j=>j.id===g)??null,w=FT(),D=Di(j=>j.navFace),k=OE(D),E=k.filter(j=>j.group==="Workspace"),b=k.filter(j=>j.group==="Configure"),C=OT(k),y=D==="home"&&!p,[x,A]=B.useState(()=>LT()),P=B.useRef(x);P.current=x;const N=B.useCallback(j=>{j.preventDefault();const H=j.clientX,W=P.current;let re=W;const de=me=>{re=Math.min(QS,Math.max(ZS,W+(me.clientX-H))),A(re)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(q_,String(re))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=B.useCallback(()=>{A(K_);try{localStorage.setItem(q_,String(K_))}catch{}},[]);return h.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?zT:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx(WT,{tab:m,navFace:D,onNewSession:t,rail:p,onToggleRail:d}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:y?h.jsxs(h.Fragment,{children:[h.jsx(Zv,{label:"Workspace",desc:Vv.Workspace,collapsed:n.has("Workspace"),count:E.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&E.map(j=>h.jsx(Qv,{item:j,active:i===j.key,live:j.liveKind?w[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Zv,{label:"Configure",desc:Vv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Qv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Zv,{label:"Tools",desc:Vv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(Jy,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:k.map(j=>j.group==="Tools"?h.jsx(Jy,{tool:{key:j.key,label:j.label,icon:j.icon,hint:j.hint},active:i===j.key,onClick:()=>e(j.key),rail:p},j.key):h.jsx(Qv,{item:j,active:i===j.key,live:j.liveKind?w[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(UT,{rail:p,navFace:D}),!p&&h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:L,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 WT({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Jb((i==null?void 0:i.cwd)??null);return n?h.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[h.jsx("button",{onClick:t,"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:h.jsx(Dn,{name:"plus",size:15,stroke:1.8})}),h.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:h.jsx(Dn,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),h.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(Dn,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.jsxs("button",{onClick:t,"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:[h.jsx(Dn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),h.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(Dn,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[h.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),h.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),h.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.jsxs("button",{onClick:t,"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:[h.jsx(Dn,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Zv({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return h.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[h.jsxs("button",{onClick:r,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[h.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),h.jsx("span",{className:"flex-1",children:i}),t&&h.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&h.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 Qv({item:i,active:e,live:t,onClick:n,rail:r}){return h.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(Dn,{name:i.icon,size:17,stroke:1.6})}),!r&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&h.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 Jy({tool:i,active:e,onClick:t,rail:n}){return h.jsxs("button",{onClick:t,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${n?"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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(Dn,{name:i.icon,size:15,stroke:1.6})}),!n&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function UT({rail:i,navFace:e}){const t=kt(d=>d.isRecording),n=St(d=>d.tabs),r=St(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=B.useState(null);return B.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return bS(l.presetId).then(f=>{d||a((f==null?void 0:f.model)??null)}).catch(()=>{d||a(null)}),()=>{d=!0}},[l==null?void 0:l.presetId]),i?h.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):h.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:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"}),(t||e==="project")&&h.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Xb(p)}`:"Claude Code"})]})}const An={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},VT={dialog:50};function qT(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function KT(i,e,t){return{tabId:i,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function YT(i,e,t){const n=Date.now(),r={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,d)=>a.length>d?a.slice(0,d-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];r.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,d=a.input,f={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])d&&g in d&&(f[g]=d[g]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),w=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,D=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,k=w?w.split("/").pop()??w:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:w??D,toolName:a.name}),m&&w&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(w.split("/").pop()??w,34)}`,target:w,toolName:a.name})}break}case"plan":{const a=e.data,d=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);r.plans=[{at:n,content:d??""},...i.plans].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"plan-revision",at:n,label:"Plan revised"});break}case"agent_spawn":{const a=e.data;r.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,d=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,g=a.output_tokens??a.outputTokens??0,m=d+f+g;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+g,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(d/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const a=e.data;r.agents=qT(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Hg=On((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,r)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:KT(t,n,r)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:r}).then(async a=>{const d=e().tabs[t];if(!d)return;if(!a.ok){const{toast:g}=await qn(async()=>{const{toast:m}=await Promise.resolve().then(()=>xS);return{toast:m}},void 0,import.meta.url);g.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...d,path:null}}});return}i({tabs:{...e().tabs,[t]:{...d,path:a.path}}});const f=await window.api.transcripts.buffer(t);e().ingestBatch(t,f,{replay:!0})}).catch(a=>console.error("[live] transcripts.subscribe failed:",t,a))},unsubscribe:t=>{const n={...e().refs};if(!n[t])return;if(n[t]--,n[t]>0){i({refs:n});return}delete n[t];const r=e().unsubs[t];r==null||r();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,r)=>{e().ingestBatch(t,[n],r)},ingestBatch:(t,n,r)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const d of n){const{next:f,newActivity:g}=YT(p,d,r);p=f,a=a.concat(g)}if(a.length>0){let d=l.activitySeq;const f=a.map(g=>({...g,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function XT(i){const e=Hg(r=>r.subscribe),t=Hg(r=>r.unsubscribe),n=Hg(r=>i?r.tabs[i.id]:void 0);return B.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>t(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,t]),n}function i1(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${r}h`:r>0?`${r}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function Y_(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function Zy(i,e){const t=Y_(e);if(t==null)return`${i} — usage unavailable`;const n=i1((e==null?void 0:e.resets_at)??null),r=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${r} — click to open Home`}function JT({onNavigate:i}){const e=St(P=>P.tabs),t=St(P=>P.activeTabId),n=e.find(P=>P.id===t)??null,r=XT(n),l=(r==null?void 0:r.lastEventAt)??0,p=Pf(P=>P.data),a=Or(P=>{var N;return((N=P.snapshot)==null?void 0:N.paused)??null}),d=Jb((n==null?void 0:n.cwd)??null),[,f]=B.useState(0);B.useEffect(()=>{const P=setInterval(()=>f(N=>N+1),6e4);return()=>clearInterval(P)},[]);const g=(r==null?void 0:r.todos)??[],[m,w]=B.useState(!1),D=B.useRef(null);B.useEffect(()=>{if(!m)return;const P=N=>{D.current&&!D.current.contains(N.target)&&w(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[m]),B.useEffect(()=>{g.length===0&&w(!1)},[g.length]);const k=JS(p),E=(k==null?void 0:k.usage.five_hour)??null,b=(k==null?void 0:k.usage.seven_day)??null,C=Y_(E),y=Y_(b),x=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",A=l>0?e2(Date.now()-l):"—";return h.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:[h.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:x?"Connected to Anthropic":"Disconnected",children:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${x?"bg-sage":"bg-fg-faint"}`}),h.jsx("span",{children:x?"connected":"offline"})]}),h.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Zy("Session (5h window)",E),"data-testid":"footer-usage-session",children:["session ",h.jsx("span",{className:"text-fg",children:C!=null?`${C}%`:"—"})]}),h.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Zy("Weekly window (all models)",b),"data-testid":"footer-usage-weekly",children:["weekly ",h.jsx("span",{className:"text-fg",children:y!=null?`${y}%`:"—"})]}),a&&h.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.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:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&h.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&h.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),h.jsxs("span",{className:"text-fg-faint",children:["last activity: ",h.jsx("span",{className:"text-fg-dim",children:A})]}),g.length>0&&h.jsx(ZT,{ref:D,todos:g,open:m,onToggle:()=>w(P=>!P)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.80.0"]})]})}const ZT=B.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return h.jsxs("div",{ref:r,className:"relative",children:[h.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[h.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),h.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),h.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),h.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&h.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 ${An.dialog}`,"data-testid":"footer-todos-popover",children:h.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>h.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[h.jsx(QT,{status:p.status}),h.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function QT({status:i}){return i==="completed"?h.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?h.jsx("span",{className:"w-3 shrink-0",children:h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):h.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function e2(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function t2({onClose:i,onSent:e}){const t=St(L=>L.tabs),[n,r]=B.useState(""),[l,p]=B.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=B.useState(!1),[f,g]=B.useState({}),m=B.useRef(null),w=B.useRef(e);B.useEffect(()=>{w.current=e},[e]),B.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),B.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),B.useEffect(()=>window.api.pty.onWriteError(j=>{g(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),B.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>w.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,E=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!E,C=()=>{if(!b)return;d(!0);const L=St.getState().tabs,j=new Set(L.map(W=>W.id)),H={};for(const W of D)j.has(W)?(window.api.pty.write({tabId:W,data:n+"\r"}),H[W]="sent"):H[W]="skipped";g(H),d(!1)},y=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),C())},x=t.length>0&&t.every(L=>l[L.id]),A=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},P=Object.values(f).some(L=>L==="skipped"),N=E?P?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return h.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:y,"data-testid":"broadcast-bar",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),h.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),h.jsx("textarea",{ref:m,value:n,onChange:L=>r(L.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"}),h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:x,onChange:A,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),h.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>h.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:j=>p(H=>({...H,[L.id]:j.target.checked})),className:"accent-accent"}),h.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&h.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&h.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),h.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[h.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),h.jsx("button",{onClick:C,disabled:!b,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:N})]})]})}function i2({tabId:i,cwd:e,onClose:t}){const n=Af(k=>k.watchersForTab(i)),r=Af(k=>k.add),l=Af(k=>k.remove),p=B.useRef(null),[a,d]=B.useState(""),[f,g]=B.useState(""),[m,w]=B.useState(!1);B.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),B.useEffect(()=>{const k=E=>{p.current&&!p.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||m)return;w(!0);const E=await r({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),E&&(d(""),g(""))};return h.jsxs("div",{ref:p,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:[h.jsxs("div",{className:"flex items-center mb-2",children:[h.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),h.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),h.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[h.jsx("input",{value:a,onChange:k=>d(k.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"}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("input",{value:f,onChange:k=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},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"}),h.jsx("button",{onClick:D,disabled:!f.trim()||m,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"})]}),h.jsxs("span",{className:"text-fg-faint",children:["cwd: ",h.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?h.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):h.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const E=k.lines[k.lines.length-1];return h.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),h.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2911
2911
|
* dockview-core
|
|
2912
2912
|
* @version 6.6.1
|
|
2913
2913
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3022,7 +3022,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3022
3022
|
|
|
3023
3023
|
${t}`}const Tf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},dj=["popover","review","diff"],PC=["popover","review"];function uj(i,e){switch(e.type){case"SELECT":return{...Tf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Tf,editCount:i.editCount};case"LISTEN":return PC.includes(i.phase)?{...i,phase:"listening",transcript:"",modelStatus:null}:i;case"HEARD":return i.phase!=="listening"?i:{...i,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return dj.includes(i.phase)?{...i,phase:"thinking",instruction:e.recordInstruction?e.instruction:i.instruction}:i;case"RUN_OK":return i.phase!=="thinking"?i:{...i,phase:"diff",diff:e.diff};case"RUN_ERR":return i.phase!=="thinking"?i:{...i,phase:"popover",transcript:"",diff:null};case"ACCEPT":return i.phase!=="diff"?i:{...Tf,editCount:i.editCount+1};case"RESET_FILE":return{...Tf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function hj(i,e){let t=null;for(const n of e){const r=n.cwd;!r||!(i===r||i.startsWith(r.endsWith("/")?r:`${r}/`))||(t===null||r.length>t.length)&&(t=r)}return t}function pj(i,e,t){var l;let n=null,r=-1/0;for(const p of e){if(p.cwd!==i||p.status!=="dormant")continue;const a=((l=t[p.id])==null?void 0:l.lastEventAt)??0;(n===null||a>r)&&(n=p,r=a)}return n}const fj="sonnet";function mj(i,e){const[t,n]=B.useReducer(uj,Tf),r=B.useRef(0),l=B.useRef(null),p=B.useRef(i),a=B.useRef(new Map);B.useEffect(()=>window.api.docEdit.onSessionResult(x=>{const A=a.current.get(x.requestId);A&&(a.current.delete(x.requestId),A(x))}),[]),B.useEffect(()=>{p.current!==i&&(p.current=i,r.current+=1,d(),n({type:"RESET_FILE"}))},[i]);function d(){const x=l.current;x&&(l.current=null,x.stop().catch(()=>{}),x.destroy(),kt.setState({externalRecording:!1}))}const f=B.useCallback(x=>{r.current+=1,d(),n({type:"SELECT",selection:x})},[]),g=B.useCallback(()=>{r.current+=1,d(),n({type:"CANCEL"})},[]),m=B.useCallback(()=>{if(!PC.includes(t.phase))return;if(kt.getState().isRecording){st.error("Microphone is already in use");return}if(!_v()){st.error("Microphone or Web Worker not available");return}const x=++r.current;n({type:"LISTEN"}),kt.setState({externalRecording:!0});const A=()=>{l.current===P&&(l.current=null),kt.setState({externalRecording:!1})},P=qS({onFinal:N=>{if(r.current!==x)return;P.stop().catch(()=>{}),P.destroy(),A();const L=N.trim();if(!L){n({type:"CANCEL"});return}n({type:"HEARD",transcript:L})},onError:N=>{r.current===x&&(P.destroy(),A(),st.error(`Microphone error: ${N}`),n({type:"CANCEL"}))},onModelStatus:(N,L)=>{r.current===x&&n({type:"MODEL_STATUS",status:N,message:L})},onProgress:N=>{r.current===x&&n({type:"MODEL_STATUS",status:"loading",message:`${N}%`})}});l.current=P,P.start().catch(N=>{r.current===x&&(P.destroy(),A(),st.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),w=B.useCallback(()=>{const x=hj(i,St.getState().tabs);if(!x)return null;const A=pj(x,St.getState().tabs,Hg.getState().tabs);return!A||hi.getState().get(A.id).running?null:A},[i]),D=B.useCallback((x,A,P,N,L,j)=>{const H=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(W=>{a.current.set(H,W),window.api.docEdit.runInSession({tabId:x,sessionId:A,cwd:P,before:N,instruction:L,documentText:j,requestId:H})})},[]),k=B.useCallback(async(x,A)=>{const P=t.selection;if(!P)return;const N=++r.current;n({type:"RUN",instruction:x,recordInstruction:A});const L=cj(e);try{const j=w(),H=j?await D(j.id,j.sessionId,j.cwd,P.text,x,L):await window.api.docEdit.run({path:i,before:P.text,instruction:x,documentText:L});if(r.current!==N)return;if(!H.ok){st.error(H.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:P.text,after:H.after??""}})}catch(j){if(r.current!==N)return;st.error(j instanceof Error?j.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,w,D]),E=B.useCallback(x=>{k(x,!0)},[k]),b=B.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),C=B.useCallback(()=>{const x=t.instruction;x&&k(`${x}
|
|
3024
3024
|
|
|
3025
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),y=B.useCallback(x=>{const A=t.diff;if(!A)return{ok:!1,reason:"not-found"};const P=aj(x,A.before,A.after);return P.ok?(r.current+=1,n({type:"ACCEPT"})):st.error(P.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),P},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:b,run:E,retry:C,accept:y}}const gj=[{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."}],g0=320,gf=8;function vj(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function _j(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,gf),Math.max(gf,e-g0-gf)),n=Math.max(i.top-gf,gf);return{position:"fixed",left:t,top:n,width:g0,transform:"translateY(-100%)",zIndex:VT.dialog}}function bj({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:g,onReject:m,onRetry:w}){const[D,k]=B.useState(""),E=()=>{const b=D.trim();b&&(p(b),k(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:_j(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&h.jsxs("div",{className:"p-2",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.jsx("button",{onClick:a,"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"}),gj.map(b=>h.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),h.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),h.jsx("input",{autoFocus:!0,value:D,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?E():b.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&h.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[h.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[h.jsxs("span",{className:"flex items-center gap-2",children:[h.jsx(vj,{}),"Listening…"]}),r&&h.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),h.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&h.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[h.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsxs("div",{className:"p-3 flex items-center justify-between",children:[h.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),h.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&h.jsxs("div",{className:"p-3",children:[h.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function wj(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function v0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:g}){return h.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[h.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),h.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Xb(fj)})]}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&h.jsxs("div",{className:"text-fg-faint",children:[h.jsx("p",{children:"Select text in the doc…"}),h.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&h.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&h.jsxs("div",{children:[h.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[h.jsx(wj,{}),"Listening…"]}),r&&h.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),h.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&h.jsxs("div",{children:[h.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&h.jsxs("div",{children:[h.jsxs("div",{className:"mb-3 space-y-2",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function yj(){const i=St(t=>t.tabs),e=St(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function _0(i){return i.split("/").filter(Boolean).pop()||i}function xj({path:i,onRenamed:e,onDeleted:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(!1),[a,d]=B.useState(""),[f,g]=B.useState(!1),m=Pi(W=>W.buffers[i]),w=Pi(W=>W.openFile),D=Pi(W=>W.renameOpenFile),k=Pi(W=>W.closeFile),E=yj(),b=_0(i),C=()=>r(!1),y=()=>{d(b),p(!0),C()},x=async()=>{const W=a.trim();if(!W||W===b){p(!1);return}try{const re=await window.api.files.rename(i,W);if(re.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=re.newPath??`${de}/${W}`;D(i,Z),e==null||e(i,Z),st.info(`Renamed to ${W}`)}else st.error(re.error??`Couldn't rename ${b}`)}catch(re){st.error(re instanceof Error?re.message:`Couldn't rename ${b}`)}p(!1)},A=async()=>{C();try{const W=await window.api.files.duplicate(i);W.ok&&W.path?(w(W.path),st.info(`Duplicated as ${_0(W.path)}`)):st.error(W.error??`Couldn't duplicate ${b}`)}catch(W){st.error(W instanceof Error?W.message:`Couldn't duplicate ${b}`)}},P=async()=>{try{const W=await window.api.files.delete(i);W.ok?(k(i),t==null||t(i),st.info(`Deleted ${b}`)):st.error(W.error??`Couldn't delete ${b}`)}catch(W){st.error(W instanceof Error?W.message:`Couldn't delete ${b}`)}g(!1)},N=async()=>{C();const W=m??"";try{await navigator.clipboard.writeText(W),st.info(`Copied ${W.length} chars`)}catch(re){st.error(re instanceof Error?re.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!E){st.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${i} `}),st.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(W=>{W.ok||st.error(W.error??`Couldn't open ${b}`)}).catch(W=>st.error(W instanceof Error?W.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(W=>{W.ok||st.error(W.error??`Couldn't reveal ${b}`)}).catch(W=>st.error(W instanceof Error?W.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(W=>!W),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:"Document actions",children:"Document ▾"}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${An.contextMenuScrim}`,onMouseDown:C}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${An.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[h.jsx(m_,{children:"Edit"}),h.jsx(ed,{label:"Rename",onClick:y}),h.jsx(ed,{label:"Duplicate",onClick:A}),h.jsx(ed,{label:"Delete document",danger:!0,onClick:()=>{C(),g(!0)}}),h.jsx(b0,{}),h.jsx(m_,{children:"Open"}),h.jsx(ed,{label:"Open in default app",onClick:j}),h.jsx(ed,{label:"Reveal in OS",onClick:H}),h.jsx(b0,{}),h.jsx(m_,{children:"Export"}),h.jsx(ed,{label:"Copy as Markdown",onClick:N}),h.jsx(ed,{label:"Add to Claude context",onClick:L,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(Sj,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(Cj,{name:b,onCancel:()=>g(!1),onConfirm:()=>void P()})]})}function m_({children:i}){return h.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function ed({label:i,onClick:e,danger:t,disabled:n,title:r}){return h.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function b0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function Sj({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),h.jsx("input",{autoFocus:!0,value:i,onChange:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function Cj({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function kj(){const[i,e]=B.useState(!1),t=ih();return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${An.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${An.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[h.jsx(Qu,{label:"Text size",children:h.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[h.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),h.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),h.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),h.jsx(Qu,{label:"Word wrap",children:h.jsx(Ag,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Qu,{label:"Minimap",children:h.jsx(Ag,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Qu,{label:"Theme",children:h.jsx("button",{onClick:()=>t.setTheme(t.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:t.theme==="dark"?"Dark":"Paper"})}),h.jsx(Qu,{label:"Autosave",children:h.jsx(Ag,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Qu,{label:"Wide measure",children:h.jsx(Ag,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Qu({label:i,children:e}){return h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Ag({on:i,onClick:e}){return h.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const Ej=B.lazy(()=>qn(()=>import("./TiptapBody-yADC2RWE.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function $g(i){return i.split("/").filter(Boolean).pop()||i}function Ig(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Pg(i){return sC(i)||rC(i)}function Tj(){const i=cw(),e=Pi(ze=>ze.openFiles),t=Pi(ze=>ze.activeFilePath),n=Pi(ze=>ze.dirty),r=Pi(ze=>ze.viewMode),l=Pi(ze=>ze.buffers),p=Pi(ze=>ze.setActive),a=Pi(ze=>ze.closeFile),d=Pi(ze=>ze.closeOthers),f=Pi(ze=>ze.closeToTheRight),g=Pi(ze=>ze.closeAll),m=Pi(ze=>ze.loadBuffer),w=Pi(ze=>ze.setBuffer),D=Pi(ze=>ze.markSaved),k=Pi(ze=>ze.setViewMode),E=ih(),[b,C]=B.useState({}),[y,x]=B.useState({}),[A,P]=B.useState(null),[N,L]=B.useState(null),[j,H]=B.useState(!1),[W,re]=B.useState(!1),[de,Z]=B.useState(!0),me=B.useRef(null),te=B.useRef(null),pe=B.useRef(void 0),_e=B.useRef(null),Ce=B.useRef(null),U=mj(t??"",l[t??""]??""),ie=B.useCallback(ze=>{me.current=ze},[]),q=B.useCallback(()=>me.current,[]);B.useEffect(()=>{const ze=t;if(!ze||Pg(ze))return;if(Pi.getState().hasBuffer(ze)){C(ct=>ct[ze]==="ready"?ct:{...ct,[ze]:"ready"});return}let ft=!1;return C(ct=>({...ct,[ze]:"loading"})),window.api.files.read(ze).then(ct=>{ft||(ct.binary?C(Zt=>({...Zt,[ze]:{binary:!0,size:ct.size??0,mime:ct.mime??"application/octet-stream",reason:ct.error??"Binary file"}})):ct.ok?(m(ze,ct.text),C(Zt=>({...Zt,[ze]:"ready"}))):C(Zt=>({...Zt,[ze]:{error:ct.error??"failed to read"}})))}),()=>{ft=!0}},[t,m]),B.useEffect(()=>{L(null)},[t]);const oe=B.useCallback(async(ze,ft=!1)=>{const ct=Pi.getState().buffers[ze];if(ct==null)return;ft&&H(!0);const Zt=await window.api.files.write(ze,ct);Zt.ok?(D(ze),x(ai=>({...ai,[ze]:(ai[ze]??0)+1})),ft||st.info(`Saved ${$g(ze)}`)):st.error(Zt.error??`Couldn't save ${$g(ze)}`),ft&&H(!1)},[D]);B.useEffect(()=>{if(!E.autosave)return;const ze=t;if(!(!ze||Pg(ze)||!n[ze]))return window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{oe(ze,!0)},1200),()=>window.clearTimeout(pe.current)},[E.autosave,t,n,l,oe]);const ge=B.useCallback(ze=>{ze.length&&(C(ft=>Ig(ft,ze)),x(ft=>Ig(ft,ze)))},[]),ke=B.useCallback((ze,ft)=>{C(ct=>ze in ct?{...Ig(ct,[ze]),[ft]:ct[ze]}:ct),x(ct=>ze in ct?{...Ig(ct,[ze]),[ft]:ct[ze]}:ct)},[]),$e=B.useCallback(ze=>{n[ze]?P({kind:"one",path:ze}):(a(ze),ge([ze]))},[n,a,ge]),He=B.useCallback(ze=>{e.some(ct=>ct.path!==ze&&n[ct.path])?P({kind:"others",path:ze}):(d(ze),ge(e.filter(ct=>ct.path!==ze).map(ct=>ct.path)))},[e,n,d,ge]),ve=B.useCallback(ze=>{const ft=e.findIndex(Zt=>Zt.path===ze);ft!==-1&&e.slice(ft+1).some(Zt=>n[Zt.path])?P({kind:"right",path:ze}):(f(ze),ge(ft!==-1?e.slice(ft+1).map(Zt=>Zt.path):[]))},[e,n,f,ge]);B.useEffect(()=>{const ze=ft=>{if(i.current)if((ft.metaKey||ft.ctrlKey)&&(ft.key==="s"||ft.key==="S")){const ct=Pi.getState().activeFilePath;ct&&!Pg(ct)&&(ft.preventDefault(),oe(ct))}else if((ft.metaKey||ft.ctrlKey)&&ft.shiftKey&&(ft.key==="f"||ft.key==="F"))ft.preventDefault(),re(ct=>!ct);else if((ft.metaKey||ft.ctrlKey)&&ft.shiftKey&&(ft.key==="w"||ft.key==="W")){const ct=Pi.getState().activeFilePath;ct&&Pi.getState().openFiles.length>1&&(ft.preventDefault(),He(ct))}else ft.key==="Escape"&&U.state.phase!=="idle"?U.cancel():ft.key==="Escape"&&W&&re(!1)};return window.addEventListener("keydown",ze),()=>window.removeEventListener("keydown",ze)},[oe,W,He,U.state.phase,U.cancel]),B.useEffect(()=>{if(U.state.phase==="idle")return;const ze=ft=>{var Zt,ai;const ct=ft.target;(Zt=Ce.current)!=null&&Zt.contains(ct)||(ai=_e.current)!=null&&ai.contains(ct)||U.cancel()};return window.addEventListener("mousedown",ze),()=>window.removeEventListener("mousedown",ze)},[U.state.phase,U.cancel]),B.useEffect(()=>{U.cancel()},[t,U.cancel]);const X=B.useCallback(()=>{e.some(ft=>n[ft.path])?P({kind:"all",path:""}):(g(),C({}),x({}))},[e,n,g]),Ie=()=>{if(A){if(A.kind==="one")a(A.path),ge([A.path]);else if(A.kind==="others"){const ze=e.filter(ft=>ft.path!==A.path).map(ft=>ft.path);d(A.path),ge(ze)}else if(A.kind==="right"){const ze=e.findIndex(ct=>ct.path===A.path),ft=ze!==-1?e.slice(ze+1).map(ct=>ct.path):[];f(A.path),ge(ft)}else g(),C({}),x({});P(null)}};if(e.length===0)return h.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"mb-2",children:"no file open"}),h.jsxs("div",{children:["open the ",h.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const he=t,Pe=he?$g(he):"",Qe=he?b[he]:void 0,pt=he?lC(he):!1,Pt=he?pI(he):!1,dt=he&&pt?r[he]??fI(he):"edit",Yt=!!he&&!Pg(he)&&Qe==="ready",Fe=Yt,Ct=Pt?["edit","wysiwyg","preview","split"]:pt?["edit","preview"]:[],Me=he&&h.jsx(AP,{path:he,name:Pe,value:l[he]??"",onChange:ze=>w(he,ze),onSave:()=>void oe(he),onReady:ie,onCursor:L}),ot=j?"Saving…":he&&n[he]?E.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!W&&h.jsx(vI,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:$e,onCloseOthers:He,onCloseToTheRight:ve,onCloseAll:X}),he&&!W&&h.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[h.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Pe}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:he}),Yt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ot]}),Ya(he)&&(dt==="preview"||dt==="split")&&h.jsx("button",{onClick:()=>Z(ze=>!ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ya(he)&&(dt==="preview"||dt==="split")&&h.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Ct.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Ct.map(ze=>h.jsx("button",{onClick:()=>k(he,ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${dt===ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:ze},ze))}),h.jsx("div",{className:"flex-1"}),h.jsx(xj,{path:he,onRenamed:ke,onDeleted:ze=>ge([ze])}),Yt&&h.jsx(kj,{}),h.jsx("button",{onClick:()=>re(!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"})]}),W&&h.jsx("button",{onClick:()=>re(!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"}),h.jsx("div",{className:"flex-1 min-h-0",children:he?sC(he)?h.jsx(ZR,{path:he,name:Pe}):rC(he)?h.jsx(QR,{path:he}):Qe&&typeof Qe=="object"&&"binary"in Qe?h.jsx(oj,{path:he,name:Pe,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?h.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):dt==="wysiwyg"&&Ya(he)?h.jsx(B.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(Ej,{value:l[he]??"",onChange:ze=>w(he,ze)},he)}):dt==="split"&&Ya(he)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(p0,{text:l[he]??"",scrollRef:te}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(h0,{getEditor:q}),h.jsx("div",{className:"flex-1 min-h-0",children:Me})]}),h.jsx("div",{ref:_e,className:"flex-1 min-w-0",children:h.jsx(wb,{ref:te,text:l[he]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!W&&E.assistantRail&&h.jsx(v0,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)},onReject:U.cancel,onRetry:U.retry})]}):dt==="preview"&&Ya(he)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(p0,{text:l[he]??"",scrollRef:te}),h.jsx("div",{ref:_e,className:"flex-1 min-w-0",children:h.jsx(wb,{ref:te,text:l[he]??"",wideMeasure:E.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!W&&E.assistantRail&&h.jsx(v0,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)},onReject:U.cancel,onRetry:U.retry})]}):dt==="preview"&&nC(he)?h.jsx(XR,{path:he,dirty:!!n[he],reloadToken:y[he]??0}):dt==="preview"&&oC(he)?h.jsx(tj,{path:he,text:l[he]??""}):dt==="preview"&&aC(he)?h.jsx(sj,{path:he,text:l[he]??""}):Ya(he)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(h0,{getEditor:q}),h.jsx("div",{className:"flex-1 min-h-0",children:Me})]}):Me:null}),Fe&&h.jsx(YR,{text:l[he]??"",cursor:N,language:Lr(he)||void 0}),he&&Ya(he)&&(dt==="preview"||dt==="split")&&U.state.phase!=="idle"&&U.state.selection&&h.jsx("div",{ref:Ce,children:h.jsx(bj,{phase:U.state.phase,rect:U.state.selection.rect,diff:U.state.diff,transcript:U.state.transcript,modelStatus:U.state.modelStatus,onQuickAction:U.run,onRunCustom:U.run,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onReject:U.cancel,onRetry:U.retry,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)}})}),A&&h.jsx(Dj,{message:A.kind==="one"?`Discard unsaved changes to ${$g(A.path)}?`:A.kind==="others"?"Discard unsaved changes in the other open files?":A.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>P(null),onConfirm:Ie})]})}const Sb=B.memo(Tj);function Dj({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Aj={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},w0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Tw({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&h.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),h.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=B.useRef(null),f=B.useRef(null),g=B.useRef(e);if(g.current=e,B.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(w0);C?C.focus():b.focus()},0),E=b=>{if(b.key==="Escape"){b.stopPropagation(),g.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const y=Array.from(C.querySelectorAll(w0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(y.length===0){b.preventDefault(),C.focus();return}const x=y[0],A=y[y.length-1],P=document.activeElement;b.shiftKey?(P===x||!C.contains(P))&&(b.preventDefault(),A.focus()):(P===A||!C.contains(P))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",E),()=>{clearTimeout(k),document.removeEventListener("keydown",E);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=D=>{D.target===D.currentTarget&&e()},w=h.jsx("div",{className:`fixed inset-0 ${An.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:h.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":n??"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 ${Aj[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?h.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?h.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Jf.createPortal(w,document.body):w}class RC extends B.Component{constructor(){super(...arguments);Fi(this,"state",{error:null});Fi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):h.jsxs("div",{className:"p-6 text-xs",children:[h.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),h.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),h.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 $j({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(Tw,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&h.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[h.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),h.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:"✕"})]}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(RC,{children:n})})]})}function jC(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const y0=i=>Symbol.iterator in i,x0=i=>"entries"in i,S0=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},Ij=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function Pj(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:y0(i)&&y0(e)?x0(i)&&x0(e)?S0(i,e):Ij(i,e):S0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Dw(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return Pj(e.current,n)?e.current:e.current=n}}let C0=0;const Rj=1e3;function jj(i){const e=performance.now();e-C0<Rj||(C0=e,gt.debug("voice","mic.gate.click_rejected",{reason:i}))}function Nj(){const i=kt(f=>f.isRecording),e=kt(f=>f.error),t=kt(f=>f.loadingProgress),n=kt(Dw(iv)),r=()=>{const f=kt.getState(),{canRecord:g,reason:m}=iv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return jj(m);const w=St.getState().activeTabId;w&&f.startRecording(w)},l=jC(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,d=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return h.jsx("button",{onClick:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${d}`,children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),h.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),h.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function Mj(){const i=kt(t=>t.ttsEnabled),e=kt(t=>t.toggleTTS);return h.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?h.jsxs(h.Fragment,{children:[h.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),h.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),h.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),h.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Oj(i){return/^monitor of /i.test(i.trim())}function k0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function E0(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=k0(e),l=t.filter(p=>p.label&&k0(p.label)===r);return l.length===1?l[0]:null}async function T0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&Oj(n.label))):[]}const D0=!1;function NC(){const i=kt(f=>f.isRecording);kt(f=>f.startRecording),kt(f=>f.stopRecording);const[e,t]=B.useState([]),[n,r]=B.useState(null),[l,p]=B.useState(null);B.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await T0(D0);if(f)return;t(m),p(g.selectedLabel);const w=E0(g.selectedDeviceId,g.selectedLabel,m);w?(r(w.deviceId),g.selectedDeviceId&&w.deviceId!==g.selectedDeviceId&&(gt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),gt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){gt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=B.useCallback(async()=>{try{const f=await T0(D0);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=E0(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){gt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);B.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var D;const g=f.target.value,m=g===""?null:g,w=m?((D=e.find(k=>k.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:w}),gt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){gt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await kt.getState().restartWithDevice()}catch(k){gt.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return h.jsxs("select",{value:n??"",onChange:d,onFocus:()=>{a()},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:[h.jsx("option",{value:"",children:"Default"}),e.map(f=>h.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function Lj(){const i=kt(D=>D.isRecording),e=kt(D=>D.levelMeterEnabled),[t,n]=B.useState(0),[r,l]=B.useState(0),p=B.useRef(0);p.current=r;const[a,d]=B.useState(0),[f,g]=B.useState(!1),m=B.useRef(null);if(B.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,E=null,b=null;const C=()=>{if(k)return;const x=b??XS();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,E=new Uint8Array(new ArrayBuffer(x.fftSize)));const A=E;x.getByteTimeDomainData(A);let P=0;for(let H=0;H<A.length;H++){const W=A[H]-128;P+=W*W}const N=Math.sqrt(P/A.length)/128,L=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(L+60)/60));l(N),n(j),N>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const y=setInterval(()=>{k||d(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(y),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return h.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${f?"ring-1 ring-red-500":""}`,children:h.jsx("div",{className:`h-full ${w} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function MC(){const i=kt(f=>f.submitCountdownStartAt),e=kt(f=>f.submitDelayMs),[t,n]=B.useState(()=>performance.now());if(B.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,d=kt.getState().cancelSubmit;return h.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:h.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:h.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function zj({open:i,onClose:e,variant:t="overlay"}){return h.jsx($j,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(Hj,{}),h.jsx(MC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(Nj,{}),h.jsx(NC,{}),h.jsx(Mj,{})]}),h.jsx(Bj,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.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"}),h.jsx(Fj,{})]}),h.jsx(Lj,{})]})})}function Bj(){const i=kt(l=>l.isRecording),[e,t]=B.useState(null);if(B.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(a=>{l||t(a)}).catch(()=>{});const p=window.api.voice.onHotkeyConfigChanged(a=>t(a));return()=>{l=!0,p()}},[]),i||!e)return null;const n=e.mode==="hold"?"Hold":"Press",r=Gj(e.accelerator);return h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("span",{children:[n," "]}),h.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),h.jsx("span",{children:" to record"})]})}function Gj(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function Fj(){const[i,e]=B.useState(null);if(B.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>gt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){gt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return h.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:[h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),h.jsx("span",{children:"Tap on/off"})]}),h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),h.jsx("span",{children:"Hold to talk"})]})]})}function Hj(){const i=kt(l=>l.isRecording),e=kt(l=>l.lastTranscript),t=kt(l=>l.error),n=kt(l=>l.modelStatus),r=kt(l=>l.loadingProgress);return t?h.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?h.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),h.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{children:"Loading speech model"}),h.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),h.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const OC="~/.claude/session-manager/projects-prefs.json",Wj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Fl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(OC,t).catch(()=>{})}const A0=On((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(OC);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Fl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":Wj[t];i({sort:{col:t,dir:r}}),Fl(e)},setRecentFilter:t=>{i({recentFilter:t}),Fl(e)},setHasRemote:t=>{i({hasRemote:t}),Fl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Fl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Fl(e)},setSearch:t=>{i({search:t}),Fl(e)},setEditor:t=>{i({editor:t}),Fl(e)}})),LC=i=>`sm.fileTree.expanded:${i}`;function Uj(i){try{const e=localStorage.getItem(LC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Vj(i,e){try{localStorage.setItem(LC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const zC="sm.fileTree.showHidden";function qj(){try{const i=localStorage.getItem(zC);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function Kj(i){try{localStorage.setItem(zC,JSON.stringify(i))}catch{}}function g_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const v_={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},Yj=new Set(["md","txt","json","jsonl","ndjson","js","jsx","ts","tsx","py","go","rs","rb","c","cpp","h","hpp","java","sh","bash","css","scss","html","xml","yaml","yml","toml","ini","conf","env","log","sql","gitignore","csv","tsv"]);function Xj(i){const e=Lr(i);return Yj.has(e)||iC.has(e)||e==="pdf"}function Jj(i,e){if(e)return"#d97757";switch(Lr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function vf(i){var e;try{const t=window.api;return(e=t==null?void 0:t.git)!=null&&e.fileStatus?await t.git.fileStatus(i):{}}catch{return{}}}function Zj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=cw(),l=lw(),[p,a]=B.useState([]),[d,f]=B.useState(new Set),g=B.useRef(d);g.current=d;const[m,w]=B.useState(""),[D,k]=B.useState(qj),E=B.useCallback(Fe=>{k(Ct=>{const Me=typeof Fe=="function"?Fe(Ct):Fe;return Kj(Me),Me})},[]),[b,C]=B.useState(!1),[y,x]=B.useState(null),[A,P]=B.useState({}),[N,L]=B.useState(null),[j,H]=B.useState(null),[W,re]=B.useState(""),[de,Z]=B.useState(null),[me,te]=B.useState(""),[pe,_e]=B.useState(null),Ce=B.useRef(null),U=B.useRef(null),ie=B.useRef(0),q=B.useCallback(async()=>{if(!i)return;const Fe=++ie.current;C(!0),x(null);const Ct=await window.api.files.list(i,D);ie.current===Fe&&(Ct.ok?a(Ct.entries.map(Me=>({...Me}))):(x(Ct.error??"failed to list"),a([])),C(!1))},[i,D]),oe=B.useCallback(async Fe=>{const Ct=ie.current,Me=new Map;for(const ze of Fe){const ft=ze.split("/").length,ct=Me.get(ft);ct?ct.push(ze):Me.set(ft,[ze])}const ot=[];for(const ze of[...Me.keys()].sort((ft,ct)=>ft-ct)){const ft=Me.get(ze),ct=await Promise.all(ft.map(async Zt=>({p:Zt,result:await window.api.files.list(Zt,D)})));if(ie.current!==Ct)return ot;for(const{p:Zt,result:ai}of ct)ai.ok?a(Zi=>Ug(Zi,Zt,ai.entries.map($n=>({...$n})))):ot.push(Zt)}return ot},[D]),ge=B.useCallback(async Fe=>(await q(),Fe.length?oe(Fe):[]),[q,oe]);B.useEffect(()=>{w(""),H(null),L(null),Z(null),_e(null),P({});const Fe=Uj(i),Ct=new Set(Fe);g.current=Ct,f(Ct);let Me=!1;return(async()=>{const ot=await ge(Fe);Me||!ot.length||$e(ze=>{const ft=new Set;let ct=!1;for(const Zt of ze){if(ot.some(ai=>Zt===ai||Zt.startsWith(ai+"/"))){ct=!0;continue}ft.add(Zt)}return ct?ft:ze})})(),vf(i).then(ot=>{Me||P(ot)}),()=>{Me=!0}},[i]);const ke=B.useRef(!0);B.useEffect(()=>{if(ke.current){ke.current=!1;return}ge([...g.current])},[D]),B.useEffect(()=>{if(!i||!l)return;vf(i).then(P);const Fe=window.setInterval(()=>{vf(i).then(P)},5e3);return()=>window.clearInterval(Fe)},[i,l]),B.useEffect(()=>{if(!N)return;const Fe=()=>L(null),Ct=Me=>{r.current&&Me.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Fe),window.addEventListener("keydown",Ct),()=>{window.removeEventListener("mousedown",Fe),window.removeEventListener("keydown",Ct)}},[N]),B.useEffect(()=>{j&&setTimeout(()=>{var Fe;return(Fe=Ce.current)==null?void 0:Fe.select()},30)},[j]),B.useEffect(()=>{de&&setTimeout(()=>{var Fe;return(Fe=U.current)==null?void 0:Fe.focus()},30)},[de]);const $e=B.useCallback(Fe=>{const Ct=g.current,Me=Fe(Ct);Me!==Ct&&(g.current=Me,f(Me),Vj(i,Me))},[i]),He=B.useCallback(async Fe=>{if(d.has(Fe.path)){$e(Me=>g_(Me,Fe.path));return}if($e(Me=>new Set(Me).add(Fe.path)),Fe.children)return;const Ct=await window.api.files.list(Fe.path,D);Ct.ok&&a(Me=>Ug(Me,Fe.path,Ct.entries.map(ot=>({...ot}))))},[d,D,$e]),ve=B.useCallback(async Fe=>{if(Fe===i){await q();return}const Ct=await window.api.files.list(Fe,D);Ct.ok&&a(Me=>Ug(Me,Fe,Ct.entries.map(ot=>({...ot}))))},[i,q,D]),X=B.useCallback(Fe=>{if(Fe.isDirectory){He(Fe);return}Xj(Fe.name)&&e?e(Fe.path):window.api.shell.open({as:"openPath",path:Fe.path})},[He,e]),Ie=B.useCallback(Fe=>{if(t){t(Fe);return}if(n){const Ct=Fe.startsWith(i+"/")?Fe.slice(i.length+1):Fe;window.api.pty.write({tabId:n,data:`@${Ct} `})}},[t,n,i]),he=B.useCallback((Fe,Ct)=>{Fe.preventDefault(),Fe.stopPropagation(),L({x:Fe.clientX,y:Fe.clientY,node:Ct})},[]),Pe=Fe=>{H(Fe.path),re(Fe.name)},Qe=async()=>{if(!j)return;const Fe=W.trim();if(!Fe){H(null);return}const Ct=await window.api.files.rename(j,Fe);if(H(null),Ct.ok){const Me=j.slice(0,j.lastIndexOf("/"));$e(ot=>g_(ot,j)),await ve(Me||i),vf(i).then(P)}else{const Me=Ct.error??"rename failed";x(Me),st.error(Me)}},pt=async()=>{if(!de)return;const Fe=me.trim();if(!Fe){Z(null),te("");return}const Ct=await window.api.files.create(de.parent,Fe,de.kind);if(Z(null),te(""),Ct.ok)await ve(de.parent),de.kind==="folder"&&$e(Me=>new Set(Me).add(de.parent));else{const Me=Ct.error??"create failed";x(Me),st.error(Me)}},Pt=async()=>{if(!pe)return;const Fe=await window.api.files.delete(pe.path),Ct=pe.path.slice(0,pe.path.lastIndexOf("/"));if(_e(null),Fe.ok)$e(Me=>g_(Me,pe.path)),await ve(Ct||i),vf(i).then(P);else{const Me=Fe.error??"delete failed";x(Me),st.error(Me)}},dt=B.useMemo(()=>{if(!m.trim())return p;const Fe=m.toLowerCase();return p.filter(Ct=>Ct.name.toLowerCase().includes(Fe))},[p,m]),Yt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return h.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[h.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[h.jsx(GC,{size:14,className:"shrink-0 text-accent"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("p",{className:"text-xs font-medium text-fg truncate",children:Yt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:q,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(sN,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Fe=>w(Fe.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),h.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[h.jsx("button",{onClick:()=>Z({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:h.jsx(rN,{size:12})}),h.jsx("button",{onClick:()=>Z({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:h.jsx(oN,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>E(Fe=>!Fe),className:`p-1.5 rounded transition-colors ${D?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:D?"Hide hidden files":"Show hidden files",children:D?h.jsx(aN,{size:12}):h.jsx(lN,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[y&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:y}),!y&&dt.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!y&&h.jsx(BC,{nodes:dt,depth:0,expanded:d,gitStatus:A,renaming:j,renameValue:W,renameInputRef:Ce,onRenameChange:re,onRenameCommit:Qe,onRenameCancel:()=>H(null),onToggleDir:He,onFileClick:X,onSendToChat:Ie,onContextMenu:he})]}),h.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),N&&h.jsx(Qj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Pe(N.node),L(null)},onDelete:()=>{_e(N.node),L(null)},onNewFile:()=>{Z({parent:N.node.path,kind:"file"}),L(null)},onNewFolder:()=>{Z({parent:N.node.path,kind:"folder"}),L(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:N.node.path}),L(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:N.node.path}),L(null)},onCopyPath:()=>{var Fe;(Fe=navigator.clipboard)==null||Fe.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx($0,{title:`New ${de.kind}`,subtitle:`in ${eN(de.parent)}`,onCancel:()=>{Z(null),te("")},onConfirm:pt,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:U,value:me,onChange:Fe=>te(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&pt(),Fe.key==="Escape"&&(Z(null),te(""))},placeholder:de.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),pe&&h.jsx($0,{title:`Delete ${pe.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>_e(null),onConfirm:Pt,confirmLabel:"Delete",danger:!0,children:h.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",h.jsxs("span",{className:"text-fg font-medium",children:['"',pe.name,'"']})," to the trash?",pe.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function BC(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return h.jsx(h.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,g=r[a.path],m=Jj(a.name,a.isDirectory);return h.jsxs("div",{children:[h.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?h.jsx(nN,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):h.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?h.jsx(tN,{size:12,color:m}):h.jsx(GC,{size:12,color:m}):h.jsx(iN,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):h.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),g&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:v_[g].color,backgroundColor:`${v_[g].color}20`},title:g,children:v_[g].label}),!a.isDirectory&&h.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:h.jsx(cN,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(BC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function Qj(i){const{x:e,y:t,node:n}=i;return h.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${An.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&h.jsx(Hl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Hl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Hl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(__,{}),h.jsx(Hl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Hl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(__,{}),h.jsx(Hl,{label:"New file",onClick:i.onNewFile}),h.jsx(Hl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(__,{}),h.jsx(Hl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Hl({label:i,onClick:e,danger:t}){return h.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function __(){return h.jsx("div",{className:"my-1 border-t border-line"})}function $0(i){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&h.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),h.jsx("div",{className:"mb-4",children:i.children}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),h.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function eN(i){return i.split("/").filter(Boolean).pop()||i}function Ug(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Ug(n.children,e,t)}:n)}function ba({size:i,children:e,className:t,color:n}){return h.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function GC({size:i,className:e,color:t}){return h.jsx(ba,{size:i,className:e,color:t,children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function tN({size:i,className:e,color:t}){return h.jsx(ba,{size:i,className:e,color:t,children:h.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function iN({size:i,className:e,color:t}){return h.jsxs(ba,{size:i,className:e,color:t,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function nN({size:i,className:e}){return h.jsx(ba,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function sN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("polyline",{points:"1 20 1 14 7 14"}),h.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function rN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"}),h.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),h.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function oN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),h.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),h.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function aN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function lN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),h.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function cN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),h.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function dN({content:i,children:e,align:t="bottom-right"}){const[n,r]=B.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return h.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&h.jsx("span",{role:"tooltip",className:`absolute ${An.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function Lf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Cb="sm.projects.splitPct",kb=33,FC=20,HC=60,WC="sm.projects.fileTreeCollapsed",uN=32;function hN(){try{const i=parseFloat(localStorage.getItem(Cb)??"");if(Number.isFinite(i))return Math.min(HC,Math.max(FC,i))}catch{}return kb}function pN(){try{return localStorage.getItem(WC)==="1"}catch{return!1}}function fN(){const i=St(W=>W.tabs),e=St(W=>W.activeTabId),t=i.find(W=>W.id===e)??null,n=Di(W=>W.navFace),[r,l]=B.useState(null);B.useEffect(()=>{if(n!=="home"||r)return;let W=!1;return window.api.app.homeDir().then(re=>{W||l(re)}).catch(()=>{}),()=>{W=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=B.useState(()=>hN()),[f,g]=B.useState(()=>pN()),[m,w]=B.useState(!1),D=B.useRef(a);D.current=a;const k=B.useRef(null),E=B.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:y}=mh(),x=A0(W=>W.pinned),A=A0(W=>W.togglePin),P=[...b].sort((W,re)=>(x[re.cwd]?1:0)-(x[W.cwd]?1:0));B.useEffect(()=>{if(!m)return;const W=re=>{E.current&&!E.current.contains(re.target)&&w(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const N=B.useCallback(W=>{Pi.getState().openFile(W)},[]),L=B.useCallback(W=>{W.preventDefault();const re=W.clientX,de=D.current;let Z=de;const me=pe=>{const _e=k.current;if(!_e)return;const Ce=_e.getBoundingClientRect(),U=pe.clientX-re;Z=Math.min(HC,Math.max(FC,de+U/Ce.width*100)),d(Z)},te=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",te),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Cb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",te),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=B.useCallback(()=>{d(kb);try{localStorage.setItem(Cb,String(kb))}catch{}},[]),H=B.useCallback(()=>{g(W=>{const re=!W;try{localStorage.setItem(WC,re?"1":"0")}catch{}return re})},[]);return f?h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("button",{onClick:H,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:uN},children:[h.jsx("span",{className:"text-[11px]",children:"▸"}),h.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(Sb,{})})]}):h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[h.jsxs("div",{ref:E,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(W=>!W),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[h.jsx("span",{className:"flex-1 truncate text-left",children:p?Lf(p):"Projects"}),h.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),h.jsx("button",{onClick:H,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&h.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${An.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:P.length===0?h.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):P.map(W=>{const re=Lf(W.cwd);return h.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[h.jsx(dN,{content:x[W.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>A(W.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[W.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[W.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(W.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await y(W)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},W.cwd)})})]}),p?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:p,children:Lf(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(Zj,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):h.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:L,onDoubleClick:j,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(Sb,{})})]})}const mN=B.memo(fN),gN={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a Whisper model that loads the first time you record (a progress bar shows the download). A press-to-record hotkey starts and stops the mic; what you say is typed into the active terminal, and an auto-submit timer fires it for you a moment after you stop speaking. A one-time mic check confirms your microphone works.",sections:[{title:"Recording controls",items:[{term:"Hotkey",body:"Press your mic hotkey to record. The default is Ctrl+Shift+Space (Cmd+Option+V on Mac); the panel shows the live binding. Two behaviours: 'Hold to talk' records only while the key is held (push-to-talk), 'Tap on/off' starts on one press and stops on the next. The default is hold-to-talk; switch with the radio buttons."},{term:"Mic button & device",body:"The mic button toggles recording with the mouse. The device picker chooses which microphone to use, and a live level meter shows that audio is coming through."},{term:"Run mic check",body:"Opens a short wizard that confirms your mic is picking up sound. It runs automatically once after a settings-format change, or any time you click 'Run mic check'."}]},{title:"Speaking & hearing back",items:[{term:"Live transcript",body:"While recording, a pulsing red dot and the latest transcribed words appear so you can see what was heard. Errors (e.g. mic blocked) surface inline in red."},{term:"TTS (read replies aloud)",body:"The speaker button toggles text-to-speech. When on, Claude's replies are read back to you out loud."}]}],tips:["The speech model downloads on first use only, then stays cached — later recordings start instantly.","Hold-to-talk is best for quick interjections; Tap on/off is better for longer dictation where you don't want to hold a key."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},"tag-library":{headline:"Tag Library — the Epic intent-tag taxonomy",intro:"Every Epic carries an initial intent tag — feature, bug, discussion, or build — chosen at creation. The tag sets how eagerly /develop should fire inside that Epic's session: feature/bug/build treat PRD decomposition as the expected next step, discussion keeps /develop available but never assumed until whether-to-build is settled.",sections:[{title:"What it shows",items:[{term:"Tag",body:"The four intent tags an Epic can be created with."},{term:"/develop eagerness",body:"Whether PRD decomposition is the expected default for that tag, or available-but-not-assumed."},{term:"Agents carrying this tag",body:"Which Agent Library personas have this tag in their `tags:` frontmatter — the same relationship Agent Library edits from the agent side. Assign or remove an agent here to update that persona's file directly."}]}],tips:["Home face only — the taxonomy is machine-wide, not scoped to one project.","The tag taxonomy itself is read-only here — change an existing Epic's tag from its queue row menu, not from this page. The agent↔tag assignment, though, is editable from either Tag Library or Agent Library."]},"bilko-host":{headline:"Host on Bilko.run — publish this project's Marketing page",intro:"Turns the Marketing lens of this project's already-generated Project Pages into a live static-path listing on bilko.run, using the bilko-host MCP's existing gated publish pipeline (manifest/budget/golden/a11y/audit checks) — never a second, competing hosting mechanism.",sections:[{title:"What it shows",items:[{term:"Status",body:"not-published → bundle-ready → publishing → published/publish-failed, mirroring the on-disk publish-state.json a bilko-host-publisher Epic writes."},{term:"Slug",body:"The bilko.run/projects/<slug>/ path this project would publish to — defaults from package.json's name."},{term:"Bundle",body:"Size, build time, and git sha of the dist/ bundle Prepare Bundle last wrote."}]}],tips:["Project face only — publishing is always scoped to the active project's tab.",`Requires a generated Marketing Project Page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}},Aw="sm.learningPanel.collapsed";function I0(){try{const i=localStorage.getItem(Aw);if(i===null)return!1;if(i.startsWith("{")){const e=JSON.parse(i);return!!(e&&typeof e=="object"&&Object.values(e).some(Boolean))}return i==="1"||i==="true"}catch{return!1}}function P0(i){try{localStorage.setItem(Aw,i?"1":"0")}catch{}}function vN({active:i}){const[e,t]=B.useState(()=>!I0()),n=B.useRef(null),r=B.useCallback(()=>{t(a=>{const d=!a;return P0(!d),d})},[]);B.useEffect(()=>{const a=d=>{d.key===Aw&&t(!I0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),B.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),P0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=B.useRef(!1);B.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=gN[i];return p?h.jsxs("span",{ref:n,className:"relative inline-block",children:[h.jsx("button",{type:"button",onClick:r,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":e,title:e?"Close learning panel":"What is this?",children:"Learn"}),e&&h.jsxs("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:[h.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.intro}),p.sections.map(a=>h.jsxs("div",{className:"mb-3 last:mb-0",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:a.title}),h.jsx("ul",{className:"space-y-1",children:a.items.map((d,f)=>h.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[d.term&&h.jsx("span",{className:"text-fg font-medium",children:d.term}),d.term&&" — ",h.jsx("span",{children:d.body})]},f))})]},a.title)),p.tips&&p.tips.length>0&&h.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),h.jsx("ul",{className:"space-y-1",children:p.tips.map((a,d)=>h.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",a]},d))})]})]})]}):null}function _N({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&h.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[h.jsxs("div",{className:"max-w-[820px]",children:[i&&h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&h.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&h.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&h.jsx(vN,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const bN=B.lazy(()=>qn(()=>import("./Skills-C0GzzVrQ.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),wN=B.lazy(()=>qn(()=>import("./History-2GJMS703.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),yN=B.lazy(()=>qn(()=>import("./Scheduler-Dc5qiP24.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),xN=B.lazy(()=>qn(()=>import("./Settings-C2dEFb-v.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),SN=B.lazy(()=>qn(()=>import("./Permissions-UBam0bJG.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),CN=B.lazy(()=>qn(()=>import("./SystemPrompt-mtGPK8zo.js"),__vite__mapDeps([19,4,7,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),kN=B.lazy(()=>qn(()=>import("./Memory-7UdaOTtl.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),EN=B.lazy(()=>qn(()=>import("./Plugins-B3gUDkeb.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),TN=B.lazy(()=>qn(()=>import("./McpServers-BzyThQSM.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),DN=B.lazy(()=>qn(()=>import("./Hooks-DM2nS3RT.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),AN=B.lazy(()=>qn(()=>import("./AgentLibrary-13pfo8uY.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),$N=B.lazy(()=>qn(()=>import("./TagLibrary-DX54-mpd.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),IN=B.lazy(()=>qn(()=>import("./HostBilko-BLeC-lpp.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),PN=B.lazy(()=>qn(()=>import("./DataModel-SUyQbFlg.js"),__vite__mapDeps([27,4,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),RN=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function vr({children:i}){return h.jsx(B.Suspense,{fallback:RN,children:i})}const jN={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"Every session, ever",intro:"Resumable transcripts across every project you have opened. Pick a row to reattach Claude to the same conversation."},plugins:{title:"Plugins",intro:"Extensions for Claude Code. Install, enable, or remove plugins per-scope."},mcp:{title:"MCP Servers",intro:"External tools and integrations the agent can call. Add a new server or test an existing connection."},hooks:{title:"Hooks",intro:"Run scripts on session events. Tail logs, format files, post to Slack — anything that responds to a shell command."},memory:{title:"Memory",intro:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},"bilko-host":{title:"Host on Bilko.run",intro:"Publish this project's generated Marketing page to bilko.run as a static-path listing, via the bilko-host MCP's gated publish pipeline."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},NN=()=>{},R0=new Map;function MN(i,e){const t=R0.get(i);if(t&&t.ctx===e)return t.node;const n=ON(i,e);return R0.set(i,{ctx:e,node:n}),n}function ON(i,e){switch(i){case"overview":return h.jsx(o$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(aI,{});case"editor":return h.jsx(Sb,{});case"projects":return h.jsx(mN,{})}const t=jN[i],n=(()=>{switch(i){case"skills":return h.jsx(vr,{children:h.jsx(bN,{})});case"history":return h.jsx(vr,{children:h.jsx(wN,{})});case"scheduler":return h.jsx(vr,{children:h.jsx(yN,{navigate:e.onNavigate})});case"plugins":return h.jsx(vr,{children:h.jsx(EN,{})});case"mcp":return h.jsx(vr,{children:h.jsx(TN,{})});case"hooks":return h.jsx(vr,{children:h.jsx(DN,{})});case"memory":return h.jsx(vr,{children:h.jsx(kN,{})});case"system-prompt":return h.jsx(vr,{children:h.jsx(CN,{})});case"permissions":return h.jsx(vr,{children:h.jsx(SN,{})});case"settings":return h.jsx(vr,{children:h.jsx(xN,{})});case"agent-library":return h.jsx(vr,{children:h.jsx(AN,{})});case"tag-library":return h.jsx(vr,{children:h.jsx($N,{})});case"bilko-host":return h.jsx(vr,{children:h.jsx(IN,{})});case"data-model":return h.jsx(vr,{children:h.jsx(PN,{})});case"voice":return h.jsx(zj,{open:!0,onClose:NN,variant:"page"});default:return null}})();if(!n)return null;const r=LE[i];return t&&r?h.jsx(_N,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var b_={exports:{}},j0;function LN(){return j0||(j0=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(y,x,A,P){var N,L=arguments.length,j=L<3?x:P===null?P=Object.getOwnPropertyDescriptor(x,A):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(y,x,A,P);else for(var H=y.length-1;H>=0;H--)(N=y[H])&&(j=(L<3?N(j):L>3?N(x,A,j):N(x,A))||j);return L>3&&j&&Object.defineProperty(x,A,j),j},g=this&&this.__param||function(y,x){return function(A,P){x(A,P,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),w=d(9924),D=d(844),k=d(4725),E=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(y,x,A,P){super(),this._terminal=y,this._coreBrowserService=A,this._renderService=P,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3025
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),y=B.useCallback(x=>{const A=t.diff;if(!A)return{ok:!1,reason:"not-found"};const P=aj(x,A.before,A.after);return P.ok?(r.current+=1,n({type:"ACCEPT"})):st.error(P.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),P},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:b,run:E,retry:C,accept:y}}const gj=[{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."}],g0=320,gf=8;function vj(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function _j(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,gf),Math.max(gf,e-g0-gf)),n=Math.max(i.top-gf,gf);return{position:"fixed",left:t,top:n,width:g0,transform:"translateY(-100%)",zIndex:VT.dialog}}function bj({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:g,onReject:m,onRetry:w}){const[D,k]=B.useState(""),E=()=>{const b=D.trim();b&&(p(b),k(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:_j(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&h.jsxs("div",{className:"p-2",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.jsx("button",{onClick:a,"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"}),gj.map(b=>h.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),h.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),h.jsx("input",{autoFocus:!0,value:D,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?E():b.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&h.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[h.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[h.jsxs("span",{className:"flex items-center gap-2",children:[h.jsx(vj,{}),"Listening…"]}),r&&h.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),h.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&h.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[h.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsxs("div",{className:"p-3 flex items-center justify-between",children:[h.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),h.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&h.jsxs("div",{className:"p-3",children:[h.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function wj(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function v0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:g}){return h.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[h.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),h.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Xb(fj)})]}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&h.jsxs("div",{className:"text-fg-faint",children:[h.jsx("p",{children:"Select text in the doc…"}),h.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&h.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&h.jsxs("div",{children:[h.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[h.jsx(wj,{}),"Listening…"]}),r&&h.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),h.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&h.jsxs("div",{children:[h.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&h.jsxs("div",{children:[h.jsxs("div",{className:"mb-3 space-y-2",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function yj(){const i=St(t=>t.tabs),e=St(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function _0(i){return i.split("/").filter(Boolean).pop()||i}function xj({path:i,onRenamed:e,onDeleted:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(!1),[a,d]=B.useState(""),[f,g]=B.useState(!1),m=Pi(W=>W.buffers[i]),w=Pi(W=>W.openFile),D=Pi(W=>W.renameOpenFile),k=Pi(W=>W.closeFile),E=yj(),b=_0(i),C=()=>r(!1),y=()=>{d(b),p(!0),C()},x=async()=>{const W=a.trim();if(!W||W===b){p(!1);return}try{const re=await window.api.files.rename(i,W);if(re.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=re.newPath??`${de}/${W}`;D(i,Z),e==null||e(i,Z),st.info(`Renamed to ${W}`)}else st.error(re.error??`Couldn't rename ${b}`)}catch(re){st.error(re instanceof Error?re.message:`Couldn't rename ${b}`)}p(!1)},A=async()=>{C();try{const W=await window.api.files.duplicate(i);W.ok&&W.path?(w(W.path),st.info(`Duplicated as ${_0(W.path)}`)):st.error(W.error??`Couldn't duplicate ${b}`)}catch(W){st.error(W instanceof Error?W.message:`Couldn't duplicate ${b}`)}},P=async()=>{try{const W=await window.api.files.delete(i);W.ok?(k(i),t==null||t(i),st.info(`Deleted ${b}`)):st.error(W.error??`Couldn't delete ${b}`)}catch(W){st.error(W instanceof Error?W.message:`Couldn't delete ${b}`)}g(!1)},N=async()=>{C();const W=m??"";try{await navigator.clipboard.writeText(W),st.info(`Copied ${W.length} chars`)}catch(re){st.error(re instanceof Error?re.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!E){st.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${i} `}),st.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(W=>{W.ok||st.error(W.error??`Couldn't open ${b}`)}).catch(W=>st.error(W instanceof Error?W.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(W=>{W.ok||st.error(W.error??`Couldn't reveal ${b}`)}).catch(W=>st.error(W instanceof Error?W.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(W=>!W),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:"Document actions",children:"Document ▾"}),n&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${An.contextMenuScrim}`,onMouseDown:C}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${An.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[h.jsx(m_,{children:"Edit"}),h.jsx(ed,{label:"Rename",onClick:y}),h.jsx(ed,{label:"Duplicate",onClick:A}),h.jsx(ed,{label:"Delete document",danger:!0,onClick:()=>{C(),g(!0)}}),h.jsx(b0,{}),h.jsx(m_,{children:"Open"}),h.jsx(ed,{label:"Open in default app",onClick:j}),h.jsx(ed,{label:"Reveal in OS",onClick:H}),h.jsx(b0,{}),h.jsx(m_,{children:"Export"}),h.jsx(ed,{label:"Copy as Markdown",onClick:N}),h.jsx(ed,{label:"Add to Claude context",onClick:L,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(Sj,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(Cj,{name:b,onCancel:()=>g(!1),onConfirm:()=>void P()})]})}function m_({children:i}){return h.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function ed({label:i,onClick:e,danger:t,disabled:n,title:r}){return h.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function b0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function Sj({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),h.jsx("input",{autoFocus:!0,value:i,onChange:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function Cj({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function kj(){const[i,e]=B.useState(!1),t=ih();return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${An.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${An.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[h.jsx(Qu,{label:"Text size",children:h.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[h.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),h.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),h.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),h.jsx(Qu,{label:"Word wrap",children:h.jsx(Ag,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Qu,{label:"Minimap",children:h.jsx(Ag,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Qu,{label:"Theme",children:h.jsx("button",{onClick:()=>t.setTheme(t.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:t.theme==="dark"?"Dark":"Paper"})}),h.jsx(Qu,{label:"Autosave",children:h.jsx(Ag,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Qu,{label:"Wide measure",children:h.jsx(Ag,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Qu({label:i,children:e}){return h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Ag({on:i,onClick:e}){return h.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const Ej=B.lazy(()=>qn(()=>import("./TiptapBody-D9iz4xQx.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function $g(i){return i.split("/").filter(Boolean).pop()||i}function Ig(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Pg(i){return sC(i)||rC(i)}function Tj(){const i=cw(),e=Pi(ze=>ze.openFiles),t=Pi(ze=>ze.activeFilePath),n=Pi(ze=>ze.dirty),r=Pi(ze=>ze.viewMode),l=Pi(ze=>ze.buffers),p=Pi(ze=>ze.setActive),a=Pi(ze=>ze.closeFile),d=Pi(ze=>ze.closeOthers),f=Pi(ze=>ze.closeToTheRight),g=Pi(ze=>ze.closeAll),m=Pi(ze=>ze.loadBuffer),w=Pi(ze=>ze.setBuffer),D=Pi(ze=>ze.markSaved),k=Pi(ze=>ze.setViewMode),E=ih(),[b,C]=B.useState({}),[y,x]=B.useState({}),[A,P]=B.useState(null),[N,L]=B.useState(null),[j,H]=B.useState(!1),[W,re]=B.useState(!1),[de,Z]=B.useState(!0),me=B.useRef(null),te=B.useRef(null),pe=B.useRef(void 0),_e=B.useRef(null),Ce=B.useRef(null),U=mj(t??"",l[t??""]??""),ie=B.useCallback(ze=>{me.current=ze},[]),q=B.useCallback(()=>me.current,[]);B.useEffect(()=>{const ze=t;if(!ze||Pg(ze))return;if(Pi.getState().hasBuffer(ze)){C(ct=>ct[ze]==="ready"?ct:{...ct,[ze]:"ready"});return}let ft=!1;return C(ct=>({...ct,[ze]:"loading"})),window.api.files.read(ze).then(ct=>{ft||(ct.binary?C(Zt=>({...Zt,[ze]:{binary:!0,size:ct.size??0,mime:ct.mime??"application/octet-stream",reason:ct.error??"Binary file"}})):ct.ok?(m(ze,ct.text),C(Zt=>({...Zt,[ze]:"ready"}))):C(Zt=>({...Zt,[ze]:{error:ct.error??"failed to read"}})))}),()=>{ft=!0}},[t,m]),B.useEffect(()=>{L(null)},[t]);const oe=B.useCallback(async(ze,ft=!1)=>{const ct=Pi.getState().buffers[ze];if(ct==null)return;ft&&H(!0);const Zt=await window.api.files.write(ze,ct);Zt.ok?(D(ze),x(ai=>({...ai,[ze]:(ai[ze]??0)+1})),ft||st.info(`Saved ${$g(ze)}`)):st.error(Zt.error??`Couldn't save ${$g(ze)}`),ft&&H(!1)},[D]);B.useEffect(()=>{if(!E.autosave)return;const ze=t;if(!(!ze||Pg(ze)||!n[ze]))return window.clearTimeout(pe.current),pe.current=window.setTimeout(()=>{oe(ze,!0)},1200),()=>window.clearTimeout(pe.current)},[E.autosave,t,n,l,oe]);const ge=B.useCallback(ze=>{ze.length&&(C(ft=>Ig(ft,ze)),x(ft=>Ig(ft,ze)))},[]),ke=B.useCallback((ze,ft)=>{C(ct=>ze in ct?{...Ig(ct,[ze]),[ft]:ct[ze]}:ct),x(ct=>ze in ct?{...Ig(ct,[ze]),[ft]:ct[ze]}:ct)},[]),$e=B.useCallback(ze=>{n[ze]?P({kind:"one",path:ze}):(a(ze),ge([ze]))},[n,a,ge]),He=B.useCallback(ze=>{e.some(ct=>ct.path!==ze&&n[ct.path])?P({kind:"others",path:ze}):(d(ze),ge(e.filter(ct=>ct.path!==ze).map(ct=>ct.path)))},[e,n,d,ge]),ve=B.useCallback(ze=>{const ft=e.findIndex(Zt=>Zt.path===ze);ft!==-1&&e.slice(ft+1).some(Zt=>n[Zt.path])?P({kind:"right",path:ze}):(f(ze),ge(ft!==-1?e.slice(ft+1).map(Zt=>Zt.path):[]))},[e,n,f,ge]);B.useEffect(()=>{const ze=ft=>{if(i.current)if((ft.metaKey||ft.ctrlKey)&&(ft.key==="s"||ft.key==="S")){const ct=Pi.getState().activeFilePath;ct&&!Pg(ct)&&(ft.preventDefault(),oe(ct))}else if((ft.metaKey||ft.ctrlKey)&&ft.shiftKey&&(ft.key==="f"||ft.key==="F"))ft.preventDefault(),re(ct=>!ct);else if((ft.metaKey||ft.ctrlKey)&&ft.shiftKey&&(ft.key==="w"||ft.key==="W")){const ct=Pi.getState().activeFilePath;ct&&Pi.getState().openFiles.length>1&&(ft.preventDefault(),He(ct))}else ft.key==="Escape"&&U.state.phase!=="idle"?U.cancel():ft.key==="Escape"&&W&&re(!1)};return window.addEventListener("keydown",ze),()=>window.removeEventListener("keydown",ze)},[oe,W,He,U.state.phase,U.cancel]),B.useEffect(()=>{if(U.state.phase==="idle")return;const ze=ft=>{var Zt,ai;const ct=ft.target;(Zt=Ce.current)!=null&&Zt.contains(ct)||(ai=_e.current)!=null&&ai.contains(ct)||U.cancel()};return window.addEventListener("mousedown",ze),()=>window.removeEventListener("mousedown",ze)},[U.state.phase,U.cancel]),B.useEffect(()=>{U.cancel()},[t,U.cancel]);const X=B.useCallback(()=>{e.some(ft=>n[ft.path])?P({kind:"all",path:""}):(g(),C({}),x({}))},[e,n,g]),Ie=()=>{if(A){if(A.kind==="one")a(A.path),ge([A.path]);else if(A.kind==="others"){const ze=e.filter(ft=>ft.path!==A.path).map(ft=>ft.path);d(A.path),ge(ze)}else if(A.kind==="right"){const ze=e.findIndex(ct=>ct.path===A.path),ft=ze!==-1?e.slice(ze+1).map(ct=>ct.path):[];f(A.path),ge(ft)}else g(),C({}),x({});P(null)}};if(e.length===0)return h.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"mb-2",children:"no file open"}),h.jsxs("div",{children:["open the ",h.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const he=t,Pe=he?$g(he):"",Qe=he?b[he]:void 0,pt=he?lC(he):!1,Pt=he?pI(he):!1,dt=he&&pt?r[he]??fI(he):"edit",Yt=!!he&&!Pg(he)&&Qe==="ready",Fe=Yt,Ct=Pt?["edit","wysiwyg","preview","split"]:pt?["edit","preview"]:[],Me=he&&h.jsx(AP,{path:he,name:Pe,value:l[he]??"",onChange:ze=>w(he,ze),onSave:()=>void oe(he),onReady:ie,onCursor:L}),ot=j?"Saving…":he&&n[he]?E.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!W&&h.jsx(vI,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:$e,onCloseOthers:He,onCloseToTheRight:ve,onCloseAll:X}),he&&!W&&h.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[h.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Pe}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:he}),Yt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ot]}),Ya(he)&&(dt==="preview"||dt==="split")&&h.jsx("button",{onClick:()=>Z(ze=>!ze),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ya(he)&&(dt==="preview"||dt==="split")&&h.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Ct.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Ct.map(ze=>h.jsx("button",{onClick:()=>k(he,ze),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${dt===ze?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:ze},ze))}),h.jsx("div",{className:"flex-1"}),h.jsx(xj,{path:he,onRenamed:ke,onDeleted:ze=>ge([ze])}),Yt&&h.jsx(kj,{}),h.jsx("button",{onClick:()=>re(!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"})]}),W&&h.jsx("button",{onClick:()=>re(!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"}),h.jsx("div",{className:"flex-1 min-h-0",children:he?sC(he)?h.jsx(ZR,{path:he,name:Pe}):rC(he)?h.jsx(QR,{path:he}):Qe&&typeof Qe=="object"&&"binary"in Qe?h.jsx(oj,{path:he,name:Pe,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?h.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):dt==="wysiwyg"&&Ya(he)?h.jsx(B.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(Ej,{value:l[he]??"",onChange:ze=>w(he,ze)},he)}):dt==="split"&&Ya(he)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(p0,{text:l[he]??"",scrollRef:te}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(h0,{getEditor:q}),h.jsx("div",{className:"flex-1 min-h-0",children:Me})]}),h.jsx("div",{ref:_e,className:"flex-1 min-w-0",children:h.jsx(wb,{ref:te,text:l[he]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!W&&E.assistantRail&&h.jsx(v0,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)},onReject:U.cancel,onRetry:U.retry})]}):dt==="preview"&&Ya(he)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(p0,{text:l[he]??"",scrollRef:te}),h.jsx("div",{ref:_e,className:"flex-1 min-w-0",children:h.jsx(wb,{ref:te,text:l[he]??"",wideMeasure:E.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!W&&E.assistantRail&&h.jsx(v0,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)},onReject:U.cancel,onRetry:U.retry})]}):dt==="preview"&&nC(he)?h.jsx(XR,{path:he,dirty:!!n[he],reloadToken:y[he]??0}):dt==="preview"&&oC(he)?h.jsx(tj,{path:he,text:l[he]??""}):dt==="preview"&&aC(he)?h.jsx(sj,{path:he,text:l[he]??""}):Ya(he)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(h0,{getEditor:q}),h.jsx("div",{className:"flex-1 min-h-0",children:Me})]}):Me:null}),Fe&&h.jsx(YR,{text:l[he]??"",cursor:N,language:Lr(he)||void 0}),he&&Ya(he)&&(dt==="preview"||dt==="split")&&U.state.phase!=="idle"&&U.state.selection&&h.jsx("div",{ref:Ce,children:h.jsx(bj,{phase:U.state.phase,rect:U.state.selection.rect,diff:U.state.diff,transcript:U.state.transcript,modelStatus:U.state.modelStatus,onQuickAction:U.run,onRunCustom:U.run,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onReject:U.cancel,onRetry:U.retry,onAccept:()=>{const ze=U.accept(l[he]??"");ze.ok&&w(he,ze.next)}})}),A&&h.jsx(Dj,{message:A.kind==="one"?`Discard unsaved changes to ${$g(A.path)}?`:A.kind==="others"?"Discard unsaved changes in the other open files?":A.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>P(null),onConfirm:Ie})]})}const Sb=B.memo(Tj);function Dj({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Aj={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},w0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Tw({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&h.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),h.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=B.useRef(null),f=B.useRef(null),g=B.useRef(e);if(g.current=e,B.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(w0);C?C.focus():b.focus()},0),E=b=>{if(b.key==="Escape"){b.stopPropagation(),g.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const y=Array.from(C.querySelectorAll(w0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(y.length===0){b.preventDefault(),C.focus();return}const x=y[0],A=y[y.length-1],P=document.activeElement;b.shiftKey?(P===x||!C.contains(P))&&(b.preventDefault(),A.focus()):(P===A||!C.contains(P))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",E),()=>{clearTimeout(k),document.removeEventListener("keydown",E);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=D=>{D.target===D.currentTarget&&e()},w=h.jsx("div",{className:`fixed inset-0 ${An.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:h.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":n??"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 ${Aj[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?h.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?h.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Jf.createPortal(w,document.body):w}class RC extends B.Component{constructor(){super(...arguments);Fi(this,"state",{error:null});Fi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):h.jsxs("div",{className:"p-6 text-xs",children:[h.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),h.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),h.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 $j({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(Tw,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&h.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[h.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),h.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:"✕"})]}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(RC,{children:n})})]})}function jC(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const y0=i=>Symbol.iterator in i,x0=i=>"entries"in i,S0=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},Ij=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function Pj(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:y0(i)&&y0(e)?x0(i)&&x0(e)?S0(i,e):Ij(i,e):S0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Dw(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return Pj(e.current,n)?e.current:e.current=n}}let C0=0;const Rj=1e3;function jj(i){const e=performance.now();e-C0<Rj||(C0=e,gt.debug("voice","mic.gate.click_rejected",{reason:i}))}function Nj(){const i=kt(f=>f.isRecording),e=kt(f=>f.error),t=kt(f=>f.loadingProgress),n=kt(Dw(iv)),r=()=>{const f=kt.getState(),{canRecord:g,reason:m}=iv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return jj(m);const w=St.getState().activeTabId;w&&f.startRecording(w)},l=jC(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,d=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return h.jsx("button",{onClick:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${d}`,children:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),h.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),h.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function Mj(){const i=kt(t=>t.ttsEnabled),e=kt(t=>t.toggleTTS);return h.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?h.jsxs(h.Fragment,{children:[h.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),h.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),h.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),h.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Oj(i){return/^monitor of /i.test(i.trim())}function k0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function E0(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=k0(e),l=t.filter(p=>p.label&&k0(p.label)===r);return l.length===1?l[0]:null}async function T0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&Oj(n.label))):[]}const D0=!1;function NC(){const i=kt(f=>f.isRecording);kt(f=>f.startRecording),kt(f=>f.stopRecording);const[e,t]=B.useState([]),[n,r]=B.useState(null),[l,p]=B.useState(null);B.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await T0(D0);if(f)return;t(m),p(g.selectedLabel);const w=E0(g.selectedDeviceId,g.selectedLabel,m);w?(r(w.deviceId),g.selectedDeviceId&&w.deviceId!==g.selectedDeviceId&&(gt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),gt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){gt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=B.useCallback(async()=>{try{const f=await T0(D0);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=E0(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){gt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);B.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var D;const g=f.target.value,m=g===""?null:g,w=m?((D=e.find(k=>k.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:w}),gt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){gt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await kt.getState().restartWithDevice()}catch(k){gt.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return h.jsxs("select",{value:n??"",onChange:d,onFocus:()=>{a()},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:[h.jsx("option",{value:"",children:"Default"}),e.map(f=>h.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function Lj(){const i=kt(D=>D.isRecording),e=kt(D=>D.levelMeterEnabled),[t,n]=B.useState(0),[r,l]=B.useState(0),p=B.useRef(0);p.current=r;const[a,d]=B.useState(0),[f,g]=B.useState(!1),m=B.useRef(null);if(B.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,E=null,b=null;const C=()=>{if(k)return;const x=b??XS();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,E=new Uint8Array(new ArrayBuffer(x.fftSize)));const A=E;x.getByteTimeDomainData(A);let P=0;for(let H=0;H<A.length;H++){const W=A[H]-128;P+=W*W}const N=Math.sqrt(P/A.length)/128,L=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(L+60)/60));l(N),n(j),N>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const y=setInterval(()=>{k||d(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(y),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return h.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${f?"ring-1 ring-red-500":""}`,children:h.jsx("div",{className:`h-full ${w} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function MC(){const i=kt(f=>f.submitCountdownStartAt),e=kt(f=>f.submitDelayMs),[t,n]=B.useState(()=>performance.now());if(B.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,d=kt.getState().cancelSubmit;return h.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:h.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:h.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function zj({open:i,onClose:e,variant:t="overlay"}){return h.jsx($j,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(Hj,{}),h.jsx(MC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(Nj,{}),h.jsx(NC,{}),h.jsx(Mj,{})]}),h.jsx(Bj,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.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"}),h.jsx(Fj,{})]}),h.jsx(Lj,{})]})})}function Bj(){const i=kt(l=>l.isRecording),[e,t]=B.useState(null);if(B.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(a=>{l||t(a)}).catch(()=>{});const p=window.api.voice.onHotkeyConfigChanged(a=>t(a));return()=>{l=!0,p()}},[]),i||!e)return null;const n=e.mode==="hold"?"Hold":"Press",r=Gj(e.accelerator);return h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("span",{children:[n," "]}),h.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),h.jsx("span",{children:" to record"})]})}function Gj(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function Fj(){const[i,e]=B.useState(null);if(B.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>gt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){gt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return h.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:[h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),h.jsx("span",{children:"Tap on/off"})]}),h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),h.jsx("span",{children:"Hold to talk"})]})]})}function Hj(){const i=kt(l=>l.isRecording),e=kt(l=>l.lastTranscript),t=kt(l=>l.error),n=kt(l=>l.modelStatus),r=kt(l=>l.loadingProgress);return t?h.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?h.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),h.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{children:"Loading speech model"}),h.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),h.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const OC="~/.claude/session-manager/projects-prefs.json",Wj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Fl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(OC,t).catch(()=>{})}const A0=On((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(OC);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Fl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":Wj[t];i({sort:{col:t,dir:r}}),Fl(e)},setRecentFilter:t=>{i({recentFilter:t}),Fl(e)},setHasRemote:t=>{i({hasRemote:t}),Fl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Fl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Fl(e)},setSearch:t=>{i({search:t}),Fl(e)},setEditor:t=>{i({editor:t}),Fl(e)}})),LC=i=>`sm.fileTree.expanded:${i}`;function Uj(i){try{const e=localStorage.getItem(LC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function Vj(i,e){try{localStorage.setItem(LC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const zC="sm.fileTree.showHidden";function qj(){try{const i=localStorage.getItem(zC);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function Kj(i){try{localStorage.setItem(zC,JSON.stringify(i))}catch{}}function g_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const v_={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},Yj=new Set(["md","txt","json","jsonl","ndjson","js","jsx","ts","tsx","py","go","rs","rb","c","cpp","h","hpp","java","sh","bash","css","scss","html","xml","yaml","yml","toml","ini","conf","env","log","sql","gitignore","csv","tsv"]);function Xj(i){const e=Lr(i);return Yj.has(e)||iC.has(e)||e==="pdf"}function Jj(i,e){if(e)return"#d97757";switch(Lr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function vf(i){var e;try{const t=window.api;return(e=t==null?void 0:t.git)!=null&&e.fileStatus?await t.git.fileStatus(i):{}}catch{return{}}}function Zj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=cw(),l=lw(),[p,a]=B.useState([]),[d,f]=B.useState(new Set),g=B.useRef(d);g.current=d;const[m,w]=B.useState(""),[D,k]=B.useState(qj),E=B.useCallback(Fe=>{k(Ct=>{const Me=typeof Fe=="function"?Fe(Ct):Fe;return Kj(Me),Me})},[]),[b,C]=B.useState(!1),[y,x]=B.useState(null),[A,P]=B.useState({}),[N,L]=B.useState(null),[j,H]=B.useState(null),[W,re]=B.useState(""),[de,Z]=B.useState(null),[me,te]=B.useState(""),[pe,_e]=B.useState(null),Ce=B.useRef(null),U=B.useRef(null),ie=B.useRef(0),q=B.useCallback(async()=>{if(!i)return;const Fe=++ie.current;C(!0),x(null);const Ct=await window.api.files.list(i,D);ie.current===Fe&&(Ct.ok?a(Ct.entries.map(Me=>({...Me}))):(x(Ct.error??"failed to list"),a([])),C(!1))},[i,D]),oe=B.useCallback(async Fe=>{const Ct=ie.current,Me=new Map;for(const ze of Fe){const ft=ze.split("/").length,ct=Me.get(ft);ct?ct.push(ze):Me.set(ft,[ze])}const ot=[];for(const ze of[...Me.keys()].sort((ft,ct)=>ft-ct)){const ft=Me.get(ze),ct=await Promise.all(ft.map(async Zt=>({p:Zt,result:await window.api.files.list(Zt,D)})));if(ie.current!==Ct)return ot;for(const{p:Zt,result:ai}of ct)ai.ok?a(Zi=>Ug(Zi,Zt,ai.entries.map($n=>({...$n})))):ot.push(Zt)}return ot},[D]),ge=B.useCallback(async Fe=>(await q(),Fe.length?oe(Fe):[]),[q,oe]);B.useEffect(()=>{w(""),H(null),L(null),Z(null),_e(null),P({});const Fe=Uj(i),Ct=new Set(Fe);g.current=Ct,f(Ct);let Me=!1;return(async()=>{const ot=await ge(Fe);Me||!ot.length||$e(ze=>{const ft=new Set;let ct=!1;for(const Zt of ze){if(ot.some(ai=>Zt===ai||Zt.startsWith(ai+"/"))){ct=!0;continue}ft.add(Zt)}return ct?ft:ze})})(),vf(i).then(ot=>{Me||P(ot)}),()=>{Me=!0}},[i]);const ke=B.useRef(!0);B.useEffect(()=>{if(ke.current){ke.current=!1;return}ge([...g.current])},[D]),B.useEffect(()=>{if(!i||!l)return;vf(i).then(P);const Fe=window.setInterval(()=>{vf(i).then(P)},5e3);return()=>window.clearInterval(Fe)},[i,l]),B.useEffect(()=>{if(!N)return;const Fe=()=>L(null),Ct=Me=>{r.current&&Me.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Fe),window.addEventListener("keydown",Ct),()=>{window.removeEventListener("mousedown",Fe),window.removeEventListener("keydown",Ct)}},[N]),B.useEffect(()=>{j&&setTimeout(()=>{var Fe;return(Fe=Ce.current)==null?void 0:Fe.select()},30)},[j]),B.useEffect(()=>{de&&setTimeout(()=>{var Fe;return(Fe=U.current)==null?void 0:Fe.focus()},30)},[de]);const $e=B.useCallback(Fe=>{const Ct=g.current,Me=Fe(Ct);Me!==Ct&&(g.current=Me,f(Me),Vj(i,Me))},[i]),He=B.useCallback(async Fe=>{if(d.has(Fe.path)){$e(Me=>g_(Me,Fe.path));return}if($e(Me=>new Set(Me).add(Fe.path)),Fe.children)return;const Ct=await window.api.files.list(Fe.path,D);Ct.ok&&a(Me=>Ug(Me,Fe.path,Ct.entries.map(ot=>({...ot}))))},[d,D,$e]),ve=B.useCallback(async Fe=>{if(Fe===i){await q();return}const Ct=await window.api.files.list(Fe,D);Ct.ok&&a(Me=>Ug(Me,Fe,Ct.entries.map(ot=>({...ot}))))},[i,q,D]),X=B.useCallback(Fe=>{if(Fe.isDirectory){He(Fe);return}Xj(Fe.name)&&e?e(Fe.path):window.api.shell.open({as:"openPath",path:Fe.path})},[He,e]),Ie=B.useCallback(Fe=>{if(t){t(Fe);return}if(n){const Ct=Fe.startsWith(i+"/")?Fe.slice(i.length+1):Fe;window.api.pty.write({tabId:n,data:`@${Ct} `})}},[t,n,i]),he=B.useCallback((Fe,Ct)=>{Fe.preventDefault(),Fe.stopPropagation(),L({x:Fe.clientX,y:Fe.clientY,node:Ct})},[]),Pe=Fe=>{H(Fe.path),re(Fe.name)},Qe=async()=>{if(!j)return;const Fe=W.trim();if(!Fe){H(null);return}const Ct=await window.api.files.rename(j,Fe);if(H(null),Ct.ok){const Me=j.slice(0,j.lastIndexOf("/"));$e(ot=>g_(ot,j)),await ve(Me||i),vf(i).then(P)}else{const Me=Ct.error??"rename failed";x(Me),st.error(Me)}},pt=async()=>{if(!de)return;const Fe=me.trim();if(!Fe){Z(null),te("");return}const Ct=await window.api.files.create(de.parent,Fe,de.kind);if(Z(null),te(""),Ct.ok)await ve(de.parent),de.kind==="folder"&&$e(Me=>new Set(Me).add(de.parent));else{const Me=Ct.error??"create failed";x(Me),st.error(Me)}},Pt=async()=>{if(!pe)return;const Fe=await window.api.files.delete(pe.path),Ct=pe.path.slice(0,pe.path.lastIndexOf("/"));if(_e(null),Fe.ok)$e(Me=>g_(Me,pe.path)),await ve(Ct||i),vf(i).then(P);else{const Me=Fe.error??"delete failed";x(Me),st.error(Me)}},dt=B.useMemo(()=>{if(!m.trim())return p;const Fe=m.toLowerCase();return p.filter(Ct=>Ct.name.toLowerCase().includes(Fe))},[p,m]),Yt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return h.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[h.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[h.jsx(GC,{size:14,className:"shrink-0 text-accent"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("p",{className:"text-xs font-medium text-fg truncate",children:Yt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:q,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(sN,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Fe=>w(Fe.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),h.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[h.jsx("button",{onClick:()=>Z({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:h.jsx(rN,{size:12})}),h.jsx("button",{onClick:()=>Z({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:h.jsx(oN,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>E(Fe=>!Fe),className:`p-1.5 rounded transition-colors ${D?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:D?"Hide hidden files":"Show hidden files",children:D?h.jsx(aN,{size:12}):h.jsx(lN,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[y&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:y}),!y&&dt.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!y&&h.jsx(BC,{nodes:dt,depth:0,expanded:d,gitStatus:A,renaming:j,renameValue:W,renameInputRef:Ce,onRenameChange:re,onRenameCommit:Qe,onRenameCancel:()=>H(null),onToggleDir:He,onFileClick:X,onSendToChat:Ie,onContextMenu:he})]}),h.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),N&&h.jsx(Qj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Pe(N.node),L(null)},onDelete:()=>{_e(N.node),L(null)},onNewFile:()=>{Z({parent:N.node.path,kind:"file"}),L(null)},onNewFolder:()=>{Z({parent:N.node.path,kind:"folder"}),L(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:N.node.path}),L(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:N.node.path}),L(null)},onCopyPath:()=>{var Fe;(Fe=navigator.clipboard)==null||Fe.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx($0,{title:`New ${de.kind}`,subtitle:`in ${eN(de.parent)}`,onCancel:()=>{Z(null),te("")},onConfirm:pt,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:U,value:me,onChange:Fe=>te(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&pt(),Fe.key==="Escape"&&(Z(null),te(""))},placeholder:de.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),pe&&h.jsx($0,{title:`Delete ${pe.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>_e(null),onConfirm:Pt,confirmLabel:"Delete",danger:!0,children:h.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",h.jsxs("span",{className:"text-fg font-medium",children:['"',pe.name,'"']})," to the trash?",pe.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function BC(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return h.jsx(h.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,g=r[a.path],m=Jj(a.name,a.isDirectory);return h.jsxs("div",{children:[h.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?h.jsx(nN,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):h.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?h.jsx(tN,{size:12,color:m}):h.jsx(GC,{size:12,color:m}):h.jsx(iN,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):h.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),g&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:v_[g].color,backgroundColor:`${v_[g].color}20`},title:g,children:v_[g].label}),!a.isDirectory&&h.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:h.jsx(cN,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(BC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function Qj(i){const{x:e,y:t,node:n}=i;return h.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${An.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&h.jsx(Hl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Hl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Hl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(__,{}),h.jsx(Hl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Hl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(__,{}),h.jsx(Hl,{label:"New file",onClick:i.onNewFile}),h.jsx(Hl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(__,{}),h.jsx(Hl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Hl({label:i,onClick:e,danger:t}){return h.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function __(){return h.jsx("div",{className:"my-1 border-t border-line"})}function $0(i){return h.jsx("div",{className:`fixed inset-0 ${An.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&h.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),h.jsx("div",{className:"mb-4",children:i.children}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),h.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function eN(i){return i.split("/").filter(Boolean).pop()||i}function Ug(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Ug(n.children,e,t)}:n)}function ba({size:i,children:e,className:t,color:n}){return h.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function GC({size:i,className:e,color:t}){return h.jsx(ba,{size:i,className:e,color:t,children:h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function tN({size:i,className:e,color:t}){return h.jsx(ba,{size:i,className:e,color:t,children:h.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function iN({size:i,className:e,color:t}){return h.jsxs(ba,{size:i,className:e,color:t,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function nN({size:i,className:e}){return h.jsx(ba,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function sN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("polyline",{points:"1 20 1 14 7 14"}),h.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function rN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"}),h.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),h.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function oN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),h.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),h.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function aN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function lN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),h.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function cN({size:i,className:e}){return h.jsxs(ba,{size:i,className:e,children:[h.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),h.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function dN({content:i,children:e,align:t="bottom-right"}){const[n,r]=B.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return h.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&h.jsx("span",{role:"tooltip",className:`absolute ${An.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function Lf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Cb="sm.projects.splitPct",kb=33,FC=20,HC=60,WC="sm.projects.fileTreeCollapsed",uN=32;function hN(){try{const i=parseFloat(localStorage.getItem(Cb)??"");if(Number.isFinite(i))return Math.min(HC,Math.max(FC,i))}catch{}return kb}function pN(){try{return localStorage.getItem(WC)==="1"}catch{return!1}}function fN(){const i=St(W=>W.tabs),e=St(W=>W.activeTabId),t=i.find(W=>W.id===e)??null,n=Di(W=>W.navFace),[r,l]=B.useState(null);B.useEffect(()=>{if(n!=="home"||r)return;let W=!1;return window.api.app.homeDir().then(re=>{W||l(re)}).catch(()=>{}),()=>{W=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=B.useState(()=>hN()),[f,g]=B.useState(()=>pN()),[m,w]=B.useState(!1),D=B.useRef(a);D.current=a;const k=B.useRef(null),E=B.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:y}=mh(),x=A0(W=>W.pinned),A=A0(W=>W.togglePin),P=[...b].sort((W,re)=>(x[re.cwd]?1:0)-(x[W.cwd]?1:0));B.useEffect(()=>{if(!m)return;const W=re=>{E.current&&!E.current.contains(re.target)&&w(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const N=B.useCallback(W=>{Pi.getState().openFile(W)},[]),L=B.useCallback(W=>{W.preventDefault();const re=W.clientX,de=D.current;let Z=de;const me=pe=>{const _e=k.current;if(!_e)return;const Ce=_e.getBoundingClientRect(),U=pe.clientX-re;Z=Math.min(HC,Math.max(FC,de+U/Ce.width*100)),d(Z)},te=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",te),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Cb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",te),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=B.useCallback(()=>{d(kb);try{localStorage.setItem(Cb,String(kb))}catch{}},[]),H=B.useCallback(()=>{g(W=>{const re=!W;try{localStorage.setItem(WC,re?"1":"0")}catch{}return re})},[]);return f?h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("button",{onClick:H,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:uN},children:[h.jsx("span",{className:"text-[11px]",children:"▸"}),h.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(Sb,{})})]}):h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[h.jsxs("div",{ref:E,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(W=>!W),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[h.jsx("span",{className:"flex-1 truncate text-left",children:p?Lf(p):"Projects"}),h.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),h.jsx("button",{onClick:H,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&h.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${An.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:P.length===0?h.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):P.map(W=>{const re=Lf(W.cwd);return h.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[h.jsx(dN,{content:x[W.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>A(W.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[W.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[W.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(W.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await y(W)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},W.cwd)})})]}),p?h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:p,children:Lf(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(Zj,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):h.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:L,onDoubleClick:j,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(Sb,{})})]})}const mN=B.memo(fN),gN={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a Whisper model that loads the first time you record (a progress bar shows the download). A press-to-record hotkey starts and stops the mic; what you say is typed into the active terminal, and an auto-submit timer fires it for you a moment after you stop speaking. A one-time mic check confirms your microphone works.",sections:[{title:"Recording controls",items:[{term:"Hotkey",body:"Press your mic hotkey to record. The default is Ctrl+Shift+Space (Cmd+Option+V on Mac); the panel shows the live binding. Two behaviours: 'Hold to talk' records only while the key is held (push-to-talk), 'Tap on/off' starts on one press and stops on the next. The default is hold-to-talk; switch with the radio buttons."},{term:"Mic button & device",body:"The mic button toggles recording with the mouse. The device picker chooses which microphone to use, and a live level meter shows that audio is coming through."},{term:"Run mic check",body:"Opens a short wizard that confirms your mic is picking up sound. It runs automatically once after a settings-format change, or any time you click 'Run mic check'."}]},{title:"Speaking & hearing back",items:[{term:"Live transcript",body:"While recording, a pulsing red dot and the latest transcribed words appear so you can see what was heard. Errors (e.g. mic blocked) surface inline in red."},{term:"TTS (read replies aloud)",body:"The speaker button toggles text-to-speech. When on, Claude's replies are read back to you out loud."}]}],tips:["The speech model downloads on first use only, then stays cached — later recordings start instantly.","Hold-to-talk is best for quick interjections; Tap on/off is better for longer dictation where you don't want to hold a key."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},"tag-library":{headline:"Tag Library — the Epic intent-tag taxonomy",intro:"Every Epic carries an initial intent tag — feature, bug, discussion, or build — chosen at creation. The tag sets how eagerly /develop should fire inside that Epic's session: feature/bug/build treat PRD decomposition as the expected next step, discussion keeps /develop available but never assumed until whether-to-build is settled.",sections:[{title:"What it shows",items:[{term:"Tag",body:"The four intent tags an Epic can be created with."},{term:"/develop eagerness",body:"Whether PRD decomposition is the expected default for that tag, or available-but-not-assumed."},{term:"Agents carrying this tag",body:"Which Agent Library personas have this tag in their `tags:` frontmatter — the same relationship Agent Library edits from the agent side. Assign or remove an agent here to update that persona's file directly."}]}],tips:["Home face only — the taxonomy is machine-wide, not scoped to one project.","The tag taxonomy itself is read-only here — change an existing Epic's tag from its queue row menu, not from this page. The agent↔tag assignment, though, is editable from either Tag Library or Agent Library."]},"bilko-host":{headline:"Host on Bilko.run — publish this project's Marketing page",intro:"Turns the Marketing lens of this project's already-generated Project Pages into a live static-path listing on bilko.run, using the bilko-host MCP's existing gated publish pipeline (manifest/budget/golden/a11y/audit checks) — never a second, competing hosting mechanism.",sections:[{title:"What it shows",items:[{term:"Status",body:"not-published → bundle-ready → publishing → published/publish-failed, mirroring the on-disk publish-state.json a bilko-host-publisher Epic writes."},{term:"Slug",body:"The bilko.run/projects/<slug>/ path this project would publish to — defaults from package.json's name."},{term:"Bundle",body:"Size, build time, and git sha of the dist/ bundle Prepare Bundle last wrote."}]}],tips:["Project face only — publishing is always scoped to the active project's tab.",`Requires a generated Marketing Project Page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}},Aw="sm.learningPanel.collapsed";function I0(){try{const i=localStorage.getItem(Aw);if(i===null)return!1;if(i.startsWith("{")){const e=JSON.parse(i);return!!(e&&typeof e=="object"&&Object.values(e).some(Boolean))}return i==="1"||i==="true"}catch{return!1}}function P0(i){try{localStorage.setItem(Aw,i?"1":"0")}catch{}}function vN({active:i}){const[e,t]=B.useState(()=>!I0()),n=B.useRef(null),r=B.useCallback(()=>{t(a=>{const d=!a;return P0(!d),d})},[]);B.useEffect(()=>{const a=d=>{d.key===Aw&&t(!I0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),B.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),P0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=B.useRef(!1);B.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=gN[i];return p?h.jsxs("span",{ref:n,className:"relative inline-block",children:[h.jsx("button",{type:"button",onClick:r,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":e,title:e?"Close learning panel":"What is this?",children:"Learn"}),e&&h.jsxs("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:[h.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.intro}),p.sections.map(a=>h.jsxs("div",{className:"mb-3 last:mb-0",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:a.title}),h.jsx("ul",{className:"space-y-1",children:a.items.map((d,f)=>h.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[d.term&&h.jsx("span",{className:"text-fg font-medium",children:d.term}),d.term&&" — ",h.jsx("span",{children:d.body})]},f))})]},a.title)),p.tips&&p.tips.length>0&&h.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),h.jsx("ul",{className:"space-y-1",children:p.tips.map((a,d)=>h.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",a]},d))})]})]})]}):null}function _N({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&h.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[h.jsxs("div",{className:"max-w-[820px]",children:[i&&h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&h.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&h.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&h.jsx(vN,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const bN=B.lazy(()=>qn(()=>import("./Skills-D_qAqxZ_.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),wN=B.lazy(()=>qn(()=>import("./History-C6JRuqfT.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),yN=B.lazy(()=>qn(()=>import("./Scheduler-Bf_6MdJo.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),xN=B.lazy(()=>qn(()=>import("./Settings-Djd8OoBA.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),SN=B.lazy(()=>qn(()=>import("./Permissions-BfC2-HN4.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),CN=B.lazy(()=>qn(()=>import("./SystemPrompt-DbHFLQV3.js"),__vite__mapDeps([19,4,7,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),kN=B.lazy(()=>qn(()=>import("./Memory-DSBYQdJR.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),EN=B.lazy(()=>qn(()=>import("./Plugins-BKi40jT5.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),TN=B.lazy(()=>qn(()=>import("./McpServers-BzMv-_84.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),DN=B.lazy(()=>qn(()=>import("./Hooks-BafPy9mB.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),AN=B.lazy(()=>qn(()=>import("./AgentLibrary-zS3jw_1e.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),$N=B.lazy(()=>qn(()=>import("./TagLibrary-C2y91BT0.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),IN=B.lazy(()=>qn(()=>import("./HostBilko-BZwhQOFt.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),PN=B.lazy(()=>qn(()=>import("./DataModel-Cy_vxTpi.js"),__vite__mapDeps([27,4,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),RN=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function vr({children:i}){return h.jsx(B.Suspense,{fallback:RN,children:i})}const jN={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"Every session, ever",intro:"Resumable transcripts across every project you have opened. Pick a row to reattach Claude to the same conversation."},plugins:{title:"Plugins",intro:"Extensions for Claude Code. Install, enable, or remove plugins per-scope."},mcp:{title:"MCP Servers",intro:"External tools and integrations the agent can call. Add a new server or test an existing connection."},hooks:{title:"Hooks",intro:"Run scripts on session events. Tail logs, format files, post to Slack — anything that responds to a shell command."},memory:{title:"Memory",intro:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},"bilko-host":{title:"Host on Bilko.run",intro:"Publish this project's generated Marketing page to bilko.run as a static-path listing, via the bilko-host MCP's gated publish pipeline."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},NN=()=>{},R0=new Map;function MN(i,e){const t=R0.get(i);if(t&&t.ctx===e)return t.node;const n=ON(i,e);return R0.set(i,{ctx:e,node:n}),n}function ON(i,e){switch(i){case"overview":return h.jsx(o$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(aI,{});case"editor":return h.jsx(Sb,{});case"projects":return h.jsx(mN,{})}const t=jN[i],n=(()=>{switch(i){case"skills":return h.jsx(vr,{children:h.jsx(bN,{})});case"history":return h.jsx(vr,{children:h.jsx(wN,{})});case"scheduler":return h.jsx(vr,{children:h.jsx(yN,{navigate:e.onNavigate})});case"plugins":return h.jsx(vr,{children:h.jsx(EN,{})});case"mcp":return h.jsx(vr,{children:h.jsx(TN,{})});case"hooks":return h.jsx(vr,{children:h.jsx(DN,{})});case"memory":return h.jsx(vr,{children:h.jsx(kN,{})});case"system-prompt":return h.jsx(vr,{children:h.jsx(CN,{})});case"permissions":return h.jsx(vr,{children:h.jsx(SN,{})});case"settings":return h.jsx(vr,{children:h.jsx(xN,{})});case"agent-library":return h.jsx(vr,{children:h.jsx(AN,{})});case"tag-library":return h.jsx(vr,{children:h.jsx($N,{})});case"bilko-host":return h.jsx(vr,{children:h.jsx(IN,{})});case"data-model":return h.jsx(vr,{children:h.jsx(PN,{})});case"voice":return h.jsx(zj,{open:!0,onClose:NN,variant:"page"});default:return null}})();if(!n)return null;const r=LE[i];return t&&r?h.jsx(_N,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var b_={exports:{}},j0;function LN(){return j0||(j0=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(y,x,A,P){var N,L=arguments.length,j=L<3?x:P===null?P=Object.getOwnPropertyDescriptor(x,A):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(y,x,A,P);else for(var H=y.length-1;H>=0;H--)(N=y[H])&&(j=(L<3?N(j):L>3?N(x,A,j):N(x,A))||j);return L>3&&j&&Object.defineProperty(x,A,j),j},g=this&&this.__param||function(y,x){return function(A,P){x(A,P,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),w=d(9924),D=d(844),k=d(4725),E=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(y,x,A,P){super(),this._terminal=y,this._coreBrowserService=A,this._renderService=P,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3026
3026
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,b.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,D.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(y){for(let x=0;x<y;x++)this._handleChar(" ")}_handleChar(y){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==y&&(this._charsToAnnounce+=y):this._charsToAnnounce+=y,y===`
|
|
3027
3027
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(y){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(y)||this._charsToConsume.push(y)}_refreshRows(y,x){this._liveRegionDebouncer.refresh(y,x,this._terminal.rows)}_renderRows(y,x){const A=this._terminal.buffer,P=A.lines.length.toString();for(let N=y;N<=x;N++){const L=A.lines.get(A.ydisp+N),j=[],H=(L==null?void 0:L.translateToString(!0,void 0,void 0,j))||"",W=(A.ydisp+N+1).toString(),re=this._rowElements[N];re&&(H.length===0?(re.innerText=" ",this._rowColumns.set(re,[0,1])):(re.textContent=H,this._rowColumns.set(re,j)),re.setAttribute("aria-posinset",W),re.setAttribute("aria-setsize",P))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(y,x){const A=y.target,P=this._rowElements[x===0?1:this._rowElements.length-2];if(A.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||y.relatedTarget!==P)return;let N,L;if(x===0?(N=A,L=this._rowElements.pop(),this._rowContainer.removeChild(L)):(N=this._rowElements.shift(),L=A,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),L.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const j=this._createAccessibilityTreeNode();this._rowElements.unshift(j),this._rowContainer.insertAdjacentElement("afterbegin",j)}else{const j=this._createAccessibilityTreeNode();this._rowElements.push(j),this._rowContainer.appendChild(j)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),y.preventDefault(),y.stopImmediatePropagation()}_handleSelectionChange(){var H;if(this._rowElements.length===0)return;const y=document.getSelection();if(!y)return;if(y.isCollapsed)return void(this._rowContainer.contains(y.anchorNode)&&this._terminal.clearSelection());if(!y.anchorNode||!y.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:y.anchorNode,offset:y.anchorOffset},A={node:y.focusNode,offset:y.focusOffset};if((x.node.compareDocumentPosition(A.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===A.node&&x.offset>A.offset)&&([x,A]=[A,x]),x.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(x={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(x.node))return;const P=this._rowElements.slice(-1)[0];if(A.node.compareDocumentPosition(P)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(A={node:P,offset:((H=P.textContent)==null?void 0:H.length)??0}),!this._rowContainer.contains(A.node))return;const N=({node:W,offset:re})=>{const de=W instanceof Text?W.parentNode:W;let Z=parseInt(de==null?void 0:de.getAttribute("aria-posinset"),10)-1;if(isNaN(Z))return console.warn("row is invalid. Race condition?"),null;const me=this._rowColumns.get(de);if(!me)return console.warn("columns is null. Race condition?"),null;let te=re<me.length?me[re]:me.slice(-1)[0]+1;return te>=this._terminal.cols&&(++Z,te=0),{row:Z,column:te}},L=N(x),j=N(A);if(L&&j){if(L.row>j.row||L.row===j.row&&L.column>=j.column)throw new Error("invalid range");this._terminal.select(L.column,L.row,(j.row-L.row)*this._terminal.cols-L.column+j.column)}}_handleResize(y){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let x=this._rowContainer.children.length;x<this._terminal.rows;x++)this._rowElements[x]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[x]);for(;this._rowElements.length>y;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const y=this._coreBrowserService.mainDocument.createElement("div");return y.setAttribute("role","listitem"),y.tabIndex=-1,this._refreshRowDimensions(y),y}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let y=0;y<this._terminal.rows;y++)this._refreshRowDimensions(this._rowElements[y])}}_refreshRowDimensions(y){y.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=C=f([g(1,E.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],C)},3614:(p,a)=>{function d(w){return w.replace(/\r?\n/g,"\r")}function f(w,D){return D?"\x1B[200~"+w+"\x1B[201~":w}function g(w,D,k,E){w=f(w=d(w),k.decPrivateModes.bracketedPasteMode&&E.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(w,!0),D.value=""}function m(w,D,k){const E=k.getBoundingClientRect(),b=w.clientX-E.left-10,C=w.clientY-E.top-10;D.style.width="20px",D.style.height="20px",D.style.left=`${b}px`,D.style.top=`${C}px`,D.style.zIndex="1000",D.focus()}Object.defineProperty(a,"__esModule",{value:!0}),a.rightClickHandler=a.moveTextAreaUnderMouseCursor=a.paste=a.handlePasteEvent=a.copyHandler=a.bracketTextForPaste=a.prepareTextForTerminal=void 0,a.prepareTextForTerminal=d,a.bracketTextForPaste=f,a.copyHandler=function(w,D){w.clipboardData&&w.clipboardData.setData("text/plain",D.selectionText),w.preventDefault()},a.handlePasteEvent=function(w,D,k,E){w.stopPropagation(),w.clipboardData&&g(w.clipboardData.getData("text/plain"),D,k,E)},a.paste=g,a.moveTextAreaUnderMouseCursor=m,a.rightClickHandler=function(w,D,k,E,b){m(w,D,k),b&&E.rightClickSelect(w),D.value=E.selectionText,D.select()}},7239:(p,a,d)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorContrastCache=void 0;const f=d(1505);a.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(g,m,w){this._css.set(g,m,w)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,w){this._color.set(g,m,w)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(d,f,g,m){d.addEventListener(f,g,m);let w=!1;return{dispose:()=>{w||(w=!0,d.removeEventListener(f,g,m))}}}},3551:function(p,a,d){var f=this&&this.__decorate||function(C,y,x,A){var P,N=arguments.length,L=N<3?y:A===null?A=Object.getOwnPropertyDescriptor(y,x):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(C,y,x,A);else for(var j=C.length-1;j>=0;j--)(P=C[j])&&(L=(N<3?P(L):N>3?P(y,x,L):P(y,x))||L);return N>3&&L&&Object.defineProperty(y,x,L),L},g=this&&this.__param||function(C,y){return function(x,A){y(x,A,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const m=d(3656),w=d(8460),D=d(844),k=d(2585),E=d(4725);let b=a.Linkifier=class extends D.Disposable{get currentLink(){return this._currentLink}constructor(C,y,x,A,P){super(),this._element=C,this._mouseService=y,this._renderService=x,this._bufferService=A,this._linkProviderService=P,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new w.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new w.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,D.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,D.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(C){this._lastMouseEvent=C;const y=this._positionFromMouseEvent(C,this._element,this._mouseService);if(!y)return;this._isMouseOut=!1;const x=C.composedPath();for(let A=0;A<x.length;A++){const P=x[A];if(P.classList.contains("xterm"))break;if(P.classList.contains("xterm-hover"))return}this._lastBufferCell&&y.x===this._lastBufferCell.x&&y.y===this._lastBufferCell.y||(this._handleHover(y),this._lastBufferCell=y)}_handleHover(C){if(this._activeLine!==C.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(C,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,C)||(this._clearCurrentLink(),this._askForLink(C,!0))}_askForLink(C,y){var A,P;this._activeProviderReplies&&y||((A=this._activeProviderReplies)==null||A.forEach((N=>{N==null||N.forEach((L=>{L.link.dispose&&L.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=C.y);let x=!1;for(const[N,L]of this._linkProviderService.linkProviders.entries())y?(P=this._activeProviderReplies)!=null&&P.get(N)&&(x=this._checkLinkProviderResult(N,C,x)):L.provideLinks(C.y,(j=>{var W,re;if(this._isMouseOut)return;const H=j==null?void 0:j.map((de=>({link:de})));(W=this._activeProviderReplies)==null||W.set(N,H),x=this._checkLinkProviderResult(N,C,x),((re=this._activeProviderReplies)==null?void 0:re.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(C.y,this._activeProviderReplies)}))}_removeIntersectingLinks(C,y){const x=new Set;for(let A=0;A<y.size;A++){const P=y.get(A);if(P)for(let N=0;N<P.length;N++){const L=P[N],j=L.link.range.start.y<C?0:L.link.range.start.x,H=L.link.range.end.y>C?this._bufferService.cols:L.link.range.end.x;for(let W=j;W<=H;W++){if(x.has(W)){P.splice(N--,1);break}x.add(W)}}}}_checkLinkProviderResult(C,y,x){var N;if(!this._activeProviderReplies)return x;const A=this._activeProviderReplies.get(C);let P=!1;for(let L=0;L<C;L++)this._activeProviderReplies.has(L)&&!this._activeProviderReplies.get(L)||(P=!0);if(!P&&A){const L=A.find((j=>this._linkAtPosition(j.link,y)));L&&(x=!0,this._handleNewLink(L))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let L=0;L<this._activeProviderReplies.size;L++){const j=(N=this._activeProviderReplies.get(L))==null?void 0:N.find((H=>this._linkAtPosition(H.link,y)));if(j){x=!0,this._handleNewLink(j);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(C){if(!this._currentLink)return;const y=this._positionFromMouseEvent(C,this._element,this._mouseService);y&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,y)&&this._currentLink.link.activate(C,this._currentLink.link.text)}_clearCurrentLink(C,y){this._currentLink&&this._lastMouseEvent&&(!C||!y||this._currentLink.link.range.start.y>=C&&this._currentLink.link.range.end.y<=y)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,D.disposeArray)(this._linkCacheDisposables))}_handleNewLink(C){if(!this._lastMouseEvent)return;const y=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);y&&this._linkAtPosition(C.link,y)&&(this._currentLink=C,this._currentLink.state={decorations:{underline:C.link.decorations===void 0||C.link.decorations.underline,pointerCursor:C.link.decorations===void 0||C.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,C.link,this._lastMouseEvent),C.link.decorations={},Object.defineProperties(C.link.decorations,{pointerCursor:{get:()=>{var x,A;return(A=(x=this._currentLink)==null?void 0:x.state)==null?void 0:A.decorations.pointerCursor},set:x=>{var A;(A=this._currentLink)!=null&&A.state&&this._currentLink.state.decorations.pointerCursor!==x&&(this._currentLink.state.decorations.pointerCursor=x,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",x))}},underline:{get:()=>{var x,A;return(A=(x=this._currentLink)==null?void 0:x.state)==null?void 0:A.decorations.underline},set:x=>{var A,P,N;(A=this._currentLink)!=null&&A.state&&((N=(P=this._currentLink)==null?void 0:P.state)==null?void 0:N.decorations.underline)!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(C.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const A=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,P=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=A&&this._currentLink.link.range.end.y<=P&&(this._clearCurrentLink(A,P),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(C,y,x){var A;(A=this._currentLink)!=null&&A.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!0),this._currentLink.state.decorations.pointerCursor&&C.classList.add("xterm-cursor-pointer")),y.hover&&y.hover(x,y.text)}_fireUnderlineEvent(C,y){const x=C.range,A=this._bufferService.buffer.ydisp,P=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-A-1,x.end.x,x.end.y-A-1,void 0);(y?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(P)}_linkLeave(C,y,x){var A;(A=this._currentLink)!=null&&A.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!1),this._currentLink.state.decorations.pointerCursor&&C.classList.remove("xterm-cursor-pointer")),y.leave&&y.leave(x,y.text)}_linkAtPosition(C,y){const x=C.range.start.y*this._bufferService.cols+C.range.start.x,A=C.range.end.y*this._bufferService.cols+C.range.end.x,P=y.y*this._bufferService.cols+y.x;return x<=P&&P<=A}_positionFromMouseEvent(C,y,x){const A=x.getCoords(C,y,this._bufferService.cols,this._bufferService.rows);if(A)return{x:A[0],y:A[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(C,y,x,A,P){return{x1:C,y1:y,x2:x,y2:A,cols:this._bufferService.cols,fg:P}}};a.Linkifier=b=f([g(1,E.IMouseService),g(2,E.IRenderService),g(3,k.IBufferService),g(4,E.ILinkProviderService)],b)},9042:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(p,a,d){var f=this&&this.__decorate||function(E,b,C,y){var x,A=arguments.length,P=A<3?b:y===null?y=Object.getOwnPropertyDescriptor(b,C):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(E,b,C,y);else for(var N=E.length-1;N>=0;N--)(x=E[N])&&(P=(A<3?x(P):A>3?x(b,C,P):x(b,C))||P);return A>3&&P&&Object.defineProperty(b,C,P),P},g=this&&this.__param||function(E,b){return function(C,y){b(C,y,E)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const m=d(511),w=d(2585);let D=a.OscLinkProvider=class{constructor(E,b,C){this._bufferService=E,this._optionsService=b,this._oscLinkService=C}provideLinks(E,b){var H;const C=this._bufferService.buffer.lines.get(E-1);if(!C)return void b(void 0);const y=[],x=this._optionsService.rawOptions.linkHandler,A=new m.CellData,P=C.getTrimmedLength();let N=-1,L=-1,j=!1;for(let W=0;W<P;W++)if(L!==-1||C.hasContent(W)){if(C.loadCell(W,A),A.hasExtendedAttrs()&&A.extended.urlId){if(L===-1){L=W,N=A.extended.urlId;continue}j=A.extended.urlId!==N}else L!==-1&&(j=!0);if(j||L!==-1&&W===P-1){const re=(H=this._oscLinkService.getLinkData(N))==null?void 0:H.uri;if(re){const de={start:{x:L+1,y:E},end:{x:W+(j||W!==P-1?0:1),y:E}};let Z=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const me=new URL(re);["http:","https:"].includes(me.protocol)||(Z=!0)}catch{Z=!0}Z||y.push({text:re,range:de,activate:(me,te)=>x?x.activate(me,te,de):k(0,te),hover:(me,te)=>{var pe;return(pe=x==null?void 0:x.hover)==null?void 0:pe.call(x,me,te,de)},leave:(me,te)=>{var pe;return(pe=x==null?void 0:x.leave)==null?void 0:pe.call(x,me,te,de)}})}j=!1,A.hasExtendedAttrs()&&A.extended.urlId?(L=W,N=A.extended.urlId):(L=-1,N=-1)}}b(y)}};function k(E,b){if(confirm(`Do you want to navigate to ${b}?
|
|
3028
3028
|
|