claude-code-session-manager 0.69.0 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/assets/AgentLibrary-ClxN8f2w.js +3 -0
  2. package/dist/assets/{History-CiqbZNCW.js → History-EDAc-ZMb.js} +2 -2
  3. package/dist/assets/{Hooks-1LHEEKhK.js → Hooks-aRH7nMJd.js} +3 -3
  4. package/dist/assets/HostBilko-SlCefAAH.js +1 -0
  5. package/dist/assets/{Library-BXt58QDN.js → Library-BCIBTN21.js} +1 -1
  6. package/dist/assets/{ListDetail-V5JV-SVN.js → ListDetail-CJZGbxwd.js} +1 -1
  7. package/dist/assets/{MarkdownEditor-BYUdiq8p.js → MarkdownEditor-Due9TO9x.js} +1 -1
  8. package/dist/assets/{McpServers-C3b18FY5.js → McpServers-BYKw9iDf.js} +2 -2
  9. package/dist/assets/{Memory-MyToD3ri.js → Memory-CIqDISVo.js} +4 -4
  10. package/dist/assets/{Panel-D1z0ZvX_.js → Panel-C6JXCGRu.js} +1 -1
  11. package/dist/assets/{Permissions-BDRMk8Uu.js → Permissions-C1gnBLDo.js} +3 -3
  12. package/dist/assets/Plugins-BysI_znb.js +2 -0
  13. package/dist/assets/ProvenanceBadge-BxphD65P.js +1 -0
  14. package/dist/assets/{SaveBar-DOJnzj3n.js → SaveBar-4DXRUXpo.js} +1 -1
  15. package/dist/assets/{Scheduler-LdawPR1e.js → Scheduler-BmbVLNFH.js} +6 -6
  16. package/dist/assets/{ScopeSwitcher-Cl3g7YOM.js → ScopeSwitcher-Dlbq0DLs.js} +1 -1
  17. package/dist/assets/Settings-BZtTqlKA.js +3 -0
  18. package/dist/assets/{SkillReferenceGraph-B_KqYC6R.js → SkillReferenceGraph-CQ-0ZVDl.js} +1 -1
  19. package/dist/assets/Skills-BGBKWxNl.js +3 -0
  20. package/dist/assets/SystemPrompt-Bc715ZOf.js +1 -0
  21. package/dist/assets/TagLibrary-CAnB2jV8.js +1 -0
  22. package/dist/assets/{TiptapBody-A93HQtTH.js → TiptapBody-CxLrfTQ5.js} +1 -1
  23. package/dist/assets/{Toggle-CoFtvmoX.js → Toggle-CLcPpQX-.js} +1 -1
  24. package/dist/assets/{index-B77KHr7n.css → index-CFtzZuq7.css} +1 -1
  25. package/dist/assets/{index-C-iwyX_s.js → index-DVVeB50r.js} +5 -5
  26. package/dist/assets/{settingsSchema-DHDH8NJR.js → settingsSchema-DS2QMkuB.js} +1 -1
  27. package/dist/index.html +2 -2
  28. package/package.json +1 -1
  29. package/dist/assets/AgentLibrary-DngWZmn2.js +0 -3
  30. package/dist/assets/HostBilko-DruBVVx_.js +0 -1
  31. package/dist/assets/Plugins-Bd1wIgVW.js +0 -2
  32. package/dist/assets/ProvenanceBadge-BIX0JW7m.js +0 -1
  33. package/dist/assets/Settings-7jHzkgfK.js +0 -3
  34. package/dist/assets/Skills-H8pCR_6D.js +0 -3
  35. package/dist/assets/SystemPrompt-fCD2rD2R.js +0 -1
  36. package/dist/assets/TagLibrary-erEiP4bj.js +0 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-A93HQtTH.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-H8pCR_6D.js","./Panel-D1z0ZvX_.js","./ListDetail-V5JV-SVN.js","./MarkdownEditor-BYUdiq8p.js","./SaveBar-DOJnzj3n.js","./ScopeSwitcher-Cl3g7YOM.js","./Toggle-CoFtvmoX.js","./ProvenanceBadge-BIX0JW7m.js","./Library-BXt58QDN.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-CiqbZNCW.js","./Scheduler-LdawPR1e.js","./Settings-7jHzkgfK.js","./settingsSchema-DHDH8NJR.js","./Permissions-BDRMk8Uu.js","./SystemPrompt-fCD2rD2R.js","./Memory-MyToD3ri.js","./Plugins-Bd1wIgVW.js","./McpServers-C3b18FY5.js","./Hooks-1LHEEKhK.js","./AgentLibrary-DngWZmn2.js","./TagLibrary-erEiP4bj.js","./HostBilko-DruBVVx_.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-CxLrfTQ5.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-BGBKWxNl.js","./Panel-C6JXCGRu.js","./ListDetail-CJZGbxwd.js","./MarkdownEditor-Due9TO9x.js","./SaveBar-4DXRUXpo.js","./ScopeSwitcher-Dlbq0DLs.js","./Toggle-CLcPpQX-.js","./ProvenanceBadge-BxphD65P.js","./Library-BCIBTN21.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-EDAc-ZMb.js","./Scheduler-BmbVLNFH.js","./Settings-BZtTqlKA.js","./settingsSchema-DS2QMkuB.js","./Permissions-C1gnBLDo.js","./SystemPrompt-Bc715ZOf.js","./Memory-CIqDISVo.js","./Plugins-BysI_znb.js","./McpServers-BYKw9iDf.js","./Hooks-aRH7nMJd.js","./AgentLibrary-ClxN8f2w.js","./TagLibrary-CAnB2jV8.js","./HostBilko-SlCefAAH.js"])))=>i.map(i=>d[i]);
2
2
  var _k=Object.defineProperty;var bk=(i,e,t)=>e in i?_k(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Bi=(i,e,t)=>bk(i,typeof e!="symbol"?e+"":e,t);import{_ as os}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 jb(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var zv={exports:{}},Vp={},Bv={exports:{}},pi={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -2907,7 +2907,7 @@ ${I}`,M=g.createShaderModule({code:R,label:s.name});ni("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 $y;function FE(){return $y||($y=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof eo<"u"?eo:typeof Proxy<"u"?new Proxy(Y,{get:(se,he)=>(typeof eo<"u"?eo:se)[he]}):Y)(function(Y){if(typeof eo<"u")return eo.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 he in se)n(Y,he,{get:se[he],enumerable:!0})},v=(Y,se,he,Te)=>{if(se&&typeof se=="object"||typeof se=="function")for(let xe of l(se))!p.call(Y,xe)&&xe!==he&&n(Y,xe,{get:()=>se[xe],enumerable:!(Te=r(se,xe))||Te.enumerable});return Y},m=Y=>v(n({},"__esModule",{value:!0}),Y),y,D,E,T,b,C=d(()=>{y=new Map,D=[],E=(Y,se,he)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Te=y.get(Y);if(Te===void 0)y.set(Y,{backend:se,priority:he});else{if(Te.priority>he)return;if(Te.priority===he&&Te.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${he}`)}if(he>=0){let xe=D.indexOf(Y);xe!==-1&&D.splice(xe,1);for(let Oe=0;Oe<D.length;Oe++)if(y.get(D[Oe]).priority<=he){D.splice(Oe,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},T=async Y=>{let se=y.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let he=!!se.initPromise;try{return he||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Te){return he||(se.error=`${Te}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],he=se.map(Le=>typeof Le=="string"?Le:Le.name),Te=he.length===0?D:he,xe,Oe=[],$e=new Set;for(let Le of Te){let tt=await T(Le);typeof tt=="string"?Oe.push({name:Le,err:tt}):(xe||(xe=tt),xe===tt&&$e.add(Le))}if(!xe)throw new Error(`no available backend found. ERR: ${Oe.map(Le=>`[${Le.name}] ${Le.err}`).join(", ")}`);for(let{name:Le,err:tt}of Oe)he.includes(Le)&&console.warn(`removing requested execution provider "${Le}" from session options because it is not available: ${tt}`);let Ae=se.filter(Le=>$e.has(typeof Le=="string"?Le:Le.name));return[xe,new Proxy(Y,{get:(Le,tt)=>tt==="executionProviders"?Ae:Reflect.get(Le,tt)})]}}),w=d(()=>{C()}),x,$=d(()=>{x="1.26.0"}),P,N,L=d(()=>{$(),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}),U,oe,de=d(()=>{U=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=Y.dims[3],he.height=Y.dims[2];let Te=he.getContext("2d");if(Te!=null){let xe,Oe;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2]);let $e=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Le,tt;Ae===void 0||Ae.mean===void 0?Le=[255,255,255,255]:typeof Ae.mean=="number"?Le=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Le=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Le[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?tt=[0,0,0,0]:typeof Ae.bias=="number"?tt=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(tt=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(tt[3]=Ae.bias[3]));let rt=Oe*xe,it=0,qe=rt,It=rt*2,Ne=-1;$e==="RGBA"?(it=0,qe=rt,It=rt*2,Ne=rt*3):$e==="RGB"?(it=0,qe=rt,It=rt*2):$e==="RBG"&&(it=0,It=rt,qe=rt*2);for(let dt=0;dt<Oe;dt++)for(let Ci=0;Ci<xe;Ci++){let Zt=(Y.data[it++]-tt[0])*Le[0],Qt=(Y.data[qe++]-tt[1])*Le[1],ki=(Y.data[It++]-tt[2])*Le[2],Ot=Ne===-1?255:(Y.data[Ne++]-tt[3])*Le[3];Te.fillStyle="rgba("+Zt+","+Qt+","+ki+","+Ot+")",Te.fillRect(Ci,dt,1,1)}if("toDataURL"in he)return he.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},oe=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(he!=null){let xe,Oe,$e;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[1],$e=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2],$e=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Le=se==null?void 0:se.norm,tt,rt;Le===void 0||Le.mean===void 0?tt=[255,255,255,255]:typeof Le.mean=="number"?tt=[Le.mean,Le.mean,Le.mean,Le.mean]:(tt=[Le.mean[0],Le.mean[1],Le.mean[2],255],Le.mean[3]!==void 0&&(tt[3]=Le.mean[3])),Le===void 0||Le.bias===void 0?rt=[0,0,0,0]:typeof Le.bias=="number"?rt=[Le.bias,Le.bias,Le.bias,Le.bias]:(rt=[Le.bias[0],Le.bias[1],Le.bias[2],0],Le.bias[3]!==void 0&&(rt[3]=Le.bias[3]));let it=Oe*xe;if(se!==void 0&&(se.format!==void 0&&$e===4&&se.format!=="RGBA"||$e===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let qe=4,It=0,Ne=1,dt=2,Ci=3,Zt=0,Qt=it,ki=it*2,Ot=-1;Ae==="RGBA"?(Zt=0,Qt=it,ki=it*2,Ot=it*3):Ae==="RGB"?(Zt=0,Qt=it,ki=it*2):Ae==="RBG"&&(Zt=0,ki=it,Qt=it*2),Te=he.createImageData(xe,Oe);for(let Ri=0;Ri<Oe*xe;It+=qe,Ne+=qe,dt+=qe,Ci+=qe,Ri++)Te.data[It]=(Y.data[Zt++]-rt[0])*tt[0],Te.data[Ne]=(Y.data[Qt++]-rt[1])*tt[1],Te.data[dt]=(Y.data[ki++]-rt[2])*tt[2],Te.data[Ci]=Ot===-1?255:(Y.data[Ot++]-rt[3])*tt[3]}else throw new Error("Can not access image data");return Te}}),Z,me,ie,ue,Ce,Ee,W=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:he,width:Te}=se,xe=se.norm??{mean:255,bias:0},Oe,$e;typeof xe.mean=="number"?Oe=[xe.mean,xe.mean,xe.mean,xe.mean]:Oe=[xe.mean[0],xe.mean[1],xe.mean[2],xe.mean[3]??255],typeof xe.bias=="number"?$e=[xe.bias,xe.bias,xe.bias,xe.bias]:$e=[xe.bias[0],xe.bias[1],xe.bias[2],xe.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Le=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",tt=he*Te,rt=Le==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,qe=0,It=1,Ne=2,dt=3,Ci=0,Zt=tt,Qt=tt*2,ki=-1;Ae==="RGB"&&(it=3,qe=0,It=1,Ne=2,dt=-1),Le==="RGBA"?ki=tt*3:Le==="RBG"?(Ci=0,Qt=tt,Zt=tt*2):Le==="BGR"&&(Qt=0,Zt=tt,Ci=tt*2);for(let Ot=0;Ot<tt;Ot++,qe+=it,Ne+=it,It+=it,dt+=it)rt[Ci++]=(Y[qe]+$e[0])/Oe[0],rt[Zt++]=(Y[It]+$e[1])/Oe[1],rt[Qt++]=(Y[Ne]+$e[2])/Oe[2],ki!==-1&&dt!==-1&&(rt[ki++]=(Y[dt]+$e[3])/Oe[3]);return Le==="RGBA"?new X("float32",rt,[1,4,he,Te]):new X("float32",rt,[1,3,he,Te])},me=async(Y,se)=>{let he=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,xe=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Oe=typeof Y=="string",$e,Ae=se??{},Le=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(qe=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=qe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It;it.drawImage(Y,0,0),$e=it.getImageData(0,0,It,qe).data}else throw new Error("Can not access image data")}else if(Te){let rt,it;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,it=se.resizedWidth):(rt=Y.height,it=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=it,se!==void 0){let qe=Le();qe.width=it,qe.height=rt;let It=tt(qe);if(It!=null)It.putImageData(Y,0,0),$e=It.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else $e=Y.data}else if(xe){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;return it.drawImage(Y,0,0,It,qe),$e=it.getImageData(0,0,It,qe).data,Ae.height=qe,Ae.width=It,Z($e,Ae)}else throw new Error("Can not access image data")}else{if(Oe)return new Promise((rt,it)=>{let qe=Le(),It=tt(qe);if(!Y||!It)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=Y,Ne.onload=()=>{qe.width=Ne.width,qe.height=Ne.height,It.drawImage(Ne,0,0,qe.width,qe.height);let dt=It.getImageData(0,0,qe.width,qe.height);Ae.height=qe.height,Ae.width=qe.width,rt(Z(dt.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},ie=(Y,se)=>{let{width:he,height:Te,download:xe,dispose:Oe}=se,$e=[1,Te,he,4];return new X({location:"texture",type:"float32",texture:Y,dims:$e,download:xe,dispose:Oe})},ue=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"gpu-buffer",type:he??"float32",gpuBuffer:Y,dims:Te,download:xe,dispose:Oe})},Ce=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"ml-tensor",type:he??"float32",mlTensor:Y,dims:Te,download:xe,dispose:Oe})},Ee=(Y,se,he)=>new X({location:"cpu-pinned",type:Y,data:se,dims:he??[se.length]})}),te,K,re,ve,_e=d(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),re=!1,ve=()=>{if(!re){re=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,Te=typeof he<"u"&&he.from;Y&&(te.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),se&&(te.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),Te?(te.set("float16",he),K.set(he,"float16")):te.set("float16",Uint16Array)}}}),Me,et,we=d(()=>{Ie(),Me=Y=>{let se=1;for(let he=0;he<Y.length;he++){let Te=Y[he];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${he}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${Te}`);se*=Te}return se},et=(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(),W(),_e(),we(),X=class{constructor(Y,se,he){ve();let Te,xe;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,xe=Y.dims,Y.location){case"cpu-pinned":{let $e=te.get(Te);if(!$e)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(Y.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=Y.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" 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 $e,Ae;if(typeof Y=="string")if(Te=Y,Ae=he,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");$e=se}else{let Le=te.get(Y);if(Le===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Le===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Le.name} as data.`);Y==="uint64"||Y==="int64"?$e=Le.from(se,BigInt):$e=Le.from(se)}else if(se instanceof Le)$e=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")$e=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Le!==Uint16Array)$e=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Le}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Le=typeof Y[0];if(Le==="string")Te="string",$e=Y;else if(Le==="boolean")Te="bool",$e=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Le}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",$e=Uint8Array.from(Y);else{let Le=K.get(Y.constructor);if(Le===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Le,$e=Y}if(Ae===void 0)Ae=[$e.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");xe=Ae,this.cpuData=$e,this.dataLocation="cpu"}let Oe=Me(xe);if(this.cpuData&&Oe!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Oe/2)===this.cpuData.length))throw new Error(`Tensor's size(${Oe}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=xe,this.size=Oe}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return ie(Y,se)}static fromGpuBuffer(Y,se){return ue(Y,se)}static fromMLTensor(Y,se){return Ce(Y,se)}static fromPinnedBuffer(Y,se,he){return Ee(Y,se,he)}toDataURL(Y){return U(this,Y)}toImageData(Y){return oe(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 et(this,Y)}}}),pe,Ze=d(()=>{Ie(),pe=X}),ge,Ke,vt,st,Kt,Be,Dt=d(()=>{L(),ge=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},Ke=(Y,se)=>{var xe;let he=((xe=new Error().stack)==null?void 0:xe.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Oe=0;Oe<he.length;Oe++){if(Te&&!he[Oe].includes("TRACE_FUNC")){let $e=`FUNC_${Y}::${he[Oe].trim().split(" ")[1]}`;se&&($e+=`::${se}`),ge("CPU",$e);return}he[Oe].includes("TRACE_FUNC")&&(Te=!0)}},vt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("BEGIN",Y)},st=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("END",Y)},Kt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Be=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),_t,ri=d(()=>{C(),Ze(),Dt(),_t=class A1{constructor(se){this.handler=se}async run(se,he,Te){vt(),Kt("InferenceSession.run");let xe={},Oe={};if(typeof se!="object"||se===null||se instanceof pe||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof pe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(he)){if(he.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of he){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);xe[tt]=null}if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let qe=he[it];(qe===null||qe instanceof pe)&&(tt=!0,$e=!1,xe[it]=qe)}if(tt){if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Oe=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof se[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)xe[tt]=null;let Ae=await this.handler.run(se,xe,Oe),Le={};for(let tt in Ae)if(Object.hasOwnProperty.call(Ae,tt)){let rt=Ae[tt];rt instanceof pe?Le[tt]=rt:Le[tt]=new pe(rt.type,rt.data,rt.dims)}return Be("InferenceSession.run"),st(),Le}async release(){return this.handler.dispose()}static async create(se,he,Te,xe){vt(),Kt("InferenceSession.create");let Oe,$e={};if(typeof se=="string"){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,it=0,qe=se.byteLength;if(typeof he=="object"&&he!==null)$e=he;else if(typeof he=="number"){if(it=he,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(qe=se.byteLength-it,typeof Te=="number"){if(qe=Te,!Number.isSafeInteger(qe))throw new RangeError("'byteLength' must be an integer.");if(qe<=0||it+qe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof xe=="object"&&xe!==null)$e=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Oe=new Uint8Array(rt,it,qe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Le]=await b($e),tt=await Ae.createInferenceSessionHandler(Oe,Le);return Be("InferenceSession.create"),st(),new A1(tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ye,St=d(()=>{ri(),Ye=_t}),ut=d(()=>{}),Xe=d(()=>{}),Pt=d(()=>{}),oi=d(()=>{}),Fi={};f(Fi,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,env:()=>j,registerBackend:()=>E});var li=d(()=>{w(),H(),St(),Ze(),ut(),Xe(),Dt(),Pt(),oi()}),tn=d(()=>{}),Ii={};f(Ii,{default:()=>pr});var Ui,ui,pr,ga=d(()=>{var Y;fe(),Hn(),Fn(),Ui="ort-wasm-proxy-worker",ui=((Y=globalThis.self)==null?void 0:Y.name)===Ui,ui&&(self.onmessage=se=>{let{type:he,in:Te}=se.data;try{switch(he){case"init-wasm":Js(Te.wasm).then(()=>{Lo(Te).then(()=>{postMessage({type:he})},xe=>{postMessage({type:he,err:xe})})},xe=>{postMessage({type:he,err:xe})});break;case"init-ep":{let{epName:xe,env:Oe}=Te;wr(Oe,xe).then(()=>{postMessage({type:he})},$e=>{postMessage({type:he,err:$e})});break}case"copy-from":{let{buffer:xe}=Te,Oe=ni(xe);postMessage({type:he,out:Oe});break}case"create":{let{model:xe,options:Oe}=Te;us(xe,Oe).then($e=>{postMessage({type:he,out:$e})},$e=>{postMessage({type:he,err:$e})});break}case"release":zr(Te),postMessage({type:he});break;case"run":{let{sessionId:xe,inputIndices:Oe,inputs:$e,outputIndices:Ae,options:Le}=Te;Ve(xe,Oe,$e,Ae,new Array(Ae.length).fill(null),Le).then(tt=>{tt.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:tt},ft([...$e,...tt]))},tt=>{postMessage({type:he,err:tt})});break}case"end-profiling":Un(Te),postMessage({type:he});break;default:}}catch(xe){postMessage({type:he,err:xe})}}),pr=ui?null:se=>new Worker(se??vi,{type:"classic",name:Ui})}),Mo,fr,vi,Gn,nn,mr,Rs,as,Mr,gr,vr,js,Pn,Fn=d(()=>{tn(),Mo=typeof location>"u"?void 0:location.origin,fr=()=>{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},vi=fr(),Gn=()=>{if(vi&&!vi.startsWith("blob:"))return vi.substring(0,vi.lastIndexOf("/")+1)},nn=(Y,se)=>{try{let he=se??vi;return(he?new URL(Y,he):new URL(Y)).origin===Mo}catch{return!1}},mr=(Y,se)=>{let he=se??vi;try{return(he?new URL(Y,he):new URL(Y)).href}catch{return}},Rs=(Y,se)=>`${se??"./"}${Y}`,as=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},Mr=async Y=>(await import(Y)).default,gr=(ga(),m(Ii)).default,vr=async()=>{if(!vi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(vi))return[void 0,gr()];let Y=await as(vi);return[Y,gr(Y)]},js=void 0,Pn=async(Y,se,he,Te)=>{let xe=js&&!(Y||se);if(xe)if(vi)xe=nn(vi)||Te&&!he;else if(Te&&!he)xe=!0;else throw new Error("cannot determine the script source URL.");if(xe)return[void 0,js];{let Oe="ort-wasm-simd-threaded.mjs",$e=Y??mr(Oe,se),Ae=he&&$e&&!nn($e,se),Le=Ae?await as($e):$e??Rs(Oe,se);return[Ae?Le:void 0,await Mr(Le)]}}}),Ks,Rn,ls,Es,no,Ys,Xs,Js,zt,Hn=d(()=>{Fn(),Rn=!1,ls=!1,Es=!1,no=()=>{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}},Ys=()=>{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}},Xs=()=>{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}},Js=async Y=>{if(Rn)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let se=Y.initTimeout,he=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!Xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ys())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=no();he>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+he+", 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=he=1);let xe=Y.wasmPaths,Oe=typeof xe=="string"?xe:void 0,$e=xe==null?void 0:xe.mjs,Ae=($e==null?void 0:$e.href)??$e,Le=xe==null?void 0:xe.wasm,tt=(Le==null?void 0:Le.href)??Le,rt=Y.wasmBinary,[it,qe]=await Pn(Ae,Oe,he>1,!!rt||!!tt),It=!1,Ne=[];if(se>0&&Ne.push(new Promise(dt=>{setTimeout(()=>{It=!0,dt()},se)})),Ne.push(new Promise((dt,Ci)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(tt||Oe)Zt.locateFile=Qt=>tt??Oe+Qt;else if(Ae&&Ae.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Ae).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=ki=>Qt+ki)}qe(Zt).then(Qt=>{ls=!1,Rn=!0,Ks=Qt,dt(),it&&URL.revokeObjectURL(it)},Qt=>{ls=!1,Es=!0,Ci(Qt)})})),await Promise.race(Ne),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Hi,yi,kt,Or=d(()=>{Hn(),Hi=(Y,se)=>{let he=zt(),Te=he.lengthBytesUTF8(Y)+1,xe=he._malloc(Te);return he.stringToUTF8(Y,xe,Te),se.push(xe),xe},yi=(Y,se,he,Te)=>{if(typeof Y=="object"&&Y!==null){if(he.has(Y))throw new Error("Circular reference in options");he.add(Y)}Object.entries(Y).forEach(([xe,Oe])=>{let $e=se?se+xe:xe;if(typeof Oe=="object")yi(Oe,$e+".",he,Te);else if(typeof Oe=="string"||typeof Oe=="number")Te($e,Oe.toString());else if(typeof Oe=="boolean")Te($e,Oe?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Oe}`)})},kt=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetLastError(xe,xe+Te);let Oe=Number(se.getValue(xe,Te===4?"i32":"i64")),$e=se.getValue(xe+Te,"*"),Ae=$e?se.UTF8ToString($e):"";throw new Error(`${Y} ERROR_CODE: ${Oe}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(he)}}}),so,va=d(()=>{Hn(),Or(),so=Y=>{let se=zt(),he=0,Te=[],xe=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)xe.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)xe.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&&(xe.terminate=!1);let Oe=0;return(Y==null?void 0:Y.tag)!==void 0&&(Oe=Hi(Y.tag,Te)),he=se._OrtCreateRunOptions(xe.logSeverityLevel,xe.logVerbosityLevel,!!xe.terminate,Oe),he===0&&kt("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&yi(Y.extra,"",new WeakSet,($e,Ae)=>{let Le=Hi($e,Te),tt=Hi(Ae,Te);se._OrtAddRunConfigEntry(he,Le,tt)!==0&&kt(`Can't set a run config entry: ${$e} - ${Ae}.`)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseRunOptions(he),Te.forEach($e=>se._free($e)),Oe}}}),ro,oo,Oo,kn,_a,ba,xi=d(()=>{Hn(),Or(),ro=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}`)}},oo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},Oo=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(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(Y.enableMemPattern=!1)},kn=(Y,se,he,Te)=>{let xe=Hi(se,Te),Oe=Hi(he,Te);zt()._OrtAddSessionConfigEntry(Y,xe,Oe)!==0&&kt(`Can't set a session config entry: ${se} - ${he}.`)},_a=async(Y,se,he)=>{let Te=se.executionProviders;for(let xe of Te){let Oe=typeof xe=="string"?xe:xe.name,$e=[];switch(Oe){case"webnn":if(Oe="WEBNN",kn(Y,"session.disable_quant_qdq","1",he),kn(Y,"session.disable_qdq_constant_folding","1",he),typeof xe!="string"){let it=xe==null?void 0:xe.deviceType;it&&kn(Y,"deviceType",it,he)}break;case"webgpu":if(Oe="JS",typeof xe!="string"){let it=xe;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);kn(Y,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Oe}`)}let Ae=Hi(Oe,he),Le=$e.length,tt=0,rt=0;if(Le>0){tt=zt()._malloc(Le*zt().PTR_SIZE),he.push(tt),rt=zt()._malloc(Le*zt().PTR_SIZE),he.push(rt);for(let it=0;it<Le;it++)zt().setValue(tt+it*zt().PTR_SIZE,$e[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,$e[it][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,tt,rt,Le)!==0&&kt(`Can't append execution provider: ${Oe}.`)}},ba=async Y=>{let se=zt(),he=0,Te=[],xe=Y||{};Oo(xe);try{let Oe=ro(xe.graphOptimizationLevel??"all"),$e=oo(xe.executionMode??"sequential"),Ae=typeof xe.logId=="string"?Hi(xe.logId,Te):0,Le=xe.logSeverityLevel??2;if(!Number.isInteger(Le)||Le<0||Le>4)throw new Error(`log severity level is not valid: ${Le}`);let tt=xe.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let rt=typeof xe.optimizedModelFilePath=="string"?Hi(xe.optimizedModelFilePath,Te):0;if(he=se._OrtCreateSessionOptions(Oe,!!xe.enableCpuMemArena,!!xe.enableMemPattern,$e,!!xe.enableProfiling,0,Ae,Le,tt,rt),he===0&&kt("Can't create session options."),xe.executionProviders&&await _a(he,xe,Te),xe.enableGraphCapture!==void 0){if(typeof xe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${xe.enableGraphCapture}`);kn(he,"enableGraphCapture",xe.enableGraphCapture.toString(),Te)}if(xe.freeDimensionOverrides)for(let[it,qe]of Object.entries(xe.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof qe!="number"||!Number.isInteger(qe)||qe<0)throw new Error(`free dimension override value must be a non-negative integer: ${qe}`);let It=Hi(it,Te);se._OrtAddFreeDimensionOverride(he,It,qe)!==0&&kt(`Can't set a free dimension override: ${it} - ${qe}.`)}return xe.extra!==void 0&&yi(xe.extra,"",new WeakSet,(it,qe)=>{kn(he,it,qe,Te)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseSessionOptions(he)!==0&&kt("Can't release session options."),Te.forEach($e=>se._free($e)),Oe}}}),jn,Vi,Nn,Zs,Lr,_r,cs,gn,Bt=d(()=>{jn=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}`)}},Vi=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}`)}},Nn=(Y,se)=>{let he=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Y],Te=typeof se=="number"?se:se.reduce((xe,Oe)=>xe*Oe,1);return he>0?Math.ceil(Te*he):void 0},Zs=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}`)}},Lr=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}`)}},_r=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",cs=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",gn=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}`)}}}),qi,br=d(()=>{tn(),qi=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 he=se.headers.get("Content-Length"),Te=he?parseInt(he,10):0;if(Te<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let xe=se.body.getReader(),Oe;try{Oe=new ArrayBuffer(Te)}catch(Ae){if(Ae instanceof RangeError){let Le=Math.ceil(Te/65536);Oe=new WebAssembly.Memory({initial:Le,maximum:Le}).buffer}else throw Ae}let $e=0;for(;;){let{done:Ae,value:Le}=await xe.read();if(Ae)break;let tt=Le.byteLength;new Uint8Array(Oe,$e,tt).set(Le),$e+=tt}return new Uint8Array(Oe,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),ds,Lo,wr,Wn,Ns,yr,ni,us,zr,Ts,Ve,Un,ft,fe=d(()=>{li(),va(),xi(),Bt(),Hn(),Or(),br(),ds=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&kt("Can't initialize onnxruntime.")},Lo=async Y=>{ds(Y.wasm.numThreads,Lr(Y.logLevel))},wr=async(Y,se)=>{var Te,xe;(xe=(Te=zt()).asyncInit)==null||xe.call(Te);let he=Y.webgpu.adapter;if(se==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(he){if(typeof he.limits!="object"||typeof he.features!="object"||typeof he.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Oe=Y.webgpu.powerPreference;if(Oe!==void 0&&Oe!=="low-power"&&Oe!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Oe}"`);let $e=Y.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Oe,forceFallbackAdapter:$e}),!he)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")},Wn=new Map,Ns=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetInputOutputCount(Y,xe,xe+Te)!==0&&kt("Can't get session input/output count.");let Oe=Te===4?"i32":"i64";return[Number(se.getValue(xe,Oe)),Number(se.getValue(xe+Te,Oe))]}finally{se.stackRestore(he)}},yr=(Y,se)=>{let he=zt(),Te=he.stackSave(),xe=0;try{let Oe=he.PTR_SIZE,$e=he.stackAlloc(2*Oe);he._OrtGetInputOutputMetadata(Y,se,$e,$e+Oe)!==0&&kt("Can't get session input/output metadata.");let Ae=Number(he.getValue($e,"*"));xe=Number(he.getValue($e+Oe,"*"));let Le=he.HEAP32[xe/4];if(Le===0)return[Ae,0];let tt=he.HEAPU32[xe/4+1],rt=[];for(let it=0;it<tt;it++){let qe=Number(he.getValue(xe+8+it*Oe,"*"));rt.push(qe!==0?he.UTF8ToString(qe):Number(he.getValue(xe+8+(it+tt)*Oe,"*")))}return[Ae,Le,rt]}finally{he.stackRestore(Te),xe!==0&&he._OrtFree(xe)}},ni=Y=>{let se=zt(),he=se._malloc(Y.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,he),[he,Y.byteLength]},us=async(Y,se)=>{var rt,it,qe;let he,Te,xe=zt();Array.isArray(Y)?[he,Te]=Y:Y.buffer===xe.HEAPU8.buffer?[he,Te]=[Y.byteOffset,Y.byteLength]:[he,Te]=ni(Y);let Oe=0,$e=0,Ae=[],Le=[],tt=[];try{if([$e,Ae]=await ba(se),(se==null?void 0:se.externalData)&&xe.mountExternalData){let Ri=[];for(let ci of se.externalData){let vn=typeof ci=="string"?ci:ci.path;Ri.push(qi(typeof ci=="string"?ci:ci.data).then(Mn=>{xe.mountExternalData(vn,Mn)}))}await Promise.all(Ri)}for(let Ri of(se==null?void 0:se.executionProviders)??[])if((typeof Ri=="string"?Ri:Ri.name)==="webnn"){if(xe.shouldTransferToMLTensor=!1,typeof Ri!="string"){let ci=Ri,vn=ci==null?void 0:ci.context,Mn=ci==null?void 0:ci.gpuDevice,Vn=ci==null?void 0:ci.deviceType,ya=ci==null?void 0:ci.powerPreference;vn?xe.currentContext=vn:Mn?xe.currentContext=await xe.webnnCreateMLContext(Mn):xe.currentContext=await xe.webnnCreateMLContext({deviceType:Vn,powerPreference:ya})}else xe.currentContext=await xe.webnnCreateMLContext();break}Oe=await xe._OrtCreateSession(he,Te,$e),(rt=xe.webgpuOnCreateSession)==null||rt.call(xe,Oe),Oe===0&&kt("Can't create a session."),(it=xe.jsepOnCreateSession)==null||it.call(xe),xe.currentContext&&(xe.webnnRegisterMLContext(Oe,xe.currentContext),xe.currentContext=void 0,xe.shouldTransferToMLTensor=!0);let[It,Ne]=Ns(Oe),dt=!!(se!=null&&se.enableGraphCapture),Ci=[],Zt=[],Qt=[],ki=[],Ot=[];for(let Ri=0;Ri<It;Ri++){let[ci,vn,Mn]=yr(Oe,Ri);ci===0&&kt("Can't get an input name."),Le.push(ci);let Vn=xe.UTF8ToString(ci);Ci.push(Vn),Qt.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}for(let Ri=0;Ri<Ne;Ri++){let[ci,vn,Mn]=yr(Oe,Ri+It);ci===0&&kt("Can't get an output name."),tt.push(ci);let Vn=xe.UTF8ToString(ci);Zt.push(Vn),ki.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}return Wn.set(Oe,[Oe,Le,tt,null,dt,!1]),[Oe,Ci,Zt,Qt,ki]}catch(It){throw Le.forEach(Ne=>xe._OrtFree(Ne)),tt.forEach(Ne=>xe._OrtFree(Ne)),Oe!==0&&xe._OrtReleaseSession(Oe)!==0&&kt("Can't release session."),It}finally{xe._free(he),$e!==0&&xe._OrtReleaseSessionOptions($e)!==0&&kt("Can't release session options."),Ae.forEach(It=>xe._free(It)),(qe=xe.unmountExternalData)==null||qe.call(xe)}},zr=Y=>{var Le,tt,rt;let se=zt(),he=Wn.get(Y);if(!he)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,xe,Oe,$e,Ae]=he;$e&&(Ae&&se._OrtClearBoundOutputs($e.handle)!==0&&kt("Can't clear bound outputs."),se._OrtReleaseBinding($e.handle)!==0&&kt("Can't release IO binding.")),(Le=se.jsepOnReleaseSession)==null||Le.call(se,Y),(tt=se.webnnOnReleaseSession)==null||tt.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),xe.forEach(it=>se._OrtFree(it)),Oe.forEach(it=>se._OrtFree(it)),se._OrtReleaseSession(Te)!==0&&kt("Can't release session."),Wn.delete(Y)},Ts=async(Y,se,he,Te,xe,Oe,$e=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Le=Ae.PTR_SIZE,tt=Y[0],rt=Y[1],it=Y[3],qe=it,It,Ne;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Oe} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=Y[2].gpuBuffer;Ne=Nn(jn(tt),rt);{let Qt=Ae.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=Qt(Te,Oe,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=Y[2].mlTensor;Ne=Nn(jn(tt),rt);let Qt=Ae.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=Qt(Te,Zt,jn(tt),rt)}else{let Zt=Y[2];if(Array.isArray(Zt)){Ne=Le*Zt.length,It=Ae._malloc(Ne),he.push(It);for(let Qt=0;Qt<Zt.length;Qt++){if(typeof Zt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Ae.setValue(It+Qt*Le,Hi(Zt[Qt],he),"*")}}else{let Qt=Ae.webnnIsGraphInput,ki=Ae.webnnIsGraphOutput;if(tt!=="string"&&Qt&&ki){let Ot=Ae.UTF8ToString(xe);if(Qt(Te,Ot)||ki(Te,Ot)){let Ri=jn(tt);Ne=Nn(Ri,rt),qe="ml-tensor";let ci=Ae.webnnCreateTemporaryTensor,vn=Ae.webnnUploadTensor;if(!ci||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Mn=await ci(Te,Ri,rt);vn(Mn,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),It=Mn}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}}let dt=Ae.stackSave(),Ci=Ae.stackAlloc(4*rt.length);try{rt.forEach((Qt,ki)=>Ae.setValue(Ci+ki*Le,Qt,Le===4?"i32":"i64"));let Zt=Ae._OrtCreateTensor(jn(tt),It,Ne,Ci,rt.length,gn(qe));Zt===0&&kt(`Can't create tensor for input/output. session=${Te}, index=${Oe}.`),se.push(Zt)}finally{Ae.stackRestore(dt)}},Ve=async(Y,se,he,Te,xe,Oe)=>{var qn,ol,ic;let $e=zt(),Ae=$e.PTR_SIZE,Le=Wn.get(Y);if(!Le)throw new Error(`cannot run inference. invalid session id: ${Y}`);let tt=Le[0],rt=Le[1],it=Le[2],qe=Le[3],It=Le[4];Le[5];let Ne=se.length,dt=Te.length,Ci=0,Zt=[],Qt=[],ki=[],Ot=[],Ri=[],ci=$e.stackSave(),vn=$e.stackAlloc(Ne*Ae),Mn=$e.stackAlloc(Ne*Ae),Vn=$e.stackAlloc(dt*Ae),ya=$e.stackAlloc(dt*Ae);try{[Ci,Zt]=so(Oe),Kt("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)await Ts(he[ai],Qt,Ot,Y,rt[se[ai]],se[ai],It);for(let ai=0;ai<dt;ai++)await Ts(xe[ai],ki,Ot,Y,it[Te[ai]],Ne+Te[ai],It);Be("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)$e.setValue(vn+ai*Ae,Qt[ai],"*"),$e.setValue(Mn+ai*Ae,rt[se[ai]],"*");for(let ai=0;ai<dt;ai++)$e.setValue(Vn+ai*Ae,ki[ai],"*"),$e.setValue(ya+ai*Ae,it[Te[ai]],"*");(qn=$e.jsepOnRunStart)==null||qn.call($e,tt),(ol=$e.webnnOnRunStart)==null||ol.call($e,tt);let _n;_n=await $e._OrtRun(tt,Mn,vn,Ne,ya,dt,Vn,Ci),_n!==0&&kt("failed to call OrtRun().");let er=[],nc=[];Kt("wasm ProcessOutputTensor");for(let ai=0;ai<dt;ai++){let Os=Number($e.getValue(Vn+ai*Ae,"*"));if(Os===ki[ai]||Ri.includes(ki[ai])){er.push(xe[ai]),Os!==ki[ai]&&$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.");continue}let dd=$e.stackSave(),Cr=$e.stackAlloc(4*Ae),zo=!1,an,Kn=0;try{$e._OrtGetTensorData(Os,Cr,Cr+Ae,Cr+2*Ae,Cr+3*Ae)!==0&&kt(`Can't access output tensor data on index ${ai}.`);let al=Ae===4?"i32":"i64",Yn=Number($e.getValue(Cr,al));Kn=$e.getValue(Cr+Ae,"*");let sc=$e.getValue(Cr+Ae*2,"*"),ud=Number($e.getValue(Cr+Ae*3,al)),kr=[];for(let ln=0;ln<ud;ln++)kr.push(Number($e.getValue(sc+ln*Ae,al)));$e._OrtFree(sc)!==0&&kt("Can't free memory for tensor dims.");let Ls=kr.reduce((ln,Wi)=>ln*Wi,1);an=Vi(Yn);let tr=qe==null?void 0:qe.outputPreferredLocations[Te[ai]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Wi=0;Wi<Ls;Wi++){let zs=$e.getValue(Kn+Wi*Ae,"*"),rc=$e.getValue(Kn+(Wi+1)*Ae,"*"),oc=Wi===Ls-1?void 0:rc-zs;ln.push($e.UTF8ToString(zs,oc))}er.push([an,kr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ls>0){let ln=$e.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wi=ln(Kn),zs=Nn(Yn,Ls);if(zs===void 0||!_r(an))throw new Error(`Unsupported data type: ${an}`);zo=!0,er.push([an,kr,{gpuBuffer:Wi,download:$e.jsepCreateDownloader(Wi,zs,an),dispose:()=>{$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ls>0){let ln=$e.webnnEnsureTensor,Wi=$e.webnnIsGraphInputOutputTypeSupported;if(!ln||!Wi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Nn(Yn,Ls)===void 0||!cs(an))throw new Error(`Unsupported data type: ${an}`);if(!Wi(Y,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let zs=await ln(Y,Kn,Yn,kr,!1);zo=!0,er.push([an,kr,{mlTensor:zs,download:$e.webnnCreateMLTensorDownloader(Kn,an),dispose:()=>{$e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ls>0){let ln=$e.webnnCreateMLTensorDownloader(Kn,an)(),Wi=er.length;zo=!0,nc.push((async()=>{let zs=[Wi,await ln];return $e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os),zs})()),er.push([an,kr,[],"cpu"])}else{let ln=Zs(an),Wi=new ln(Ls);new Uint8Array(Wi.buffer,Wi.byteOffset,Wi.byteLength).set($e.HEAPU8.subarray(Kn,Kn+Wi.byteLength)),er.push([an,kr,Wi,"cpu"])}}finally{$e.stackRestore(dd),an==="string"&&Kn&&$e._free(Kn),zo||$e._OrtReleaseTensor(Os)}}qe&&!It&&($e._OrtClearBoundOutputs(qe.handle)!==0&&kt("Can't clear bound outputs."),Wn.set(Y,[tt,rt,it,qe,It,!1]));for(let[ai,Os]of await Promise.all(nc))er[ai][2]=Os;return Be("wasm ProcessOutputTensor"),er}finally{(ic=$e.webnnOnRunEnd)==null||ic.call($e,tt),$e.stackRestore(ci),Qt.forEach(_n=>$e._OrtReleaseTensor(_n)),ki.forEach(_n=>$e._OrtReleaseTensor(_n)),Ot.forEach(_n=>$e._free(_n)),Ci!==0&&$e._OrtReleaseRunOptions(Ci),Zt.forEach(_n=>$e._free(_n))}},Un=Y=>{let se=zt(),he=Wn.get(Y);if(!he)throw new Error("invalid session id");let Te=he[0],xe=se._OrtEndProfiling(Te);xe===0&&kt("Can't get an profile file name."),se._OrtFree(xe)},ft=Y=>{let se=[];for(let he of Y){let Te=he[2];!Array.isArray(Te)&&"buffer"in Te&&se.push(Te.buffer)}return se}}),Re,Je,Tt,ti,si,Pi,Ti,sn,Oi,on,Di,Ms,Br,ao,Qs,cd,lo,co,Ql=d(()=>{li(),fe(),Hn(),Fn(),Re=()=>!!j.wasm.proxy&&typeof document<"u",Tt=!1,ti=!1,si=!1,sn=new Map,Oi=(Y,se)=>{let he=sn.get(Y);he?he.push(se):sn.set(Y,[se])},on=()=>{if(Tt||!ti||si||!Je)throw new Error("worker not ready")},Di=Y=>{switch(Y.data.type){case"init-wasm":Tt=!1,Y.data.err?(si=!0,Ti[1](Y.data.err)):(ti=!0,Ti[0]()),Pi&&(URL.revokeObjectURL(Pi),Pi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=sn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Ms=async()=>{if(!ti){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(si)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Re())return new Promise((Y,se)=>{Je==null||Je.terminate(),vr().then(([he,Te])=>{try{Je=Te,Je.onerror=Oe=>se(Oe),Je.onmessage=Di,Ti=[Y,se];let xe={type:"init-wasm",in:j};if(!xe.in.wasm.wasmPaths&&he){let Oe=Gn();Oe&&(xe.in.wasm.wasmPaths=Oe)}Je.postMessage(xe),Pi=he}catch(xe){se(xe)}},se)});try{await Js(j.wasm),await Lo(j),ti=!0}catch(Y){throw si=!0,Y}finally{Tt=!1}}},Br=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("init-ep",[se,he]);let Te={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Te)});await wr(j,Y)},ao=async Y=>Re()?(on(),new Promise((se,he)=>{Oi("copy-from",[se,he]);let Te={type:"copy-from",in:{buffer:Y}};Je.postMessage(Te,[Y.buffer])})):ni(Y),Qs=async(Y,se)=>{if(Re()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,Te)=>{Oi("create",[he,Te]);let xe={type:"create",in:{model:Y,options:{...se}}},Oe=[];Y instanceof Uint8Array&&Oe.push(Y.buffer),Je.postMessage(xe,Oe)})}else return us(Y,se)},cd=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("release",[se,he]);let Te={type:"release",in:Y};Je.postMessage(Te)});zr(Y)},lo=async(Y,se,he,Te,xe,Oe)=>{if(Re()){if(he.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(xe.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise(($e,Ae)=>{Oi("run",[$e,Ae]);let Le=he,tt={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Le,outputIndices:Te,options:Oe}};Je.postMessage(tt,ft(Le))})}else return Ve(Y,se,he,Te,xe,Oe)},co=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("end-profiling",[se,he]);let Te={type:"end-profiling",in:Y};Je.postMessage(Te)});Un(Y)}}),il,uo,wa,nl=d(()=>{li(),Ql(),Bt(),tn(),br(),il=(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()}`)}},uo=Y=>{switch(Y[3]){case"cpu":return new pe(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!_r(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:he,download:Te,dispose:xe}=Y[2];return pe.fromGpuBuffer(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}case"ml-tensor":{let se=Y[0];if(!cs(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:he,download:Te,dispose:xe}=Y[2];return pe.fromMLTensor(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}default:throw new Error(`invalid data location: ${Y[3]}`)}},wa=class{async fetchModelAndCopyToWasmMemory(Y){return ao(await qi(Y))}async loadModel(Y,se){vt();let he;typeof Y=="string"?he=await this.fetchModelAndCopyToWasmMemory(Y):he=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,se),st()}async dispose(){return cd(this.sessionId)}async run(Y,se,he){vt();let Te=[],xe=[];Object.entries(Y).forEach(it=>{let qe=it[0],It=it[1],Ne=this.inputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid input '${qe}'`);Te.push(It),xe.push(Ne)});let Oe=[],$e=[];Object.entries(se).forEach(it=>{let qe=it[0],It=it[1],Ne=this.outputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid output '${qe}'`);Oe.push(It),$e.push(Ne)});let Ae=Te.map((it,qe)=>il(it,()=>`input "${this.inputNames[xe[qe]]}"`)),Le=Oe.map((it,qe)=>it?il(it,()=>`output "${this.outputNames[$e[qe]]}"`):null),tt=await lo(this.sessionId,xe,Ae,$e,Le,he),rt={};for(let it=0;it<tt.length;it++)rt[this.outputNames[$e[it]]]=Oe[it]??uo(tt[it]);return st(),rt}startProfiling(){}endProfiling(){co(this.sessionId)}}}),xr={};f(xr,{OnnxruntimeWebAssemblyBackend:()=>Sr,initializeFlags:()=>Gr,wasmBackend:()=>ho});var Gr,Sr,ho,ec=d(()=>{li(),Ql(),nl(),Gr=()=>{(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))}},Sr=class{async init(Y){Gr(),await Ms(),await Br(Y)}async createInferenceSessionHandler(Y,se){let he=new wa;return await he.loadModel(Y,se),he}},ho=new Sr}),tc={};f(tc,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,default:()=>rl,env:()=>j,registerBackend:()=>E}),li(),li(),li();var sl="1.26.0",rl=Fi;{let Y=(ec(),m(xr)).wasmBackend;E("cpu",Y,10),E("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:sl,enumerable:!0}),m(tc)})();i.exports=t})(Yv)),Yv.exports}var Ay;function HE(){return Ay||(Ay=1,(function(i){var e=Ua&&Ua.__createBinding||(Object.create?(function(x,$,P,N){N===void 0&&(N=P);var L=Object.getOwnPropertyDescriptor($,P);(!L||("get"in L?!$.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return $[P]}}),Object.defineProperty(x,N,L)}):(function(x,$,P,N){N===void 0&&(N=P),x[N]=$[P]})),t=Ua&&Ua.__setModuleDefault||(Object.create?(function(x,$){Object.defineProperty(x,"default",{enumerable:!0,value:$})}):function(x,$){x.default=$}),n=Ua&&Ua.__importStar||function(x){if(x&&x.__esModule)return x;var $={};if(x!=null)for(var P in x)P!=="default"&&Object.prototype.hasOwnProperty.call(x,P)&&e($,x,P);return t($,x),$};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(FE()),l=Fb(),p=Hb(),a=Yf(),d=gv(),f=D1(),v=$1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",y="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",E=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 $=>{$.getTracks().forEach(P=>{P.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:$=>{$.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=E;const T=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,$,P,N,L){await P.audioWorklet.addModule(x),$.processorOptions={...$.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(P,"vad-helper-worklet",$);return j.port.onmessage=async H=>{const U=H.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case d.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const oe=new Float32Array(U.data);await L(oe);break}}},j}async function C(x,$,P){const N=new v.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:$});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async U=>{if(!H){H=!0;try{const oe=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=N.process(oe);for(const me of Z)await P(me)}catch(oe){console.error("Error processing audio:",oe)}finally{H=!1}}},j.connect(x.destination),j}class w{constructor($,P,N,L,j=!1,H=null,U=null,oe=null,de=null,Z=null,me=null,ie="uninitialized",ue=!1){this.options=$,this.frameProcessor=P,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=U,this._audioContext=oe,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=ie,this.ownsAudioContext=ue,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=Ce=>{this.initializationState="errored",this.errored=Ce},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(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}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"?T(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:Ce,audioContext:Ee,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const te=new MediaStreamAudioSourceNode(Ee,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(W);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:Ce,mediaStreamAudioSourceNode:Ee}=this.getAudioInstances();await this.options.pauseStream(Ce),Ee.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ee;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ee=this._audioContext)==null?void 0:Ee.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.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(Ce.audio);break}}}static async new($={}){const P={...(0,i.getDefaultRealTimeVADOptions)($.model??i.DEFAULT_MODEL),...$};(0,p.validateOptions)(P),i.ort.env.wasm.wasmPaths=P.onnxWASMBasePath,P.ortConfig!==void 0&&P.ortConfig(i.ort);const N=P.model==="v5"?y: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 U=P.model==="v5"?512:1536,oe=U/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},oe),Z=new w(P,de,H,U);if(P.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=w})(Ua)),Ua}var Iy;function WE(){return Iy||(Iy=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=k1();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=Fb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Hb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=gv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=BE();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=GE();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=HE();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}})})(Vv)),Vv}var UE=WE();function ig(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 pt={debug:(i,e,t)=>ig(i,"debug",e,t),info:(i,e,t)=>ig(i,"info",e,t),warn:(i,e,t)=>ig(i,"warn",e,t),error:(i,e,t,n)=>ig(i,"error",e,t,n)},I1=16e3,VE=6,Wu=I1*VE,qE=400,KE=I1*qE/1e3,Py=300,Ry=2e3,jy=1500,Ny=3e3,YE=600,P1=.5,R1=.35,My=.85,Oy=.7;let hr=null,pa=!1,qs=!1;const L_=new Set;function ng(i){for(const e of Array.from(L_))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Xv=0;const Ly=2;let ih=!1,j1=!1;function N1(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";pt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),XE(`error:${e.message||"unknown"}`)})}function Qg(){return hr||(hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),N1(hr),pt.info("speech","worker spawned"),hr)}let sg=!1;function XE(i){if(!ih){if(sg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(sg=!0,Xv+=1,j1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:Xv}),ng({reason:i,respawned:!1,finalOnly:!0}),Xv>Ly){if(ih=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Ly}),hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1,ng({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),sg=!1;return}if(hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1;try{hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),N1(hr),qs=!0,hr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),ng({reason:i,respawned:!0,finalOnly:!0})}catch(e){ih=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),ng({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{sg=!1}}}function JE(i,e){if(pa||qs)return;qs=!0;const t=Qg();pt.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"&&(pa=!0,qs=!1,pt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(qs=!1,pt.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 ZE(){pt.info("speech","resetModel: clearing load flags"),pa=!1,qs=!1}function vv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function QE(i){const e=Qg();return!pa&&!qs&&(qs=!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"&&(pa=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function M1(i){let e=Qg(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let v=null,m=0,y=!1,D=0,E=!1,T=!1,b=0,C=0,w=0,x=-1,$=Py,P=0,N=null,L="",j="",H=!1,U=0;function oe(ve,_e){const Me=Math.min(ve.length,_e.length);let et=0;for(;et<Me&&ve.charCodeAt(et)===_e.charCodeAt(et);)et++;return et}function de(ve){const _e=oe(L,ve);return L=ve,_e>j.length&&(j=ve.slice(0,_e)),j.length>ve.length&&(j=ve),j}const Z=()=>(v||(v=new Float32Array(Wu)),v),me=()=>{m=0},ie=ve=>{const _e=Z(),Me=ve.length;if(Me>=Wu){_e.set(ve.subarray(Me-Wu)),m=Wu;return}if(m+Me<=Wu){_e.set(ve,m),m+=Me;return}const et=m+Me-Wu;_e.copyWithin(0,et,m),m-=et,_e.set(ve,m),m+=Me},ue=()=>{N&&(clearTimeout(N),N=null)},Ce=()=>{ue(),y=!1,E=!1,T=!1,$=Py,L="",j="",H=!1,U=0,me()},Ee=()=>{if(t||!y||T||E||N)return;if(m<KE){N=setTimeout(()=>{N=null,Ee()},$);return}const ve=performance.now()-b;if(ve<$&&b!==0){N=setTimeout(()=>{N=null,Ee()},$-ve);return}if(j1||ih||i.partialsEnabled&&!i.partialsEnabled())return;const _e=Z(),Me=new Float32Array(m);Me.set(_e.subarray(0,m)),C+=1,w=C,E=!0,P=performance.now(),b=P,e.postMessage({type:"transcribe-partial",audio:Me,seq:C},[Me.buffer])},W=ve=>ve.length===0?Promise.resolve():ih?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(_e=>{d.push(_e),C+=1;const Me=C;x=Me,e.postMessage({type:"transcribe",audio:ve,seq:Me},[ve.buffer])}),te=ve=>{const _e=W(ve);return f.add(_e),_e.finally(()=>{f.delete(_e)}),_e},K=ve=>{var _e,Me,et,we,X;if(ve.data.type==="result"){const Ie=ve.data.text,pe=ve.data.seq??0;pe&&pe<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:pe,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(_e=d.shift())==null||_e()}else if(ve.data.type==="partial"){const Ie=ve.data.seq??0,pe=ve.data.text??"",Ze=performance.now()-P;E=!1,Ze>=Ny?(T=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ze),seq:Ie})):Ze>=jy&&($=Math.min($*2,Ry),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ze),newIntervalMs:$,seq:Ie})),H||(H=!0,Ze>YE&&$<500&&($=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ze),newIntervalMs:500})));const ge=Ie!==w||Ie<=x;if(!t&&!ge&&pe){const Ke=de(pe);Ke&&((Me=i.onPartial)==null||Me.call(i,Ke),U===0&&(U=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-D)})))}Ee()}else if(ve.data.type==="partial-error"){const Ie=performance.now()-P;E=!1,Ie>=Ny?(T=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ve.data.seq})):Ie>=jy&&($=Math.min($*2,Ry),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:$,seq:ve.data.seq})),pt.warn("speech","partial encode failed",{error:ve.data.error,seq:ve.data.seq}),Ee()}else ve.data.type==="error"?(t||i.onError(ve.data.error),(et=d.shift())==null||et()):ve.data.type==="status"?(t||(we=i.onModelStatus)==null||we.call(i,ve.data.status,ve.data.message),ve.data.status==="ready"&&(pa=!0,qs=!1)):ve.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ve.data.pct))};e.addEventListener("message",K);const re=ve=>{var _e,Me;if(!t){for(pt.warn("speech","createRecognition: worker death event",ve),(_e=i.onStatusChange)==null||_e.call(i,"restarting");d.length;)(Me=d.shift())==null||Me();if(f.clear(),ue(),E=!1,ve.respawned){try{e.removeEventListener("message",K)}catch{}e=Qg(),e.addEventListener("message",K)}}};return L_.add(re),{start:async()=>{if(!t){if(ih){i.onError("Speech recognition disabled — please reload the app.");return}!pa&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:pa,modelLoading:qs});try{const ve=new URL("vad/",document.baseURI).href,_e=i.inputDeviceId||null,Me={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};_e&&(Me.deviceId={exact:_e}),pt.info("speech","getUserMedia",{hasDeviceId:!!_e,deviceIdPrefix:_e?_e.slice(0,8):null});const et=await navigator.mediaDevices.getUserMedia({audio:Me});r=et,l=new AudioContext;for(const we of et.getAudioTracks())we.addEventListener("ended",()=>{t||(pt.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(we){pt.warn("speech","analyser init failed",{error:we instanceof Error?we.message:String(we)}),a=null,p=null}n=await UE.MicVAD.new({audioContext:l,getStream:async()=>et,resumeStream:async()=>et,pauseStream:async()=>{},baseAssetPath:ve,onnxWASMBasePath:ve,model:"v5",positiveSpeechThreshold:P1,negativeSpeechThreshold:R1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(we,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,we),y&&(ie(X),Ee()))},onSpeechStart:()=>{var we;t||(Ce(),y=!0,D=performance.now(),(we=i.onSpeechStart)==null||we.call(i))},onSpeechEnd:we=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),Ce(),te(we))},onVADMisfire:()=>{var we,X;t||((we=i.onStatusChange)==null||we.call(i,"idle"),Ce(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ve){const _e=ve instanceof Error?ve.message:"Microphone access denied",Me=ve instanceof Error?ve.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:_e,stack:Me}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(et=>et.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(_e)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(Ce();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(ve=>ve.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ve,_e)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ve,negativeSpeechThreshold:_e})}catch(Me){pt.warn("speech","setVadThresholds failed",{error:Me instanceof Error?Me.message:String(Me)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,Ce(),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(ve=>ve.stop())}catch{}r=null}L_.delete(re),e.removeEventListener("message",K)}}}let Df=null;const z_=new Set,B_=new Set;function e2(){for(const i of z_)try{i()}catch{}}function G_(){for(const i of B_)try{i()}catch{}}function t2(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 i2(i){if(!window.speechSynthesis)return;const e=t2(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Df=performance.now(),e2()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,G_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,G_())},window.speechSynthesis.speak(t)}function O1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Df=null,G_())}function L1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function n2(){return Df}function s2(i){return z_.add(i),()=>{z_.delete(i)}}function r2(i){return B_.add(i),()=>{B_.delete(i)}}function o2(i){L1()&&(i.setVadThresholds(My,Oy),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=s2(()=>{i.setVadThresholds(My,Oy),pt.info("voice","tts.duck.on")}),t=r2(()=>{i.setVadThresholds(P1,R1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const a2=[{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 l2(i){const e=i.trim();return a2.find(t=>t.match.test(e))??null}const c2=4e4;let nd=null;function nh(){nd&&clearTimeout(nd),nd=setTimeout(()=>{nd=null,Ct.getState().stopRecording()},c2)}function rg(){nd&&(clearTimeout(nd),nd=null)}let Yl=null,Ul=null;const d2=.04,u2=.3;let ev=0,F_=0;function h2(i){Ul!==null&&cancelAnimationFrame(Ul);const e=()=>{if(Yl===null||Ct.getState().submitCountdownStartAt===null){Ul=null;return}const t=performance.now();if(t-F_<200&&ev>u2){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:ev.toFixed(2),msIntoCountdown:Math.round(r)}),Hl(),nh();return}const n=z1();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>d2){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Hl(),nh();return}}Ul=requestAnimationFrame(e)};Ul=requestAnimationFrame(e)}function zy(i){Yl&&clearTimeout(Yl);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),Yl=setTimeout(()=>{var r;Yl=null,Ct.setState({submitCountdownStartAt:null});const n=xt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=di.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(di.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),di.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){pt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}nh()},e),h2(t)}function Hl(){Ul!==null&&(cancelAnimationFrame(Ul),Ul=null),Yl&&(clearTimeout(Yl),Yl=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let ss=null,Is=null,nf=null;function z1(){var i;return((i=ss==null?void 0:ss.getAnalyser)==null?void 0:i.call(ss))??null}const og=1e4;let $f=null;function ag(){$f&&(clearTimeout($f),$f=null)}let Og=null,Lg=null;function lg(){Og=null,Lg&&(Lg(),Lg=null)}const p2=1500,f2=9e4;let cg=0,zg=null,H_=-1;function dg(){zg&&(clearTimeout(zg),zg=null,H_=-1)}const m2=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=In((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++cg,n=()=>{t===cg&&(dg(),H_=t,zg=setTimeout(()=>{H_===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},f2))};n(),JE((r,l)=>{t===cg&&(r==="ready"?(dg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(dg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===cg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),dg(),ZE(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ss){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!vv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=M1({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=>{ev=a.isSpeech,F_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),rg(),Hl(),L1()){const d=n2(),f=d!==null?performance.now()-d:null;O1(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else pt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),nh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&pt.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var y;nh();const d=a.trim();if(!d||m2.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(nf){nf(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((y=xt.getState().tabs.find(D=>D.id===t))==null?void 0:y.status)==="dormant"){di.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&zy(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const v=l2(d);if(v){pt.info("voice","voice-command",{tabId:t,label:v.label,transcript:d}),window.api.pty.write({tabId:t,data:v.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Hl();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&&zy(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{pt.error("voice","recognition error",{err:a}),Hl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,rg(),ss==null||ss.destroy(),ss=null,nf=null,lt.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)})});ss=p,nf=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),nh(),p.start().then(()=>{ss===p&&(Is==null||Is(),Is=o2(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),lt.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=>{pt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=ss;t&&(rg(),Hl(),ev=0,F_=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ss===t&&(ss=null,nf=null),e().hotkeyState==="stopping"&&(ag(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ss;if(!t)return;rg(),Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){pt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),ss===t&&(ss=null);const{useSessions:n}=await os(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>_E);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:()=>Hl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(pt.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"?pt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&&pt.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}=tv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){pt.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"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),lg(),Og={tabId:l,source:n,mode:r},Lg=Ct.subscribe((f,v)=>{if(Og&&f.modelStatus==="ready"&&v.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Og;if(lg(),!m.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),Ct.getState().startRecording(m.tabId)}});return}if(!l){pt.warn("voice-hotkey","no-active-tab",{source:n});return}pt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){lg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(lg(),Hl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(ag(),i({hotkeyState:"destroyed"}))}})),g2=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),tv=i=>vv()?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=Ct,i.__transcripts=[]}const v2=6e4,_2=5e3,Af=In(()=>({data:null,refreshing:!1}));let By=!1,Bg=null,Gy=null,Fy=!1;async function Wb(){Af.setState({refreshing:!0});let i=v2;try{const e=await Ob(window.api.billing.fetch(),_2,"billing.fetch");Af.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Gy==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Gy=e.kind}catch(e){if(Af.setState({refreshing:!1}),!Fy){Fy=!0;const t=e instanceof Error?e.message:String(e);lt.warn(`Billing usage fetch failed: ${t}`)}}Bg=setTimeout(Wb,i)}function b2(){By||(By=!0,Wb())}function B1(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 w2(){Bg!==null&&(clearTimeout(Bg),Bg=null),Wb()}function Ub(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 ug=new Map,y2=3e4;function Vb(i){const[e,t]=G.useState(()=>{var n;return i?((n=ug.get(i))==null?void 0:n.value)??null:null});return G.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=ug.get(i);if(l&&Date.now()-l.ts<y2){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;ug.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;ug.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function x2(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 W_="sm.almanac.sidebarWidth",G1=180,F1=480,U_=252;function S2(){try{const i=parseInt(localStorage.getItem(W_)??"",10);if(Number.isFinite(i))return Math.min(F1,Math.max(G1,i))}catch{}return U_}const C2=52,H1="sm.almanac.sidebarCollapsed";function k2(){try{return localStorage.getItem(H1)==="1"}catch{}return!1}const W1="sm.almanac.collapsedGroups";function E2(){try{const i=localStorage.getItem(W1);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 T2(){const i=xt(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:jr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function D2({active:i,onNavigate:e,onNewSession:t}){const[n,r]=G.useState(()=>E2()),l=G.useCallback(j=>{r(H=>{const U=new Set(H);U.has(j)?U.delete(j):U.add(j);try{localStorage.setItem(W1,JSON.stringify(Array.from(U)))}catch{}return U})},[]),[p,a]=G.useState(()=>k2()),d=G.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(H1,H?"1":"0")}catch{}return H})},[]),f=xt(j=>j.tabs),v=xt(j=>j.activeTabId),m=f.find(j=>j.id===v)??null,y=T2(),D=Ei(j=>j.navFace),E=xE(D),T=E.filter(j=>j.group==="Workspace"),b=E.filter(j=>j.group==="Configure"),C=x2(E),w=D==="home"&&!p,[x,$]=G.useState(()=>S2()),P=G.useRef(x);P.current=x;const N=G.useCallback(j=>{j.preventDefault();const H=j.clientX,U=P.current;let oe=U;const de=me=>{oe=Math.min(F1,Math.max(G1,U+(me.clientX-H))),$(oe)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(W_,String(oe))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=G.useCallback(()=>{$(U_);try{localStorage.setItem(W_,String(U_))}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?C2:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx($2,{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:w?h.jsxs(h.Fragment,{children:[h.jsx(Jv,{label:"Workspace",desc:Uv.Workspace,collapsed:n.has("Workspace"),count:T.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&T.map(j=>h.jsx(Zv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Jv,{label:"Configure",desc:Uv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Zv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Jv,{label:"Tools",desc:Uv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(Hy,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:E.map(j=>j.group==="Tools"?h.jsx(Hy,{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(Zv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(A2,{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 $2({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Vb((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(rs,{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(rs,{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(rs,{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(rs,{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(rs,{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(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Jv({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 Zv({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":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(rs,{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 Hy({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(rs,{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 A2({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=xt(d=>d.tabs),r=xt(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=G.useState(null);return G.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return l1(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 · ${Ub(p)}`:"Claude Code"})]})}const Cn={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},I2={dialog:50};function P2(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function R2(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 j2(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 v of["command","file_path","pattern","url","query","subagent_type","description"])d&&v in d&&(f[v]=d[v]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const v=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),y=typeof(v==null?void 0:v.file_path)=="string"?v.file_path:void 0,D=typeof(v==null?void 0:v.command)=="string"?v.command:void 0,E=y?y.split("/").pop()??y:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:E?`${a.name} · ${E}`:a.name,target:y??D,toolName:a.name}),m&&y&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(y.split("/").pop()??y,34)}`,target:y,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,v=a.output_tokens??a.outputTokens??0,m=d+f+v;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+v,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=P2(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Gg=In((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]:R2(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:v}=await os(async()=>{const{toast:m}=await Promise.resolve().then(()=>u1);return{toast:m}},void 0,import.meta.url);v.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:v}=j2(p,d,r);p=f,a=a.concat(v)}if(a.length>0){let d=l.activitySeq;const f=a.map(v=>({...v,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function N2(i){const e=Gg(r=>r.subscribe),t=Gg(r=>r.unsubscribe),n=Gg(r=>i?r.tabs[i.id]:void 0);return G.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 U1(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 V_(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function Wy(i,e){const t=V_(e);if(t==null)return`${i} — usage unavailable`;const n=U1((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 M2({onNavigate:i}){const e=xt(P=>P.tabs),t=xt(P=>P.activeTabId),n=e.find(P=>P.id===t)??null,r=N2(n),l=(r==null?void 0:r.lastEventAt)??0,p=Af(P=>P.data),a=jr(P=>{var N;return((N=P.snapshot)==null?void 0:N.paused)??null}),d=Vb((n==null?void 0:n.cwd)??null),[,f]=G.useState(0);G.useEffect(()=>{const P=setInterval(()=>f(N=>N+1),6e4);return()=>clearInterval(P)},[]);const v=(r==null?void 0:r.todos)??[],[m,y]=G.useState(!1),D=G.useRef(null);G.useEffect(()=>{if(!m)return;const P=N=>{D.current&&!D.current.contains(N.target)&&y(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[m]),G.useEffect(()=>{v.length===0&&y(!1)},[v.length]);const E=B1(p),T=(E==null?void 0:E.usage.five_hour)??null,b=(E==null?void 0:E.usage.seven_day)??null,C=V_(T),w=V_(b),x=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",$=l>0?z2(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:Wy("Session (5h window)",T),"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:Wy("Weekly window (all models)",b),"data-testid":"footer-usage-weekly",children:["weekly ",h.jsx("span",{className:"text-fg",children:w!=null?`${w}%`:"—"})]}),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:$})]}),v.length>0&&h.jsx(O2,{ref:D,todos:v,open:m,onToggle:()=>y(P=>!P)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.69.0"]})]})}const O2=G.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 ${Cn.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(L2,{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 L2({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 z2(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 B2({onClose:i,onSent:e}){const t=xt(L=>L.tabs),[n,r]=G.useState(""),[l,p]=G.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=G.useState(!1),[f,v]=G.useState({}),m=G.useRef(null),y=G.useRef(e);G.useEffect(()=>{y.current=e},[e]),G.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),G.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),G.useEffect(()=>window.api.pty.onWriteError(j=>{v(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),G.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>y.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),E=D.length,T=Object.keys(f).length>0,b=n.length>0&&E>0&&!a&&!T,C=()=>{if(!b)return;d(!0);const L=xt.getState().tabs,j=new Set(L.map(U=>U.id)),H={};for(const U of D)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),H[U]="sent"):H[U]="skipped";v(H),d(!1)},w=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]),$=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},P=Object.values(f).some(L=>L==="skipped"),N=T?P?"Sent (some skipped)":"Sent":`Send to ${E} tab${E===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:w,"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:$,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",E,"/",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 G2({tabId:i,cwd:e,onClose:t}){const n=Tf(E=>E.watchersForTab(i)),r=Tf(E=>E.add),l=Tf(E=>E.remove),p=G.useRef(null),[a,d]=G.useState(""),[f,v]=G.useState(""),[m,y]=G.useState(!1);G.useEffect(()=>{const E=T=>{T.key==="Escape"&&t()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]),G.useEffect(()=>{const E=T=>{p.current&&!p.current.contains(T.target)&&t()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[t]);const D=async()=>{const E=f.trim();if(!E||m)return;y(!0);const T=await r({tabId:i,label:a.trim(),command:E,cwd:e});y(!1),T&&(d(""),v(""))};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:E=>d(E.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:E=>v(E.target.value),onKeyDown:E=>{E.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(E=>{const T=E.lines[E.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:E.label}),h.jsxs("span",{className:"text-fg-faint",children:[E.lineCount," line",E.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(E.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${E.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:E.command,children:E.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(T==null?void 0:T.line)??"",children:T?T.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},E.watcherId)})})]})}/**
2910
+ */var $y;function FE(){return $y||($y=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof eo<"u"?eo:typeof Proxy<"u"?new Proxy(Y,{get:(se,he)=>(typeof eo<"u"?eo:se)[he]}):Y)(function(Y){if(typeof eo<"u")return eo.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 he in se)n(Y,he,{get:se[he],enumerable:!0})},v=(Y,se,he,Te)=>{if(se&&typeof se=="object"||typeof se=="function")for(let xe of l(se))!p.call(Y,xe)&&xe!==he&&n(Y,xe,{get:()=>se[xe],enumerable:!(Te=r(se,xe))||Te.enumerable});return Y},m=Y=>v(n({},"__esModule",{value:!0}),Y),y,D,E,T,b,C=d(()=>{y=new Map,D=[],E=(Y,se,he)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Te=y.get(Y);if(Te===void 0)y.set(Y,{backend:se,priority:he});else{if(Te.priority>he)return;if(Te.priority===he&&Te.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${he}`)}if(he>=0){let xe=D.indexOf(Y);xe!==-1&&D.splice(xe,1);for(let Oe=0;Oe<D.length;Oe++)if(y.get(D[Oe]).priority<=he){D.splice(Oe,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},T=async Y=>{let se=y.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let he=!!se.initPromise;try{return he||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Te){return he||(se.error=`${Te}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],he=se.map(Le=>typeof Le=="string"?Le:Le.name),Te=he.length===0?D:he,xe,Oe=[],$e=new Set;for(let Le of Te){let tt=await T(Le);typeof tt=="string"?Oe.push({name:Le,err:tt}):(xe||(xe=tt),xe===tt&&$e.add(Le))}if(!xe)throw new Error(`no available backend found. ERR: ${Oe.map(Le=>`[${Le.name}] ${Le.err}`).join(", ")}`);for(let{name:Le,err:tt}of Oe)he.includes(Le)&&console.warn(`removing requested execution provider "${Le}" from session options because it is not available: ${tt}`);let Ae=se.filter(Le=>$e.has(typeof Le=="string"?Le:Le.name));return[xe,new Proxy(Y,{get:(Le,tt)=>tt==="executionProviders"?Ae:Reflect.get(Le,tt)})]}}),w=d(()=>{C()}),x,$=d(()=>{x="1.26.0"}),P,N,L=d(()=>{$(),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}),U,oe,de=d(()=>{U=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=Y.dims[3],he.height=Y.dims[2];let Te=he.getContext("2d");if(Te!=null){let xe,Oe;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2]);let $e=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Le,tt;Ae===void 0||Ae.mean===void 0?Le=[255,255,255,255]:typeof Ae.mean=="number"?Le=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Le=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Le[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?tt=[0,0,0,0]:typeof Ae.bias=="number"?tt=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(tt=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(tt[3]=Ae.bias[3]));let rt=Oe*xe,it=0,qe=rt,It=rt*2,Ne=-1;$e==="RGBA"?(it=0,qe=rt,It=rt*2,Ne=rt*3):$e==="RGB"?(it=0,qe=rt,It=rt*2):$e==="RBG"&&(it=0,It=rt,qe=rt*2);for(let dt=0;dt<Oe;dt++)for(let Ci=0;Ci<xe;Ci++){let Zt=(Y.data[it++]-tt[0])*Le[0],Qt=(Y.data[qe++]-tt[1])*Le[1],ki=(Y.data[It++]-tt[2])*Le[2],Ot=Ne===-1?255:(Y.data[Ne++]-tt[3])*Le[3];Te.fillStyle="rgba("+Zt+","+Qt+","+ki+","+Ot+")",Te.fillRect(Ci,dt,1,1)}if("toDataURL"in he)return he.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},oe=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(he!=null){let xe,Oe,$e;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[1],$e=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2],$e=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Le=se==null?void 0:se.norm,tt,rt;Le===void 0||Le.mean===void 0?tt=[255,255,255,255]:typeof Le.mean=="number"?tt=[Le.mean,Le.mean,Le.mean,Le.mean]:(tt=[Le.mean[0],Le.mean[1],Le.mean[2],255],Le.mean[3]!==void 0&&(tt[3]=Le.mean[3])),Le===void 0||Le.bias===void 0?rt=[0,0,0,0]:typeof Le.bias=="number"?rt=[Le.bias,Le.bias,Le.bias,Le.bias]:(rt=[Le.bias[0],Le.bias[1],Le.bias[2],0],Le.bias[3]!==void 0&&(rt[3]=Le.bias[3]));let it=Oe*xe;if(se!==void 0&&(se.format!==void 0&&$e===4&&se.format!=="RGBA"||$e===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let qe=4,It=0,Ne=1,dt=2,Ci=3,Zt=0,Qt=it,ki=it*2,Ot=-1;Ae==="RGBA"?(Zt=0,Qt=it,ki=it*2,Ot=it*3):Ae==="RGB"?(Zt=0,Qt=it,ki=it*2):Ae==="RBG"&&(Zt=0,ki=it,Qt=it*2),Te=he.createImageData(xe,Oe);for(let Ri=0;Ri<Oe*xe;It+=qe,Ne+=qe,dt+=qe,Ci+=qe,Ri++)Te.data[It]=(Y.data[Zt++]-rt[0])*tt[0],Te.data[Ne]=(Y.data[Qt++]-rt[1])*tt[1],Te.data[dt]=(Y.data[ki++]-rt[2])*tt[2],Te.data[Ci]=Ot===-1?255:(Y.data[Ot++]-rt[3])*tt[3]}else throw new Error("Can not access image data");return Te}}),Z,me,ie,ue,Ce,Ee,W=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:he,width:Te}=se,xe=se.norm??{mean:255,bias:0},Oe,$e;typeof xe.mean=="number"?Oe=[xe.mean,xe.mean,xe.mean,xe.mean]:Oe=[xe.mean[0],xe.mean[1],xe.mean[2],xe.mean[3]??255],typeof xe.bias=="number"?$e=[xe.bias,xe.bias,xe.bias,xe.bias]:$e=[xe.bias[0],xe.bias[1],xe.bias[2],xe.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Le=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",tt=he*Te,rt=Le==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,qe=0,It=1,Ne=2,dt=3,Ci=0,Zt=tt,Qt=tt*2,ki=-1;Ae==="RGB"&&(it=3,qe=0,It=1,Ne=2,dt=-1),Le==="RGBA"?ki=tt*3:Le==="RBG"?(Ci=0,Qt=tt,Zt=tt*2):Le==="BGR"&&(Qt=0,Zt=tt,Ci=tt*2);for(let Ot=0;Ot<tt;Ot++,qe+=it,Ne+=it,It+=it,dt+=it)rt[Ci++]=(Y[qe]+$e[0])/Oe[0],rt[Zt++]=(Y[It]+$e[1])/Oe[1],rt[Qt++]=(Y[Ne]+$e[2])/Oe[2],ki!==-1&&dt!==-1&&(rt[ki++]=(Y[dt]+$e[3])/Oe[3]);return Le==="RGBA"?new X("float32",rt,[1,4,he,Te]):new X("float32",rt,[1,3,he,Te])},me=async(Y,se)=>{let he=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,xe=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Oe=typeof Y=="string",$e,Ae=se??{},Le=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(qe=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=qe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It;it.drawImage(Y,0,0),$e=it.getImageData(0,0,It,qe).data}else throw new Error("Can not access image data")}else if(Te){let rt,it;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,it=se.resizedWidth):(rt=Y.height,it=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=it,se!==void 0){let qe=Le();qe.width=it,qe.height=rt;let It=tt(qe);if(It!=null)It.putImageData(Y,0,0),$e=It.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else $e=Y.data}else if(xe){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;return it.drawImage(Y,0,0,It,qe),$e=it.getImageData(0,0,It,qe).data,Ae.height=qe,Ae.width=It,Z($e,Ae)}else throw new Error("Can not access image data")}else{if(Oe)return new Promise((rt,it)=>{let qe=Le(),It=tt(qe);if(!Y||!It)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=Y,Ne.onload=()=>{qe.width=Ne.width,qe.height=Ne.height,It.drawImage(Ne,0,0,qe.width,qe.height);let dt=It.getImageData(0,0,qe.width,qe.height);Ae.height=qe.height,Ae.width=qe.width,rt(Z(dt.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},ie=(Y,se)=>{let{width:he,height:Te,download:xe,dispose:Oe}=se,$e=[1,Te,he,4];return new X({location:"texture",type:"float32",texture:Y,dims:$e,download:xe,dispose:Oe})},ue=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"gpu-buffer",type:he??"float32",gpuBuffer:Y,dims:Te,download:xe,dispose:Oe})},Ce=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"ml-tensor",type:he??"float32",mlTensor:Y,dims:Te,download:xe,dispose:Oe})},Ee=(Y,se,he)=>new X({location:"cpu-pinned",type:Y,data:se,dims:he??[se.length]})}),te,K,re,ve,_e=d(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),re=!1,ve=()=>{if(!re){re=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,Te=typeof he<"u"&&he.from;Y&&(te.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),se&&(te.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),Te?(te.set("float16",he),K.set(he,"float16")):te.set("float16",Uint16Array)}}}),Me,et,we=d(()=>{Ie(),Me=Y=>{let se=1;for(let he=0;he<Y.length;he++){let Te=Y[he];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${he}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${Te}`);se*=Te}return se},et=(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(),W(),_e(),we(),X=class{constructor(Y,se,he){ve();let Te,xe;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,xe=Y.dims,Y.location){case"cpu-pinned":{let $e=te.get(Te);if(!$e)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(Y.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=Y.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" 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 $e,Ae;if(typeof Y=="string")if(Te=Y,Ae=he,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");$e=se}else{let Le=te.get(Y);if(Le===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Le===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Le.name} as data.`);Y==="uint64"||Y==="int64"?$e=Le.from(se,BigInt):$e=Le.from(se)}else if(se instanceof Le)$e=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")$e=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Le!==Uint16Array)$e=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Le}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Le=typeof Y[0];if(Le==="string")Te="string",$e=Y;else if(Le==="boolean")Te="bool",$e=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Le}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",$e=Uint8Array.from(Y);else{let Le=K.get(Y.constructor);if(Le===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Le,$e=Y}if(Ae===void 0)Ae=[$e.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");xe=Ae,this.cpuData=$e,this.dataLocation="cpu"}let Oe=Me(xe);if(this.cpuData&&Oe!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Oe/2)===this.cpuData.length))throw new Error(`Tensor's size(${Oe}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=xe,this.size=Oe}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return ie(Y,se)}static fromGpuBuffer(Y,se){return ue(Y,se)}static fromMLTensor(Y,se){return Ce(Y,se)}static fromPinnedBuffer(Y,se,he){return Ee(Y,se,he)}toDataURL(Y){return U(this,Y)}toImageData(Y){return oe(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 et(this,Y)}}}),pe,Ze=d(()=>{Ie(),pe=X}),ge,Ke,vt,st,Kt,Be,Dt=d(()=>{L(),ge=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},Ke=(Y,se)=>{var xe;let he=((xe=new Error().stack)==null?void 0:xe.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Oe=0;Oe<he.length;Oe++){if(Te&&!he[Oe].includes("TRACE_FUNC")){let $e=`FUNC_${Y}::${he[Oe].trim().split(" ")[1]}`;se&&($e+=`::${se}`),ge("CPU",$e);return}he[Oe].includes("TRACE_FUNC")&&(Te=!0)}},vt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("BEGIN",Y)},st=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("END",Y)},Kt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Be=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),_t,ri=d(()=>{C(),Ze(),Dt(),_t=class A1{constructor(se){this.handler=se}async run(se,he,Te){vt(),Kt("InferenceSession.run");let xe={},Oe={};if(typeof se!="object"||se===null||se instanceof pe||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof pe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(he)){if(he.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of he){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);xe[tt]=null}if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let qe=he[it];(qe===null||qe instanceof pe)&&(tt=!0,$e=!1,xe[it]=qe)}if(tt){if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Oe=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof se[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)xe[tt]=null;let Ae=await this.handler.run(se,xe,Oe),Le={};for(let tt in Ae)if(Object.hasOwnProperty.call(Ae,tt)){let rt=Ae[tt];rt instanceof pe?Le[tt]=rt:Le[tt]=new pe(rt.type,rt.data,rt.dims)}return Be("InferenceSession.run"),st(),Le}async release(){return this.handler.dispose()}static async create(se,he,Te,xe){vt(),Kt("InferenceSession.create");let Oe,$e={};if(typeof se=="string"){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,it=0,qe=se.byteLength;if(typeof he=="object"&&he!==null)$e=he;else if(typeof he=="number"){if(it=he,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(qe=se.byteLength-it,typeof Te=="number"){if(qe=Te,!Number.isSafeInteger(qe))throw new RangeError("'byteLength' must be an integer.");if(qe<=0||it+qe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof xe=="object"&&xe!==null)$e=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Oe=new Uint8Array(rt,it,qe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Le]=await b($e),tt=await Ae.createInferenceSessionHandler(Oe,Le);return Be("InferenceSession.create"),st(),new A1(tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Ye,St=d(()=>{ri(),Ye=_t}),ut=d(()=>{}),Xe=d(()=>{}),Pt=d(()=>{}),oi=d(()=>{}),Fi={};f(Fi,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,env:()=>j,registerBackend:()=>E});var li=d(()=>{w(),H(),St(),Ze(),ut(),Xe(),Dt(),Pt(),oi()}),tn=d(()=>{}),Ii={};f(Ii,{default:()=>pr});var Ui,ui,pr,ga=d(()=>{var Y;fe(),Hn(),Fn(),Ui="ort-wasm-proxy-worker",ui=((Y=globalThis.self)==null?void 0:Y.name)===Ui,ui&&(self.onmessage=se=>{let{type:he,in:Te}=se.data;try{switch(he){case"init-wasm":Js(Te.wasm).then(()=>{Lo(Te).then(()=>{postMessage({type:he})},xe=>{postMessage({type:he,err:xe})})},xe=>{postMessage({type:he,err:xe})});break;case"init-ep":{let{epName:xe,env:Oe}=Te;wr(Oe,xe).then(()=>{postMessage({type:he})},$e=>{postMessage({type:he,err:$e})});break}case"copy-from":{let{buffer:xe}=Te,Oe=ni(xe);postMessage({type:he,out:Oe});break}case"create":{let{model:xe,options:Oe}=Te;us(xe,Oe).then($e=>{postMessage({type:he,out:$e})},$e=>{postMessage({type:he,err:$e})});break}case"release":zr(Te),postMessage({type:he});break;case"run":{let{sessionId:xe,inputIndices:Oe,inputs:$e,outputIndices:Ae,options:Le}=Te;Ve(xe,Oe,$e,Ae,new Array(Ae.length).fill(null),Le).then(tt=>{tt.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:tt},ft([...$e,...tt]))},tt=>{postMessage({type:he,err:tt})});break}case"end-profiling":Un(Te),postMessage({type:he});break;default:}}catch(xe){postMessage({type:he,err:xe})}}),pr=ui?null:se=>new Worker(se??vi,{type:"classic",name:Ui})}),Mo,fr,vi,Gn,nn,mr,Rs,as,Mr,gr,vr,js,Pn,Fn=d(()=>{tn(),Mo=typeof location>"u"?void 0:location.origin,fr=()=>{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},vi=fr(),Gn=()=>{if(vi&&!vi.startsWith("blob:"))return vi.substring(0,vi.lastIndexOf("/")+1)},nn=(Y,se)=>{try{let he=se??vi;return(he?new URL(Y,he):new URL(Y)).origin===Mo}catch{return!1}},mr=(Y,se)=>{let he=se??vi;try{return(he?new URL(Y,he):new URL(Y)).href}catch{return}},Rs=(Y,se)=>`${se??"./"}${Y}`,as=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},Mr=async Y=>(await import(Y)).default,gr=(ga(),m(Ii)).default,vr=async()=>{if(!vi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(vi))return[void 0,gr()];let Y=await as(vi);return[Y,gr(Y)]},js=void 0,Pn=async(Y,se,he,Te)=>{let xe=js&&!(Y||se);if(xe)if(vi)xe=nn(vi)||Te&&!he;else if(Te&&!he)xe=!0;else throw new Error("cannot determine the script source URL.");if(xe)return[void 0,js];{let Oe="ort-wasm-simd-threaded.mjs",$e=Y??mr(Oe,se),Ae=he&&$e&&!nn($e,se),Le=Ae?await as($e):$e??Rs(Oe,se);return[Ae?Le:void 0,await Mr(Le)]}}}),Ks,Rn,ls,Es,no,Ys,Xs,Js,zt,Hn=d(()=>{Fn(),Rn=!1,ls=!1,Es=!1,no=()=>{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}},Ys=()=>{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}},Xs=()=>{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}},Js=async Y=>{if(Rn)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let se=Y.initTimeout,he=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!Xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ys())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=no();he>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+he+", 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=he=1);let xe=Y.wasmPaths,Oe=typeof xe=="string"?xe:void 0,$e=xe==null?void 0:xe.mjs,Ae=($e==null?void 0:$e.href)??$e,Le=xe==null?void 0:xe.wasm,tt=(Le==null?void 0:Le.href)??Le,rt=Y.wasmBinary,[it,qe]=await Pn(Ae,Oe,he>1,!!rt||!!tt),It=!1,Ne=[];if(se>0&&Ne.push(new Promise(dt=>{setTimeout(()=>{It=!0,dt()},se)})),Ne.push(new Promise((dt,Ci)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(tt||Oe)Zt.locateFile=Qt=>tt??Oe+Qt;else if(Ae&&Ae.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Ae).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=ki=>Qt+ki)}qe(Zt).then(Qt=>{ls=!1,Rn=!0,Ks=Qt,dt(),it&&URL.revokeObjectURL(it)},Qt=>{ls=!1,Es=!0,Ci(Qt)})})),await Promise.race(Ne),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Hi,yi,kt,Or=d(()=>{Hn(),Hi=(Y,se)=>{let he=zt(),Te=he.lengthBytesUTF8(Y)+1,xe=he._malloc(Te);return he.stringToUTF8(Y,xe,Te),se.push(xe),xe},yi=(Y,se,he,Te)=>{if(typeof Y=="object"&&Y!==null){if(he.has(Y))throw new Error("Circular reference in options");he.add(Y)}Object.entries(Y).forEach(([xe,Oe])=>{let $e=se?se+xe:xe;if(typeof Oe=="object")yi(Oe,$e+".",he,Te);else if(typeof Oe=="string"||typeof Oe=="number")Te($e,Oe.toString());else if(typeof Oe=="boolean")Te($e,Oe?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Oe}`)})},kt=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetLastError(xe,xe+Te);let Oe=Number(se.getValue(xe,Te===4?"i32":"i64")),$e=se.getValue(xe+Te,"*"),Ae=$e?se.UTF8ToString($e):"";throw new Error(`${Y} ERROR_CODE: ${Oe}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(he)}}}),so,va=d(()=>{Hn(),Or(),so=Y=>{let se=zt(),he=0,Te=[],xe=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)xe.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)xe.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&&(xe.terminate=!1);let Oe=0;return(Y==null?void 0:Y.tag)!==void 0&&(Oe=Hi(Y.tag,Te)),he=se._OrtCreateRunOptions(xe.logSeverityLevel,xe.logVerbosityLevel,!!xe.terminate,Oe),he===0&&kt("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&yi(Y.extra,"",new WeakSet,($e,Ae)=>{let Le=Hi($e,Te),tt=Hi(Ae,Te);se._OrtAddRunConfigEntry(he,Le,tt)!==0&&kt(`Can't set a run config entry: ${$e} - ${Ae}.`)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseRunOptions(he),Te.forEach($e=>se._free($e)),Oe}}}),ro,oo,Oo,kn,_a,ba,xi=d(()=>{Hn(),Or(),ro=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}`)}},oo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},Oo=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(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(Y.enableMemPattern=!1)},kn=(Y,se,he,Te)=>{let xe=Hi(se,Te),Oe=Hi(he,Te);zt()._OrtAddSessionConfigEntry(Y,xe,Oe)!==0&&kt(`Can't set a session config entry: ${se} - ${he}.`)},_a=async(Y,se,he)=>{let Te=se.executionProviders;for(let xe of Te){let Oe=typeof xe=="string"?xe:xe.name,$e=[];switch(Oe){case"webnn":if(Oe="WEBNN",kn(Y,"session.disable_quant_qdq","1",he),kn(Y,"session.disable_qdq_constant_folding","1",he),typeof xe!="string"){let it=xe==null?void 0:xe.deviceType;it&&kn(Y,"deviceType",it,he)}break;case"webgpu":if(Oe="JS",typeof xe!="string"){let it=xe;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);kn(Y,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Oe}`)}let Ae=Hi(Oe,he),Le=$e.length,tt=0,rt=0;if(Le>0){tt=zt()._malloc(Le*zt().PTR_SIZE),he.push(tt),rt=zt()._malloc(Le*zt().PTR_SIZE),he.push(rt);for(let it=0;it<Le;it++)zt().setValue(tt+it*zt().PTR_SIZE,$e[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,$e[it][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,tt,rt,Le)!==0&&kt(`Can't append execution provider: ${Oe}.`)}},ba=async Y=>{let se=zt(),he=0,Te=[],xe=Y||{};Oo(xe);try{let Oe=ro(xe.graphOptimizationLevel??"all"),$e=oo(xe.executionMode??"sequential"),Ae=typeof xe.logId=="string"?Hi(xe.logId,Te):0,Le=xe.logSeverityLevel??2;if(!Number.isInteger(Le)||Le<0||Le>4)throw new Error(`log severity level is not valid: ${Le}`);let tt=xe.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let rt=typeof xe.optimizedModelFilePath=="string"?Hi(xe.optimizedModelFilePath,Te):0;if(he=se._OrtCreateSessionOptions(Oe,!!xe.enableCpuMemArena,!!xe.enableMemPattern,$e,!!xe.enableProfiling,0,Ae,Le,tt,rt),he===0&&kt("Can't create session options."),xe.executionProviders&&await _a(he,xe,Te),xe.enableGraphCapture!==void 0){if(typeof xe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${xe.enableGraphCapture}`);kn(he,"enableGraphCapture",xe.enableGraphCapture.toString(),Te)}if(xe.freeDimensionOverrides)for(let[it,qe]of Object.entries(xe.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof qe!="number"||!Number.isInteger(qe)||qe<0)throw new Error(`free dimension override value must be a non-negative integer: ${qe}`);let It=Hi(it,Te);se._OrtAddFreeDimensionOverride(he,It,qe)!==0&&kt(`Can't set a free dimension override: ${it} - ${qe}.`)}return xe.extra!==void 0&&yi(xe.extra,"",new WeakSet,(it,qe)=>{kn(he,it,qe,Te)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseSessionOptions(he)!==0&&kt("Can't release session options."),Te.forEach($e=>se._free($e)),Oe}}}),jn,Vi,Nn,Zs,Lr,_r,cs,gn,Bt=d(()=>{jn=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}`)}},Vi=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}`)}},Nn=(Y,se)=>{let he=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Y],Te=typeof se=="number"?se:se.reduce((xe,Oe)=>xe*Oe,1);return he>0?Math.ceil(Te*he):void 0},Zs=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}`)}},Lr=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}`)}},_r=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",cs=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",gn=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}`)}}}),qi,br=d(()=>{tn(),qi=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 he=se.headers.get("Content-Length"),Te=he?parseInt(he,10):0;if(Te<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let xe=se.body.getReader(),Oe;try{Oe=new ArrayBuffer(Te)}catch(Ae){if(Ae instanceof RangeError){let Le=Math.ceil(Te/65536);Oe=new WebAssembly.Memory({initial:Le,maximum:Le}).buffer}else throw Ae}let $e=0;for(;;){let{done:Ae,value:Le}=await xe.read();if(Ae)break;let tt=Le.byteLength;new Uint8Array(Oe,$e,tt).set(Le),$e+=tt}return new Uint8Array(Oe,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),ds,Lo,wr,Wn,Ns,yr,ni,us,zr,Ts,Ve,Un,ft,fe=d(()=>{li(),va(),xi(),Bt(),Hn(),Or(),br(),ds=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&kt("Can't initialize onnxruntime.")},Lo=async Y=>{ds(Y.wasm.numThreads,Lr(Y.logLevel))},wr=async(Y,se)=>{var Te,xe;(xe=(Te=zt()).asyncInit)==null||xe.call(Te);let he=Y.webgpu.adapter;if(se==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(he){if(typeof he.limits!="object"||typeof he.features!="object"||typeof he.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Oe=Y.webgpu.powerPreference;if(Oe!==void 0&&Oe!=="low-power"&&Oe!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Oe}"`);let $e=Y.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Oe,forceFallbackAdapter:$e}),!he)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")},Wn=new Map,Ns=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetInputOutputCount(Y,xe,xe+Te)!==0&&kt("Can't get session input/output count.");let Oe=Te===4?"i32":"i64";return[Number(se.getValue(xe,Oe)),Number(se.getValue(xe+Te,Oe))]}finally{se.stackRestore(he)}},yr=(Y,se)=>{let he=zt(),Te=he.stackSave(),xe=0;try{let Oe=he.PTR_SIZE,$e=he.stackAlloc(2*Oe);he._OrtGetInputOutputMetadata(Y,se,$e,$e+Oe)!==0&&kt("Can't get session input/output metadata.");let Ae=Number(he.getValue($e,"*"));xe=Number(he.getValue($e+Oe,"*"));let Le=he.HEAP32[xe/4];if(Le===0)return[Ae,0];let tt=he.HEAPU32[xe/4+1],rt=[];for(let it=0;it<tt;it++){let qe=Number(he.getValue(xe+8+it*Oe,"*"));rt.push(qe!==0?he.UTF8ToString(qe):Number(he.getValue(xe+8+(it+tt)*Oe,"*")))}return[Ae,Le,rt]}finally{he.stackRestore(Te),xe!==0&&he._OrtFree(xe)}},ni=Y=>{let se=zt(),he=se._malloc(Y.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,he),[he,Y.byteLength]},us=async(Y,se)=>{var rt,it,qe;let he,Te,xe=zt();Array.isArray(Y)?[he,Te]=Y:Y.buffer===xe.HEAPU8.buffer?[he,Te]=[Y.byteOffset,Y.byteLength]:[he,Te]=ni(Y);let Oe=0,$e=0,Ae=[],Le=[],tt=[];try{if([$e,Ae]=await ba(se),(se==null?void 0:se.externalData)&&xe.mountExternalData){let Ri=[];for(let ci of se.externalData){let vn=typeof ci=="string"?ci:ci.path;Ri.push(qi(typeof ci=="string"?ci:ci.data).then(Mn=>{xe.mountExternalData(vn,Mn)}))}await Promise.all(Ri)}for(let Ri of(se==null?void 0:se.executionProviders)??[])if((typeof Ri=="string"?Ri:Ri.name)==="webnn"){if(xe.shouldTransferToMLTensor=!1,typeof Ri!="string"){let ci=Ri,vn=ci==null?void 0:ci.context,Mn=ci==null?void 0:ci.gpuDevice,Vn=ci==null?void 0:ci.deviceType,ya=ci==null?void 0:ci.powerPreference;vn?xe.currentContext=vn:Mn?xe.currentContext=await xe.webnnCreateMLContext(Mn):xe.currentContext=await xe.webnnCreateMLContext({deviceType:Vn,powerPreference:ya})}else xe.currentContext=await xe.webnnCreateMLContext();break}Oe=await xe._OrtCreateSession(he,Te,$e),(rt=xe.webgpuOnCreateSession)==null||rt.call(xe,Oe),Oe===0&&kt("Can't create a session."),(it=xe.jsepOnCreateSession)==null||it.call(xe),xe.currentContext&&(xe.webnnRegisterMLContext(Oe,xe.currentContext),xe.currentContext=void 0,xe.shouldTransferToMLTensor=!0);let[It,Ne]=Ns(Oe),dt=!!(se!=null&&se.enableGraphCapture),Ci=[],Zt=[],Qt=[],ki=[],Ot=[];for(let Ri=0;Ri<It;Ri++){let[ci,vn,Mn]=yr(Oe,Ri);ci===0&&kt("Can't get an input name."),Le.push(ci);let Vn=xe.UTF8ToString(ci);Ci.push(Vn),Qt.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}for(let Ri=0;Ri<Ne;Ri++){let[ci,vn,Mn]=yr(Oe,Ri+It);ci===0&&kt("Can't get an output name."),tt.push(ci);let Vn=xe.UTF8ToString(ci);Zt.push(Vn),ki.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}return Wn.set(Oe,[Oe,Le,tt,null,dt,!1]),[Oe,Ci,Zt,Qt,ki]}catch(It){throw Le.forEach(Ne=>xe._OrtFree(Ne)),tt.forEach(Ne=>xe._OrtFree(Ne)),Oe!==0&&xe._OrtReleaseSession(Oe)!==0&&kt("Can't release session."),It}finally{xe._free(he),$e!==0&&xe._OrtReleaseSessionOptions($e)!==0&&kt("Can't release session options."),Ae.forEach(It=>xe._free(It)),(qe=xe.unmountExternalData)==null||qe.call(xe)}},zr=Y=>{var Le,tt,rt;let se=zt(),he=Wn.get(Y);if(!he)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,xe,Oe,$e,Ae]=he;$e&&(Ae&&se._OrtClearBoundOutputs($e.handle)!==0&&kt("Can't clear bound outputs."),se._OrtReleaseBinding($e.handle)!==0&&kt("Can't release IO binding.")),(Le=se.jsepOnReleaseSession)==null||Le.call(se,Y),(tt=se.webnnOnReleaseSession)==null||tt.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),xe.forEach(it=>se._OrtFree(it)),Oe.forEach(it=>se._OrtFree(it)),se._OrtReleaseSession(Te)!==0&&kt("Can't release session."),Wn.delete(Y)},Ts=async(Y,se,he,Te,xe,Oe,$e=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Le=Ae.PTR_SIZE,tt=Y[0],rt=Y[1],it=Y[3],qe=it,It,Ne;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Oe} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=Y[2].gpuBuffer;Ne=Nn(jn(tt),rt);{let Qt=Ae.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=Qt(Te,Oe,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=Y[2].mlTensor;Ne=Nn(jn(tt),rt);let Qt=Ae.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=Qt(Te,Zt,jn(tt),rt)}else{let Zt=Y[2];if(Array.isArray(Zt)){Ne=Le*Zt.length,It=Ae._malloc(Ne),he.push(It);for(let Qt=0;Qt<Zt.length;Qt++){if(typeof Zt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Ae.setValue(It+Qt*Le,Hi(Zt[Qt],he),"*")}}else{let Qt=Ae.webnnIsGraphInput,ki=Ae.webnnIsGraphOutput;if(tt!=="string"&&Qt&&ki){let Ot=Ae.UTF8ToString(xe);if(Qt(Te,Ot)||ki(Te,Ot)){let Ri=jn(tt);Ne=Nn(Ri,rt),qe="ml-tensor";let ci=Ae.webnnCreateTemporaryTensor,vn=Ae.webnnUploadTensor;if(!ci||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Mn=await ci(Te,Ri,rt);vn(Mn,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),It=Mn}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}}let dt=Ae.stackSave(),Ci=Ae.stackAlloc(4*rt.length);try{rt.forEach((Qt,ki)=>Ae.setValue(Ci+ki*Le,Qt,Le===4?"i32":"i64"));let Zt=Ae._OrtCreateTensor(jn(tt),It,Ne,Ci,rt.length,gn(qe));Zt===0&&kt(`Can't create tensor for input/output. session=${Te}, index=${Oe}.`),se.push(Zt)}finally{Ae.stackRestore(dt)}},Ve=async(Y,se,he,Te,xe,Oe)=>{var qn,ol,ic;let $e=zt(),Ae=$e.PTR_SIZE,Le=Wn.get(Y);if(!Le)throw new Error(`cannot run inference. invalid session id: ${Y}`);let tt=Le[0],rt=Le[1],it=Le[2],qe=Le[3],It=Le[4];Le[5];let Ne=se.length,dt=Te.length,Ci=0,Zt=[],Qt=[],ki=[],Ot=[],Ri=[],ci=$e.stackSave(),vn=$e.stackAlloc(Ne*Ae),Mn=$e.stackAlloc(Ne*Ae),Vn=$e.stackAlloc(dt*Ae),ya=$e.stackAlloc(dt*Ae);try{[Ci,Zt]=so(Oe),Kt("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)await Ts(he[ai],Qt,Ot,Y,rt[se[ai]],se[ai],It);for(let ai=0;ai<dt;ai++)await Ts(xe[ai],ki,Ot,Y,it[Te[ai]],Ne+Te[ai],It);Be("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)$e.setValue(vn+ai*Ae,Qt[ai],"*"),$e.setValue(Mn+ai*Ae,rt[se[ai]],"*");for(let ai=0;ai<dt;ai++)$e.setValue(Vn+ai*Ae,ki[ai],"*"),$e.setValue(ya+ai*Ae,it[Te[ai]],"*");(qn=$e.jsepOnRunStart)==null||qn.call($e,tt),(ol=$e.webnnOnRunStart)==null||ol.call($e,tt);let _n;_n=await $e._OrtRun(tt,Mn,vn,Ne,ya,dt,Vn,Ci),_n!==0&&kt("failed to call OrtRun().");let er=[],nc=[];Kt("wasm ProcessOutputTensor");for(let ai=0;ai<dt;ai++){let Os=Number($e.getValue(Vn+ai*Ae,"*"));if(Os===ki[ai]||Ri.includes(ki[ai])){er.push(xe[ai]),Os!==ki[ai]&&$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.");continue}let dd=$e.stackSave(),Cr=$e.stackAlloc(4*Ae),zo=!1,an,Kn=0;try{$e._OrtGetTensorData(Os,Cr,Cr+Ae,Cr+2*Ae,Cr+3*Ae)!==0&&kt(`Can't access output tensor data on index ${ai}.`);let al=Ae===4?"i32":"i64",Yn=Number($e.getValue(Cr,al));Kn=$e.getValue(Cr+Ae,"*");let sc=$e.getValue(Cr+Ae*2,"*"),ud=Number($e.getValue(Cr+Ae*3,al)),kr=[];for(let ln=0;ln<ud;ln++)kr.push(Number($e.getValue(sc+ln*Ae,al)));$e._OrtFree(sc)!==0&&kt("Can't free memory for tensor dims.");let Ls=kr.reduce((ln,Wi)=>ln*Wi,1);an=Vi(Yn);let tr=qe==null?void 0:qe.outputPreferredLocations[Te[ai]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Wi=0;Wi<Ls;Wi++){let zs=$e.getValue(Kn+Wi*Ae,"*"),rc=$e.getValue(Kn+(Wi+1)*Ae,"*"),oc=Wi===Ls-1?void 0:rc-zs;ln.push($e.UTF8ToString(zs,oc))}er.push([an,kr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ls>0){let ln=$e.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wi=ln(Kn),zs=Nn(Yn,Ls);if(zs===void 0||!_r(an))throw new Error(`Unsupported data type: ${an}`);zo=!0,er.push([an,kr,{gpuBuffer:Wi,download:$e.jsepCreateDownloader(Wi,zs,an),dispose:()=>{$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ls>0){let ln=$e.webnnEnsureTensor,Wi=$e.webnnIsGraphInputOutputTypeSupported;if(!ln||!Wi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Nn(Yn,Ls)===void 0||!cs(an))throw new Error(`Unsupported data type: ${an}`);if(!Wi(Y,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let zs=await ln(Y,Kn,Yn,kr,!1);zo=!0,er.push([an,kr,{mlTensor:zs,download:$e.webnnCreateMLTensorDownloader(Kn,an),dispose:()=>{$e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ls>0){let ln=$e.webnnCreateMLTensorDownloader(Kn,an)(),Wi=er.length;zo=!0,nc.push((async()=>{let zs=[Wi,await ln];return $e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os),zs})()),er.push([an,kr,[],"cpu"])}else{let ln=Zs(an),Wi=new ln(Ls);new Uint8Array(Wi.buffer,Wi.byteOffset,Wi.byteLength).set($e.HEAPU8.subarray(Kn,Kn+Wi.byteLength)),er.push([an,kr,Wi,"cpu"])}}finally{$e.stackRestore(dd),an==="string"&&Kn&&$e._free(Kn),zo||$e._OrtReleaseTensor(Os)}}qe&&!It&&($e._OrtClearBoundOutputs(qe.handle)!==0&&kt("Can't clear bound outputs."),Wn.set(Y,[tt,rt,it,qe,It,!1]));for(let[ai,Os]of await Promise.all(nc))er[ai][2]=Os;return Be("wasm ProcessOutputTensor"),er}finally{(ic=$e.webnnOnRunEnd)==null||ic.call($e,tt),$e.stackRestore(ci),Qt.forEach(_n=>$e._OrtReleaseTensor(_n)),ki.forEach(_n=>$e._OrtReleaseTensor(_n)),Ot.forEach(_n=>$e._free(_n)),Ci!==0&&$e._OrtReleaseRunOptions(Ci),Zt.forEach(_n=>$e._free(_n))}},Un=Y=>{let se=zt(),he=Wn.get(Y);if(!he)throw new Error("invalid session id");let Te=he[0],xe=se._OrtEndProfiling(Te);xe===0&&kt("Can't get an profile file name."),se._OrtFree(xe)},ft=Y=>{let se=[];for(let he of Y){let Te=he[2];!Array.isArray(Te)&&"buffer"in Te&&se.push(Te.buffer)}return se}}),Re,Je,Tt,ti,si,Pi,Ti,sn,Oi,on,Di,Ms,Br,ao,Qs,cd,lo,co,Ql=d(()=>{li(),fe(),Hn(),Fn(),Re=()=>!!j.wasm.proxy&&typeof document<"u",Tt=!1,ti=!1,si=!1,sn=new Map,Oi=(Y,se)=>{let he=sn.get(Y);he?he.push(se):sn.set(Y,[se])},on=()=>{if(Tt||!ti||si||!Je)throw new Error("worker not ready")},Di=Y=>{switch(Y.data.type){case"init-wasm":Tt=!1,Y.data.err?(si=!0,Ti[1](Y.data.err)):(ti=!0,Ti[0]()),Pi&&(URL.revokeObjectURL(Pi),Pi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=sn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Ms=async()=>{if(!ti){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(si)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Re())return new Promise((Y,se)=>{Je==null||Je.terminate(),vr().then(([he,Te])=>{try{Je=Te,Je.onerror=Oe=>se(Oe),Je.onmessage=Di,Ti=[Y,se];let xe={type:"init-wasm",in:j};if(!xe.in.wasm.wasmPaths&&he){let Oe=Gn();Oe&&(xe.in.wasm.wasmPaths=Oe)}Je.postMessage(xe),Pi=he}catch(xe){se(xe)}},se)});try{await Js(j.wasm),await Lo(j),ti=!0}catch(Y){throw si=!0,Y}finally{Tt=!1}}},Br=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("init-ep",[se,he]);let Te={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Te)});await wr(j,Y)},ao=async Y=>Re()?(on(),new Promise((se,he)=>{Oi("copy-from",[se,he]);let Te={type:"copy-from",in:{buffer:Y}};Je.postMessage(Te,[Y.buffer])})):ni(Y),Qs=async(Y,se)=>{if(Re()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,Te)=>{Oi("create",[he,Te]);let xe={type:"create",in:{model:Y,options:{...se}}},Oe=[];Y instanceof Uint8Array&&Oe.push(Y.buffer),Je.postMessage(xe,Oe)})}else return us(Y,se)},cd=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("release",[se,he]);let Te={type:"release",in:Y};Je.postMessage(Te)});zr(Y)},lo=async(Y,se,he,Te,xe,Oe)=>{if(Re()){if(he.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(xe.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise(($e,Ae)=>{Oi("run",[$e,Ae]);let Le=he,tt={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Le,outputIndices:Te,options:Oe}};Je.postMessage(tt,ft(Le))})}else return Ve(Y,se,he,Te,xe,Oe)},co=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("end-profiling",[se,he]);let Te={type:"end-profiling",in:Y};Je.postMessage(Te)});Un(Y)}}),il,uo,wa,nl=d(()=>{li(),Ql(),Bt(),tn(),br(),il=(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()}`)}},uo=Y=>{switch(Y[3]){case"cpu":return new pe(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!_r(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:he,download:Te,dispose:xe}=Y[2];return pe.fromGpuBuffer(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}case"ml-tensor":{let se=Y[0];if(!cs(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:he,download:Te,dispose:xe}=Y[2];return pe.fromMLTensor(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}default:throw new Error(`invalid data location: ${Y[3]}`)}},wa=class{async fetchModelAndCopyToWasmMemory(Y){return ao(await qi(Y))}async loadModel(Y,se){vt();let he;typeof Y=="string"?he=await this.fetchModelAndCopyToWasmMemory(Y):he=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,se),st()}async dispose(){return cd(this.sessionId)}async run(Y,se,he){vt();let Te=[],xe=[];Object.entries(Y).forEach(it=>{let qe=it[0],It=it[1],Ne=this.inputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid input '${qe}'`);Te.push(It),xe.push(Ne)});let Oe=[],$e=[];Object.entries(se).forEach(it=>{let qe=it[0],It=it[1],Ne=this.outputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid output '${qe}'`);Oe.push(It),$e.push(Ne)});let Ae=Te.map((it,qe)=>il(it,()=>`input "${this.inputNames[xe[qe]]}"`)),Le=Oe.map((it,qe)=>it?il(it,()=>`output "${this.outputNames[$e[qe]]}"`):null),tt=await lo(this.sessionId,xe,Ae,$e,Le,he),rt={};for(let it=0;it<tt.length;it++)rt[this.outputNames[$e[it]]]=Oe[it]??uo(tt[it]);return st(),rt}startProfiling(){}endProfiling(){co(this.sessionId)}}}),xr={};f(xr,{OnnxruntimeWebAssemblyBackend:()=>Sr,initializeFlags:()=>Gr,wasmBackend:()=>ho});var Gr,Sr,ho,ec=d(()=>{li(),Ql(),nl(),Gr=()=>{(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))}},Sr=class{async init(Y){Gr(),await Ms(),await Br(Y)}async createInferenceSessionHandler(Y,se){let he=new wa;return await he.loadModel(Y,se),he}},ho=new Sr}),tc={};f(tc,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,default:()=>rl,env:()=>j,registerBackend:()=>E}),li(),li(),li();var sl="1.26.0",rl=Fi;{let Y=(ec(),m(xr)).wasmBackend;E("cpu",Y,10),E("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:sl,enumerable:!0}),m(tc)})();i.exports=t})(Yv)),Yv.exports}var Ay;function HE(){return Ay||(Ay=1,(function(i){var e=Ua&&Ua.__createBinding||(Object.create?(function(x,$,P,N){N===void 0&&(N=P);var L=Object.getOwnPropertyDescriptor($,P);(!L||("get"in L?!$.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return $[P]}}),Object.defineProperty(x,N,L)}):(function(x,$,P,N){N===void 0&&(N=P),x[N]=$[P]})),t=Ua&&Ua.__setModuleDefault||(Object.create?(function(x,$){Object.defineProperty(x,"default",{enumerable:!0,value:$})}):function(x,$){x.default=$}),n=Ua&&Ua.__importStar||function(x){if(x&&x.__esModule)return x;var $={};if(x!=null)for(var P in x)P!=="default"&&Object.prototype.hasOwnProperty.call(x,P)&&e($,x,P);return t($,x),$};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(FE()),l=Fb(),p=Hb(),a=Yf(),d=gv(),f=D1(),v=$1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",y="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",E=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 $=>{$.getTracks().forEach(P=>{P.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:$=>{$.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=E;const T=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,$,P,N,L){await P.audioWorklet.addModule(x),$.processorOptions={...$.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(P,"vad-helper-worklet",$);return j.port.onmessage=async H=>{const U=H.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case d.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const oe=new Float32Array(U.data);await L(oe);break}}},j}async function C(x,$,P){const N=new v.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:$});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async U=>{if(!H){H=!0;try{const oe=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=N.process(oe);for(const me of Z)await P(me)}catch(oe){console.error("Error processing audio:",oe)}finally{H=!1}}},j.connect(x.destination),j}class w{constructor($,P,N,L,j=!1,H=null,U=null,oe=null,de=null,Z=null,me=null,ie="uninitialized",ue=!1){this.options=$,this.frameProcessor=P,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=U,this._audioContext=oe,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=ie,this.ownsAudioContext=ue,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=Ce=>{this.initializationState="errored",this.errored=Ce},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(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}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"?T(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:Ce,audioContext:Ee,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const te=new MediaStreamAudioSourceNode(Ee,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(W);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:Ce,mediaStreamAudioSourceNode:Ee}=this.getAudioInstances();await this.options.pauseStream(Ce),Ee.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ee;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ee=this._audioContext)==null?void 0:Ee.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.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(Ce.audio);break}}}static async new($={}){const P={...(0,i.getDefaultRealTimeVADOptions)($.model??i.DEFAULT_MODEL),...$};(0,p.validateOptions)(P),i.ort.env.wasm.wasmPaths=P.onnxWASMBasePath,P.ortConfig!==void 0&&P.ortConfig(i.ort);const N=P.model==="v5"?y: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 U=P.model==="v5"?512:1536,oe=U/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},oe),Z=new w(P,de,H,U);if(P.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=w})(Ua)),Ua}var Iy;function WE(){return Iy||(Iy=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=k1();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=Fb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Hb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=gv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=BE();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=GE();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=HE();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}})})(Vv)),Vv}var UE=WE();function ig(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 pt={debug:(i,e,t)=>ig(i,"debug",e,t),info:(i,e,t)=>ig(i,"info",e,t),warn:(i,e,t)=>ig(i,"warn",e,t),error:(i,e,t,n)=>ig(i,"error",e,t,n)},I1=16e3,VE=6,Wu=I1*VE,qE=400,KE=I1*qE/1e3,Py=300,Ry=2e3,jy=1500,Ny=3e3,YE=600,P1=.5,R1=.35,My=.85,Oy=.7;let hr=null,pa=!1,qs=!1;const L_=new Set;function ng(i){for(const e of Array.from(L_))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Xv=0;const Ly=2;let ih=!1,j1=!1;function N1(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";pt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),XE(`error:${e.message||"unknown"}`)})}function Qg(){return hr||(hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),N1(hr),pt.info("speech","worker spawned"),hr)}let sg=!1;function XE(i){if(!ih){if(sg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(sg=!0,Xv+=1,j1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:Xv}),ng({reason:i,respawned:!1,finalOnly:!0}),Xv>Ly){if(ih=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Ly}),hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1,ng({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),sg=!1;return}if(hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1;try{hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),N1(hr),qs=!0,hr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),ng({reason:i,respawned:!0,finalOnly:!0})}catch(e){ih=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),ng({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{sg=!1}}}function JE(i,e){if(pa||qs)return;qs=!0;const t=Qg();pt.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"&&(pa=!0,qs=!1,pt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(qs=!1,pt.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 ZE(){pt.info("speech","resetModel: clearing load flags"),pa=!1,qs=!1}function vv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function QE(i){const e=Qg();return!pa&&!qs&&(qs=!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"&&(pa=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function M1(i){let e=Qg(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let v=null,m=0,y=!1,D=0,E=!1,T=!1,b=0,C=0,w=0,x=-1,$=Py,P=0,N=null,L="",j="",H=!1,U=0;function oe(ve,_e){const Me=Math.min(ve.length,_e.length);let et=0;for(;et<Me&&ve.charCodeAt(et)===_e.charCodeAt(et);)et++;return et}function de(ve){const _e=oe(L,ve);return L=ve,_e>j.length&&(j=ve.slice(0,_e)),j.length>ve.length&&(j=ve),j}const Z=()=>(v||(v=new Float32Array(Wu)),v),me=()=>{m=0},ie=ve=>{const _e=Z(),Me=ve.length;if(Me>=Wu){_e.set(ve.subarray(Me-Wu)),m=Wu;return}if(m+Me<=Wu){_e.set(ve,m),m+=Me;return}const et=m+Me-Wu;_e.copyWithin(0,et,m),m-=et,_e.set(ve,m),m+=Me},ue=()=>{N&&(clearTimeout(N),N=null)},Ce=()=>{ue(),y=!1,E=!1,T=!1,$=Py,L="",j="",H=!1,U=0,me()},Ee=()=>{if(t||!y||T||E||N)return;if(m<KE){N=setTimeout(()=>{N=null,Ee()},$);return}const ve=performance.now()-b;if(ve<$&&b!==0){N=setTimeout(()=>{N=null,Ee()},$-ve);return}if(j1||ih||i.partialsEnabled&&!i.partialsEnabled())return;const _e=Z(),Me=new Float32Array(m);Me.set(_e.subarray(0,m)),C+=1,w=C,E=!0,P=performance.now(),b=P,e.postMessage({type:"transcribe-partial",audio:Me,seq:C},[Me.buffer])},W=ve=>ve.length===0?Promise.resolve():ih?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(_e=>{d.push(_e),C+=1;const Me=C;x=Me,e.postMessage({type:"transcribe",audio:ve,seq:Me},[ve.buffer])}),te=ve=>{const _e=W(ve);return f.add(_e),_e.finally(()=>{f.delete(_e)}),_e},K=ve=>{var _e,Me,et,we,X;if(ve.data.type==="result"){const Ie=ve.data.text,pe=ve.data.seq??0;pe&&pe<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:pe,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(_e=d.shift())==null||_e()}else if(ve.data.type==="partial"){const Ie=ve.data.seq??0,pe=ve.data.text??"",Ze=performance.now()-P;E=!1,Ze>=Ny?(T=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ze),seq:Ie})):Ze>=jy&&($=Math.min($*2,Ry),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ze),newIntervalMs:$,seq:Ie})),H||(H=!0,Ze>YE&&$<500&&($=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ze),newIntervalMs:500})));const ge=Ie!==w||Ie<=x;if(!t&&!ge&&pe){const Ke=de(pe);Ke&&((Me=i.onPartial)==null||Me.call(i,Ke),U===0&&(U=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-D)})))}Ee()}else if(ve.data.type==="partial-error"){const Ie=performance.now()-P;E=!1,Ie>=Ny?(T=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ve.data.seq})):Ie>=jy&&($=Math.min($*2,Ry),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:$,seq:ve.data.seq})),pt.warn("speech","partial encode failed",{error:ve.data.error,seq:ve.data.seq}),Ee()}else ve.data.type==="error"?(t||i.onError(ve.data.error),(et=d.shift())==null||et()):ve.data.type==="status"?(t||(we=i.onModelStatus)==null||we.call(i,ve.data.status,ve.data.message),ve.data.status==="ready"&&(pa=!0,qs=!1)):ve.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ve.data.pct))};e.addEventListener("message",K);const re=ve=>{var _e,Me;if(!t){for(pt.warn("speech","createRecognition: worker death event",ve),(_e=i.onStatusChange)==null||_e.call(i,"restarting");d.length;)(Me=d.shift())==null||Me();if(f.clear(),ue(),E=!1,ve.respawned){try{e.removeEventListener("message",K)}catch{}e=Qg(),e.addEventListener("message",K)}}};return L_.add(re),{start:async()=>{if(!t){if(ih){i.onError("Speech recognition disabled — please reload the app.");return}!pa&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:pa,modelLoading:qs});try{const ve=new URL("vad/",document.baseURI).href,_e=i.inputDeviceId||null,Me={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};_e&&(Me.deviceId={exact:_e}),pt.info("speech","getUserMedia",{hasDeviceId:!!_e,deviceIdPrefix:_e?_e.slice(0,8):null});const et=await navigator.mediaDevices.getUserMedia({audio:Me});r=et,l=new AudioContext;for(const we of et.getAudioTracks())we.addEventListener("ended",()=>{t||(pt.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(we){pt.warn("speech","analyser init failed",{error:we instanceof Error?we.message:String(we)}),a=null,p=null}n=await UE.MicVAD.new({audioContext:l,getStream:async()=>et,resumeStream:async()=>et,pauseStream:async()=>{},baseAssetPath:ve,onnxWASMBasePath:ve,model:"v5",positiveSpeechThreshold:P1,negativeSpeechThreshold:R1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(we,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,we),y&&(ie(X),Ee()))},onSpeechStart:()=>{var we;t||(Ce(),y=!0,D=performance.now(),(we=i.onSpeechStart)==null||we.call(i))},onSpeechEnd:we=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),Ce(),te(we))},onVADMisfire:()=>{var we,X;t||((we=i.onStatusChange)==null||we.call(i,"idle"),Ce(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ve){const _e=ve instanceof Error?ve.message:"Microphone access denied",Me=ve instanceof Error?ve.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:_e,stack:Me}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(et=>et.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(_e)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(Ce();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(ve=>ve.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ve,_e)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ve,negativeSpeechThreshold:_e})}catch(Me){pt.warn("speech","setVadThresholds failed",{error:Me instanceof Error?Me.message:String(Me)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,Ce(),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(ve=>ve.stop())}catch{}r=null}L_.delete(re),e.removeEventListener("message",K)}}}let Df=null;const z_=new Set,B_=new Set;function e2(){for(const i of z_)try{i()}catch{}}function G_(){for(const i of B_)try{i()}catch{}}function t2(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 i2(i){if(!window.speechSynthesis)return;const e=t2(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Df=performance.now(),e2()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,G_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,G_())},window.speechSynthesis.speak(t)}function O1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Df=null,G_())}function L1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function n2(){return Df}function s2(i){return z_.add(i),()=>{z_.delete(i)}}function r2(i){return B_.add(i),()=>{B_.delete(i)}}function o2(i){L1()&&(i.setVadThresholds(My,Oy),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=s2(()=>{i.setVadThresholds(My,Oy),pt.info("voice","tts.duck.on")}),t=r2(()=>{i.setVadThresholds(P1,R1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const a2=[{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 l2(i){const e=i.trim();return a2.find(t=>t.match.test(e))??null}const c2=4e4;let nd=null;function nh(){nd&&clearTimeout(nd),nd=setTimeout(()=>{nd=null,Ct.getState().stopRecording()},c2)}function rg(){nd&&(clearTimeout(nd),nd=null)}let Yl=null,Ul=null;const d2=.04,u2=.3;let ev=0,F_=0;function h2(i){Ul!==null&&cancelAnimationFrame(Ul);const e=()=>{if(Yl===null||Ct.getState().submitCountdownStartAt===null){Ul=null;return}const t=performance.now();if(t-F_<200&&ev>u2){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:ev.toFixed(2),msIntoCountdown:Math.round(r)}),Hl(),nh();return}const n=z1();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>d2){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Hl(),nh();return}}Ul=requestAnimationFrame(e)};Ul=requestAnimationFrame(e)}function zy(i){Yl&&clearTimeout(Yl);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),Yl=setTimeout(()=>{var r;Yl=null,Ct.setState({submitCountdownStartAt:null});const n=xt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=di.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(di.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),di.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){pt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}nh()},e),h2(t)}function Hl(){Ul!==null&&(cancelAnimationFrame(Ul),Ul=null),Yl&&(clearTimeout(Yl),Yl=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let ss=null,Is=null,nf=null;function z1(){var i;return((i=ss==null?void 0:ss.getAnalyser)==null?void 0:i.call(ss))??null}const og=1e4;let $f=null;function ag(){$f&&(clearTimeout($f),$f=null)}let Og=null,Lg=null;function lg(){Og=null,Lg&&(Lg(),Lg=null)}const p2=1500,f2=9e4;let cg=0,zg=null,H_=-1;function dg(){zg&&(clearTimeout(zg),zg=null,H_=-1)}const m2=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=In((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++cg,n=()=>{t===cg&&(dg(),H_=t,zg=setTimeout(()=>{H_===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},f2))};n(),JE((r,l)=>{t===cg&&(r==="ready"?(dg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(dg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===cg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),dg(),ZE(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ss){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!vv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=M1({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=>{ev=a.isSpeech,F_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),rg(),Hl(),L1()){const d=n2(),f=d!==null?performance.now()-d:null;O1(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else pt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),nh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&pt.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var y;nh();const d=a.trim();if(!d||m2.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(nf){nf(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((y=xt.getState().tabs.find(D=>D.id===t))==null?void 0:y.status)==="dormant"){di.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&zy(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const v=l2(d);if(v){pt.info("voice","voice-command",{tabId:t,label:v.label,transcript:d}),window.api.pty.write({tabId:t,data:v.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Hl();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&&zy(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{pt.error("voice","recognition error",{err:a}),Hl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,rg(),ss==null||ss.destroy(),ss=null,nf=null,lt.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)})});ss=p,nf=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),nh(),p.start().then(()=>{ss===p&&(Is==null||Is(),Is=o2(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),lt.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=>{pt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=ss;t&&(rg(),Hl(),ev=0,F_=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ss===t&&(ss=null,nf=null),e().hotkeyState==="stopping"&&(ag(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ss;if(!t)return;rg(),Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){pt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),ss===t&&(ss=null);const{useSessions:n}=await os(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>_E);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:()=>Hl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(pt.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"?pt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&&pt.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}=tv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){pt.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"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),lg(),Og={tabId:l,source:n,mode:r},Lg=Ct.subscribe((f,v)=>{if(Og&&f.modelStatus==="ready"&&v.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Og;if(lg(),!m.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),Ct.getState().startRecording(m.tabId)}});return}if(!l){pt.warn("voice-hotkey","no-active-tab",{source:n});return}pt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){lg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(lg(),Hl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(ag(),i({hotkeyState:"destroyed"}))}})),g2=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),tv=i=>vv()?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=Ct,i.__transcripts=[]}const v2=6e4,_2=5e3,Af=In(()=>({data:null,refreshing:!1}));let By=!1,Bg=null,Gy=null,Fy=!1;async function Wb(){Af.setState({refreshing:!0});let i=v2;try{const e=await Ob(window.api.billing.fetch(),_2,"billing.fetch");Af.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Gy==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Gy=e.kind}catch(e){if(Af.setState({refreshing:!1}),!Fy){Fy=!0;const t=e instanceof Error?e.message:String(e);lt.warn(`Billing usage fetch failed: ${t}`)}}Bg=setTimeout(Wb,i)}function b2(){By||(By=!0,Wb())}function B1(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 w2(){Bg!==null&&(clearTimeout(Bg),Bg=null),Wb()}function Ub(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 ug=new Map,y2=3e4;function Vb(i){const[e,t]=G.useState(()=>{var n;return i?((n=ug.get(i))==null?void 0:n.value)??null:null});return G.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=ug.get(i);if(l&&Date.now()-l.ts<y2){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;ug.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;ug.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function x2(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 W_="sm.almanac.sidebarWidth",G1=180,F1=480,U_=252;function S2(){try{const i=parseInt(localStorage.getItem(W_)??"",10);if(Number.isFinite(i))return Math.min(F1,Math.max(G1,i))}catch{}return U_}const C2=52,H1="sm.almanac.sidebarCollapsed";function k2(){try{return localStorage.getItem(H1)==="1"}catch{}return!1}const W1="sm.almanac.collapsedGroups";function E2(){try{const i=localStorage.getItem(W1);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 T2(){const i=xt(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:jr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function D2({active:i,onNavigate:e,onNewSession:t}){const[n,r]=G.useState(()=>E2()),l=G.useCallback(j=>{r(H=>{const U=new Set(H);U.has(j)?U.delete(j):U.add(j);try{localStorage.setItem(W1,JSON.stringify(Array.from(U)))}catch{}return U})},[]),[p,a]=G.useState(()=>k2()),d=G.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(H1,H?"1":"0")}catch{}return H})},[]),f=xt(j=>j.tabs),v=xt(j=>j.activeTabId),m=f.find(j=>j.id===v)??null,y=T2(),D=Ei(j=>j.navFace),E=xE(D),T=E.filter(j=>j.group==="Workspace"),b=E.filter(j=>j.group==="Configure"),C=x2(E),w=D==="home"&&!p,[x,$]=G.useState(()=>S2()),P=G.useRef(x);P.current=x;const N=G.useCallback(j=>{j.preventDefault();const H=j.clientX,U=P.current;let oe=U;const de=me=>{oe=Math.min(F1,Math.max(G1,U+(me.clientX-H))),$(oe)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(W_,String(oe))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=G.useCallback(()=>{$(U_);try{localStorage.setItem(W_,String(U_))}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?C2:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx($2,{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:w?h.jsxs(h.Fragment,{children:[h.jsx(Jv,{label:"Workspace",desc:Uv.Workspace,collapsed:n.has("Workspace"),count:T.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&T.map(j=>h.jsx(Zv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Jv,{label:"Configure",desc:Uv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Zv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Jv,{label:"Tools",desc:Uv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(Hy,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:E.map(j=>j.group==="Tools"?h.jsx(Hy,{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(Zv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(A2,{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 $2({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Vb((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(rs,{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(rs,{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(rs,{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(rs,{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(rs,{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(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Jv({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 Zv({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":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(rs,{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 Hy({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(rs,{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 A2({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=xt(d=>d.tabs),r=xt(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=G.useState(null);return G.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return l1(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 · ${Ub(p)}`:"Claude Code"})]})}const Cn={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},I2={dialog:50};function P2(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function R2(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 j2(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 v of["command","file_path","pattern","url","query","subagent_type","description"])d&&v in d&&(f[v]=d[v]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const v=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),y=typeof(v==null?void 0:v.file_path)=="string"?v.file_path:void 0,D=typeof(v==null?void 0:v.command)=="string"?v.command:void 0,E=y?y.split("/").pop()??y:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:E?`${a.name} · ${E}`:a.name,target:y??D,toolName:a.name}),m&&y&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(y.split("/").pop()??y,34)}`,target:y,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,v=a.output_tokens??a.outputTokens??0,m=d+f+v;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+v,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=P2(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Gg=In((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]:R2(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:v}=await os(async()=>{const{toast:m}=await Promise.resolve().then(()=>u1);return{toast:m}},void 0,import.meta.url);v.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:v}=j2(p,d,r);p=f,a=a.concat(v)}if(a.length>0){let d=l.activitySeq;const f=a.map(v=>({...v,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function N2(i){const e=Gg(r=>r.subscribe),t=Gg(r=>r.unsubscribe),n=Gg(r=>i?r.tabs[i.id]:void 0);return G.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 U1(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 V_(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function Wy(i,e){const t=V_(e);if(t==null)return`${i} — usage unavailable`;const n=U1((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 M2({onNavigate:i}){const e=xt(P=>P.tabs),t=xt(P=>P.activeTabId),n=e.find(P=>P.id===t)??null,r=N2(n),l=(r==null?void 0:r.lastEventAt)??0,p=Af(P=>P.data),a=jr(P=>{var N;return((N=P.snapshot)==null?void 0:N.paused)??null}),d=Vb((n==null?void 0:n.cwd)??null),[,f]=G.useState(0);G.useEffect(()=>{const P=setInterval(()=>f(N=>N+1),6e4);return()=>clearInterval(P)},[]);const v=(r==null?void 0:r.todos)??[],[m,y]=G.useState(!1),D=G.useRef(null);G.useEffect(()=>{if(!m)return;const P=N=>{D.current&&!D.current.contains(N.target)&&y(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[m]),G.useEffect(()=>{v.length===0&&y(!1)},[v.length]);const E=B1(p),T=(E==null?void 0:E.usage.five_hour)??null,b=(E==null?void 0:E.usage.seven_day)??null,C=V_(T),w=V_(b),x=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",$=l>0?z2(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:Wy("Session (5h window)",T),"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:Wy("Weekly window (all models)",b),"data-testid":"footer-usage-weekly",children:["weekly ",h.jsx("span",{className:"text-fg",children:w!=null?`${w}%`:"—"})]}),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:$})]}),v.length>0&&h.jsx(O2,{ref:D,todos:v,open:m,onToggle:()=>y(P=>!P)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.70.0"]})]})}const O2=G.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 ${Cn.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(L2,{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 L2({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 z2(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 B2({onClose:i,onSent:e}){const t=xt(L=>L.tabs),[n,r]=G.useState(""),[l,p]=G.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=G.useState(!1),[f,v]=G.useState({}),m=G.useRef(null),y=G.useRef(e);G.useEffect(()=>{y.current=e},[e]),G.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),G.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),G.useEffect(()=>window.api.pty.onWriteError(j=>{v(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),G.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>y.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),E=D.length,T=Object.keys(f).length>0,b=n.length>0&&E>0&&!a&&!T,C=()=>{if(!b)return;d(!0);const L=xt.getState().tabs,j=new Set(L.map(U=>U.id)),H={};for(const U of D)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),H[U]="sent"):H[U]="skipped";v(H),d(!1)},w=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]),$=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},P=Object.values(f).some(L=>L==="skipped"),N=T?P?"Sent (some skipped)":"Sent":`Send to ${E} tab${E===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:w,"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:$,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",E,"/",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 G2({tabId:i,cwd:e,onClose:t}){const n=Tf(E=>E.watchersForTab(i)),r=Tf(E=>E.add),l=Tf(E=>E.remove),p=G.useRef(null),[a,d]=G.useState(""),[f,v]=G.useState(""),[m,y]=G.useState(!1);G.useEffect(()=>{const E=T=>{T.key==="Escape"&&t()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]),G.useEffect(()=>{const E=T=>{p.current&&!p.current.contains(T.target)&&t()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[t]);const D=async()=>{const E=f.trim();if(!E||m)return;y(!0);const T=await r({tabId:i,label:a.trim(),command:E,cwd:e});y(!1),T&&(d(""),v(""))};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:E=>d(E.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:E=>v(E.target.value),onKeyDown:E=>{E.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(E=>{const T=E.lines[E.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:E.label}),h.jsxs("span",{className:"text-fg-faint",children:[E.lineCount," line",E.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(E.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${E.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:E.command,children:E.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(T==null?void 0:T.line)??"",children:T?T.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},E.watcherId)})})]})}/**
2911
2911
  * dockview-core
2912
2912
  * @version 6.6.1
2913
2913
  * @link https://github.com/mathuo/dockview
@@ -2947,7 +2947,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
2947
2947
  monaco.config({ paths: { vs: '...' } })
2948
2948
 
2949
2949
  For more please check the link https://github.com/suren-atoyan/monaco-loader#config
2950
- `},Px=aI(uI)(KS),hI={config:cI},pI=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(l,p){return p(l)},r)}};function YS(i,e){return Object.keys(e).forEach(function(t){e[t]instanceof Object&&i[t]&&Object.assign(e[t],YS(i[t],e[t]))}),$x($x({},i),e)}var fI={type:"cancelation",msg:"operation is manually canceled"};function o_(i){var e=!1,t=new Promise(function(n,r){i.then(function(l){return e?r(fI):n(l)}),i.catch(r)});return t.cancel=function(){return e=!0},t}var mI=["monaco"],gI=rI.create({config:oI,isInitialized:!1,resolve:null,reject:null,monaco:null}),XS=GA(gI,2),Qf=XS[0],kv=XS[1];function vI(i){var e=hI.config(i),t=e.monaco,n=zA(e,mI);kv(function(r){return{config:YS(r.config,n),monaco:t}})}function _I(){var i=Qf(function(e){var t=e.monaco,n=e.isInitialized,r=e.resolve;return{monaco:t,isInitialized:n,resolve:r}});if(!i.isInitialized){if(kv({isInitialized:!0}),i.monaco)return i.resolve(i.monaco),o_(a_);if(window.monaco&&window.monaco.editor)return JS(window.monaco),i.resolve(window.monaco),o_(a_);pI(bI,yI)(xI)}return o_(a_)}function bI(i){return document.body.appendChild(i)}function wI(i){var e=document.createElement("script");return i&&(e.src=i),e}function yI(i){var e=Qf(function(n){var r=n.config,l=n.reject;return{config:r,reject:l}}),t=wI("".concat(e.config.paths.vs,"/loader.js"));return t.onload=function(){return i()},t.onerror=e.reject,t}function xI(){var i=Qf(function(t){var n=t.config,r=t.resolve,l=t.reject;return{config:n,resolve:r,reject:l}}),e=window.require;e.config(i.config),e(["vs/editor/editor.main"],function(t){var n=t.m||t;JS(n),i.resolve(n)},function(t){i.reject(t)})}function JS(i){Qf().monaco||kv({monaco:i})}function SI(){return Qf(function(i){var e=i.monaco;return e})}var a_=new Promise(function(i,e){return kv({resolve:i,reject:e})}),uw={config:vI,init:_I,__getMonacoInstance:SI},CI={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},l_=CI,kI={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},EI=kI;function TI({children:i}){return Rt.createElement("div",{style:EI.container},i)}var DI=TI,$I=DI;function AI({width:i,height:e,isEditorReady:t,loading:n,_ref:r,className:l,wrapperProps:p}){return Rt.createElement("section",{style:{...l_.wrapper,width:i,height:e},...p},!t&&Rt.createElement($I,null,n),Rt.createElement("div",{ref:r,style:{...l_.fullWidth,...!t&&l_.hide},className:l}))}var II=AI,ZS=G.memo(II);function PI(i){G.useEffect(i,[])}var QS=PI;function RI(i,e,t=!0){let n=G.useRef(!0);G.useEffect(n.current||!t?()=>{n.current=!1}:i,e)}var Pr=RI;function jf(){}function eh(i,e,t,n){return jI(i,n)||NI(i,e,t,n)}function jI(i,e){return i.editor.getModel(eC(i,e))}function NI(i,e,t,n){return i.editor.createModel(e,t,n?eC(i,n):void 0)}function eC(i,e){return i.Uri.parse(e)}function MI({original:i,modified:e,language:t,originalLanguage:n,modifiedLanguage:r,originalModelPath:l,modifiedModelPath:p,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:d=!1,theme:f="light",loading:v="Loading...",options:m={},height:y="100%",width:D="100%",className:E,wrapperProps:T={},beforeMount:b=jf,onMount:C=jf}){let[w,x]=G.useState(!1),[$,P]=G.useState(!0),N=G.useRef(null),L=G.useRef(null),j=G.useRef(null),H=G.useRef(C),U=G.useRef(b),oe=G.useRef(!1);QS(()=>{let ie=uw.init();return ie.then(ue=>(L.current=ue)&&P(!1)).catch(ue=>(ue==null?void 0:ue.type)!=="cancelation"&&console.error("Monaco initialization: error:",ue)),()=>N.current?me():ie.cancel()}),Pr(()=>{if(N.current&&L.current){let ie=N.current.getOriginalEditor(),ue=eh(L.current,i||"",n||t||"text",l||"");ue!==ie.getModel()&&ie.setModel(ue)}},[l],w),Pr(()=>{if(N.current&&L.current){let ie=N.current.getModifiedEditor(),ue=eh(L.current,e||"",r||t||"text",p||"");ue!==ie.getModel()&&ie.setModel(ue)}},[p],w),Pr(()=>{let ie=N.current.getModifiedEditor();ie.getOption(L.current.editor.EditorOption.readOnly)?ie.setValue(e||""):e!==ie.getValue()&&(ie.executeEdits("",[{range:ie.getModel().getFullModelRange(),text:e||"",forceMoveMarkers:!0}]),ie.pushUndoStop())},[e],w),Pr(()=>{var ie,ue;(ue=(ie=N.current)==null?void 0:ie.getModel())==null||ue.original.setValue(i||"")},[i],w),Pr(()=>{let{original:ie,modified:ue}=N.current.getModel();L.current.editor.setModelLanguage(ie,n||t||"text"),L.current.editor.setModelLanguage(ue,r||t||"text")},[t,n,r],w),Pr(()=>{var ie;(ie=L.current)==null||ie.editor.setTheme(f)},[f],w),Pr(()=>{var ie;(ie=N.current)==null||ie.updateOptions(m)},[m],w);let de=G.useCallback(()=>{var Ce;if(!L.current)return;U.current(L.current);let ie=eh(L.current,i||"",n||t||"text",l||""),ue=eh(L.current,e||"",r||t||"text",p||"");(Ce=N.current)==null||Ce.setModel({original:ie,modified:ue})},[t,e,r,i,n,l,p]),Z=G.useCallback(()=>{var ie;!oe.current&&j.current&&(N.current=L.current.editor.createDiffEditor(j.current,{automaticLayout:!0,...m}),de(),(ie=L.current)==null||ie.editor.setTheme(f),x(!0),oe.current=!0)},[m,f,de]);G.useEffect(()=>{w&&H.current(N.current,L.current)},[w]),G.useEffect(()=>{!$&&!w&&Z()},[$,w,Z]);function me(){var ue,Ce,Ee,W;let ie=(ue=N.current)==null?void 0:ue.getModel();a||((Ce=ie==null?void 0:ie.original)==null||Ce.dispose()),d||((Ee=ie==null?void 0:ie.modified)==null||Ee.dispose()),(W=N.current)==null||W.dispose()}return Rt.createElement(ZS,{width:D,height:y,isEditorReady:w,loading:v,_ref:j,className:E,wrapperProps:T})}var OI=MI;G.memo(OI);function LI(i){let e=G.useRef();return G.useEffect(()=>{e.current=i},[i]),e.current}var zI=LI,Sg=new Map;function BI({defaultValue:i,defaultLanguage:e,defaultPath:t,value:n,language:r,path:l,theme:p="light",line:a,loading:d="Loading...",options:f={},overrideServices:v={},saveViewState:m=!0,keepCurrentModel:y=!1,width:D="100%",height:E="100%",className:T,wrapperProps:b={},beforeMount:C=jf,onMount:w=jf,onChange:x,onValidate:$=jf}){let[P,N]=G.useState(!1),[L,j]=G.useState(!0),H=G.useRef(null),U=G.useRef(null),oe=G.useRef(null),de=G.useRef(w),Z=G.useRef(C),me=G.useRef(),ie=G.useRef(n),ue=zI(l),Ce=G.useRef(!1),Ee=G.useRef(!1);QS(()=>{let K=uw.init();return K.then(re=>(H.current=re)&&j(!1)).catch(re=>(re==null?void 0:re.type)!=="cancelation"&&console.error("Monaco initialization: error:",re)),()=>U.current?te():K.cancel()}),Pr(()=>{var re,ve,_e,Me;let K=eh(H.current,i||n||"",e||r||"",l||t||"");K!==((re=U.current)==null?void 0:re.getModel())&&(m&&Sg.set(ue,(ve=U.current)==null?void 0:ve.saveViewState()),(_e=U.current)==null||_e.setModel(K),m&&((Me=U.current)==null||Me.restoreViewState(Sg.get(l))))},[l],P),Pr(()=>{var K;(K=U.current)==null||K.updateOptions(f)},[f],P),Pr(()=>{!U.current||n===void 0||(U.current.getOption(H.current.editor.EditorOption.readOnly)?U.current.setValue(n):n!==U.current.getValue()&&(Ee.current=!0,U.current.executeEdits("",[{range:U.current.getModel().getFullModelRange(),text:n,forceMoveMarkers:!0}]),U.current.pushUndoStop(),Ee.current=!1))},[n],P),Pr(()=>{var re,ve;let K=(re=U.current)==null?void 0:re.getModel();K&&r&&((ve=H.current)==null||ve.editor.setModelLanguage(K,r))},[r],P),Pr(()=>{var K;a!==void 0&&((K=U.current)==null||K.revealLine(a))},[a],P),Pr(()=>{var K;(K=H.current)==null||K.editor.setTheme(p)},[p],P);let W=G.useCallback(()=>{var K;if(!(!oe.current||!H.current)&&!Ce.current){Z.current(H.current);let re=l||t,ve=eh(H.current,n||i||"",e||r||"",re||"");U.current=(K=H.current)==null?void 0:K.editor.create(oe.current,{model:ve,automaticLayout:!0,...f},v),m&&U.current.restoreViewState(Sg.get(re)),H.current.editor.setTheme(p),a!==void 0&&U.current.revealLine(a),N(!0),Ce.current=!0}},[i,e,t,n,r,l,f,v,m,p,a]);G.useEffect(()=>{P&&de.current(U.current,H.current)},[P]),G.useEffect(()=>{!L&&!P&&W()},[L,P,W]),ie.current=n,G.useEffect(()=>{var K,re;P&&x&&((K=me.current)==null||K.dispose(),me.current=(re=U.current)==null?void 0:re.onDidChangeModelContent(ve=>{Ee.current||x(U.current.getValue(),ve)}))},[P,x]),G.useEffect(()=>{if(P){let K=H.current.editor.onDidChangeMarkers(re=>{var _e;let ve=(_e=U.current.getModel())==null?void 0:_e.uri;if(ve&&re.find(Me=>Me.path===ve.path)){let Me=H.current.editor.getModelMarkers({resource:ve});$==null||$(Me)}});return()=>{K==null||K.dispose()}}return()=>{}},[P,$]);function te(){var K,re;(K=me.current)==null||K.dispose(),y?m&&Sg.set(l,U.current.saveViewState()):(re=U.current.getModel())==null||re.dispose(),U.current.dispose()}return Rt.createElement(ZS,{width:D,height:E,isEditorReady:P,loading:d,_ref:oe,className:T,wrapperProps:b})}var GI=BI,FI=G.memo(GI),tC=FI;const HI={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",json:"json",jsonl:"json",ndjson:"json",py:"python",go:"go",rs:"rust",rb:"ruby",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",java:"java",sh:"shell",bash:"shell",zsh:"shell",css:"css",scss:"scss",less:"less",html:"html",htm:"html",xml:"xml",yaml:"yaml",yml:"yaml",toml:"ini",ini:"ini",conf:"ini",sql:"sql",md:"markdown",mdx:"markdown",markdown:"markdown",graphql:"graphql",dockerfile:"dockerfile"},WI=new Set(["md","mdx","markdown","txt","log"]);let Rx=!1;function UI(i){Rx||(Rx=!0,i.editor.defineTheme("sm-paper",{base:"vs",inherit:!0,rules:[],colors:{"editor.background":"#f6efe1","editor.foreground":"#2a221a","editorLineNumber.foreground":"#b8a98a","editorLineNumber.activeForeground":"#7a6a4f","editor.lineHighlightBackground":"#efe6d3","editor.selectionBackground":"#e0d3b8","editorCursor.foreground":"#b85c34","editorIndentGuide.background1":"#e6dcc4","editor.findMatchHighlightBackground":"#e8d7a8"}}),i.editor.defineTheme("sm-dark",{base:"vs-dark",inherit:!0,rules:[],colors:{"editor.background":"#1c1814","editor.foreground":"#e8dcc6","editorLineNumber.foreground":"#5b5040","editor.lineHighlightBackground":"#262017","editorCursor.foreground":"#d97a4a"}}))}function VI({path:i,name:e,value:t,onChange:n,onSave:r,onReady:l,onCursor:p}){const a=G.useRef(null),d=G.useRef(null),f=G.useRef(r);f.current=r;const v=$i(w=>w.consumeReveal),m=Qu(w=>w.fontSize),y=Qu(w=>w.wordWrap),D=Qu(w=>w.minimap),E=Qu(w=>w.theme),T=WI.has(Nr(e)),b=(w,x)=>{a.current=w,d.current=x,UI(x),x.editor.setTheme(E==="dark"?"sm-dark":"sm-paper"),w.addCommand(x.KeyMod.CtrlCmd|x.KeyCode.KeyS,()=>f.current()),l==null||l(w);const $=()=>{const P=w.getPosition(),N=w.getSelection(),L=w.getModel(),j=N&&L?L.getValueLengthInRange(N):0;P&&(p==null||p({line:P.lineNumber,col:P.column,selected:j}))};w.onDidChangeCursorPosition($),w.onDidChangeCursorSelection($),$(),C(w)},C=w=>{const x=v(i);x!=null&&x.line&&(w.revealLineInCenter(x.line),w.setPosition({lineNumber:x.line,column:x.col??1}),w.focus())};return G.useEffect(()=>{a.current&&C(a.current)},[i]),G.useEffect(()=>{var w;(w=d.current)==null||w.editor.setTheme(E==="dark"?"sm-dark":"sm-paper")},[E]),G.useEffect(()=>()=>{l==null||l(null)},[l]),h.jsx(tC,{path:`file://${i}`,language:HI[Nr(e)]||"plaintext",value:t,onChange:w=>n(w??""),onMount:b,theme:E==="dark"?"sm-dark":"sm-paper",options:{minimap:{enabled:D},fontSize:T?m+2:m,fontFamily:T?"Newsreader, Georgia, serif":'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:T?"off":"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,detectIndentation:!0,stickyScroll:{enabled:!0},automaticLayout:!0,bracketPairColorization:{enabled:!0},padding:T?{top:16,bottom:16}:void 0,lineHeight:T?26:void 0,wordWrap:T||y?"on":"off"}})}function hw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let ld=hw();function iC(i){ld=i}const nC=/[&<>"']/,qI=new RegExp(nC.source,"g"),sC=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,KI=new RegExp(sC.source,"g"),YI={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},jx=i=>YI[i];function Rr(i,e){if(e){if(nC.test(i))return i.replace(qI,jx)}else if(sC.test(i))return i.replace(KI,jx);return i}const XI=/(^|[^\[])\^/g;function Gi(i,e){let t=typeof i=="string"?i:i.source;e=e||"";const n={replace:(r,l)=>{let p=typeof l=="string"?l:l.source;return p=p.replace(XI,"$1"),t=t.replace(r,p),n},getRegex:()=>new RegExp(t,e)};return n}function Nx(i){try{i=encodeURI(i).replace(/%25/g,"%")}catch{return null}return i}const Nf={exec:()=>null};function Mx(i,e){const t=i.replace(/\|/g,(l,p,a)=>{let d=!1,f=p;for(;--f>=0&&a[f]==="\\";)d=!d;return d?"|":" |"}),n=t.split(/ \|/);let r=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(/\\\|/g,"|");return n}function lf(i,e,t){const n=i.length;if(n===0)return"";let r=0;for(;r<n&&i.charAt(n-r-1)===e;)r++;return i.slice(0,n-r)}function JI(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<i.length;n++)if(i[n]==="\\")n++;else if(i[n]===e[0])t++;else if(i[n]===e[1]&&(t--,t<0))return n;return-1}function Ox(i,e,t,n){const r=e.href,l=e.title?Rr(e.title):null,p=i[1].replace(/\\([\[\]])/g,"$1");if(i[0].charAt(0)!=="!"){n.state.inLink=!0;const a={type:"link",raw:t,href:r,title:l,text:p,tokens:n.inlineTokens(p)};return n.state.inLink=!1,a}return{type:"image",raw:t,href:r,title:l,text:Rr(p)}}function ZI(i,e){const t=i.match(/^(\s+)(?:```)/);if(t===null)return e;const n=t[1];return e.split(`
2950
+ `},Px=aI(uI)(KS),hI={config:cI},pI=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return function(r){return t.reduceRight(function(l,p){return p(l)},r)}};function YS(i,e){return Object.keys(e).forEach(function(t){e[t]instanceof Object&&i[t]&&Object.assign(e[t],YS(i[t],e[t]))}),$x($x({},i),e)}var fI={type:"cancelation",msg:"operation is manually canceled"};function o_(i){var e=!1,t=new Promise(function(n,r){i.then(function(l){return e?r(fI):n(l)}),i.catch(r)});return t.cancel=function(){return e=!0},t}var mI=["monaco"],gI=rI.create({config:oI,isInitialized:!1,resolve:null,reject:null,monaco:null}),XS=GA(gI,2),Qf=XS[0],kv=XS[1];function vI(i){var e=hI.config(i),t=e.monaco,n=zA(e,mI);kv(function(r){return{config:YS(r.config,n),monaco:t}})}function _I(){var i=Qf(function(e){var t=e.monaco,n=e.isInitialized,r=e.resolve;return{monaco:t,isInitialized:n,resolve:r}});if(!i.isInitialized){if(kv({isInitialized:!0}),i.monaco)return i.resolve(i.monaco),o_(a_);if(window.monaco&&window.monaco.editor)return JS(window.monaco),i.resolve(window.monaco),o_(a_);pI(bI,yI)(xI)}return o_(a_)}function bI(i){return document.body.appendChild(i)}function wI(i){var e=document.createElement("script");return i&&(e.src=i),e}function yI(i){var e=Qf(function(n){var r=n.config,l=n.reject;return{config:r,reject:l}}),t=wI("".concat(e.config.paths.vs,"/loader.js"));return t.onload=function(){return i()},t.onerror=e.reject,t}function xI(){var i=Qf(function(t){var n=t.config,r=t.resolve,l=t.reject;return{config:n,resolve:r,reject:l}}),e=window.require;e.config(i.config),e(["vs/editor/editor.main"],function(t){var n=t.m||t;JS(n),i.resolve(n)},function(t){i.reject(t)})}function JS(i){Qf().monaco||kv({monaco:i})}function SI(){return Qf(function(i){var e=i.monaco;return e})}var a_=new Promise(function(i,e){return kv({resolve:i,reject:e})}),uw={config:vI,init:_I,__getMonacoInstance:SI},CI={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},l_=CI,kI={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},EI=kI;function TI({children:i}){return Rt.createElement("div",{style:EI.container},i)}var DI=TI,$I=DI;function AI({width:i,height:e,isEditorReady:t,loading:n,_ref:r,className:l,wrapperProps:p}){return Rt.createElement("section",{style:{...l_.wrapper,width:i,height:e},...p},!t&&Rt.createElement($I,null,n),Rt.createElement("div",{ref:r,style:{...l_.fullWidth,...!t&&l_.hide},className:l}))}var II=AI,ZS=G.memo(II);function PI(i){G.useEffect(i,[])}var QS=PI;function RI(i,e,t=!0){let n=G.useRef(!0);G.useEffect(n.current||!t?()=>{n.current=!1}:i,e)}var Pr=RI;function jf(){}function eh(i,e,t,n){return jI(i,n)||NI(i,e,t,n)}function jI(i,e){return i.editor.getModel(eC(i,e))}function NI(i,e,t,n){return i.editor.createModel(e,t,n?eC(i,n):void 0)}function eC(i,e){return i.Uri.parse(e)}function MI({original:i,modified:e,language:t,originalLanguage:n,modifiedLanguage:r,originalModelPath:l,modifiedModelPath:p,keepCurrentOriginalModel:a=!1,keepCurrentModifiedModel:d=!1,theme:f="light",loading:v="Loading...",options:m={},height:y="100%",width:D="100%",className:E,wrapperProps:T={},beforeMount:b=jf,onMount:C=jf}){let[w,x]=G.useState(!1),[$,P]=G.useState(!0),N=G.useRef(null),L=G.useRef(null),j=G.useRef(null),H=G.useRef(C),U=G.useRef(b),oe=G.useRef(!1);QS(()=>{let ie=uw.init();return ie.then(ue=>(L.current=ue)&&P(!1)).catch(ue=>(ue==null?void 0:ue.type)!=="cancelation"&&console.error("Monaco initialization: error:",ue)),()=>N.current?me():ie.cancel()}),Pr(()=>{if(N.current&&L.current){let ie=N.current.getOriginalEditor(),ue=eh(L.current,i||"",n||t||"text",l||"");ue!==ie.getModel()&&ie.setModel(ue)}},[l],w),Pr(()=>{if(N.current&&L.current){let ie=N.current.getModifiedEditor(),ue=eh(L.current,e||"",r||t||"text",p||"");ue!==ie.getModel()&&ie.setModel(ue)}},[p],w),Pr(()=>{let ie=N.current.getModifiedEditor();ie.getOption(L.current.editor.EditorOption.readOnly)?ie.setValue(e||""):e!==ie.getValue()&&(ie.executeEdits("",[{range:ie.getModel().getFullModelRange(),text:e||"",forceMoveMarkers:!0}]),ie.pushUndoStop())},[e],w),Pr(()=>{var ie,ue;(ue=(ie=N.current)==null?void 0:ie.getModel())==null||ue.original.setValue(i||"")},[i],w),Pr(()=>{let{original:ie,modified:ue}=N.current.getModel();L.current.editor.setModelLanguage(ie,n||t||"text"),L.current.editor.setModelLanguage(ue,r||t||"text")},[t,n,r],w),Pr(()=>{var ie;(ie=L.current)==null||ie.editor.setTheme(f)},[f],w),Pr(()=>{var ie;(ie=N.current)==null||ie.updateOptions(m)},[m],w);let de=G.useCallback(()=>{var Ce;if(!L.current)return;U.current(L.current);let ie=eh(L.current,i||"",n||t||"text",l||""),ue=eh(L.current,e||"",r||t||"text",p||"");(Ce=N.current)==null||Ce.setModel({original:ie,modified:ue})},[t,e,r,i,n,l,p]),Z=G.useCallback(()=>{var ie;!oe.current&&j.current&&(N.current=L.current.editor.createDiffEditor(j.current,{automaticLayout:!0,...m}),de(),(ie=L.current)==null||ie.editor.setTheme(f),x(!0),oe.current=!0)},[m,f,de]);G.useEffect(()=>{w&&H.current(N.current,L.current)},[w]),G.useEffect(()=>{!$&&!w&&Z()},[$,w,Z]);function me(){var ue,Ce,Ee,W;let ie=(ue=N.current)==null?void 0:ue.getModel();a||((Ce=ie==null?void 0:ie.original)==null||Ce.dispose()),d||((Ee=ie==null?void 0:ie.modified)==null||Ee.dispose()),(W=N.current)==null||W.dispose()}return Rt.createElement(ZS,{width:D,height:y,isEditorReady:w,loading:v,_ref:j,className:E,wrapperProps:T})}var OI=MI;G.memo(OI);function LI(i){let e=G.useRef();return G.useEffect(()=>{e.current=i},[i]),e.current}var zI=LI,Sg=new Map;function BI({defaultValue:i,defaultLanguage:e,defaultPath:t,value:n,language:r,path:l,theme:p="light",line:a,loading:d="Loading...",options:f={},overrideServices:v={},saveViewState:m=!0,keepCurrentModel:y=!1,width:D="100%",height:E="100%",className:T,wrapperProps:b={},beforeMount:C=jf,onMount:w=jf,onChange:x,onValidate:$=jf}){let[P,N]=G.useState(!1),[L,j]=G.useState(!0),H=G.useRef(null),U=G.useRef(null),oe=G.useRef(null),de=G.useRef(w),Z=G.useRef(C),me=G.useRef(),ie=G.useRef(n),ue=zI(l),Ce=G.useRef(!1),Ee=G.useRef(!1);QS(()=>{let K=uw.init();return K.then(re=>(H.current=re)&&j(!1)).catch(re=>(re==null?void 0:re.type)!=="cancelation"&&console.error("Monaco initialization: error:",re)),()=>U.current?te():K.cancel()}),Pr(()=>{var re,ve,_e,Me;let K=eh(H.current,i||n||"",e||r||"",l||t||"");K!==((re=U.current)==null?void 0:re.getModel())&&(m&&Sg.set(ue,(ve=U.current)==null?void 0:ve.saveViewState()),(_e=U.current)==null||_e.setModel(K),m&&((Me=U.current)==null||Me.restoreViewState(Sg.get(l))))},[l],P),Pr(()=>{var K;(K=U.current)==null||K.updateOptions(f)},[f],P),Pr(()=>{!U.current||n===void 0||(U.current.getOption(H.current.editor.EditorOption.readOnly)?U.current.setValue(n):n!==U.current.getValue()&&(Ee.current=!0,U.current.executeEdits("",[{range:U.current.getModel().getFullModelRange(),text:n,forceMoveMarkers:!0}]),U.current.pushUndoStop(),Ee.current=!1))},[n],P),Pr(()=>{var re,ve;let K=(re=U.current)==null?void 0:re.getModel();K&&r&&((ve=H.current)==null||ve.editor.setModelLanguage(K,r))},[r],P),Pr(()=>{var K;a!==void 0&&((K=U.current)==null||K.revealLine(a))},[a],P),Pr(()=>{var K;(K=H.current)==null||K.editor.setTheme(p)},[p],P);let W=G.useCallback(()=>{var K;if(!(!oe.current||!H.current)&&!Ce.current){Z.current(H.current);let re=l||t,ve=eh(H.current,n||i||"",e||r||"",re||"");U.current=(K=H.current)==null?void 0:K.editor.create(oe.current,{model:ve,automaticLayout:!0,...f},v),m&&U.current.restoreViewState(Sg.get(re)),H.current.editor.setTheme(p),a!==void 0&&U.current.revealLine(a),N(!0),Ce.current=!0}},[i,e,t,n,r,l,f,v,m,p,a]);G.useEffect(()=>{P&&de.current(U.current,H.current)},[P]),G.useEffect(()=>{!L&&!P&&W()},[L,P,W]),ie.current=n,G.useEffect(()=>{var K,re;P&&x&&((K=me.current)==null||K.dispose(),me.current=(re=U.current)==null?void 0:re.onDidChangeModelContent(ve=>{Ee.current||x(U.current.getValue(),ve)}))},[P,x]),G.useEffect(()=>{if(P){let K=H.current.editor.onDidChangeMarkers(re=>{var _e;let ve=(_e=U.current.getModel())==null?void 0:_e.uri;if(ve&&re.find(Me=>Me.path===ve.path)){let Me=H.current.editor.getModelMarkers({resource:ve});$==null||$(Me)}});return()=>{K==null||K.dispose()}}return()=>{}},[P,$]);function te(){var K,re;(K=me.current)==null||K.dispose(),y?m&&Sg.set(l,U.current.saveViewState()):(re=U.current.getModel())==null||re.dispose(),U.current.dispose()}return Rt.createElement(ZS,{width:D,height:E,isEditorReady:P,loading:d,_ref:oe,className:T,wrapperProps:b})}var GI=BI,FI=G.memo(GI),tC=FI;const HI={ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",json:"json",jsonl:"json",ndjson:"json",py:"python",go:"go",rs:"rust",rb:"ruby",c:"c",h:"c",cpp:"cpp",hpp:"cpp",cc:"cpp",java:"java",sh:"shell",bash:"shell",zsh:"shell",css:"css",scss:"scss",less:"less",html:"html",htm:"html",xml:"xml",yaml:"yaml",yml:"yaml",toml:"ini",ini:"ini",conf:"ini",sql:"sql",md:"markdown",mdx:"markdown",markdown:"markdown",graphql:"graphql",dockerfile:"dockerfile"},WI=new Set(["md","mdx","markdown","txt","log"]);let Rx=!1;function UI(i){Rx||(Rx=!0,i.editor.defineTheme("sm-paper",{base:"vs",inherit:!0,rules:[],colors:{"editor.background":"#f6efe1","editor.foreground":"#2a221a","editorLineNumber.foreground":"#b8a98a","editorLineNumber.activeForeground":"#7a6a4f","editor.lineHighlightBackground":"#efe6d3","editor.selectionBackground":"#e0d3b8","editorCursor.foreground":"#b85c34","editorIndentGuide.background1":"#e6dcc4","editor.findMatchHighlightBackground":"#e8d7a8"}}),i.editor.defineTheme("sm-dark",{base:"vs-dark",inherit:!0,rules:[],colors:{"editor.background":"#1c1814","editor.foreground":"#e8dcc6","editorLineNumber.foreground":"#5b5040","editor.lineHighlightBackground":"#262017","editorCursor.foreground":"#d97a4a"}}))}function VI({path:i,name:e,value:t,onChange:n,onSave:r,onReady:l,onCursor:p,readOnly:a}){const d=G.useRef(null),f=G.useRef(null),v=G.useRef(r);v.current=r;const m=$i(x=>x.consumeReveal),y=Qu(x=>x.fontSize),D=Qu(x=>x.wordWrap),E=Qu(x=>x.minimap),T=Qu(x=>x.theme),b=WI.has(Nr(e)),C=(x,$)=>{d.current=x,f.current=$,UI($),$.editor.setTheme(T==="dark"?"sm-dark":"sm-paper"),x.addCommand($.KeyMod.CtrlCmd|$.KeyCode.KeyS,()=>v.current()),l==null||l(x);const P=()=>{const N=x.getPosition(),L=x.getSelection(),j=x.getModel(),H=L&&j?j.getValueLengthInRange(L):0;N&&(p==null||p({line:N.lineNumber,col:N.column,selected:H}))};x.onDidChangeCursorPosition(P),x.onDidChangeCursorSelection(P),P(),w(x)},w=x=>{const $=m(i);$!=null&&$.line&&(x.revealLineInCenter($.line),x.setPosition({lineNumber:$.line,column:$.col??1}),x.focus())};return G.useEffect(()=>{d.current&&w(d.current)},[i]),G.useEffect(()=>{var x;(x=f.current)==null||x.editor.setTheme(T==="dark"?"sm-dark":"sm-paper")},[T]),G.useEffect(()=>()=>{l==null||l(null)},[l]),h.jsx(tC,{path:`file://${i}`,language:HI[Nr(e)]||"plaintext",value:t,onChange:x=>n(x??""),onMount:C,theme:T==="dark"?"sm-dark":"sm-paper",options:{readOnly:!!a,minimap:{enabled:E},fontSize:b?y+2:y,fontFamily:b?"Newsreader, Georgia, serif":'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:b?"off":"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,detectIndentation:!0,stickyScroll:{enabled:!0},automaticLayout:!0,bracketPairColorization:{enabled:!0},padding:b?{top:16,bottom:16}:void 0,lineHeight:b?26:void 0,wordWrap:b||D?"on":"off"}})}function hw(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}let ld=hw();function iC(i){ld=i}const nC=/[&<>"']/,qI=new RegExp(nC.source,"g"),sC=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,KI=new RegExp(sC.source,"g"),YI={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},jx=i=>YI[i];function Rr(i,e){if(e){if(nC.test(i))return i.replace(qI,jx)}else if(sC.test(i))return i.replace(KI,jx);return i}const XI=/(^|[^\[])\^/g;function Gi(i,e){let t=typeof i=="string"?i:i.source;e=e||"";const n={replace:(r,l)=>{let p=typeof l=="string"?l:l.source;return p=p.replace(XI,"$1"),t=t.replace(r,p),n},getRegex:()=>new RegExp(t,e)};return n}function Nx(i){try{i=encodeURI(i).replace(/%25/g,"%")}catch{return null}return i}const Nf={exec:()=>null};function Mx(i,e){const t=i.replace(/\|/g,(l,p,a)=>{let d=!1,f=p;for(;--f>=0&&a[f]==="\\";)d=!d;return d?"|":" |"}),n=t.split(/ \|/);let r=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(/\\\|/g,"|");return n}function lf(i,e,t){const n=i.length;if(n===0)return"";let r=0;for(;r<n&&i.charAt(n-r-1)===e;)r++;return i.slice(0,n-r)}function JI(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<i.length;n++)if(i[n]==="\\")n++;else if(i[n]===e[0])t++;else if(i[n]===e[1]&&(t--,t<0))return n;return-1}function Ox(i,e,t,n){const r=e.href,l=e.title?Rr(e.title):null,p=i[1].replace(/\\([\[\]])/g,"$1");if(i[0].charAt(0)!=="!"){n.state.inLink=!0;const a={type:"link",raw:t,href:r,title:l,text:p,tokens:n.inlineTokens(p)};return n.state.inLink=!1,a}return{type:"image",raw:t,href:r,title:l,text:Rr(p)}}function ZI(i,e){const t=i.match(/^(\s+)(?:```)/);if(t===null)return e;const n=t[1];return e.split(`
2951
2951
  `).map(r=>{const l=r.match(/^\s+/);if(l===null)return r;const[p]=l;return p.length>=n.length?r.slice(n.length):r}).join(`
2952
2952
  `)}class lv{constructor(e){Bi(this,"options");Bi(this,"rules");Bi(this,"lexer");this.options=e||ld}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const n=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:lf(n,`
2953
2953
  `)}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const n=t[0],r=ZI(n,t[3]||"");return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(/#$/.test(n)){const r=lf(n,"#");(this.options.pedantic||!r||/ $/.test(r))&&(n=r.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:lf(t[0],`
@@ -3018,7 +3018,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3018
3018
 
3019
3019
  ${t}`}const Cf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},TR=["popover","review","diff"],gC=["popover","review"];function DR(i,e){switch(e.type){case"SELECT":return{...Cf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Cf,editCount:i.editCount};case"LISTEN":return gC.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 TR.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:{...Cf,editCount:i.editCount+1};case"RESET_FILE":return{...Cf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function $R(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 AR(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 IR="sonnet";function PR(i,e){const[t,n]=G.useReducer(DR,Cf),r=G.useRef(0),l=G.useRef(null),p=G.useRef(i),a=G.useRef(new Map);G.useEffect(()=>window.api.docEdit.onSessionResult(x=>{const $=a.current.get(x.requestId);$&&(a.current.delete(x.requestId),$(x))}),[]),G.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(),Ct.setState({externalRecording:!1}))}const f=G.useCallback(x=>{r.current+=1,d(),n({type:"SELECT",selection:x})},[]),v=G.useCallback(()=>{r.current+=1,d(),n({type:"CANCEL"})},[]),m=G.useCallback(()=>{if(!gC.includes(t.phase))return;if(Ct.getState().isRecording){lt.error("Microphone is already in use");return}if(!vv()){lt.error("Microphone or Web Worker not available");return}const x=++r.current;n({type:"LISTEN"}),Ct.setState({externalRecording:!0});const $=()=>{l.current===P&&(l.current=null),Ct.setState({externalRecording:!1})},P=M1({onFinal:N=>{if(r.current!==x)return;P.stop().catch(()=>{}),P.destroy(),$();const L=N.trim();if(!L){n({type:"CANCEL"});return}n({type:"HEARD",transcript:L})},onError:N=>{r.current===x&&(P.destroy(),$(),lt.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(),$(),lt.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),y=G.useCallback(()=>{const x=$R(i,xt.getState().tabs);if(!x)return null;const $=AR(x,xt.getState().tabs,Gg.getState().tabs);return!$||di.getState().get($.id).running?null:$},[i]),D=G.useCallback((x,$,P,N,L,j)=>{const H=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{a.current.set(H,U),window.api.docEdit.runInSession({tabId:x,sessionId:$,cwd:P,before:N,instruction:L,documentText:j,requestId:H})})},[]),E=G.useCallback(async(x,$)=>{const P=t.selection;if(!P)return;const N=++r.current;n({type:"RUN",instruction:x,recordInstruction:$});const L=ER(e);try{const j=y(),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){lt.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;lt.error(j instanceof Error?j.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,y,D]),T=G.useCallback(x=>{E(x,!0)},[E]),b=G.useCallback(()=>{t.phase==="review"&&E(t.transcript,!0)},[E,t.phase,t.transcript]),C=G.useCallback(()=>{const x=t.instruction;x&&E(`${x}
3020
3020
 
3021
- (Give a different rewrite than the last one.)`,!1)},[E,t.instruction]),w=G.useCallback(x=>{const $=t.diff;if(!$)return{ok:!1,reason:"not-found"};const P=CR(x,$.before,$.after);return P.ok?(r.current+=1,n({type:"ACCEPT"})):lt.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:v,listen:m,sendHeard:b,run:T,retry:C,accept:w}}const RR=[{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."}],n0=320,pf=8;function jR(){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 NR(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,pf),Math.max(pf,e-n0-pf)),n=Math.max(i.top-pf,pf);return{position:"fixed",left:t,top:n,width:n0,transform:"translateY(-100%)",zIndex:I2.dialog}}function MR({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:v,onReject:m,onRetry:y}){const[D,E]=G.useState(""),T=()=>{const b=D.trim();b&&(p(b),E(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:NR(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"}),RR.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=>E(b.target.value),onKeyDown:b=>{b.key==="Enter"?T():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(jR,{}),"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:y,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function OR(){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 s0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:v}){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:Ub(IR)})]}),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(OR,{}),"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:v,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 LR(){const i=xt(t=>t.tabs),e=xt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function r0(i){return i.split("/").filter(Boolean).pop()||i}function zR({path:i,onRenamed:e,onDeleted:t}){const[n,r]=G.useState(!1),[l,p]=G.useState(!1),[a,d]=G.useState(""),[f,v]=G.useState(!1),m=$i(U=>U.buffers[i]),y=$i(U=>U.openFile),D=$i(U=>U.renameOpenFile),E=$i(U=>U.closeFile),T=LR(),b=r0(i),C=()=>r(!1),w=()=>{d(b),p(!0),C()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const oe=await window.api.files.rename(i,U);if(oe.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=oe.newPath??`${de}/${U}`;D(i,Z),e==null||e(i,Z),lt.info(`Renamed to ${U}`)}else lt.error(oe.error??`Couldn't rename ${b}`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't rename ${b}`)}p(!1)},$=async()=>{C();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(y(U.path),lt.info(`Duplicated as ${r0(U.path)}`)):lt.error(U.error??`Couldn't duplicate ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},P=async()=>{try{const U=await window.api.files.delete(i);U.ok?(E(i),t==null||t(i),lt.info(`Deleted ${b}`)):lt.error(U.error??`Couldn't delete ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}v(!1)},N=async()=>{C();const U=m??"";try{await navigator.clipboard.writeText(U),lt.info(`Copied ${U.length} chars`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!T){lt.error("No terminal tab is active");return}window.api.pty.write({tabId:T.id,data:`@${i} `}),lt.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't open ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(U=>!U),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 ${Cn.contextMenuScrim}`,onMouseDown:C}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[h.jsx(f_,{children:"Edit"}),h.jsx(Jc,{label:"Rename",onClick:w}),h.jsx(Jc,{label:"Duplicate",onClick:$}),h.jsx(Jc,{label:"Delete document",danger:!0,onClick:()=>{C(),v(!0)}}),h.jsx(o0,{}),h.jsx(f_,{children:"Open"}),h.jsx(Jc,{label:"Open in default app",onClick:j}),h.jsx(Jc,{label:"Reveal in OS",onClick:H}),h.jsx(o0,{}),h.jsx(f_,{children:"Export"}),h.jsx(Jc,{label:"Copy as Markdown",onClick:N}),h.jsx(Jc,{label:"Add to Claude context",onClick:L,disabled:!T,title:T?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(BR,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(GR,{name:b,onCancel:()=>v(!1),onConfirm:()=>void P()})]})}function f_({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 Jc({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 o0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function BR({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 GR({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 FR(){const[i,e]=G.useState(!1),t=Qu();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 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[h.jsx(Yu,{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(Yu,{label:"Word wrap",children:h.jsx(Eg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Yu,{label:"Minimap",children:h.jsx(Eg,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Yu,{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(Yu,{label:"Autosave",children:h.jsx(Eg,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Yu,{label:"Wide measure",children:h.jsx(Eg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Yu({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 Eg({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 HR=G.lazy(()=>os(()=>import("./TiptapBody-A93HQtTH.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Tg(i){return i.split("/").filter(Boolean).pop()||i}function Dg(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 $g(i){return FS(i)||HS(i)}function WR(){const i=sw(),e=$i(Ye=>Ye.openFiles),t=$i(Ye=>Ye.activeFilePath),n=$i(Ye=>Ye.dirty),r=$i(Ye=>Ye.viewMode),l=$i(Ye=>Ye.buffers),p=$i(Ye=>Ye.setActive),a=$i(Ye=>Ye.closeFile),d=$i(Ye=>Ye.closeOthers),f=$i(Ye=>Ye.closeToTheRight),v=$i(Ye=>Ye.closeAll),m=$i(Ye=>Ye.loadBuffer),y=$i(Ye=>Ye.setBuffer),D=$i(Ye=>Ye.markSaved),E=$i(Ye=>Ye.setViewMode),T=Qu(),[b,C]=G.useState({}),[w,x]=G.useState({}),[$,P]=G.useState(null),[N,L]=G.useState(null),[j,H]=G.useState(!1),[U,oe]=G.useState(!1),[de,Z]=G.useState(!0),me=G.useRef(null),ie=G.useRef(null),ue=G.useRef(void 0),Ce=G.useRef(null),Ee=G.useRef(null),W=PR(t??"",l[t??""]??""),te=G.useCallback(Ye=>{me.current=Ye},[]),K=G.useCallback(()=>me.current,[]);G.useEffect(()=>{const Ye=t;if(!Ye||$g(Ye))return;if($i.getState().hasBuffer(Ye)){C(ut=>ut[Ye]==="ready"?ut:{...ut,[Ye]:"ready"});return}let St=!1;return C(ut=>({...ut,[Ye]:"loading"})),window.api.files.read(Ye).then(ut=>{St||(ut.binary?C(Xe=>({...Xe,[Ye]:{binary:!0,size:ut.size??0,mime:ut.mime??"application/octet-stream",reason:ut.error??"Binary file"}})):ut.ok?(m(Ye,ut.text),C(Xe=>({...Xe,[Ye]:"ready"}))):C(Xe=>({...Xe,[Ye]:{error:ut.error??"failed to read"}})))}),()=>{St=!0}},[t,m]),G.useEffect(()=>{L(null)},[t]);const re=G.useCallback(async(Ye,St=!1)=>{const ut=$i.getState().buffers[Ye];if(ut==null)return;St&&H(!0);const Xe=await window.api.files.write(Ye,ut);Xe.ok?(D(Ye),x(Pt=>({...Pt,[Ye]:(Pt[Ye]??0)+1})),St||lt.info(`Saved ${Tg(Ye)}`)):lt.error(Xe.error??`Couldn't save ${Tg(Ye)}`),St&&H(!1)},[D]);G.useEffect(()=>{if(!T.autosave)return;const Ye=t;if(!(!Ye||$g(Ye)||!n[Ye]))return window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{re(Ye,!0)},1200),()=>window.clearTimeout(ue.current)},[T.autosave,t,n,l,re]);const ve=G.useCallback(Ye=>{Ye.length&&(C(St=>Dg(St,Ye)),x(St=>Dg(St,Ye)))},[]),_e=G.useCallback((Ye,St)=>{C(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut),x(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut)},[]),Me=G.useCallback(Ye=>{n[Ye]?P({kind:"one",path:Ye}):(a(Ye),ve([Ye]))},[n,a,ve]),et=G.useCallback(Ye=>{e.some(ut=>ut.path!==Ye&&n[ut.path])?P({kind:"others",path:Ye}):(d(Ye),ve(e.filter(ut=>ut.path!==Ye).map(ut=>ut.path)))},[e,n,d,ve]),we=G.useCallback(Ye=>{const St=e.findIndex(Xe=>Xe.path===Ye);St!==-1&&e.slice(St+1).some(Xe=>n[Xe.path])?P({kind:"right",path:Ye}):(f(Ye),ve(St!==-1?e.slice(St+1).map(Xe=>Xe.path):[]))},[e,n,f,ve]);G.useEffect(()=>{const Ye=St=>{if(i.current)if((St.metaKey||St.ctrlKey)&&(St.key==="s"||St.key==="S")){const ut=$i.getState().activeFilePath;ut&&!$g(ut)&&(St.preventDefault(),re(ut))}else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="f"||St.key==="F"))St.preventDefault(),oe(ut=>!ut);else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="w"||St.key==="W")){const ut=$i.getState().activeFilePath;ut&&$i.getState().openFiles.length>1&&(St.preventDefault(),et(ut))}else St.key==="Escape"&&W.state.phase!=="idle"?W.cancel():St.key==="Escape"&&U&&oe(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[re,U,et,W.state.phase,W.cancel]),G.useEffect(()=>{if(W.state.phase==="idle")return;const Ye=St=>{var Xe,Pt;const ut=St.target;(Xe=Ee.current)!=null&&Xe.contains(ut)||(Pt=Ce.current)!=null&&Pt.contains(ut)||W.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[W.state.phase,W.cancel]),G.useEffect(()=>{W.cancel()},[t,W.cancel]);const X=G.useCallback(()=>{e.some(St=>n[St.path])?P({kind:"all",path:""}):(v(),C({}),x({}))},[e,n,v]),Ie=()=>{if($){if($.kind==="one")a($.path),ve([$.path]);else if($.kind==="others"){const Ye=e.filter(St=>St.path!==$.path).map(St=>St.path);d($.path),ve(Ye)}else if($.kind==="right"){const Ye=e.findIndex(ut=>ut.path===$.path),St=Ye!==-1?e.slice(Ye+1).map(ut=>ut.path):[];f($.path),ve(St)}else v(),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 pe=t,Ze=pe?Tg(pe):"",ge=pe?b[pe]:void 0,Ke=pe?VS(pe):!1,vt=pe?AA(pe):!1,st=pe&&Ke?r[pe]??IA(pe):"edit",Kt=!!pe&&!$g(pe)&&ge==="ready",Be=Kt,Dt=vt?["edit","wysiwyg","preview","split"]:Ke?["edit","preview"]:[],_t=pe&&h.jsx(VI,{path:pe,name:Ze,value:l[pe]??"",onChange:Ye=>y(pe,Ye),onSave:()=>void re(pe),onReady:te,onCursor:L}),ri=j?"Saving…":pe&&n[pe]?T.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&h.jsx(jA,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Me,onCloseOthers:et,onCloseToTheRight:we,onCloseAll:X}),pe&&!U&&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:Ze}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:pe}),Kt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ri]}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:()=>Z(Ye=>!Ye),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"}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:T.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${T.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ye=>h.jsx("button",{onClick:()=>E(pe,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${st===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),h.jsx("div",{className:"flex-1"}),h.jsx(zR,{path:pe,onRenamed:_e,onDeleted:Ye=>ve([Ye])}),Kt&&h.jsx(FR,{}),h.jsx("button",{onClick:()=>oe(!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"})]}),U&&h.jsx("button",{onClick:()=>oe(!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:pe?FS(pe)?h.jsx(mR,{path:pe,name:Ze}):HS(pe)?h.jsx(gR,{path:pe}):ge&&typeof ge=="object"&&"binary"in ge?h.jsx(SR,{path:pe,name:Ze,size:ge.size,mime:ge.mime,reason:ge.reason}):ge&&typeof ge=="object"&&"error"in ge?h.jsx("div",{className:"p-6 text-xs text-red-400",children:ge.error}):ge!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):st==="wysiwyg"&&qa(pe)?h.jsx(G.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(HR,{value:l[pe]??"",onChange:Ye=>y(pe,Ye)},pe)}):st==="split"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(e0,{text:l[pe]??"",scrollRef:ie}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(Qx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(pb,{ref:ie,text:l[pe]??"",flush:!0,wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(s0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(e0,{text:l[pe]??"",scrollRef:ie}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(pb,{ref:ie,text:l[pe]??"",wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(s0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&GS(pe)?h.jsx(pR,{path:pe,dirty:!!n[pe],reloadToken:w[pe]??0}):st==="preview"&&WS(pe)?h.jsx(_R,{path:pe,text:l[pe]??""}):st==="preview"&&US(pe)?h.jsx(yR,{path:pe,text:l[pe]??""}):qa(pe)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(Qx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),Be&&h.jsx(hR,{text:l[pe]??"",cursor:N,language:Nr(pe)||void 0}),pe&&qa(pe)&&(st==="preview"||st==="split")&&W.state.phase!=="idle"&&W.state.selection&&h.jsx("div",{ref:Ee,children:h.jsx(MR,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)}})}),$&&h.jsx(UR,{message:$.kind==="one"?`Discard unsaved changes to ${Tg($.path)}?`:$.kind==="others"?"Discard unsaved changes in the other open files?":$.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>P(null),onConfirm:Ie})]})}const gb=G.memo(WR);function UR({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 VR={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},a0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function ww({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=G.useRef(null),f=G.useRef(null),v=G.useRef(e);if(v.current=e,G.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const E=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(a0);C?C.focus():b.focus()},0),T=b=>{if(b.key==="Escape"){b.stopPropagation(),v.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const w=Array.from(C.querySelectorAll(a0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(w.length===0){b.preventDefault(),C.focus();return}const x=w[0],$=w[w.length-1],P=document.activeElement;b.shiftKey?(P===x||!C.contains(P))&&(b.preventDefault(),$.focus()):(P===$||!C.contains(P))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",T),()=>{clearTimeout(E),document.removeEventListener("keydown",T);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()},y=h.jsx("div",{className:`fixed inset-0 ${Cn.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 ${VR[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(y,document.body):y}class vC extends G.Component{constructor(){super(...arguments);Bi(this,"state",{error:null});Bi(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 qR({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(ww,{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(vC,{children:n})})]})}function _C(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 l0=i=>Symbol.iterator in i,c0=i=>"entries"in i,d0=(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},KR=(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 YR(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:l0(i)&&l0(e)?c0(i)&&c0(e)?d0(i,e):KR(i,e):d0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function yw(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return YR(e.current,n)?e.current:e.current=n}}let u0=0;const XR=1e3;function JR(i){const e=performance.now();e-u0<XR||(u0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function ZR(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(yw(tv)),r=()=>{const f=Ct.getState(),{canRecord:v,reason:m}=tv(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(!v)return JR(m);const y=xt.getState().activeTabId;y&&f.startRecording(y)},l=_C(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 QR(){const i=Ct(t=>t.ttsEnabled),e=Ct(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 ej(i){return/^monitor of /i.test(i.trim())}function h0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function p0(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=h0(e),l=t.filter(p=>p.label&&h0(p.label)===r);return l.length===1?l[0]:null}async function f0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&ej(n.label))):[]}const m0=!1;function bC(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=G.useState([]),[n,r]=G.useState(null),[l,p]=G.useState(null);G.useEffect(()=>{let f=!1;return(async()=>{try{const v=await window.api.voice.getDevicePref();if(f)return;const m=await f0(m0);if(f)return;t(m),p(v.selectedLabel);const y=p0(v.selectedDeviceId,v.selectedLabel,m);y?(r(y.deviceId),v.selectedDeviceId&&y.deviceId!==v.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:v.selectedDeviceId.slice(0,8),toIdPrefix:y.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:y.deviceId,selectedLabel:y.label||v.selectedLabel}).catch(()=>{}))):((v.selectedDeviceId||v.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:v.selectedLabel,hadId:!!v.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!v.selectedDeviceId})),r(null))}catch(v){pt.warn("voice","device-picker init failed",{error:v instanceof Error?v.message:String(v)})}})(),()=>{f=!0}},[]);const a=G.useCallback(async()=>{try{const f=await f0(m0);if(t(f),n&&!f.some(v=>v.deviceId===n)){const v=p0(null,l,f);v?(r(v.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);G.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 v=f.target.value,m=v===""?null:v,y=m?((D=e.find(E=>E.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(y);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:y}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(E){pt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(i)try{await Ct.getState().restartWithDevice()}catch(E){pt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};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 tj(){const i=Ct(D=>D.isRecording),e=Ct(D=>D.levelMeterEnabled),[t,n]=G.useState(0),[r,l]=G.useState(0),p=G.useRef(0);p.current=r;const[a,d]=G.useState(0),[f,v]=G.useState(!1),m=G.useRef(null);if(G.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,E=!1,T=null,b=null;const C=()=>{if(E)return;const x=b??z1();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,T=new Uint8Array(new ArrayBuffer(x.fftSize)));const $=T;x.getByteTimeDomainData($);let P=0;for(let H=0;H<$.length;H++){const U=$[H]-128;P+=U*U}const N=Math.sqrt(P/$.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&&(v(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>v(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const w=setInterval(()=>{E||d(Math.round(p.current*100))},250);return()=>{E=!0,cancelAnimationFrame(D),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const y=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 ${y} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function wC(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=G.useState(()=>performance.now());if(G.useEffect(()=>{if(i===null)return;let f;const v=()=>{n(performance.now()),f=requestAnimationFrame(v)};return f=requestAnimationFrame(v),()=>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=Ct.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 ij({open:i,onClose:e,variant:t="overlay"}){return h.jsx(qR,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(oj,{}),h.jsx(wC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(ZR,{}),h.jsx(bC,{}),h.jsx(QR,{})]}),h.jsx(nj,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),h.jsx(rj,{})]}),h.jsx(tj,{})]})})}function nj(){const i=Ct(l=>l.isRecording),[e,t]=G.useState(null);if(G.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=sj(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 sj(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 rj(){const[i,e]=G.useState(null);if(G.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.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){pt.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 oj(){const i=Ct(l=>l.isRecording),e=Ct(l=>l.lastTranscript),t=Ct(l=>l.error),n=Ct(l=>l.modelStatus),r=Ct(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 yC="~/.claude/session-manager/projects-prefs.json",aj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function zl(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(yC,t).catch(()=>{})}const g0=In((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(yC);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}),zl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":aj[t];i({sort:{col:t,dir:r}}),zl(e)},setRecentFilter:t=>{i({recentFilter:t}),zl(e)},setHasRemote:t=>{i({hasRemote:t}),zl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),zl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),zl(e)},setSearch:t=>{i({search:t}),zl(e)},setEditor:t=>{i({editor:t}),zl(e)}})),xC=i=>`sm.fileTree.expanded:${i}`;function lj(i){try{const e=localStorage.getItem(xC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function cj(i,e){try{localStorage.setItem(xC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const SC="sm.fileTree.showHidden";function dj(){try{const i=localStorage.getItem(SC);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function uj(i){try{localStorage.setItem(SC,JSON.stringify(i))}catch{}}function m_(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 g_={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:"!"}},hj=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 pj(i){const e=Nr(i);return hj.has(e)||BS.has(e)||e==="pdf"}function fj(i,e){if(e)return"#d97757";switch(Nr(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 ff(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 mj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=sw(),l=nw(),[p,a]=G.useState([]),[d,f]=G.useState(new Set),v=G.useRef(d);v.current=d;const[m,y]=G.useState(""),[D,E]=G.useState(dj),T=G.useCallback(Be=>{E(Dt=>{const _t=typeof Be=="function"?Be(Dt):Be;return uj(_t),_t})},[]),[b,C]=G.useState(!1),[w,x]=G.useState(null),[$,P]=G.useState({}),[N,L]=G.useState(null),[j,H]=G.useState(null),[U,oe]=G.useState(""),[de,Z]=G.useState(null),[me,ie]=G.useState(""),[ue,Ce]=G.useState(null),Ee=G.useRef(null),W=G.useRef(null),te=G.useRef(0),K=G.useCallback(async()=>{if(!i)return;const Be=++te.current;C(!0),x(null);const Dt=await window.api.files.list(i,D);te.current===Be&&(Dt.ok?a(Dt.entries.map(_t=>({..._t}))):(x(Dt.error??"failed to list"),a([])),C(!1))},[i,D]),re=G.useCallback(async Be=>{const Dt=te.current,_t=new Map;for(const Ye of Be){const St=Ye.split("/").length,ut=_t.get(St);ut?ut.push(Ye):_t.set(St,[Ye])}const ri=[];for(const Ye of[..._t.keys()].sort((St,ut)=>St-ut)){const St=_t.get(Ye),ut=await Promise.all(St.map(async Xe=>({p:Xe,result:await window.api.files.list(Xe,D)})));if(te.current!==Dt)return ri;for(const{p:Xe,result:Pt}of ut)Pt.ok?a(oi=>Wg(oi,Xe,Pt.entries.map(Fi=>({...Fi})))):ri.push(Xe)}return ri},[D]),ve=G.useCallback(async Be=>(await K(),Be.length?re(Be):[]),[K,re]);G.useEffect(()=>{y(""),H(null),L(null),Z(null),Ce(null),P({});const Be=lj(i),Dt=new Set(Be);v.current=Dt,f(Dt);let _t=!1;return(async()=>{const ri=await ve(Be);_t||!ri.length||Me(Ye=>{const St=new Set;let ut=!1;for(const Xe of Ye){if(ri.some(Pt=>Xe===Pt||Xe.startsWith(Pt+"/"))){ut=!0;continue}St.add(Xe)}return ut?St:Ye})})(),ff(i).then(ri=>{_t||P(ri)}),()=>{_t=!0}},[i]);const _e=G.useRef(!0);G.useEffect(()=>{if(_e.current){_e.current=!1;return}ve([...v.current])},[D]),G.useEffect(()=>{if(!i||!l)return;ff(i).then(P);const Be=window.setInterval(()=>{ff(i).then(P)},5e3);return()=>window.clearInterval(Be)},[i,l]),G.useEffect(()=>{if(!N)return;const Be=()=>L(null),Dt=_t=>{r.current&&_t.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Be),window.addEventListener("keydown",Dt),()=>{window.removeEventListener("mousedown",Be),window.removeEventListener("keydown",Dt)}},[N]),G.useEffect(()=>{j&&setTimeout(()=>{var Be;return(Be=Ee.current)==null?void 0:Be.select()},30)},[j]),G.useEffect(()=>{de&&setTimeout(()=>{var Be;return(Be=W.current)==null?void 0:Be.focus()},30)},[de]);const Me=G.useCallback(Be=>{const Dt=v.current,_t=Be(Dt);_t!==Dt&&(v.current=_t,f(_t),cj(i,_t))},[i]),et=G.useCallback(async Be=>{if(d.has(Be.path)){Me(_t=>m_(_t,Be.path));return}if(Me(_t=>new Set(_t).add(Be.path)),Be.children)return;const Dt=await window.api.files.list(Be.path,D);Dt.ok&&a(_t=>Wg(_t,Be.path,Dt.entries.map(ri=>({...ri}))))},[d,D,Me]),we=G.useCallback(async Be=>{if(Be===i){await K();return}const Dt=await window.api.files.list(Be,D);Dt.ok&&a(_t=>Wg(_t,Be,Dt.entries.map(ri=>({...ri}))))},[i,K,D]),X=G.useCallback(Be=>{if(Be.isDirectory){et(Be);return}pj(Be.name)&&e?e(Be.path):window.api.shell.open({as:"openPath",path:Be.path})},[et,e]),Ie=G.useCallback(Be=>{if(t){t(Be);return}if(n){const Dt=Be.startsWith(i+"/")?Be.slice(i.length+1):Be;window.api.pty.write({tabId:n,data:`@${Dt} `})}},[t,n,i]),pe=G.useCallback((Be,Dt)=>{Be.preventDefault(),Be.stopPropagation(),L({x:Be.clientX,y:Be.clientY,node:Dt})},[]),Ze=Be=>{H(Be.path),oe(Be.name)},ge=async()=>{if(!j)return;const Be=U.trim();if(!Be){H(null);return}const Dt=await window.api.files.rename(j,Be);if(H(null),Dt.ok){const _t=j.slice(0,j.lastIndexOf("/"));Me(ri=>m_(ri,j)),await we(_t||i),ff(i).then(P)}else{const _t=Dt.error??"rename failed";x(_t),lt.error(_t)}},Ke=async()=>{if(!de)return;const Be=me.trim();if(!Be){Z(null),ie("");return}const Dt=await window.api.files.create(de.parent,Be,de.kind);if(Z(null),ie(""),Dt.ok)await we(de.parent),de.kind==="folder"&&Me(_t=>new Set(_t).add(de.parent));else{const _t=Dt.error??"create failed";x(_t),lt.error(_t)}},vt=async()=>{if(!ue)return;const Be=await window.api.files.delete(ue.path),Dt=ue.path.slice(0,ue.path.lastIndexOf("/"));if(Ce(null),Be.ok)Me(_t=>m_(_t,ue.path)),await we(Dt||i),ff(i).then(P);else{const _t=Be.error??"delete failed";x(_t),lt.error(_t)}},st=G.useMemo(()=>{if(!m.trim())return p;const Be=m.toLowerCase();return p.filter(Dt=>Dt.name.toLowerCase().includes(Be))},[p,m]),Kt=(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(kC,{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:Kt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:K,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(yj,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Be=>y(Be.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(xj,{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(Sj,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>T(Be=>!Be),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(Cj,{size:12}):h.jsx(kj,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&st.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&h.jsx(CC,{nodes:st,depth:0,expanded:d,gitStatus:$,renaming:j,renameValue:U,renameInputRef:Ee,onRenameChange:oe,onRenameCommit:ge,onRenameCancel:()=>H(null),onToggleDir:et,onFileClick:X,onSendToChat:Ie,onContextMenu:pe})]}),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(gj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Ze(N.node),L(null)},onDelete:()=>{Ce(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 Be;(Be=navigator.clipboard)==null||Be.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx(v0,{title:`New ${de.kind}`,subtitle:`in ${vj(de.parent)}`,onCancel:()=>{Z(null),ie("")},onConfirm:Ke,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:W,value:me,onChange:Be=>ie(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"&&Ke(),Be.key==="Escape"&&(Z(null),ie(""))},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"})}),ue&&h.jsx(v0,{title:`Delete ${ue.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>Ce(null),onConfirm:vt,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:['"',ue.name,'"']})," to the trash?",ue.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function CC(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,v=r[a.path],m=fj(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:y=>p(y,a),children:[a.isDirectory?h.jsx(wj,{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(_j,{size:12,color:m}):h.jsx(kC,{size:12,color:m}):h.jsx(bj,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:y=>i.onRenameChange(y.target.value),onClick:y=>y.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:y=>{y.key==="Enter"&&i.onRenameCommit(),y.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}),v&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:g_[v].color,backgroundColor:`${g_[v].color}20`},title:v,children:g_[v].label}),!a.isDirectory&&h.jsx("button",{onClick:y=>{y.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(Ej,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(CC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function gj(i){const{x:e,y:t,node:n}=i;return h.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${Cn.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(Bl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Bl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Bl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(v_,{}),h.jsx(Bl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Bl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(v_,{}),h.jsx(Bl,{label:"New file",onClick:i.onNewFile}),h.jsx(Bl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(v_,{}),h.jsx(Bl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Bl({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 v_(){return h.jsx("div",{className:"my-1 border-t border-line"})}function v0(i){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 vj(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Wg(n.children,e,t)}:n)}function ma({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 kC({size:i,className:e,color:t}){return h.jsx(ma,{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 _j({size:i,className:e,color:t}){return h.jsx(ma,{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 bj({size:i,className:e,color:t}){return h.jsxs(ma,{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 wj({size:i,className:e}){return h.jsx(ma,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function yj({size:i,className:e}){return h.jsxs(ma,{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 xj({size:i,className:e}){return h.jsxs(ma,{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 Sj({size:i,className:e}){return h.jsxs(ma,{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 Cj({size:i,className:e}){return h.jsxs(ma,{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 kj({size:i,className:e}){return h.jsxs(ma,{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 Ej({size:i,className:e}){return h.jsxs(ma,{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 Tj({content:i,children:e,align:t="bottom-right"}){const[n,r]=G.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 ${Cn.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 Of(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const vb="sm.projects.splitPct",_b=33,EC=20,TC=60,DC="sm.projects.fileTreeCollapsed",Dj=32;function $j(){try{const i=parseFloat(localStorage.getItem(vb)??"");if(Number.isFinite(i))return Math.min(TC,Math.max(EC,i))}catch{}return _b}function Aj(){try{return localStorage.getItem(DC)==="1"}catch{return!1}}function Ij(){const i=xt(U=>U.tabs),e=xt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ei(U=>U.navFace),[r,l]=G.useState(null);G.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(oe=>{U||l(oe)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=G.useState(()=>$j()),[f,v]=G.useState(()=>Aj()),[m,y]=G.useState(!1),D=G.useRef(a);D.current=a;const E=G.useRef(null),T=G.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:w}=hh(),x=g0(U=>U.pinned),$=g0(U=>U.togglePin),P=[...b].sort((U,oe)=>(x[oe.cwd]?1:0)-(x[U.cwd]?1:0));G.useEffect(()=>{if(!m)return;const U=oe=>{T.current&&!T.current.contains(oe.target)&&y(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=G.useCallback(U=>{$i.getState().openFile(U)},[]),L=G.useCallback(U=>{U.preventDefault();const oe=U.clientX,de=D.current;let Z=de;const me=ue=>{const Ce=E.current;if(!Ce)return;const Ee=Ce.getBoundingClientRect(),W=ue.clientX-oe;Z=Math.min(TC,Math.max(EC,de+W/Ee.width*100)),d(Z)},ie=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",ie),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(vb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",ie),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=G.useCallback(()=>{d(_b);try{localStorage.setItem(vb,String(_b))}catch{}},[]),H=G.useCallback(()=>{v(U=>{const oe=!U;try{localStorage.setItem(DC,oe?"1":"0")}catch{}return oe})},[]);return f?h.jsxs("div",{ref:E,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:Dj},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(gb,{})})]}):h.jsxs("div",{ref:E,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:T,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>y(U=>!U),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?Of(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 ${Cn.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(U=>{const oe=Of(U.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(Tj,{content:x[U.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>$(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(U.cwd),y(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:oe}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${oe}?`)&&await w(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.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:Of(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(mj,{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(gb,{})})]})}const Pj=G.memo(Ij),Rj={"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."]}},xw="sm.learningPanel.collapsed";function _0(){try{const i=localStorage.getItem(xw);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 b0(i){try{localStorage.setItem(xw,i?"1":"0")}catch{}}function jj({active:i}){const[e,t]=G.useState(()=>!_0()),n=G.useRef(null),r=G.useCallback(()=>{t(a=>{const d=!a;return b0(!d),d})},[]);G.useEffect(()=>{const a=d=>{d.key===xw&&t(!_0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),G.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),b0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=G.useRef(!1);G.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=Rj[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 Nj({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(jj,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const Mj=G.lazy(()=>os(()=>import("./Skills-H8pCR_6D.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),Oj=G.lazy(()=>os(()=>import("./History-CiqbZNCW.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),Lj=G.lazy(()=>os(()=>import("./Scheduler-LdawPR1e.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),zj=G.lazy(()=>os(()=>import("./Settings-7jHzkgfK.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),Bj=G.lazy(()=>os(()=>import("./Permissions-BDRMk8Uu.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),Gj=G.lazy(()=>os(()=>import("./SystemPrompt-fCD2rD2R.js"),__vite__mapDeps([19,4,7,6,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),Fj=G.lazy(()=>os(()=>import("./Memory-MyToD3ri.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),Hj=G.lazy(()=>os(()=>import("./Plugins-Bd1wIgVW.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),Wj=G.lazy(()=>os(()=>import("./McpServers-C3b18FY5.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),Uj=G.lazy(()=>os(()=>import("./Hooks-1LHEEKhK.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),Vj=G.lazy(()=>os(()=>import("./AgentLibrary-DngWZmn2.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),qj=G.lazy(()=>os(()=>import("./TagLibrary-erEiP4bj.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),Kj=G.lazy(()=>os(()=>import("./HostBilko-DruBVVx_.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),Yj=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ir({children:i}){return h.jsx(G.Suspense,{fallback:Yj,children:i})}const Xj={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."}},Jj=()=>{},w0=new Map;function Zj(i,e){const t=w0.get(i);if(t&&t.ctx===e)return t.node;const n=Qj(i,e);return w0.set(i,{ctx:e,node:n}),n}function Qj(i,e){switch(i){case"overview":return h.jsx(R$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(CA,{});case"editor":return h.jsx(gb,{});case"projects":return h.jsx(Pj,{})}const t=Xj[i],n=(()=>{switch(i){case"skills":return h.jsx(Ir,{children:h.jsx(Mj,{})});case"history":return h.jsx(Ir,{children:h.jsx(Oj,{})});case"scheduler":return h.jsx(Ir,{children:h.jsx(Lj,{navigate:e.onNavigate})});case"plugins":return h.jsx(Ir,{children:h.jsx(Hj,{})});case"mcp":return h.jsx(Ir,{children:h.jsx(Wj,{})});case"hooks":return h.jsx(Ir,{children:h.jsx(Uj,{})});case"memory":return h.jsx(Ir,{children:h.jsx(Fj,{})});case"system-prompt":return h.jsx(Ir,{children:h.jsx(Gj,{})});case"permissions":return h.jsx(Ir,{children:h.jsx(Bj,{})});case"settings":return h.jsx(Ir,{children:h.jsx(zj,{})});case"agent-library":return h.jsx(Ir,{children:h.jsx(Vj,{})});case"tag-library":return h.jsx(Ir,{children:h.jsx(qj,{})});case"bilko-host":return h.jsx(Ir,{children:h.jsx(Kj,{})});case"voice":return h.jsx(ij,{open:!0,onClose:Jj,variant:"page"});default:return null}})();if(!n)return null;const r=SE[i];return t&&r?h.jsx(Nj,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var __={exports:{}},y0;function eN(){return y0||(y0=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(w,x,$,P){var N,L=arguments.length,j=L<3?x:P===null?P=Object.getOwnPropertyDescriptor(x,$):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(w,x,$,P);else for(var H=w.length-1;H>=0;H--)(N=w[H])&&(j=(L<3?N(j):L>3?N(x,$,j):N(x,$))||j);return L>3&&j&&Object.defineProperty(x,$,j),j},v=this&&this.__param||function(w,x){return function($,P){x($,P,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),y=d(9924),D=d(844),E=d(4725),T=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(w,x,$,P){super(),this._terminal=w,this._coreBrowserService=$,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 y.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(`
3021
+ (Give a different rewrite than the last one.)`,!1)},[E,t.instruction]),w=G.useCallback(x=>{const $=t.diff;if(!$)return{ok:!1,reason:"not-found"};const P=CR(x,$.before,$.after);return P.ok?(r.current+=1,n({type:"ACCEPT"})):lt.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:v,listen:m,sendHeard:b,run:T,retry:C,accept:w}}const RR=[{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."}],n0=320,pf=8;function jR(){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 NR(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,pf),Math.max(pf,e-n0-pf)),n=Math.max(i.top-pf,pf);return{position:"fixed",left:t,top:n,width:n0,transform:"translateY(-100%)",zIndex:I2.dialog}}function MR({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:v,onReject:m,onRetry:y}){const[D,E]=G.useState(""),T=()=>{const b=D.trim();b&&(p(b),E(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:NR(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"}),RR.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=>E(b.target.value),onKeyDown:b=>{b.key==="Enter"?T():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(jR,{}),"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:y,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function OR(){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 s0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:v}){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:Ub(IR)})]}),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(OR,{}),"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:v,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 LR(){const i=xt(t=>t.tabs),e=xt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function r0(i){return i.split("/").filter(Boolean).pop()||i}function zR({path:i,onRenamed:e,onDeleted:t}){const[n,r]=G.useState(!1),[l,p]=G.useState(!1),[a,d]=G.useState(""),[f,v]=G.useState(!1),m=$i(U=>U.buffers[i]),y=$i(U=>U.openFile),D=$i(U=>U.renameOpenFile),E=$i(U=>U.closeFile),T=LR(),b=r0(i),C=()=>r(!1),w=()=>{d(b),p(!0),C()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const oe=await window.api.files.rename(i,U);if(oe.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=oe.newPath??`${de}/${U}`;D(i,Z),e==null||e(i,Z),lt.info(`Renamed to ${U}`)}else lt.error(oe.error??`Couldn't rename ${b}`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't rename ${b}`)}p(!1)},$=async()=>{C();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(y(U.path),lt.info(`Duplicated as ${r0(U.path)}`)):lt.error(U.error??`Couldn't duplicate ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},P=async()=>{try{const U=await window.api.files.delete(i);U.ok?(E(i),t==null||t(i),lt.info(`Deleted ${b}`)):lt.error(U.error??`Couldn't delete ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}v(!1)},N=async()=>{C();const U=m??"";try{await navigator.clipboard.writeText(U),lt.info(`Copied ${U.length} chars`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!T){lt.error("No terminal tab is active");return}window.api.pty.write({tabId:T.id,data:`@${i} `}),lt.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't open ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(U=>!U),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 ${Cn.contextMenuScrim}`,onMouseDown:C}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[h.jsx(f_,{children:"Edit"}),h.jsx(Jc,{label:"Rename",onClick:w}),h.jsx(Jc,{label:"Duplicate",onClick:$}),h.jsx(Jc,{label:"Delete document",danger:!0,onClick:()=>{C(),v(!0)}}),h.jsx(o0,{}),h.jsx(f_,{children:"Open"}),h.jsx(Jc,{label:"Open in default app",onClick:j}),h.jsx(Jc,{label:"Reveal in OS",onClick:H}),h.jsx(o0,{}),h.jsx(f_,{children:"Export"}),h.jsx(Jc,{label:"Copy as Markdown",onClick:N}),h.jsx(Jc,{label:"Add to Claude context",onClick:L,disabled:!T,title:T?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(BR,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(GR,{name:b,onCancel:()=>v(!1),onConfirm:()=>void P()})]})}function f_({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 Jc({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 o0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function BR({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 GR({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 FR(){const[i,e]=G.useState(!1),t=Qu();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 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[h.jsx(Yu,{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(Yu,{label:"Word wrap",children:h.jsx(Eg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Yu,{label:"Minimap",children:h.jsx(Eg,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Yu,{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(Yu,{label:"Autosave",children:h.jsx(Eg,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Yu,{label:"Wide measure",children:h.jsx(Eg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Yu({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 Eg({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 HR=G.lazy(()=>os(()=>import("./TiptapBody-CxLrfTQ5.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Tg(i){return i.split("/").filter(Boolean).pop()||i}function Dg(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 $g(i){return FS(i)||HS(i)}function WR(){const i=sw(),e=$i(Ye=>Ye.openFiles),t=$i(Ye=>Ye.activeFilePath),n=$i(Ye=>Ye.dirty),r=$i(Ye=>Ye.viewMode),l=$i(Ye=>Ye.buffers),p=$i(Ye=>Ye.setActive),a=$i(Ye=>Ye.closeFile),d=$i(Ye=>Ye.closeOthers),f=$i(Ye=>Ye.closeToTheRight),v=$i(Ye=>Ye.closeAll),m=$i(Ye=>Ye.loadBuffer),y=$i(Ye=>Ye.setBuffer),D=$i(Ye=>Ye.markSaved),E=$i(Ye=>Ye.setViewMode),T=Qu(),[b,C]=G.useState({}),[w,x]=G.useState({}),[$,P]=G.useState(null),[N,L]=G.useState(null),[j,H]=G.useState(!1),[U,oe]=G.useState(!1),[de,Z]=G.useState(!0),me=G.useRef(null),ie=G.useRef(null),ue=G.useRef(void 0),Ce=G.useRef(null),Ee=G.useRef(null),W=PR(t??"",l[t??""]??""),te=G.useCallback(Ye=>{me.current=Ye},[]),K=G.useCallback(()=>me.current,[]);G.useEffect(()=>{const Ye=t;if(!Ye||$g(Ye))return;if($i.getState().hasBuffer(Ye)){C(ut=>ut[Ye]==="ready"?ut:{...ut,[Ye]:"ready"});return}let St=!1;return C(ut=>({...ut,[Ye]:"loading"})),window.api.files.read(Ye).then(ut=>{St||(ut.binary?C(Xe=>({...Xe,[Ye]:{binary:!0,size:ut.size??0,mime:ut.mime??"application/octet-stream",reason:ut.error??"Binary file"}})):ut.ok?(m(Ye,ut.text),C(Xe=>({...Xe,[Ye]:"ready"}))):C(Xe=>({...Xe,[Ye]:{error:ut.error??"failed to read"}})))}),()=>{St=!0}},[t,m]),G.useEffect(()=>{L(null)},[t]);const re=G.useCallback(async(Ye,St=!1)=>{const ut=$i.getState().buffers[Ye];if(ut==null)return;St&&H(!0);const Xe=await window.api.files.write(Ye,ut);Xe.ok?(D(Ye),x(Pt=>({...Pt,[Ye]:(Pt[Ye]??0)+1})),St||lt.info(`Saved ${Tg(Ye)}`)):lt.error(Xe.error??`Couldn't save ${Tg(Ye)}`),St&&H(!1)},[D]);G.useEffect(()=>{if(!T.autosave)return;const Ye=t;if(!(!Ye||$g(Ye)||!n[Ye]))return window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{re(Ye,!0)},1200),()=>window.clearTimeout(ue.current)},[T.autosave,t,n,l,re]);const ve=G.useCallback(Ye=>{Ye.length&&(C(St=>Dg(St,Ye)),x(St=>Dg(St,Ye)))},[]),_e=G.useCallback((Ye,St)=>{C(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut),x(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut)},[]),Me=G.useCallback(Ye=>{n[Ye]?P({kind:"one",path:Ye}):(a(Ye),ve([Ye]))},[n,a,ve]),et=G.useCallback(Ye=>{e.some(ut=>ut.path!==Ye&&n[ut.path])?P({kind:"others",path:Ye}):(d(Ye),ve(e.filter(ut=>ut.path!==Ye).map(ut=>ut.path)))},[e,n,d,ve]),we=G.useCallback(Ye=>{const St=e.findIndex(Xe=>Xe.path===Ye);St!==-1&&e.slice(St+1).some(Xe=>n[Xe.path])?P({kind:"right",path:Ye}):(f(Ye),ve(St!==-1?e.slice(St+1).map(Xe=>Xe.path):[]))},[e,n,f,ve]);G.useEffect(()=>{const Ye=St=>{if(i.current)if((St.metaKey||St.ctrlKey)&&(St.key==="s"||St.key==="S")){const ut=$i.getState().activeFilePath;ut&&!$g(ut)&&(St.preventDefault(),re(ut))}else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="f"||St.key==="F"))St.preventDefault(),oe(ut=>!ut);else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="w"||St.key==="W")){const ut=$i.getState().activeFilePath;ut&&$i.getState().openFiles.length>1&&(St.preventDefault(),et(ut))}else St.key==="Escape"&&W.state.phase!=="idle"?W.cancel():St.key==="Escape"&&U&&oe(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[re,U,et,W.state.phase,W.cancel]),G.useEffect(()=>{if(W.state.phase==="idle")return;const Ye=St=>{var Xe,Pt;const ut=St.target;(Xe=Ee.current)!=null&&Xe.contains(ut)||(Pt=Ce.current)!=null&&Pt.contains(ut)||W.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[W.state.phase,W.cancel]),G.useEffect(()=>{W.cancel()},[t,W.cancel]);const X=G.useCallback(()=>{e.some(St=>n[St.path])?P({kind:"all",path:""}):(v(),C({}),x({}))},[e,n,v]),Ie=()=>{if($){if($.kind==="one")a($.path),ve([$.path]);else if($.kind==="others"){const Ye=e.filter(St=>St.path!==$.path).map(St=>St.path);d($.path),ve(Ye)}else if($.kind==="right"){const Ye=e.findIndex(ut=>ut.path===$.path),St=Ye!==-1?e.slice(Ye+1).map(ut=>ut.path):[];f($.path),ve(St)}else v(),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 pe=t,Ze=pe?Tg(pe):"",ge=pe?b[pe]:void 0,Ke=pe?VS(pe):!1,vt=pe?AA(pe):!1,st=pe&&Ke?r[pe]??IA(pe):"edit",Kt=!!pe&&!$g(pe)&&ge==="ready",Be=Kt,Dt=vt?["edit","wysiwyg","preview","split"]:Ke?["edit","preview"]:[],_t=pe&&h.jsx(VI,{path:pe,name:Ze,value:l[pe]??"",onChange:Ye=>y(pe,Ye),onSave:()=>void re(pe),onReady:te,onCursor:L}),ri=j?"Saving…":pe&&n[pe]?T.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&h.jsx(jA,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Me,onCloseOthers:et,onCloseToTheRight:we,onCloseAll:X}),pe&&!U&&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:Ze}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:pe}),Kt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ri]}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:()=>Z(Ye=>!Ye),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"}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:T.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${T.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ye=>h.jsx("button",{onClick:()=>E(pe,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${st===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),h.jsx("div",{className:"flex-1"}),h.jsx(zR,{path:pe,onRenamed:_e,onDeleted:Ye=>ve([Ye])}),Kt&&h.jsx(FR,{}),h.jsx("button",{onClick:()=>oe(!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"})]}),U&&h.jsx("button",{onClick:()=>oe(!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:pe?FS(pe)?h.jsx(mR,{path:pe,name:Ze}):HS(pe)?h.jsx(gR,{path:pe}):ge&&typeof ge=="object"&&"binary"in ge?h.jsx(SR,{path:pe,name:Ze,size:ge.size,mime:ge.mime,reason:ge.reason}):ge&&typeof ge=="object"&&"error"in ge?h.jsx("div",{className:"p-6 text-xs text-red-400",children:ge.error}):ge!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):st==="wysiwyg"&&qa(pe)?h.jsx(G.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(HR,{value:l[pe]??"",onChange:Ye=>y(pe,Ye)},pe)}):st==="split"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(e0,{text:l[pe]??"",scrollRef:ie}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(Qx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(pb,{ref:ie,text:l[pe]??"",flush:!0,wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(s0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(e0,{text:l[pe]??"",scrollRef:ie}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(pb,{ref:ie,text:l[pe]??"",wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(s0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&GS(pe)?h.jsx(pR,{path:pe,dirty:!!n[pe],reloadToken:w[pe]??0}):st==="preview"&&WS(pe)?h.jsx(_R,{path:pe,text:l[pe]??""}):st==="preview"&&US(pe)?h.jsx(yR,{path:pe,text:l[pe]??""}):qa(pe)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(Qx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),Be&&h.jsx(hR,{text:l[pe]??"",cursor:N,language:Nr(pe)||void 0}),pe&&qa(pe)&&(st==="preview"||st==="split")&&W.state.phase!=="idle"&&W.state.selection&&h.jsx("div",{ref:Ee,children:h.jsx(MR,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)}})}),$&&h.jsx(UR,{message:$.kind==="one"?`Discard unsaved changes to ${Tg($.path)}?`:$.kind==="others"?"Discard unsaved changes in the other open files?":$.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>P(null),onConfirm:Ie})]})}const gb=G.memo(WR);function UR({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 VR={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},a0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function ww({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=G.useRef(null),f=G.useRef(null),v=G.useRef(e);if(v.current=e,G.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const E=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(a0);C?C.focus():b.focus()},0),T=b=>{if(b.key==="Escape"){b.stopPropagation(),v.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const w=Array.from(C.querySelectorAll(a0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(w.length===0){b.preventDefault(),C.focus();return}const x=w[0],$=w[w.length-1],P=document.activeElement;b.shiftKey?(P===x||!C.contains(P))&&(b.preventDefault(),$.focus()):(P===$||!C.contains(P))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",T),()=>{clearTimeout(E),document.removeEventListener("keydown",T);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()},y=h.jsx("div",{className:`fixed inset-0 ${Cn.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 ${VR[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(y,document.body):y}class vC extends G.Component{constructor(){super(...arguments);Bi(this,"state",{error:null});Bi(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 qR({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(ww,{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(vC,{children:n})})]})}function _C(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 l0=i=>Symbol.iterator in i,c0=i=>"entries"in i,d0=(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},KR=(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 YR(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:l0(i)&&l0(e)?c0(i)&&c0(e)?d0(i,e):KR(i,e):d0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function yw(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return YR(e.current,n)?e.current:e.current=n}}let u0=0;const XR=1e3;function JR(i){const e=performance.now();e-u0<XR||(u0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function ZR(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(yw(tv)),r=()=>{const f=Ct.getState(),{canRecord:v,reason:m}=tv(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(!v)return JR(m);const y=xt.getState().activeTabId;y&&f.startRecording(y)},l=_C(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 QR(){const i=Ct(t=>t.ttsEnabled),e=Ct(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 ej(i){return/^monitor of /i.test(i.trim())}function h0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function p0(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=h0(e),l=t.filter(p=>p.label&&h0(p.label)===r);return l.length===1?l[0]:null}async function f0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&ej(n.label))):[]}const m0=!1;function bC(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=G.useState([]),[n,r]=G.useState(null),[l,p]=G.useState(null);G.useEffect(()=>{let f=!1;return(async()=>{try{const v=await window.api.voice.getDevicePref();if(f)return;const m=await f0(m0);if(f)return;t(m),p(v.selectedLabel);const y=p0(v.selectedDeviceId,v.selectedLabel,m);y?(r(y.deviceId),v.selectedDeviceId&&y.deviceId!==v.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:v.selectedDeviceId.slice(0,8),toIdPrefix:y.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:y.deviceId,selectedLabel:y.label||v.selectedLabel}).catch(()=>{}))):((v.selectedDeviceId||v.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:v.selectedLabel,hadId:!!v.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!v.selectedDeviceId})),r(null))}catch(v){pt.warn("voice","device-picker init failed",{error:v instanceof Error?v.message:String(v)})}})(),()=>{f=!0}},[]);const a=G.useCallback(async()=>{try{const f=await f0(m0);if(t(f),n&&!f.some(v=>v.deviceId===n)){const v=p0(null,l,f);v?(r(v.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);G.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 v=f.target.value,m=v===""?null:v,y=m?((D=e.find(E=>E.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(y);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:y}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(E){pt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(i)try{await Ct.getState().restartWithDevice()}catch(E){pt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};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 tj(){const i=Ct(D=>D.isRecording),e=Ct(D=>D.levelMeterEnabled),[t,n]=G.useState(0),[r,l]=G.useState(0),p=G.useRef(0);p.current=r;const[a,d]=G.useState(0),[f,v]=G.useState(!1),m=G.useRef(null);if(G.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,E=!1,T=null,b=null;const C=()=>{if(E)return;const x=b??z1();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,T=new Uint8Array(new ArrayBuffer(x.fftSize)));const $=T;x.getByteTimeDomainData($);let P=0;for(let H=0;H<$.length;H++){const U=$[H]-128;P+=U*U}const N=Math.sqrt(P/$.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&&(v(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>v(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const w=setInterval(()=>{E||d(Math.round(p.current*100))},250);return()=>{E=!0,cancelAnimationFrame(D),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const y=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 ${y} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function wC(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=G.useState(()=>performance.now());if(G.useEffect(()=>{if(i===null)return;let f;const v=()=>{n(performance.now()),f=requestAnimationFrame(v)};return f=requestAnimationFrame(v),()=>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=Ct.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 ij({open:i,onClose:e,variant:t="overlay"}){return h.jsx(qR,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(oj,{}),h.jsx(wC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(ZR,{}),h.jsx(bC,{}),h.jsx(QR,{})]}),h.jsx(nj,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),h.jsx(rj,{})]}),h.jsx(tj,{})]})})}function nj(){const i=Ct(l=>l.isRecording),[e,t]=G.useState(null);if(G.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=sj(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 sj(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 rj(){const[i,e]=G.useState(null);if(G.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.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){pt.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 oj(){const i=Ct(l=>l.isRecording),e=Ct(l=>l.lastTranscript),t=Ct(l=>l.error),n=Ct(l=>l.modelStatus),r=Ct(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 yC="~/.claude/session-manager/projects-prefs.json",aj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function zl(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(yC,t).catch(()=>{})}const g0=In((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(yC);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}),zl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":aj[t];i({sort:{col:t,dir:r}}),zl(e)},setRecentFilter:t=>{i({recentFilter:t}),zl(e)},setHasRemote:t=>{i({hasRemote:t}),zl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),zl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),zl(e)},setSearch:t=>{i({search:t}),zl(e)},setEditor:t=>{i({editor:t}),zl(e)}})),xC=i=>`sm.fileTree.expanded:${i}`;function lj(i){try{const e=localStorage.getItem(xC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function cj(i,e){try{localStorage.setItem(xC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const SC="sm.fileTree.showHidden";function dj(){try{const i=localStorage.getItem(SC);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function uj(i){try{localStorage.setItem(SC,JSON.stringify(i))}catch{}}function m_(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 g_={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:"!"}},hj=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 pj(i){const e=Nr(i);return hj.has(e)||BS.has(e)||e==="pdf"}function fj(i,e){if(e)return"#d97757";switch(Nr(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 ff(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 mj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=sw(),l=nw(),[p,a]=G.useState([]),[d,f]=G.useState(new Set),v=G.useRef(d);v.current=d;const[m,y]=G.useState(""),[D,E]=G.useState(dj),T=G.useCallback(Be=>{E(Dt=>{const _t=typeof Be=="function"?Be(Dt):Be;return uj(_t),_t})},[]),[b,C]=G.useState(!1),[w,x]=G.useState(null),[$,P]=G.useState({}),[N,L]=G.useState(null),[j,H]=G.useState(null),[U,oe]=G.useState(""),[de,Z]=G.useState(null),[me,ie]=G.useState(""),[ue,Ce]=G.useState(null),Ee=G.useRef(null),W=G.useRef(null),te=G.useRef(0),K=G.useCallback(async()=>{if(!i)return;const Be=++te.current;C(!0),x(null);const Dt=await window.api.files.list(i,D);te.current===Be&&(Dt.ok?a(Dt.entries.map(_t=>({..._t}))):(x(Dt.error??"failed to list"),a([])),C(!1))},[i,D]),re=G.useCallback(async Be=>{const Dt=te.current,_t=new Map;for(const Ye of Be){const St=Ye.split("/").length,ut=_t.get(St);ut?ut.push(Ye):_t.set(St,[Ye])}const ri=[];for(const Ye of[..._t.keys()].sort((St,ut)=>St-ut)){const St=_t.get(Ye),ut=await Promise.all(St.map(async Xe=>({p:Xe,result:await window.api.files.list(Xe,D)})));if(te.current!==Dt)return ri;for(const{p:Xe,result:Pt}of ut)Pt.ok?a(oi=>Wg(oi,Xe,Pt.entries.map(Fi=>({...Fi})))):ri.push(Xe)}return ri},[D]),ve=G.useCallback(async Be=>(await K(),Be.length?re(Be):[]),[K,re]);G.useEffect(()=>{y(""),H(null),L(null),Z(null),Ce(null),P({});const Be=lj(i),Dt=new Set(Be);v.current=Dt,f(Dt);let _t=!1;return(async()=>{const ri=await ve(Be);_t||!ri.length||Me(Ye=>{const St=new Set;let ut=!1;for(const Xe of Ye){if(ri.some(Pt=>Xe===Pt||Xe.startsWith(Pt+"/"))){ut=!0;continue}St.add(Xe)}return ut?St:Ye})})(),ff(i).then(ri=>{_t||P(ri)}),()=>{_t=!0}},[i]);const _e=G.useRef(!0);G.useEffect(()=>{if(_e.current){_e.current=!1;return}ve([...v.current])},[D]),G.useEffect(()=>{if(!i||!l)return;ff(i).then(P);const Be=window.setInterval(()=>{ff(i).then(P)},5e3);return()=>window.clearInterval(Be)},[i,l]),G.useEffect(()=>{if(!N)return;const Be=()=>L(null),Dt=_t=>{r.current&&_t.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Be),window.addEventListener("keydown",Dt),()=>{window.removeEventListener("mousedown",Be),window.removeEventListener("keydown",Dt)}},[N]),G.useEffect(()=>{j&&setTimeout(()=>{var Be;return(Be=Ee.current)==null?void 0:Be.select()},30)},[j]),G.useEffect(()=>{de&&setTimeout(()=>{var Be;return(Be=W.current)==null?void 0:Be.focus()},30)},[de]);const Me=G.useCallback(Be=>{const Dt=v.current,_t=Be(Dt);_t!==Dt&&(v.current=_t,f(_t),cj(i,_t))},[i]),et=G.useCallback(async Be=>{if(d.has(Be.path)){Me(_t=>m_(_t,Be.path));return}if(Me(_t=>new Set(_t).add(Be.path)),Be.children)return;const Dt=await window.api.files.list(Be.path,D);Dt.ok&&a(_t=>Wg(_t,Be.path,Dt.entries.map(ri=>({...ri}))))},[d,D,Me]),we=G.useCallback(async Be=>{if(Be===i){await K();return}const Dt=await window.api.files.list(Be,D);Dt.ok&&a(_t=>Wg(_t,Be,Dt.entries.map(ri=>({...ri}))))},[i,K,D]),X=G.useCallback(Be=>{if(Be.isDirectory){et(Be);return}pj(Be.name)&&e?e(Be.path):window.api.shell.open({as:"openPath",path:Be.path})},[et,e]),Ie=G.useCallback(Be=>{if(t){t(Be);return}if(n){const Dt=Be.startsWith(i+"/")?Be.slice(i.length+1):Be;window.api.pty.write({tabId:n,data:`@${Dt} `})}},[t,n,i]),pe=G.useCallback((Be,Dt)=>{Be.preventDefault(),Be.stopPropagation(),L({x:Be.clientX,y:Be.clientY,node:Dt})},[]),Ze=Be=>{H(Be.path),oe(Be.name)},ge=async()=>{if(!j)return;const Be=U.trim();if(!Be){H(null);return}const Dt=await window.api.files.rename(j,Be);if(H(null),Dt.ok){const _t=j.slice(0,j.lastIndexOf("/"));Me(ri=>m_(ri,j)),await we(_t||i),ff(i).then(P)}else{const _t=Dt.error??"rename failed";x(_t),lt.error(_t)}},Ke=async()=>{if(!de)return;const Be=me.trim();if(!Be){Z(null),ie("");return}const Dt=await window.api.files.create(de.parent,Be,de.kind);if(Z(null),ie(""),Dt.ok)await we(de.parent),de.kind==="folder"&&Me(_t=>new Set(_t).add(de.parent));else{const _t=Dt.error??"create failed";x(_t),lt.error(_t)}},vt=async()=>{if(!ue)return;const Be=await window.api.files.delete(ue.path),Dt=ue.path.slice(0,ue.path.lastIndexOf("/"));if(Ce(null),Be.ok)Me(_t=>m_(_t,ue.path)),await we(Dt||i),ff(i).then(P);else{const _t=Be.error??"delete failed";x(_t),lt.error(_t)}},st=G.useMemo(()=>{if(!m.trim())return p;const Be=m.toLowerCase();return p.filter(Dt=>Dt.name.toLowerCase().includes(Be))},[p,m]),Kt=(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(kC,{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:Kt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:K,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(yj,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Be=>y(Be.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(xj,{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(Sj,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>T(Be=>!Be),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(Cj,{size:12}):h.jsx(kj,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&st.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&h.jsx(CC,{nodes:st,depth:0,expanded:d,gitStatus:$,renaming:j,renameValue:U,renameInputRef:Ee,onRenameChange:oe,onRenameCommit:ge,onRenameCancel:()=>H(null),onToggleDir:et,onFileClick:X,onSendToChat:Ie,onContextMenu:pe})]}),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(gj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Ze(N.node),L(null)},onDelete:()=>{Ce(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 Be;(Be=navigator.clipboard)==null||Be.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx(v0,{title:`New ${de.kind}`,subtitle:`in ${vj(de.parent)}`,onCancel:()=>{Z(null),ie("")},onConfirm:Ke,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:W,value:me,onChange:Be=>ie(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"&&Ke(),Be.key==="Escape"&&(Z(null),ie(""))},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"})}),ue&&h.jsx(v0,{title:`Delete ${ue.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>Ce(null),onConfirm:vt,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:['"',ue.name,'"']})," to the trash?",ue.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function CC(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,v=r[a.path],m=fj(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:y=>p(y,a),children:[a.isDirectory?h.jsx(wj,{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(_j,{size:12,color:m}):h.jsx(kC,{size:12,color:m}):h.jsx(bj,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:y=>i.onRenameChange(y.target.value),onClick:y=>y.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:y=>{y.key==="Enter"&&i.onRenameCommit(),y.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}),v&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:g_[v].color,backgroundColor:`${g_[v].color}20`},title:v,children:g_[v].label}),!a.isDirectory&&h.jsx("button",{onClick:y=>{y.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(Ej,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(CC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function gj(i){const{x:e,y:t,node:n}=i;return h.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${Cn.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(Bl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Bl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Bl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(v_,{}),h.jsx(Bl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Bl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(v_,{}),h.jsx(Bl,{label:"New file",onClick:i.onNewFile}),h.jsx(Bl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(v_,{}),h.jsx(Bl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Bl({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 v_(){return h.jsx("div",{className:"my-1 border-t border-line"})}function v0(i){return h.jsx("div",{className:`fixed inset-0 ${Cn.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 vj(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Wg(n.children,e,t)}:n)}function ma({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 kC({size:i,className:e,color:t}){return h.jsx(ma,{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 _j({size:i,className:e,color:t}){return h.jsx(ma,{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 bj({size:i,className:e,color:t}){return h.jsxs(ma,{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 wj({size:i,className:e}){return h.jsx(ma,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function yj({size:i,className:e}){return h.jsxs(ma,{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 xj({size:i,className:e}){return h.jsxs(ma,{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 Sj({size:i,className:e}){return h.jsxs(ma,{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 Cj({size:i,className:e}){return h.jsxs(ma,{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 kj({size:i,className:e}){return h.jsxs(ma,{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 Ej({size:i,className:e}){return h.jsxs(ma,{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 Tj({content:i,children:e,align:t="bottom-right"}){const[n,r]=G.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 ${Cn.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 Of(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const vb="sm.projects.splitPct",_b=33,EC=20,TC=60,DC="sm.projects.fileTreeCollapsed",Dj=32;function $j(){try{const i=parseFloat(localStorage.getItem(vb)??"");if(Number.isFinite(i))return Math.min(TC,Math.max(EC,i))}catch{}return _b}function Aj(){try{return localStorage.getItem(DC)==="1"}catch{return!1}}function Ij(){const i=xt(U=>U.tabs),e=xt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ei(U=>U.navFace),[r,l]=G.useState(null);G.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(oe=>{U||l(oe)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=G.useState(()=>$j()),[f,v]=G.useState(()=>Aj()),[m,y]=G.useState(!1),D=G.useRef(a);D.current=a;const E=G.useRef(null),T=G.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:w}=hh(),x=g0(U=>U.pinned),$=g0(U=>U.togglePin),P=[...b].sort((U,oe)=>(x[oe.cwd]?1:0)-(x[U.cwd]?1:0));G.useEffect(()=>{if(!m)return;const U=oe=>{T.current&&!T.current.contains(oe.target)&&y(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=G.useCallback(U=>{$i.getState().openFile(U)},[]),L=G.useCallback(U=>{U.preventDefault();const oe=U.clientX,de=D.current;let Z=de;const me=ue=>{const Ce=E.current;if(!Ce)return;const Ee=Ce.getBoundingClientRect(),W=ue.clientX-oe;Z=Math.min(TC,Math.max(EC,de+W/Ee.width*100)),d(Z)},ie=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",ie),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(vb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",ie),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=G.useCallback(()=>{d(_b);try{localStorage.setItem(vb,String(_b))}catch{}},[]),H=G.useCallback(()=>{v(U=>{const oe=!U;try{localStorage.setItem(DC,oe?"1":"0")}catch{}return oe})},[]);return f?h.jsxs("div",{ref:E,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:Dj},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(gb,{})})]}):h.jsxs("div",{ref:E,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:T,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>y(U=>!U),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?Of(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 ${Cn.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(U=>{const oe=Of(U.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(Tj,{content:x[U.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>$(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(U.cwd),y(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:oe}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${oe}?`)&&await w(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.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:Of(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(mj,{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(gb,{})})]})}const Pj=G.memo(Ij),Rj={"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."]}},xw="sm.learningPanel.collapsed";function _0(){try{const i=localStorage.getItem(xw);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 b0(i){try{localStorage.setItem(xw,i?"1":"0")}catch{}}function jj({active:i}){const[e,t]=G.useState(()=>!_0()),n=G.useRef(null),r=G.useCallback(()=>{t(a=>{const d=!a;return b0(!d),d})},[]);G.useEffect(()=>{const a=d=>{d.key===xw&&t(!_0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),G.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),b0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=G.useRef(!1);G.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=Rj[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 Nj({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(jj,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const Mj=G.lazy(()=>os(()=>import("./Skills-BGBKWxNl.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),Oj=G.lazy(()=>os(()=>import("./History-EDAc-ZMb.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),Lj=G.lazy(()=>os(()=>import("./Scheduler-BmbVLNFH.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),zj=G.lazy(()=>os(()=>import("./Settings-BZtTqlKA.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),Bj=G.lazy(()=>os(()=>import("./Permissions-C1gnBLDo.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),Gj=G.lazy(()=>os(()=>import("./SystemPrompt-Bc715ZOf.js"),__vite__mapDeps([19,4,7,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),Fj=G.lazy(()=>os(()=>import("./Memory-CIqDISVo.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),Hj=G.lazy(()=>os(()=>import("./Plugins-BysI_znb.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),Wj=G.lazy(()=>os(()=>import("./McpServers-BYKw9iDf.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),Uj=G.lazy(()=>os(()=>import("./Hooks-aRH7nMJd.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),Vj=G.lazy(()=>os(()=>import("./AgentLibrary-ClxN8f2w.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),qj=G.lazy(()=>os(()=>import("./TagLibrary-CAnB2jV8.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),Kj=G.lazy(()=>os(()=>import("./HostBilko-SlCefAAH.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),Yj=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ir({children:i}){return h.jsx(G.Suspense,{fallback:Yj,children:i})}const Xj={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."}},Jj=()=>{},w0=new Map;function Zj(i,e){const t=w0.get(i);if(t&&t.ctx===e)return t.node;const n=Qj(i,e);return w0.set(i,{ctx:e,node:n}),n}function Qj(i,e){switch(i){case"overview":return h.jsx(R$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(CA,{});case"editor":return h.jsx(gb,{});case"projects":return h.jsx(Pj,{})}const t=Xj[i],n=(()=>{switch(i){case"skills":return h.jsx(Ir,{children:h.jsx(Mj,{})});case"history":return h.jsx(Ir,{children:h.jsx(Oj,{})});case"scheduler":return h.jsx(Ir,{children:h.jsx(Lj,{navigate:e.onNavigate})});case"plugins":return h.jsx(Ir,{children:h.jsx(Hj,{})});case"mcp":return h.jsx(Ir,{children:h.jsx(Wj,{})});case"hooks":return h.jsx(Ir,{children:h.jsx(Uj,{})});case"memory":return h.jsx(Ir,{children:h.jsx(Fj,{})});case"system-prompt":return h.jsx(Ir,{children:h.jsx(Gj,{})});case"permissions":return h.jsx(Ir,{children:h.jsx(Bj,{})});case"settings":return h.jsx(Ir,{children:h.jsx(zj,{})});case"agent-library":return h.jsx(Ir,{children:h.jsx(Vj,{})});case"tag-library":return h.jsx(Ir,{children:h.jsx(qj,{})});case"bilko-host":return h.jsx(Ir,{children:h.jsx(Kj,{})});case"voice":return h.jsx(ij,{open:!0,onClose:Jj,variant:"page"});default:return null}})();if(!n)return null;const r=SE[i];return t&&r?h.jsx(Nj,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var __={exports:{}},y0;function eN(){return y0||(y0=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(w,x,$,P){var N,L=arguments.length,j=L<3?x:P===null?P=Object.getOwnPropertyDescriptor(x,$):P;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(w,x,$,P);else for(var H=w.length-1;H>=0;H--)(N=w[H])&&(j=(L<3?N(j):L>3?N(x,$,j):N(x,$))||j);return L>3&&j&&Object.defineProperty(x,$,j),j},v=this&&this.__param||function(w,x){return function($,P){x($,P,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),y=d(9924),D=d(844),E=d(4725),T=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(w,x,$,P){super(),this._terminal=w,this._coreBrowserService=$,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 y.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(`
3022
3022
  `)))),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(w){for(let x=0;x<w;x++)this._handleChar(" ")}_handleChar(w){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==w&&(this._charsToAnnounce+=w):this._charsToAnnounce+=w,w===`
3023
3023
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(w){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(w)||this._charsToConsume.push(w)}_refreshRows(w,x){this._liveRegionDebouncer.refresh(w,x,this._terminal.rows)}_renderRows(w,x){const $=this._terminal.buffer,P=$.lines.length.toString();for(let N=w;N<=x;N++){const L=$.lines.get($.ydisp+N),j=[],H=(L==null?void 0:L.translateToString(!0,void 0,void 0,j))||"",U=($.ydisp+N+1).toString(),oe=this._rowElements[N];oe&&(H.length===0?(oe.innerText=" ",this._rowColumns.set(oe,[0,1])):(oe.textContent=H,this._rowColumns.set(oe,j)),oe.setAttribute("aria-posinset",U),oe.setAttribute("aria-setsize",P))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(w,x){const $=w.target,P=this._rowElements[x===0?1:this._rowElements.length-2];if($.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||w.relatedTarget!==P)return;let N,L;if(x===0?(N=$,L=this._rowElements.pop(),this._rowContainer.removeChild(L)):(N=this._rowElements.shift(),L=$,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(),w.preventDefault(),w.stopImmediatePropagation()}_handleSelectionChange(){var H;if(this._rowElements.length===0)return;const w=document.getSelection();if(!w)return;if(w.isCollapsed)return void(this._rowContainer.contains(w.anchorNode)&&this._terminal.clearSelection());if(!w.anchorNode||!w.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:w.anchorNode,offset:w.anchorOffset},$={node:w.focusNode,offset:w.focusOffset};if((x.node.compareDocumentPosition($.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===$.node&&x.offset>$.offset)&&([x,$]=[$,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($.node.compareDocumentPosition(P)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&($={node:P,offset:((H=P.textContent)==null?void 0:H.length)??0}),!this._rowContainer.contains($.node))return;const N=({node:U,offset:oe})=>{const de=U instanceof Text?U.parentNode:U;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 ie=oe<me.length?me[oe]:me.slice(-1)[0]+1;return ie>=this._terminal.cols&&(++Z,ie=0),{row:Z,column:ie}},L=N(x),j=N($);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(w){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>w;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const w=this._coreBrowserService.mainDocument.createElement("div");return w.setAttribute("role","listitem"),w.tabIndex=-1,this._refreshRowDimensions(w),w}_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 w=0;w<this._terminal.rows;w++)this._refreshRowDimensions(this._rowElements[w])}}_refreshRowDimensions(w){w.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=C=f([v(1,T.IInstantiationService),v(2,E.ICoreBrowserService),v(3,E.IRenderService)],C)},3614:(p,a)=>{function d(y){return y.replace(/\r?\n/g,"\r")}function f(y,D){return D?"\x1B[200~"+y+"\x1B[201~":y}function v(y,D,E,T){y=f(y=d(y),E.decPrivateModes.bracketedPasteMode&&T.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(y,!0),D.value=""}function m(y,D,E){const T=E.getBoundingClientRect(),b=y.clientX-T.left-10,C=y.clientY-T.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(y,D){y.clipboardData&&y.clipboardData.setData("text/plain",D.selectionText),y.preventDefault()},a.handlePasteEvent=function(y,D,E,T){y.stopPropagation(),y.clipboardData&&v(y.clipboardData.getData("text/plain"),D,E,T)},a.paste=v,a.moveTextAreaUnderMouseCursor=m,a.rightClickHandler=function(y,D,E,T,b){m(y,D,E),b&&T.rightClickSelect(y),D.value=T.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(v,m,y){this._css.set(v,m,y)}getCss(v,m){return this._css.get(v,m)}setColor(v,m,y){this._color.set(v,m,y)}getColor(v,m){return this._color.get(v,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,v,m){d.addEventListener(f,v,m);let y=!1;return{dispose:()=>{y||(y=!0,d.removeEventListener(f,v,m))}}}},3551:function(p,a,d){var f=this&&this.__decorate||function(C,w,x,$){var P,N=arguments.length,L=N<3?w:$===null?$=Object.getOwnPropertyDescriptor(w,x):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(C,w,x,$);else for(var j=C.length-1;j>=0;j--)(P=C[j])&&(L=(N<3?P(L):N>3?P(w,x,L):P(w,x))||L);return N>3&&L&&Object.defineProperty(w,x,L),L},v=this&&this.__param||function(C,w){return function(x,$){w(x,$,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const m=d(3656),y=d(8460),D=d(844),E=d(2585),T=d(4725);let b=a.Linkifier=class extends D.Disposable{get currentLink(){return this._currentLink}constructor(C,w,x,$,P){super(),this._element=C,this._mouseService=w,this._renderService=x,this._bufferService=$,this._linkProviderService=P,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new y.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new y.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 w=this._positionFromMouseEvent(C,this._element,this._mouseService);if(!w)return;this._isMouseOut=!1;const x=C.composedPath();for(let $=0;$<x.length;$++){const P=x[$];if(P.classList.contains("xterm"))break;if(P.classList.contains("xterm-hover"))return}this._lastBufferCell&&w.x===this._lastBufferCell.x&&w.y===this._lastBufferCell.y||(this._handleHover(w),this._lastBufferCell=w)}_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,w){var $,P;this._activeProviderReplies&&w||(($=this._activeProviderReplies)==null||$.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())w?(P=this._activeProviderReplies)!=null&&P.get(N)&&(x=this._checkLinkProviderResult(N,C,x)):L.provideLinks(C.y,(j=>{var U,oe;if(this._isMouseOut)return;const H=j==null?void 0:j.map((de=>({link:de})));(U=this._activeProviderReplies)==null||U.set(N,H),x=this._checkLinkProviderResult(N,C,x),((oe=this._activeProviderReplies)==null?void 0:oe.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(C.y,this._activeProviderReplies)}))}_removeIntersectingLinks(C,w){const x=new Set;for(let $=0;$<w.size;$++){const P=w.get($);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 U=j;U<=H;U++){if(x.has(U)){P.splice(N--,1);break}x.add(U)}}}}_checkLinkProviderResult(C,w,x){var N;if(!this._activeProviderReplies)return x;const $=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&&$){const L=$.find((j=>this._linkAtPosition(j.link,w)));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,w)));if(j){x=!0,this._handleNewLink(j);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(C){if(!this._currentLink)return;const w=this._positionFromMouseEvent(C,this._element,this._mouseService);w&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,w)&&this._currentLink.link.activate(C,this._currentLink.link.text)}_clearCurrentLink(C,w){this._currentLink&&this._lastMouseEvent&&(!C||!w||this._currentLink.link.range.start.y>=C&&this._currentLink.link.range.end.y<=w)&&(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 w=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);w&&this._linkAtPosition(C.link,w)&&(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,$;return($=(x=this._currentLink)==null?void 0:x.state)==null?void 0:$.decorations.pointerCursor},set:x=>{var $;($=this._currentLink)!=null&&$.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,$;return($=(x=this._currentLink)==null?void 0:x.state)==null?void 0:$.decorations.underline},set:x=>{var $,P,N;($=this._currentLink)!=null&&$.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 $=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>=$&&this._currentLink.link.range.end.y<=P&&(this._clearCurrentLink($,P),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(C,w,x){var $;($=this._currentLink)!=null&&$.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!0),this._currentLink.state.decorations.pointerCursor&&C.classList.add("xterm-cursor-pointer")),w.hover&&w.hover(x,w.text)}_fireUnderlineEvent(C,w){const x=C.range,$=this._bufferService.buffer.ydisp,P=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-$-1,x.end.x,x.end.y-$-1,void 0);(w?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(P)}_linkLeave(C,w,x){var $;($=this._currentLink)!=null&&$.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!1),this._currentLink.state.decorations.pointerCursor&&C.classList.remove("xterm-cursor-pointer")),w.leave&&w.leave(x,w.text)}_linkAtPosition(C,w){const x=C.range.start.y*this._bufferService.cols+C.range.start.x,$=C.range.end.y*this._bufferService.cols+C.range.end.x,P=w.y*this._bufferService.cols+w.x;return x<=P&&P<=$}_positionFromMouseEvent(C,w,x){const $=x.getCoords(C,w,this._bufferService.cols,this._bufferService.rows);if($)return{x:$[0],y:$[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(C,w,x,$,P){return{x1:C,y1:w,x2:x,y2:$,cols:this._bufferService.cols,fg:P}}};a.Linkifier=b=f([v(1,T.IMouseService),v(2,T.IRenderService),v(3,E.IBufferService),v(4,T.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(T,b,C,w){var x,$=arguments.length,P=$<3?b:w===null?w=Object.getOwnPropertyDescriptor(b,C):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(T,b,C,w);else for(var N=T.length-1;N>=0;N--)(x=T[N])&&(P=($<3?x(P):$>3?x(b,C,P):x(b,C))||P);return $>3&&P&&Object.defineProperty(b,C,P),P},v=this&&this.__param||function(T,b){return function(C,w){b(C,w,T)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const m=d(511),y=d(2585);let D=a.OscLinkProvider=class{constructor(T,b,C){this._bufferService=T,this._optionsService=b,this._oscLinkService=C}provideLinks(T,b){var H;const C=this._bufferService.buffer.lines.get(T-1);if(!C)return void b(void 0);const w=[],x=this._optionsService.rawOptions.linkHandler,$=new m.CellData,P=C.getTrimmedLength();let N=-1,L=-1,j=!1;for(let U=0;U<P;U++)if(L!==-1||C.hasContent(U)){if(C.loadCell(U,$),$.hasExtendedAttrs()&&$.extended.urlId){if(L===-1){L=U,N=$.extended.urlId;continue}j=$.extended.urlId!==N}else L!==-1&&(j=!0);if(j||L!==-1&&U===P-1){const oe=(H=this._oscLinkService.getLinkData(N))==null?void 0:H.uri;if(oe){const de={start:{x:L+1,y:T},end:{x:U+(j||U!==P-1?0:1),y:T}};let Z=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const me=new URL(oe);["http:","https:"].includes(me.protocol)||(Z=!0)}catch{Z=!0}Z||w.push({text:oe,range:de,activate:(me,ie)=>x?x.activate(me,ie,de):E(0,ie),hover:(me,ie)=>{var ue;return(ue=x==null?void 0:x.hover)==null?void 0:ue.call(x,me,ie,de)},leave:(me,ie)=>{var ue;return(ue=x==null?void 0:x.leave)==null?void 0:ue.call(x,me,ie,de)}})}j=!1,$.hasExtendedAttrs()&&$.extended.urlId?(L=U,N=$.extended.urlId):(L=-1,N=-1)}}b(w)}};function E(T,b){if(confirm(`Do you want to navigate to ${b}?
3024
3024
 
@@ -3065,4 +3065,4 @@ ${Z.join(`
3065
3065
  `),xt.getState().setTabExited(i,P)});v.onData(P=>Ka(i,P)),v.onResize(({cols:P,rows:N})=>window.api.pty.resize({tabId:i,cols:P,rows:N})),b3({tabId:i,cwd:e}).then(P=>{P&&v.write(P)}).catch(()=>{}).finally(()=>{console.log("[Terminal] calling pty.spawn",{tabId:i,cwd:e,cols:T,rows:b}),window.api.pty.spawn({tabId:i,cwd:e,cols:T,rows:b}).then(({pid:P,reattached:N})=>{console.log("[Terminal] pty.spawn resolved, pid=",P,"tabId=",i,"reattached=",N),xt.getState().setTabRunning(i,P);const L=xt.getState().consumeRawCommand(i);if(L&&setTimeout(()=>{Ka(i,`${L}\r`)},N?150:1500),N)return;const{startupCommand:j}=xt.getState().tabs.find(H=>H.id===i)??{};j&&setTimeout(()=>{Ka(i,`${j}
3066
3066
  `)},350)}).catch(P=>{console.error("[Terminal] pty.spawn rejected for tabId=",i,P),v.write(`\r
3067
3067
  \x1B[31mfailed to spawn: ${P.message}\x1B[0m\r
3068
- `),lt.error(`Terminal failed to start: ${P.message??"spawn failed"}`),xt.getState().setTabExited(i,-1)})});const x=()=>y();window.addEventListener("resize",x),window.addEventListener(fv,x);const $=new ResizeObserver(()=>y());return $.observe(r.current),()=>{window.removeEventListener("resize",x),window.removeEventListener(fv,x),$.disconnect(),C(),w(),D(),v.dispose()}},[i,e]),t?n?h.jsx(ik,{cwd:e}):null:h.jsxs("div",{className:"relative h-full w-full",children:[h.jsx("button",{type:"button",onClick:()=>xt.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),a&&h.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:h.jsx(w3,{path:a,onDismiss:()=>d(null)},a)}),h.jsx("div",{ref:r,onMouseDown:()=>{var f;return(f=l.current)==null?void 0:f.focus()},className:"h-full w-full bg-bg"})]})}const x3={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},S3={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function C3(){const{isRecording:i,statusPill:e,lastPartial:t,lastTranscript:n,submitCountdownStartAt:r}=Ct(yw(g2)),l=i||!!t||!!n,[p,a]=G.useState(l);if(G.useEffect(()=>{if(l)a(!0);else{const f=setTimeout(()=>a(!1),300);return()=>clearTimeout(f)}},[l]),!p)return null;let d=t;return d.length>200&&(d="…"+d.slice(-200)),h.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${l?"opacity-100":"opacity-0"}`,children:h.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${x3[e]??"bg-fg-faint"}`}),h.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:S3[e]??e})]}),d&&h.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),r!==null&&h.jsx("div",{className:"shrink-0",children:h.jsx(wC,{})})]})})})}function k3({visible:i=!0}){const e=xt(p=>p.tabs),t=xt(p=>p.activeTabId),n=e.find(p=>p.id===t)??null,l=Ei(p=>p.epicsWorkspaceOpen)||!n;return h.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[l?h.jsx(ik,{}):e.map(p=>h.jsx("div",{className:"absolute inset-0",style:{visibility:p.id===t?"inherit":"hidden"},children:h.jsx(nk,{tabId:p.id,cwd:p.cwd})},`${p.id}-${p.generation}`)),h.jsx(C3,{}),i&&h.jsx(rN,{})]})}function E3(){const i=Ei(e=>e.focusedPanelId==="terminal");return h.jsx(k3,{visible:i})}const T3=1;function D3(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:T3,panels:e,dockview:i}}function Pb(i,e){const t=i.views.filter(r=>e.has(r));if(t.length===0)return null;const n=i.activeView&&t.includes(i.activeView)?i.activeView:t[0];return{...i,views:t,activeView:n}}function sk(i,e){if(i.type==="leaf"){const n=Pb(i.data,e);return n?{...i,data:n}:null}const t=i.data.map(n=>sk(n,e)).filter(n=>n!==null);return t.length===0?null:{...i,data:t}}function $3(i,e){const t=Object.keys(i.panels??{}),n=new Set(t.filter(d=>e.has(d)));if(n.size===0)return null;const r=sk(i.grid.root,n);if(!r)return null;const l={};for(const d of n)l[d]=i.panels[d];const p=(i.floatingGroups??[]).map(d=>{const f=Pb(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null),a=(i.popoutGroups??[]).map(d=>{const f=Pb(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:r},panels:l,floatingGroups:p,popoutGroups:a,activeGroup:i.activeGroup}}function A3(i,e){if(!i||typeof i!="object")return null;const t=i;if(!Array.isArray(t.panels)||!t.dockview||typeof t.dockview!="object")return null;const n=t.dockview;if(!n.grid||!n.panels)return null;try{return $3(n,e)}catch(r){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",r),null}}const I3=500,P3=new Set(id.map(i=>i.id));function Y0(i){const e=D3(i);e&&window.api.layout.save(e).catch(t=>{console.warn("[Workbench] layout save failed:",t)})}const rk=G.createContext(null),R3=G.memo(function(e){const t=G.useContext(rk);return t?h.jsx(h.Fragment,{children:N3(e.params.id,t)}):null}),j3={screen:R3},jg=id[0].id;function N3(i,e){return i==="terminal"?h.jsx(E3,{}):h.jsx(p$,{panelId:i,children:h.jsx("div",{className:"h-full overflow-auto bg-bg",children:h.jsx(vC,{children:Zj(i,e)})})})}function M3({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}){const r=G.useRef(null),l=Ei($=>$.focusedPanelId)??jg,p=Ei($=>$.focusToken),a=Ei($=>$.resetToken),d=Ct($=>$.isRecording||$.externalRecording),f=G.useRef(null),[v,m]=G.useState(!1),y=G.useRef(l);y.current=l;const D=G.useRef(null),E=G.useRef(null);G.useEffect(()=>{let $=!1;return window.api.layout.load().then(P=>{$||(P&&(f.current=A3(P,P3)),m(!0))}).catch(P=>{console.warn("[Workbench] layout load failed, using default:",P),$||m(!0)}),()=>{$=!0}},[]);const T=G.useCallback($=>{const P=r.current;if(!P)return;const N=$E($)??id[0],L=P.getPanel(N.id);if(L)L.api.setActive();else{const j=P.addPanel({id:N.id,component:N.component,title:N.title,params:{id:N.id},renderer:"always"});N.id==="terminal"&&j.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(fv))})}},[]),b=G.useCallback($=>{var j;r.current=$.api;const P=H=>{H.header.hidden=!0};E.current=$.api.onDidAddGroup(P),$.api.groups.forEach(P);const N=f.current;if(N)try{$.api.fromJSON(N);const H=(j=$.api.activePanel)==null?void 0:j.id;H&&Ei.getState().focusPanel(H)}catch(H){console.warn("[Workbench] fromJSON failed, falling back to default layout:",H),$.api.clear(),T(y.current)}else T(y.current);$.api.onDidActivePanelChange(H=>{H&&Ei.getState().focusPanel(H.id)}),D.current=$.api.onDidRemovePanel(H=>{if(H.id==="terminal"){Ei.getState().openPanel("terminal");return}$.api.totalPanels===0&&(Ei.getState().openPanel(jg),T(jg))});let L=null;$.api.onDidLayoutChange(()=>{L!==null&&window.clearTimeout(L),L=window.setTimeout(()=>Y0($.api.toJSON()),I3)})},[]);G.useEffect(()=>()=>{var $,P;($=D.current)==null||$.dispose(),(P=E.current)==null||P.dispose()},[]),G.useEffect(()=>{T(l)},[p,T]);const C=G.useRef(!0);G.useEffect(()=>{if(C.current){C.current=!1;return}const $=r.current;$&&($.clear(),f.current=null,T(jg),Y0($.toJSON()))},[a]),G.useEffect(()=>{const $=r.current;$&&($.layout($.width,$.height,!0),window.dispatchEvent(new CustomEvent(fv)))},[d]);const w=G.useMemo(()=>({components:j3,onReady:b,className:"dockview-theme-sm workbench-root"}),[b]),x=G.useMemo(()=>({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}),[i,e,t,n]);return v?h.jsx(rk.Provider,{value:x,children:h.jsx(CS,{...w})}):null}function ok(){return Ct(e=>e.isRecording||e.externalRecording)?h.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:`fixed inset-x-0 top-0 ${Cn.recording} h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0`,children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),h.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const vf=5e3;function Ao(i,e,t){var n,r;try{(r=(n=window.api)==null?void 0:n.logs)==null||r.write("voice-wizard",i,e,t)}catch{}}function O3({analyser:i}){const[e,t]=G.useState(0);return G.useEffect(()=>{if(!i){t(0);return}let n=0,r=!1;const l=new Uint8Array(new ArrayBuffer(i.fftSize)),p=()=>{if(r)return;i.getByteTimeDomainData(l);let a=0;for(let v=0;v<l.length;v++){const m=l[v]-128;a+=m*m}const d=Math.sqrt(a/l.length)/128,f=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));t(f),n=requestAnimationFrame(p)};return n=requestAnimationFrame(p),()=>{r=!0,cancelAnimationFrame(n)}},[i]),h.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function L3({open:i,onClose:e}){const t=Ct(X=>X.permissionState),n=Ct(X=>X.modelStatus),r=Ct(X=>X.loadingProgress),[l,p]=G.useState("welcome"),[a,d]=G.useState(null),[f,v]=G.useState(!1),[m,y]=G.useState(0),D=G.useRef(null),E=G.useRef(null),T=G.useRef(null),b=G.useRef(null),C=G.useRef(null),w=G.useRef(null),x=G.useRef(null),$=G.useRef(null),[P,N]=G.useState(!1),[L,j]=G.useState(Math.round(vf/1e3)),[H,U]=G.useState(!1),[oe,de]=G.useState(!1),[Z,me]=G.useState(null),[ie,ue]=G.useState(0),Ce=G.useCallback(()=>{var X;try{(X=C.current)==null||X.stop()}catch{}if(C.current=null,$.current){try{$.current.disconnect()}catch{}$.current=null}if(b.current){try{b.current.disconnect()}catch{}b.current=null}if(T.current){try{T.current.disconnect()}catch{}T.current=null}if(ue(Ie=>Ie+1),E.current){const Ie=E.current;E.current=null;try{Ie.close()}catch{}}if(D.current){try{D.current.getTracks().forEach(Ie=>Ie.stop())}catch{}D.current=null}},[]),Ee=G.useCallback(()=>{Ce(),w.current=null,x.current=null,N(!1),j(Math.round(vf/1e3)),U(!1),de(!1),me(null),d(null),v(!1)},[Ce]);G.useEffect(()=>{i?(Ao("info","wizard.opened"),p("welcome")):Ee()},[i,Ee]),G.useEffect(()=>()=>Ce(),[Ce]);const W=G.useCallback(X=>{Ao("info","wizard.step",{step:X}),d(null),p(X)},[]),te=G.useCallback(X=>{if(Ao("info","wizard.skipped",{step:l,mode:X}),Ce(),e(),X==="skip-and-record"){const Ie=Ct.getState();Ie.setWizardArmed(!1);const pe=xt.getState().activeTabId;pe&&Ie.startRecording(pe)}else Ct.getState().setWizardArmed(!1)},[l,e,Ce]),K=G.useCallback(()=>{if(t==="denied"){W("permission");return}W("permission")},[t,W]);G.useEffect(()=>{i&&l==="permission"&&t==="granted"&&W("device")},[i,l,t,W]),G.useEffect(()=>{if(!i||l!=="device")return;let X=!1;return(async()=>{var Ie;try{if(!((Ie=navigator.mediaDevices)!=null&&Ie.enumerateDevices)){X||v(!0);return}const pe=await navigator.mediaDevices.enumerateDevices();if(X)return;const Ze=pe.filter(ge=>ge.kind==="audioinput");v(Ze.length===0)}catch(pe){if(X)return;Ao("warn","wizard.error",{step:"device",error:pe instanceof Error?pe.message:String(pe)}),v(!0)}})(),()=>{X=!0}},[i,l,m]);const re=G.useCallback(async()=>{d(null),N(!0),j(Math.round(vf/1e3));try{let X=null;try{const _t=await window.api.voice.getDevicePref();X=(_t==null?void 0:_t.selectedDeviceId)??null}catch{}const Ie={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};X&&(Ie.deviceId={exact:X});const pe=await navigator.mediaDevices.getUserMedia({audio:Ie});D.current=pe;const Ze=new AudioContext;E.current=Ze;const ge=Ze.createMediaStreamSource(pe),Ke=Ze.createAnalyser();Ke.fftSize=2048,Ke.smoothingTimeConstant=.8,ge.connect(Ke),T.current=ge,b.current=Ke,ue(_t=>_t+1);const vt=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",st=new MediaRecorder(pe,vt?{mimeType:vt}:void 0);C.current=st;const Kt=[];st.ondataavailable=_t=>{_t.data&&_t.data.size>0&&Kt.push(_t.data)},st.onstop=()=>{const _t=st.mimeType||"audio/webm";if(w.current=new Blob(Kt,{type:_t}),N(!1),b.current){try{b.current.disconnect()}catch{}b.current=null}if(T.current){try{T.current.disconnect()}catch{}T.current=null}if(ue(ri=>ri+1),D.current){try{D.current.getTracks().forEach(ri=>ri.stop())}catch{}D.current=null}W("playback")},st.onerror=_t=>{var Ye;const ri=((Ye=_t.error)==null?void 0:Ye.message)??"recorder error";Ao("error","wizard.error",{step:"record",error:ri}),d(ri),N(!1),lt.error(`Mic wizard: ${ri}`)},st.start();const Be=Date.now(),Dt=setInterval(()=>{const _t=Date.now()-Be,ri=Math.max(0,Math.ceil((vf-_t)/1e3));if(j(ri),_t>=vf){clearInterval(Dt);try{st.stop()}catch{}}},250)}catch(X){const Ie=X instanceof Error?X.message:String(X);Ao("error","wizard.error",{step:"record",error:Ie}),d(Ie),N(!1),Ce(),lt.error(`Mic wizard: ${Ie}`)}},[W,Ce]),ve=G.useCallback(async()=>{d(null);const X=w.current;if(!X){d("No recording available");return}try{let Ie=E.current;(!Ie||Ie.state==="closed")&&(Ie=new AudioContext,E.current=Ie);let pe=x.current;if(!pe){const ge=await X.arrayBuffer();pe=await Ie.decodeAudioData(ge.slice(0)),x.current=pe}if($.current){try{$.current.disconnect()}catch{}$.current=null}const Ze=Ie.createBufferSource();Ze.buffer=pe,Ze.connect(Ie.destination),$.current=Ze,U(!0),Ze.onended=()=>{U(!1);try{Ze.disconnect()}catch{}$.current===Ze&&($.current=null)},Ze.start()}catch(Ie){const pe=Ie instanceof Error?Ie.message:String(Ie);Ao("error","wizard.error",{step:"playback",error:pe}),d(pe),U(!1)}},[]);G.useEffect(()=>{i&&l==="playback"&&ve().catch(()=>{})},[i,l,ve]);const _e=G.useCallback(async()=>{d(null),de(!0),me(null);try{const X=x.current;if(!X)throw new Error("No decoded audio available");const Ie=X.getChannelData(0),pe=new Float32Array(Ie.length);pe.set(Ie);const Ze=await QE(pe);me(Ze)}catch(X){const Ie=X instanceof Error?X.message:String(X);Ao("error","wizard.error",{step:"verify",error:Ie}),d(Ie)}finally{de(!1)}},[]);G.useEffect(()=>{i&&l==="verify"&&n==="ready"&&Z===null&&!oe&&!a&&_e()},[i,l,n,Z,oe,a,_e]);const Me=G.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),Ao("info","wizard.complete")}catch(X){Ao("error","wizard.error",{step:"done",error:X instanceof Error?X.message:String(X)})}Ct.getState().setWizardArmed(!1),Ce(),e()},[e,Ce]),et=G.useCallback(()=>{Ao("info","wizard.skipped",{step:l,mode:"modal-close"}),Ce(),Ct.getState().setWizardArmed(!1),e()},[l,Ce,e]),we=G.useMemo(()=>{switch(l){case"welcome":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),h.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:K,"data-testid":"wizard-start",children:"Start"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>te("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),h.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>te("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return t==="denied"?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),h.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",h.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",h.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),h.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",t]}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>W("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return f?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),h.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{v(!1),y(X=>X+1)},"data-testid":"wizard-device-retry",children:"Try again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),h.jsx(bC,{}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>W("record"),"data-testid":"wizard-device-continue",children:"Continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return h.jsxs("div",{className:"space-y-3",children:[h.jsxs("p",{className:"text-sm text-fg",children:["Say: ",h.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),h.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),P?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",L,"s"]}),h.jsx(O3,{analyser:b.current},ie)]}):h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{re()},"data-testid":"wizard-record-start",children:"Start recording"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),h.jsx("p",{className:"text-xs text-fg-dim",children:H?"Playing back…":"Playback finished."}),h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>W("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{ve()},"data-testid":"wizard-playback-replay",children:"Replay"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,W("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return n==="loading"||n==="idle"?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),h.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[h.jsx("span",{children:"Downloading"}),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}%`},"data-testid":"wizard-load-progress"})}),h.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:oe?"Transcribing your sample…":Z===null?"Ready to transcribe.":"We heard:"}),Z!==null&&h.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:Z||"(no text recognized)"}),h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",disabled:oe||Z===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>W("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,me(null),W("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),h.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{Me()},"data-testid":"wizard-done",children:"Done"})})]})}},[l,K,te,t,f,P,L,ie,H,oe,Z,n,r,a,W,re,ve,Me]);return h.jsx(ww,{open:i,onClose:et,title:"Mic check",children:h.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[h.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",l]}),a?h.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:a}):null,we]})})}const ak="sm.tour.completedAt",Wl=In((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:t=>{e().stepCount!==t&&i({stepCount:t})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:t,stepCount:n}=e();if(t>=n-1){e().complete();return}i({currentStep:t+1})},prev:()=>{const{currentStep:t}=e();t<=0||i({currentStep:t-1})},goTo:t=>{const{stepCount:n}=e();t<0||t>=n||i({currentStep:t})},complete:()=>{try{localStorage.setItem(ak,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function z3(){try{return!!localStorage.getItem(ak)}catch{return!1}}const X0={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function B3(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app",section:"session",run:()=>window.api.app.rebootApp()},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=Ct.getState(),t=xt.getState().activeTabId;e.isRecording?e.stopRecording():t&&e.startRecording(t)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>Ct.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>Ct.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{lt.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{lt.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Wl.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ei.getState().resetLayout()},{id:"nav:overview",label:"Home — this machine",section:"nav",emitOnly:!0},{id:"nav:project-home",label:"Go to Home",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0}]}function G3(i,e){if(!e)return 0;const t=i.toLowerCase(),n=e.toLowerCase();let r=0,l=-1,p=0;for(let a=0;a<t.length&&r<n.length;a++)t[a]===n[r]&&(p+=a-l,l=a,r++);return r!==n.length?null:p}function F3(i,e){if(!e)return i.map(n=>({...n,score:0}));const t=[];for(const n of i){const r=G3(n.label,e);r!==null&&t.push({...n,score:r})}return t.sort((n,r)=>n.score-r.score),t}function H3({open:i,onClose:e,onCommand:t}){const[n,r]=G.useState(""),[l,p]=G.useState(0),a=G.useRef(null),d=G.useRef(null),f=G.useRef(null),v=G.useRef(null),m=G.useMemo(()=>B3(),[]),y=G.useMemo(()=>F3(m,n),[m,n]);if(G.useEffect(()=>{if(i){const $=document.activeElement;v.current=$ instanceof HTMLElement?$:null,r(""),p(0);const P=setTimeout(()=>{var N;return(N=a.current)==null?void 0:N.focus()},0);return()=>{clearTimeout(P);const N=v.current;v.current=null,N&&requestAnimationFrame(()=>{try{N.focus()}catch{}})}}},[i]),G.useEffect(()=>{l>=y.length&&p(Math.max(0,y.length-1))},[y.length,l]),G.useEffect(()=>{if(!d.current)return;const $=d.current.querySelector(`[data-cmd-idx="${l}"]`);$&&$.scrollIntoView({block:"nearest"})},[l]),!i)return null;const D=async $=>{var P;if(e(),$.emitOnly){t($);return}try{await((P=$.run)==null?void 0:P.call($))}catch(N){console.error("[command-palette] run failed",$.id,N);const L=N instanceof Error?N.message:String(N);lt.error(`Command "${$.label}" failed: ${L}`)}t($)},E=$=>{var P,N,L,j;if($.key==="Escape"){$.preventDefault(),e();return}if($.key==="ArrowDown"){$.preventDefault(),p(H=>Math.min(y.length-1,H+1));return}if($.key==="ArrowUp"){$.preventDefault(),p(H=>Math.max(0,H-1));return}if($.key==="Home"){$.preventDefault(),p(0);return}if($.key==="End"){$.preventDefault(),p(Math.max(0,y.length-1));return}if($.key==="PageDown"){$.preventDefault(),p(H=>Math.min(y.length-1,H+5));return}if($.key==="PageUp"){$.preventDefault(),p(H=>Math.max(0,H-5));return}if($.key==="Tab"){$.preventDefault();const H=document.activeElement;$.shiftKey?H===a.current?(P=f.current)==null||P.focus():(N=a.current)==null||N.focus():H===a.current?(L=f.current)==null||L.focus():(j=a.current)==null||j.focus();return}if($.key==="Enter"){$.preventDefault();const H=y[l];H&&D(H);return}},T=[],b=new Map;y.forEach(($,P)=>{let N=b.get($.section);N===void 0&&(N=T.length,b.set($.section,N),T.push({section:$.section,items:[]})),T[N].items.push({cmd:$,absIdx:P})});const C=y[l],w=C?`cmdk-opt-${C.id}`:void 0,x=h.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-start justify-center bg-black/60 pt-[15vh]`,onClick:$=>{$.target===$.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:E,children:h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[h.jsxs("div",{className:"border-b border-line flex items-center",children:[h.jsx("input",{ref:a,id:"cmdk-title",type:"text",value:n,onChange:$=>{r($.target.value),p(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":w,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),h.jsx("button",{ref:f,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),h.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:y.length===0?h.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):T.map($=>h.jsxs("div",{role:"group","aria-label":X0[$.section],className:"py-1",children:[h.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:X0[$.section]}),$.items.map(({cmd:P,absIdx:N})=>{const L=N===l;return h.jsxs("button",{id:`cmdk-opt-${P.id}`,type:"button",role:"option","aria-selected":L,"data-cmd-idx":N,"data-cmd-id":P.id,tabIndex:-1,onMouseEnter:()=>p(N),onClick:()=>D(P),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${L?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[h.jsx("span",{className:"truncate flex-1",children:P.label}),P.hint&&h.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:P.hint})]},P.id)})]},$.section))}),h.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[h.jsx("span",{children:"↑↓ navigate"}),h.jsx("span",{children:"↵ run"}),h.jsx("span",{children:"esc close"}),h.jsxs("span",{className:"ml-auto",children:[y.length," of ",m.length]})]})]})});return typeof document<"u"&&document.body?Jf.createPortal(x,document.body):x}const W3={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function lk(){const i=ed(t=>t.toasts),e=ed(t=>t.dismiss);return i.length===0?null:h.jsx("div",{"data-testid":"toast-host",className:`fixed bottom-3 right-3 ${Cn.toast} flex flex-col gap-1.5 pointer-events-none`,children:i.map(t=>{const n=W3[t.kind];return h.jsxs("div",{"data-testid":"toast","data-kind":t.kind,role:t.kind==="error"?"alert":"status","aria-live":t.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${n.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[h.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${n.text}`,children:n.label}),h.jsx("span",{className:"flex-1 text-fg-dim break-words",children:t.message}),h.jsx("button",{type:"button",onClick:()=>e(t.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},t.id)})})}function U3(){const i=xt(r=>r.tabs),e=xt(r=>r.activeTabId),t=i.find(r=>r.id===e)??null,n=Ct(r=>r.isRecording);return h.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${n?"pt-7":""}`,children:[h.jsx(ok,{}),h.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[h.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),t&&h.jsxs("span",{className:"truncate",children:["· ",t.cwd]})]}),h.jsx("div",{className:"flex-1 min-h-0 relative",children:t?h.jsx(nk,{tabId:t.id,cwd:t.cwd},`${t.id}-${t.generation}`):h.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),h.jsx(lk,{})]})}const Zc=[{id:"welcome",title:"Welcome to Session Manager",body:"A 30-second tour so you know where everything lives. You can re-run this any time from the command palette.",position:"center"},{id:"tabs",title:"Session tabs",body:"Each tab is a separate Claude session with its own working directory. Click + new to open another, drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"Left navigation",body:"Switch between Terminal, Settings, Skills, MCP servers, History and more. Live dots show which sections are active right now.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"voice",title:"Push-to-talk dictation",body:"Hold the configured hotkey (F1 by default) to dictate into the terminal. You can also click the mic.",target:'[data-testid="mic-button"]',position:"right"},{id:"scheduler",title:"PRD scheduler",body:"Open a project tab and pick Scheduler in its sidebar: every PRD under that project's session-manager-operations/scheduler/ runs there as a token-budget-managed claude -p job. It is project-scoped — there is no machine-wide queue view.",position:"center"},{id:"mainpane-actions",title:"Session actions",body:"Press ⌘K / Ctrl+K to open the command palette — restart this session, broadcast a prompt to multiple tabs, or attach a long-running watcher command whose stdout streams back as toasts.",position:"center"},{id:"statusbar",title:"Status bar",body:"Model, 5-hour usage, branch, last activity, and the active working directory. Click restart-app to reload the whole app.",target:'[data-testid="tour-statusbar"]',position:"top"},{id:"new-session",title:"Start a new session",body:"Pick any project directory to spin up another claude session. Tabs persist across reboots — they auto-resume on next launch.",target:'[data-testid="tour-new-session"]',position:"top"}],Fl=360,Qc=220,Dn=16;function Gl(i,e,t){return Math.max(e,Math.min(t,i))}function V3(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const t=window.innerWidth,n=window.innerHeight;switch(e){case"top":return{position:"fixed",top:Gl(i.top-Qc-Dn,Dn,n-Qc-Dn),left:Gl(i.left+i.width/2-Fl/2,Dn,t-Fl-Dn)};case"bottom":return{position:"fixed",top:Gl(i.bottom+Dn,Dn,n-Qc-Dn),left:Gl(i.left+i.width/2-Fl/2,Dn,t-Fl-Dn)};case"left":return{position:"fixed",top:Gl(i.top+i.height/2-Qc/2,Dn,n-Qc-Dn),left:Gl(i.left-Fl-Dn,Dn,t-Fl-Dn)};case"right":return{position:"fixed",top:Gl(i.top+i.height/2-Qc/2,Dn,n-Qc-Dn),left:Gl(i.right+Dn,Dn,t-Fl-Dn)}}}function q3(){const i=Wl(T=>T.open),e=Wl(T=>T.currentStep),t=Wl(T=>T.next),n=Wl(T=>T.prev),r=Wl(T=>T.complete),l=Wl(T=>T.setStepCount);G.useEffect(()=>{l(Zc.length)},[l]);const[p,a]=G.useState(null),d=G.useRef(null),f=Zc[e]??Zc[0],v=e===0,m=e===Zc.length-1;if(G.useLayoutEffect(()=>{if(!i)return;let T=!1;const b=()=>{if(T)return;if(!f.target){a(null);return}const w=document.querySelector(f.target);if(!w){a(null);return}a(w.getBoundingClientRect())},C=requestAnimationFrame(b);return window.addEventListener("resize",b),()=>{T=!0,cancelAnimationFrame(C),window.removeEventListener("resize",b)}},[i,f.target,e]),G.useEffect(()=>{if(!i)return;const T=b=>{if(b.key==="Escape"){b.stopPropagation(),pt.info("tour","skipped",{step:f.id}),r();return}if(b.key==="ArrowRight"||b.key==="Enter"){b.preventDefault(),t();return}b.key==="ArrowLeft"&&(b.preventDefault(),n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[i,t,n,r,f.id]),G.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:f.id})},[i,e,f.id]),!i)return null;const y=V3(p,f.position),D=(e+1)/Zc.length*100,E=h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:`fixed inset-0 ${Cn.tour}`,children:[p?h.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:p.top-6,left:p.left-6,width:p.width+12,height:p.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):h.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),h.jsxs("div",{ref:d,style:{...y,width:Fl},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[h.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[h.jsxs("div",{children:[h.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",Zc.length]}),h.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:f.title})]}),h.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),h.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:f.body}),h.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":Zc.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${D}%`}})}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),h.jsxs("div",{className:"flex items-center gap-2",children:[!v&&h.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),h.jsx("button",{type:"button",onClick:t,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:m?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?Jf.createPortal(E,document.body):E}function _f(i){return{path:i,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function A_(i,e,t){const n={...i,diskRaw:e.raw,diskData:e.data,exists:e.exists,parseError:e.parseError,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.raw,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}function I_(i,e,t){const n={...i,diskRaw:e.text,diskData:null,exists:e.exists,parseError:null,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.text,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}const K3=In((i,e)=>({files:{},watchRefs:{},loadJson:async t=>{const n=e().files[t];i({files:{...e().files,[t]:{...n??_f(t),busy:!0}}});const r=await window.api.config.readJson(t),l=e().files[t]??_f(t);i({files:{...e().files,[t]:A_(l,r,!1)}})},loadText:async(t,n=!1)=>{const r=e().files[t];i({files:{...e().files,[t]:{...r??_f(t),busy:!0}}});const l=await window.api.config.readText(t),p=e().files[t]??_f(t);i({files:{...e().files,[t]:I_(p,l,n)}})},setDraft:(t,n)=>{const r=e().files[t]??_f(t),l=n!==r.diskRaw;i({files:{...e().files,[t]:{...r,draftRaw:n,dirty:l}}})},revert:t=>{const n=e().files[t];n&&i({files:{...e().files,[t]:{...n,draftRaw:n.diskRaw,dirty:!1}}})},saveJson:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};let r;try{r=n.draftRaw.trim()===""?{}:JSON.parse(n.draftRaw)}catch(d){return{ok:!1,error:`invalid JSON: ${d.message}`}}i({files:{...e().files,[t]:{...n,busy:!0}}});const l=await window.api.config.writeJson(t,r);if(!l.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:l.error};const p=await window.api.config.readJson(t),a=A_({...n,busy:!1},p,!1);return i({files:{...e().files,[t]:{...a,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};i({files:{...e().files,[t]:{...n,busy:!0}}});const r=await window.api.config.writeText(t,n.draftRaw);if(!r.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:r.error};const l=await window.api.config.readText(t),p=I_({...n,busy:!1},l,!1);return i({files:{...e().files,[t]:{...p,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:t=>{const n={...e().watchRefs};n[t]=(n[t]??0)+1,i({watchRefs:n}),n[t]===1&&window.api.config.watch([t])},unwatchFile:t=>{const n={...e().watchRefs};n[t]&&(n[t]--,n[t]<=0&&(delete n[t],window.api.config.unwatch([t])),i({watchRefs:n}))},onExternalChange:t=>{e().files[t]&&(t.endsWith(".json")?window.api.config.readJson(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:A_(l,r,!0)}})}):window.api.config.readText(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:I_(l,r,!0)}})}))}}));function Y3(){return window.api.config.onChanged(({path:i})=>{K3.getState().onExternalChange(i)})}let P_=null;function X3(){return P_||(P_=os(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(uw.config({monaco:i}),i))),P_}function AL({value:i,onChange:e,path:t,readOnly:n}){const r=G.useRef(null),l=p=>{r.current=p};return h.jsx(tC,{path:`file://${t}`,defaultLanguage:"json",value:i,onChange:p=>e(p??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:n,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let J0=!1;async function J3(i){if(J0)return;const e=await X3(),t=await Promise.all(i.map(async r=>{let l=r.schema;if(!l){const p=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const a=new URL(r.uri).origin;if(!p.includes(a))throw new Error("untrusted origin");const d=await fetch(r.uri);d.ok&&(l=await d.json())}catch{}}return{uri:r.uri,fileMatch:r.fileMatch,schema:l}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:t.filter(r=>r.schema),enableSchemaRequest:!0}),J0=!0}const Z3=3e4,Q3=5e3,eL=In(()=>({teams:[],loaded:!1}));let Z0=!1,Q0=!1;async function ck(){try{const i=await Ob(window.api.teams.list(),Q3,"teams.list");eL.setState({teams:i.teams,loaded:!0})}catch(i){if(!Q0){Q0=!0;const e=i instanceof Error?i.message:String(i);lt.warn(`Teams list fetch failed: ${e}`)}}setTimeout(ck,Z3)}function tL(){Z0||(Z0=!0,ck())}async function e1(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return xt.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}async function iL(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=xt.getState(),t=e.tabs.find(r=>r.cwd===i);if(t)return e.setActive(t.id),t.id;const n=crypto.randomUUID();return e.addTab({id:n,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),n}function nL(i){const e=Ct(n=>n.ttsEnabled),t=Ct(n=>n.isRecording);G.useEffect(()=>{if(!i||!e)return;const n=l=>{const p=Ct.getState().lastBargeInAt;if(p!==null&&performance.now()-p<p2){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-p)});return}i2(l)};return window.api.transcripts.onEvent(i,l=>{for(const p of l){if(p.kind!=="message")continue;const a=p.data;if(typeof a!="object"||a===null)continue;const d=a;if(d.role!=="assistant"||Ct.getState().isRecording)continue;const f=d.content;if(typeof f=="string")n(f);else if(Array.isArray(f)){const v=f.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");v&&n(v)}}})},[i,e]),G.useEffect(()=>{t&&(O1(),Ct.setState({lastBargeInAt:performance.now()}))},[t])}const dk="sm.density",sL="roomy",t1="density-compact";function rL(){try{const i=localStorage.getItem(dk);if(i==="compact"||i==="roomy")return i}catch{}return sL}function uk(i){typeof document>"u"||(i==="compact"?document.body.classList.add(t1):document.body.classList.remove(t1))}let ch=rL();const Rb=new Set;uk(ch);function oL(i){if(i!==ch){ch=i;try{localStorage.setItem(dk,i)}catch{}uk(i),Rb.forEach(e=>e(i))}}function aL(){const[i,e]=G.useState(ch);G.useEffect(()=>{const n=r=>e(r);return Rb.add(n),ch!==i&&e(ch),()=>{Rb.delete(n)}},[]);const t=G.useCallback(n=>oL(n),[]);return{density:i,setDensity:t}}let i1=!1;function lL(){aL();const i=Ei(Z=>Z.focusedPanelId)??"overview",e=Ei(Z=>Z.navFace),[t,n]=G.useState(null),[r,l]=G.useState(!1),[p,a]=G.useState(!1),[d,f]=G.useState(!1),[v,m]=G.useState(null),y=G.useCallback(Z=>{Ei.getState().setEpicsWorkspaceOpen(Z==="terminal"),Ei.getState().openPanel(Z)},[]),D=G.useCallback(()=>y("voice"),[y]),E=G.useCallback(()=>y("scheduler"),[y]);G.useCallback(Z=>{$i.getState().openFile(Z),y("editor")},[y]),G.useEffect(()=>{Ei.getState().hydrateOpenToHomePref()},[]),G.useEffect(()=>{const Z=()=>y("editor");return window.addEventListener("sm:open-editor",Z),()=>window.removeEventListener("sm:open-editor",Z)},[y]),G.useEffect(()=>{const Z=me=>y(me.detail);return window.addEventListener("sm:navigate",Z),()=>window.removeEventListener("sm:navigate",Z)},[y]);const T=xt(Z=>Z.activeTabId),b=xt(Z=>Z.tabs),C=b.find(Z=>Z.id===T)??null,w=G.useRef(T),x=G.useRef(new Set(b.map(Z=>Z.id)));G.useEffect(()=>{const Z=w.current,me=x.current,ie=new Set(b.map(Ce=>Ce.id));w.current=T,x.current=ie,Z!==null&&T!==null&&T!==Z&&ie.size===me.size&&me.has(T)&&ie.has(Z)&&Ei.getState().openProjectPanel("terminal")},[T,b]),G.useEffect(()=>{AE(i,T,e)&&Ei.getState().openPanel("overview")},[i,T,e]),G.useEffect(()=>{if(!v)return;const Z=window.setTimeout(()=>m(null),2500);return()=>window.clearTimeout(Z)},[v]),G.useEffect(()=>C?window.api.watchers.onLine(me=>{if(me.tabId!==C.id)return;const ie=me.line.replace(/\x1b\[[0-9;]*m/g,"");ie.trim()&&m(ie.length>100?`${ie.slice(0,100)}…`:ie)}):void 0,[C==null?void 0:C.id]);const $=Ct(Z=>Z.isRecording),P=Ct(Z=>Z.wizardOpen),N=Ct(Z=>Z.closeWizard);nL(T);const L=G.useCallback(()=>{const{activeTabId:Z,restartTab:me}=xt.getState();Z&&me(Z)},[]);G.useCallback(()=>{window.api.app.rebootApp()},[]);const j=G.useCallback(()=>{a(Z=>(Z||Ei.getState().openPanel("terminal"),!Z))},[]),H=G.useCallback(()=>{f(Z=>(Z||Ei.getState().openPanel("terminal"),!Z))},[]),U=G.useRef(T);U.current=T;const oe=G.useRef("hold"),de=G.useCallback(()=>{iL().catch(()=>null).finally(()=>{Ei.getState().setEpicsWorkspaceOpen(!0),Ei.getState().openProjectPanel("terminal")})},[]);return G.useEffect(()=>{var ue;if(!vv()){i1||(pt.warn("voice","mic.gate.unsupported"),i1=!0);return}Ct.getState().initModel();let Z=null,me=!1;const ie=()=>{if(!Z)return;const Ce=Z.state;Ct.getState().setPermissionState(Ce)};return typeof navigator<"u"&&((ue=navigator.permissions)!=null&&ue.query)&&navigator.permissions.query({name:"microphone"}).then(Ce=>{me||(Z=Ce,Ct.getState().setPermissionState(Ce.state),Ce.addEventListener("change",ie))}).catch(Ce=>{pt.warn("voice","permission query unsupported",{error:Ce==null?void 0:Ce.message})}),()=>{me=!0,Z&&Z.removeEventListener("change",ie)}},[]),G.useEffect(()=>{var ve;const Z=a1[0],me=_e=>{if(!_e||xt.getState().tabs.length>0)return;const Me=crypto.randomUUID(),et=c1(Z,{sessionId:Me,cwd:_e});xt.setState(we=>({tabs:[...we.tabs,{id:Me,sessionId:Me,label:_e.split("/").filter(Boolean).pop()||_e,cwd:_e,pid:null,status:"spawning",exitCode:null,startupCommand:et,presetId:Z.id,generation:0}],activeTabId:Me}))},ie=_e=>{if(!_e||xt.getState().tabs.length>0)return;const Me=crypto.randomUUID();xt.setState(et=>({tabs:[...et.tabs,{id:Me,sessionId:Me,label:_e.split("/").filter(Boolean).pop()||_e,cwd:_e,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:Z.id,generation:0}],activeTabId:Me}))};window.api.app.launchMode().then(({simple:_e,cwd:Me})=>{if(_e){n(!0),me(Me);return}n(!1),O_().then(()=>{xt.getState().tabs.length>0||qw(Z).then(et=>ie(et||"")).catch(et=>{console.warn("[App] failed to create initial tab:",et),lt.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),O_().then(()=>{xt.getState().tabs.length>0||qw(Z).then(_e=>ie(_e||"")).catch(()=>{})})});const ue=window.api.app.onNewSession(()=>{e1().catch(_e=>{console.error("[App] new-session from menu failed:",_e),lt.error("Could not start new session. The directory picker failed.")})}),Ce=window.api.app.onRebootSession(()=>{const{activeTabId:_e}=xt.getState();_e&&xt.getState().restartTab(_e)});Tf.getState().init(),b2(),tL(),qk(),window.api.app.claudeBinStatus().then(_e=>{_e.foundOnDisk||lt.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(_e=>{_e.ok||lt.error(`Home-directory self-check failed: ${_e.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const Ee=Y3();J3([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]}]).catch(_e=>console.warn("[monaco] schema install failed:",_e)),window.api.voice.getHotkeyConfig().then(_e=>{oe.current=_e.mode}).catch(_e=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(_e)}));const W=window.api.voice.onHotkeyConfigChanged(_e=>{oe.current=_e.mode}),te=window.api.voice.onHotkey(({phase:_e,source:Me})=>{Ct.getState().armHotkey({phase:_e,source:Me,mode:oe.current,tabId:U.current})}),K=()=>Ct.getState().destroyHotkey();window.addEventListener("beforeunload",K);const re=async()=>{var _e;window.dispatchEvent(new Event("mic-device-change"));try{if(!((_e=navigator.mediaDevices)!=null&&_e.enumerateDevices))return;const et=(await navigator.mediaDevices.enumerateDevices()).filter(pe=>pe.kind==="audioinput"),we=Ct.getState();if(!we.isRecording)return;let X=null;try{X=await window.api.voice.getDevicePref()}catch{}if(!X||!X.selectedDeviceId||et.some(pe=>pe.deviceId===X.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:X.selectedDeviceId.slice(0,8)}),we.stopRecording(),Ct.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(Me){pt.warn("voice","devicechange handler failed",{error:Me instanceof Error?Me.message:String(Me)})}};return typeof navigator<"u"&&((ve=navigator.mediaDevices)!=null&&ve.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",re),()=>{var _e;Ee(),ue(),Ce(),W(),te(),window.removeEventListener("beforeunload",K),typeof navigator<"u"&&((_e=navigator.mediaDevices)!=null&&_e.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",re)}},[]),G.useEffect(()=>{try{window.api.voice.setRecording($)}catch{}},[$]),G.useEffect(()=>{const Z=ie=>{var W,te;const ue=ie.target,Ce=((W=ue==null?void 0:ue.tagName)==null?void 0:W.toLowerCase())??"",Ee=((te=ue==null?void 0:ue.classList)==null?void 0:te.contains("xterm-helper-textarea"))??!1;return!!((Ce==="input"||Ce==="textarea")&&!Ee||ue!=null&&ue.closest(".monaco-editor"))},me=ie=>{if((ie.metaKey||ie.ctrlKey)&&(ie.key==="k"||ie.key==="K")){if(Z(ie))return;ie.preventDefault(),ie.stopPropagation(),l(ue=>!ue)}else if(ie.key==="Escape"&&r)l(!1);else if(ie.altKey&&!ie.ctrlKey&&!ie.metaKey&&!ie.shiftKey){const ue=/^Digit([1-5])$/.exec(ie.code);if(!ue||Z(ie))return;const Ce=parseInt(ue[1],10)-1,{tabs:Ee,setActive:W}=xt.getState(),te=Ee[Ce];if(!te)return;ie.preventDefault(),ie.stopPropagation(),W(te.id),Ei.getState().setEpicsWorkspaceOpen(!1)}};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[r]),G.useEffect(()=>{let Z=!1,me=null;return(async()=>{var ie,ue;try{const Ce=await((ue=(ie=window.api.voice).getTurnDetector)==null?void 0:ue.call(ie));if(Z||!Ce||(Ct.setState({turnDetectorMode:Ce.mode,turnDetectorState:"disabled"}),Ce.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:Ce.mode}),Z))return;me=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),me.addEventListener("message",Ee=>{const W=Ee.data;if(!(!W||typeof W!="object")&&W.type==="status"){const te=W.status;te==="ready"?Ct.getState().setTurnDetectorRuntimeState("ok"):(te==="load_failed"||te==="runtime_error")&&Ct.getState().setTurnDetectorRuntimeState(te)}}),me.addEventListener("error",Ee=>{pt.error("voice-turn","turn-detector worker error",{message:Ee.message}),Ct.getState().setTurnDetectorRuntimeState("runtime_error")}),me.postMessage({type:"load"})}catch(Ce){pt.warn("voice-turn","mount.read-settings failed",{error:Ce instanceof Error?Ce.message:String(Ce)})}})(),()=>{if(Z=!0,me){try{me.terminate()}catch{}me=null}}},[]),G.useEffect(()=>{let Z=!1;return(async()=>{var me,ie;try{const ue=await((ie=(me=window.api.app).isE2E)==null?void 0:ie.call(me));if(Z||ue||z3()||Ct.getState().wizardOpen)return;Wl.getState().start()}catch{}})(),()=>{Z=!0}},[]),G.useEffect(()=>{let Z=!1;return(async()=>{var me,ie;try{const ue=await((ie=(me=window.api.app).isE2E)==null?void 0:ie.call(me));if(Z)return;if(ue){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const Ce=await window.api.voice.getWizardState();if(Z)return;Ce.completedSchema!==Ce.currentSchema&&(Ct.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:Ce.completedSchema,currentSchema:Ce.currentSchema}))}catch(ue){pt.warn("voice-wizard","auto-arm failed",{error:ue instanceof Error?ue.message:String(ue)})}})(),()=>{Z=!0}},[]),t===!0?h.jsx(U3,{}):h.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${$?"pt-7":""}`,children:[h.jsx(ok,{}),h.jsx(NE,{}),h.jsxs("div",{className:"flex-1 flex min-h-0",children:[h.jsx(D2,{active:i,onNavigate:y,onNewSession:de}),h.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&p&&h.jsx(B2,{onClose:()=>a(!1),onSent:Z=>{a(!1),m(`Sent to ${Z} tab${Z===1?"":"s"}`)}}),i==="terminal"&&C&&d&&h.jsx("div",{className:"absolute top-12 right-4 z-30",children:h.jsx(G2,{tabId:C.id,cwd:C.cwd,onClose:()=>f(!1)})}),h.jsx("div",{className:"flex-1 min-h-0 relative",children:h.jsx(M3,{onNavigate:y,onNewSession:de,onOpenVoice:D,onOpenScheduler:E})}),v&&h.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:v})]})]}),h.jsx(M2,{onNavigate:y}),h.jsx(L3,{open:P,onClose:N}),h.jsx(q3,{}),h.jsx(lk,{}),h.jsx(H3,{open:r,onClose:()=>l(!1),onCommand:Z=>{if(l(!1),Z.id.startsWith("nav:")){y(Z.id.slice(4));return}const me=xt.getState().tabs.find(ie=>ie.id===xt.getState().activeTabId)??null;switch(Z.id){case"new-tab-pick":e1().catch(ie=>{console.error("[App] new tab (pick) failed:",ie),lt.error("Could not start new session. The directory picker failed.")});return;case"new-tab-here":{if(!me)return;xt.getState().addTab({cwd:me.cwd,startupCommand:null,dormant:!0}),Ei.getState().openProjectPanel("terminal");return}case"close-tab":me&&xt.getState().closeTab(me.id);return;case"restart-session":L();return;case"broadcast":j();return;case"watchers":H();return;case"copy-cwd":me&&window.api.clipboard.writeText(me.cwd).catch(()=>lt.error("Copy failed"));return;case"copy-transcript":me&&window.api.transcripts.pathFor(me.cwd,me.sessionId).then(ie=>window.api.clipboard.writeText(ie)).catch(()=>lt.error("Copy failed"));return;case"open-transcript":me&&window.api.transcripts.pathFor(me.cwd,me.sessionId).then(ie=>window.api.shell.open({as:"openPath",path:ie})).catch(()=>lt.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const cL=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","teams","plugins","clipboard","memory"];function dL(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,t=[];for(const n of cL){const r=e[n];r==null?t.push({kind:"namespace-missing",name:n}):typeof r!="object"&&t.push({kind:"namespace-not-object",name:n,actualType:typeof r})}return t}function n1(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function uL(){const i=dL(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",n1(e));return setTimeout(()=>{os(async()=>{const{toast:e}=await Promise.resolve().then(()=>u1);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const t=i.length===1?n1(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(t)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");uL();Dk.createRoot(document.getElementById("root")).render(h.jsx(lL,{}));export{Nb as $,TN as A,DO as B,D_ as C,yL as D,gb as E,KN as F,_L as G,nA as H,jb as I,AL as J,h as K,jj as L,ww as M,Hf as N,CL as O,DL as P,hM as Q,jk as R,$L as S,Dv as T,Ub as U,yf as V,DS as W,NC as X,G as Y,Cn as Z,C1 as _,rs as a,mL as a0,yv as a1,TL as a2,EL as a3,Wk as a4,lt as a5,LR as a6,di as a7,K3 as a8,$i as a9,kS as aa,hh as ab,Ei as ac,nw as ad,Yt as ae,fL as af,jr as ag,PS as ah,xt as ai,uM as aj,gL as ak,$O as b,xL as c,dh as d,wL as e,tC as f,SL as g,kL as h,OC as i,cM as j,Rt as k,LD as l,MO as m,$b as n,lM as o,Tj as p,ZR as q,NS as r,xv as s,In as t,el as u,yM as v,vL as w,iA as x,bL as y,OS as z};
3068
+ `),lt.error(`Terminal failed to start: ${P.message??"spawn failed"}`),xt.getState().setTabExited(i,-1)})});const x=()=>y();window.addEventListener("resize",x),window.addEventListener(fv,x);const $=new ResizeObserver(()=>y());return $.observe(r.current),()=>{window.removeEventListener("resize",x),window.removeEventListener(fv,x),$.disconnect(),C(),w(),D(),v.dispose()}},[i,e]),t?n?h.jsx(ik,{cwd:e}):null:h.jsxs("div",{className:"relative h-full w-full",children:[h.jsx("button",{type:"button",onClick:()=>xt.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),a&&h.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:h.jsx(w3,{path:a,onDismiss:()=>d(null)},a)}),h.jsx("div",{ref:r,onMouseDown:()=>{var f;return(f=l.current)==null?void 0:f.focus()},className:"h-full w-full bg-bg"})]})}const x3={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},S3={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function C3(){const{isRecording:i,statusPill:e,lastPartial:t,lastTranscript:n,submitCountdownStartAt:r}=Ct(yw(g2)),l=i||!!t||!!n,[p,a]=G.useState(l);if(G.useEffect(()=>{if(l)a(!0);else{const f=setTimeout(()=>a(!1),300);return()=>clearTimeout(f)}},[l]),!p)return null;let d=t;return d.length>200&&(d="…"+d.slice(-200)),h.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${l?"opacity-100":"opacity-0"}`,children:h.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[h.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${x3[e]??"bg-fg-faint"}`}),h.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:S3[e]??e})]}),d&&h.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),r!==null&&h.jsx("div",{className:"shrink-0",children:h.jsx(wC,{})})]})})})}function k3({visible:i=!0}){const e=xt(p=>p.tabs),t=xt(p=>p.activeTabId),n=e.find(p=>p.id===t)??null,l=Ei(p=>p.epicsWorkspaceOpen)||!n;return h.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[l?h.jsx(ik,{}):e.map(p=>h.jsx("div",{className:"absolute inset-0",style:{visibility:p.id===t?"inherit":"hidden"},children:h.jsx(nk,{tabId:p.id,cwd:p.cwd})},`${p.id}-${p.generation}`)),h.jsx(C3,{}),i&&h.jsx(rN,{})]})}function E3(){const i=Ei(e=>e.focusedPanelId==="terminal");return h.jsx(k3,{visible:i})}const T3=1;function D3(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:T3,panels:e,dockview:i}}function Pb(i,e){const t=i.views.filter(r=>e.has(r));if(t.length===0)return null;const n=i.activeView&&t.includes(i.activeView)?i.activeView:t[0];return{...i,views:t,activeView:n}}function sk(i,e){if(i.type==="leaf"){const n=Pb(i.data,e);return n?{...i,data:n}:null}const t=i.data.map(n=>sk(n,e)).filter(n=>n!==null);return t.length===0?null:{...i,data:t}}function $3(i,e){const t=Object.keys(i.panels??{}),n=new Set(t.filter(d=>e.has(d)));if(n.size===0)return null;const r=sk(i.grid.root,n);if(!r)return null;const l={};for(const d of n)l[d]=i.panels[d];const p=(i.floatingGroups??[]).map(d=>{const f=Pb(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null),a=(i.popoutGroups??[]).map(d=>{const f=Pb(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:r},panels:l,floatingGroups:p,popoutGroups:a,activeGroup:i.activeGroup}}function A3(i,e){if(!i||typeof i!="object")return null;const t=i;if(!Array.isArray(t.panels)||!t.dockview||typeof t.dockview!="object")return null;const n=t.dockview;if(!n.grid||!n.panels)return null;try{return $3(n,e)}catch(r){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",r),null}}const I3=500,P3=new Set(id.map(i=>i.id));function Y0(i){const e=D3(i);e&&window.api.layout.save(e).catch(t=>{console.warn("[Workbench] layout save failed:",t)})}const rk=G.createContext(null),R3=G.memo(function(e){const t=G.useContext(rk);return t?h.jsx(h.Fragment,{children:N3(e.params.id,t)}):null}),j3={screen:R3},jg=id[0].id;function N3(i,e){return i==="terminal"?h.jsx(E3,{}):h.jsx(p$,{panelId:i,children:h.jsx("div",{className:"h-full overflow-auto bg-bg",children:h.jsx(vC,{children:Zj(i,e)})})})}function M3({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}){const r=G.useRef(null),l=Ei($=>$.focusedPanelId)??jg,p=Ei($=>$.focusToken),a=Ei($=>$.resetToken),d=Ct($=>$.isRecording||$.externalRecording),f=G.useRef(null),[v,m]=G.useState(!1),y=G.useRef(l);y.current=l;const D=G.useRef(null),E=G.useRef(null);G.useEffect(()=>{let $=!1;return window.api.layout.load().then(P=>{$||(P&&(f.current=A3(P,P3)),m(!0))}).catch(P=>{console.warn("[Workbench] layout load failed, using default:",P),$||m(!0)}),()=>{$=!0}},[]);const T=G.useCallback($=>{const P=r.current;if(!P)return;const N=$E($)??id[0],L=P.getPanel(N.id);if(L)L.api.setActive();else{const j=P.addPanel({id:N.id,component:N.component,title:N.title,params:{id:N.id},renderer:"always"});N.id==="terminal"&&j.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(fv))})}},[]),b=G.useCallback($=>{var j;r.current=$.api;const P=H=>{H.header.hidden=!0};E.current=$.api.onDidAddGroup(P),$.api.groups.forEach(P);const N=f.current;if(N)try{$.api.fromJSON(N);const H=(j=$.api.activePanel)==null?void 0:j.id;H&&Ei.getState().focusPanel(H)}catch(H){console.warn("[Workbench] fromJSON failed, falling back to default layout:",H),$.api.clear(),T(y.current)}else T(y.current);$.api.onDidActivePanelChange(H=>{H&&Ei.getState().focusPanel(H.id)}),D.current=$.api.onDidRemovePanel(H=>{if(H.id==="terminal"){Ei.getState().openPanel("terminal");return}$.api.totalPanels===0&&(Ei.getState().openPanel(jg),T(jg))});let L=null;$.api.onDidLayoutChange(()=>{L!==null&&window.clearTimeout(L),L=window.setTimeout(()=>Y0($.api.toJSON()),I3)})},[]);G.useEffect(()=>()=>{var $,P;($=D.current)==null||$.dispose(),(P=E.current)==null||P.dispose()},[]),G.useEffect(()=>{T(l)},[p,T]);const C=G.useRef(!0);G.useEffect(()=>{if(C.current){C.current=!1;return}const $=r.current;$&&($.clear(),f.current=null,T(jg),Y0($.toJSON()))},[a]),G.useEffect(()=>{const $=r.current;$&&($.layout($.width,$.height,!0),window.dispatchEvent(new CustomEvent(fv)))},[d]);const w=G.useMemo(()=>({components:j3,onReady:b,className:"dockview-theme-sm workbench-root"}),[b]),x=G.useMemo(()=>({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}),[i,e,t,n]);return v?h.jsx(rk.Provider,{value:x,children:h.jsx(CS,{...w})}):null}function ok(){return Ct(e=>e.isRecording||e.externalRecording)?h.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:`fixed inset-x-0 top-0 ${Cn.recording} h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0`,children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),h.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const vf=5e3;function Ao(i,e,t){var n,r;try{(r=(n=window.api)==null?void 0:n.logs)==null||r.write("voice-wizard",i,e,t)}catch{}}function O3({analyser:i}){const[e,t]=G.useState(0);return G.useEffect(()=>{if(!i){t(0);return}let n=0,r=!1;const l=new Uint8Array(new ArrayBuffer(i.fftSize)),p=()=>{if(r)return;i.getByteTimeDomainData(l);let a=0;for(let v=0;v<l.length;v++){const m=l[v]-128;a+=m*m}const d=Math.sqrt(a/l.length)/128,f=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));t(f),n=requestAnimationFrame(p)};return n=requestAnimationFrame(p),()=>{r=!0,cancelAnimationFrame(n)}},[i]),h.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function L3({open:i,onClose:e}){const t=Ct(X=>X.permissionState),n=Ct(X=>X.modelStatus),r=Ct(X=>X.loadingProgress),[l,p]=G.useState("welcome"),[a,d]=G.useState(null),[f,v]=G.useState(!1),[m,y]=G.useState(0),D=G.useRef(null),E=G.useRef(null),T=G.useRef(null),b=G.useRef(null),C=G.useRef(null),w=G.useRef(null),x=G.useRef(null),$=G.useRef(null),[P,N]=G.useState(!1),[L,j]=G.useState(Math.round(vf/1e3)),[H,U]=G.useState(!1),[oe,de]=G.useState(!1),[Z,me]=G.useState(null),[ie,ue]=G.useState(0),Ce=G.useCallback(()=>{var X;try{(X=C.current)==null||X.stop()}catch{}if(C.current=null,$.current){try{$.current.disconnect()}catch{}$.current=null}if(b.current){try{b.current.disconnect()}catch{}b.current=null}if(T.current){try{T.current.disconnect()}catch{}T.current=null}if(ue(Ie=>Ie+1),E.current){const Ie=E.current;E.current=null;try{Ie.close()}catch{}}if(D.current){try{D.current.getTracks().forEach(Ie=>Ie.stop())}catch{}D.current=null}},[]),Ee=G.useCallback(()=>{Ce(),w.current=null,x.current=null,N(!1),j(Math.round(vf/1e3)),U(!1),de(!1),me(null),d(null),v(!1)},[Ce]);G.useEffect(()=>{i?(Ao("info","wizard.opened"),p("welcome")):Ee()},[i,Ee]),G.useEffect(()=>()=>Ce(),[Ce]);const W=G.useCallback(X=>{Ao("info","wizard.step",{step:X}),d(null),p(X)},[]),te=G.useCallback(X=>{if(Ao("info","wizard.skipped",{step:l,mode:X}),Ce(),e(),X==="skip-and-record"){const Ie=Ct.getState();Ie.setWizardArmed(!1);const pe=xt.getState().activeTabId;pe&&Ie.startRecording(pe)}else Ct.getState().setWizardArmed(!1)},[l,e,Ce]),K=G.useCallback(()=>{if(t==="denied"){W("permission");return}W("permission")},[t,W]);G.useEffect(()=>{i&&l==="permission"&&t==="granted"&&W("device")},[i,l,t,W]),G.useEffect(()=>{if(!i||l!=="device")return;let X=!1;return(async()=>{var Ie;try{if(!((Ie=navigator.mediaDevices)!=null&&Ie.enumerateDevices)){X||v(!0);return}const pe=await navigator.mediaDevices.enumerateDevices();if(X)return;const Ze=pe.filter(ge=>ge.kind==="audioinput");v(Ze.length===0)}catch(pe){if(X)return;Ao("warn","wizard.error",{step:"device",error:pe instanceof Error?pe.message:String(pe)}),v(!0)}})(),()=>{X=!0}},[i,l,m]);const re=G.useCallback(async()=>{d(null),N(!0),j(Math.round(vf/1e3));try{let X=null;try{const _t=await window.api.voice.getDevicePref();X=(_t==null?void 0:_t.selectedDeviceId)??null}catch{}const Ie={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};X&&(Ie.deviceId={exact:X});const pe=await navigator.mediaDevices.getUserMedia({audio:Ie});D.current=pe;const Ze=new AudioContext;E.current=Ze;const ge=Ze.createMediaStreamSource(pe),Ke=Ze.createAnalyser();Ke.fftSize=2048,Ke.smoothingTimeConstant=.8,ge.connect(Ke),T.current=ge,b.current=Ke,ue(_t=>_t+1);const vt=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",st=new MediaRecorder(pe,vt?{mimeType:vt}:void 0);C.current=st;const Kt=[];st.ondataavailable=_t=>{_t.data&&_t.data.size>0&&Kt.push(_t.data)},st.onstop=()=>{const _t=st.mimeType||"audio/webm";if(w.current=new Blob(Kt,{type:_t}),N(!1),b.current){try{b.current.disconnect()}catch{}b.current=null}if(T.current){try{T.current.disconnect()}catch{}T.current=null}if(ue(ri=>ri+1),D.current){try{D.current.getTracks().forEach(ri=>ri.stop())}catch{}D.current=null}W("playback")},st.onerror=_t=>{var Ye;const ri=((Ye=_t.error)==null?void 0:Ye.message)??"recorder error";Ao("error","wizard.error",{step:"record",error:ri}),d(ri),N(!1),lt.error(`Mic wizard: ${ri}`)},st.start();const Be=Date.now(),Dt=setInterval(()=>{const _t=Date.now()-Be,ri=Math.max(0,Math.ceil((vf-_t)/1e3));if(j(ri),_t>=vf){clearInterval(Dt);try{st.stop()}catch{}}},250)}catch(X){const Ie=X instanceof Error?X.message:String(X);Ao("error","wizard.error",{step:"record",error:Ie}),d(Ie),N(!1),Ce(),lt.error(`Mic wizard: ${Ie}`)}},[W,Ce]),ve=G.useCallback(async()=>{d(null);const X=w.current;if(!X){d("No recording available");return}try{let Ie=E.current;(!Ie||Ie.state==="closed")&&(Ie=new AudioContext,E.current=Ie);let pe=x.current;if(!pe){const ge=await X.arrayBuffer();pe=await Ie.decodeAudioData(ge.slice(0)),x.current=pe}if($.current){try{$.current.disconnect()}catch{}$.current=null}const Ze=Ie.createBufferSource();Ze.buffer=pe,Ze.connect(Ie.destination),$.current=Ze,U(!0),Ze.onended=()=>{U(!1);try{Ze.disconnect()}catch{}$.current===Ze&&($.current=null)},Ze.start()}catch(Ie){const pe=Ie instanceof Error?Ie.message:String(Ie);Ao("error","wizard.error",{step:"playback",error:pe}),d(pe),U(!1)}},[]);G.useEffect(()=>{i&&l==="playback"&&ve().catch(()=>{})},[i,l,ve]);const _e=G.useCallback(async()=>{d(null),de(!0),me(null);try{const X=x.current;if(!X)throw new Error("No decoded audio available");const Ie=X.getChannelData(0),pe=new Float32Array(Ie.length);pe.set(Ie);const Ze=await QE(pe);me(Ze)}catch(X){const Ie=X instanceof Error?X.message:String(X);Ao("error","wizard.error",{step:"verify",error:Ie}),d(Ie)}finally{de(!1)}},[]);G.useEffect(()=>{i&&l==="verify"&&n==="ready"&&Z===null&&!oe&&!a&&_e()},[i,l,n,Z,oe,a,_e]);const Me=G.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),Ao("info","wizard.complete")}catch(X){Ao("error","wizard.error",{step:"done",error:X instanceof Error?X.message:String(X)})}Ct.getState().setWizardArmed(!1),Ce(),e()},[e,Ce]),et=G.useCallback(()=>{Ao("info","wizard.skipped",{step:l,mode:"modal-close"}),Ce(),Ct.getState().setWizardArmed(!1),e()},[l,Ce,e]),we=G.useMemo(()=>{switch(l){case"welcome":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),h.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:K,"data-testid":"wizard-start",children:"Start"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>te("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),h.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>te("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return t==="denied"?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),h.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",h.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",h.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),h.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",t]}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>W("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return f?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),h.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{v(!1),y(X=>X+1)},"data-testid":"wizard-device-retry",children:"Try again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),h.jsx(bC,{}),h.jsxs("div",{className:"flex gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>W("record"),"data-testid":"wizard-device-continue",children:"Continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return h.jsxs("div",{className:"space-y-3",children:[h.jsxs("p",{className:"text-sm text-fg",children:["Say: ",h.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),h.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),P?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",L,"s"]}),h.jsx(O3,{analyser:b.current},ie)]}):h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{re()},"data-testid":"wizard-record-start",children:"Start recording"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),h.jsx("p",{className:"text-xs text-fg-dim",children:H?"Playing back…":"Playback finished."}),h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>W("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{ve()},"data-testid":"wizard-playback-replay",children:"Replay"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,W("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return n==="loading"||n==="idle"?h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),h.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[h.jsx("span",{children:"Downloading"}),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}%`},"data-testid":"wizard-load-progress"})}),h.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:oe?"Transcribing your sample…":Z===null?"Ready to transcribe.":"We heard:"}),Z!==null&&h.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:Z||"(no text recognized)"}),h.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[h.jsx("button",{type:"button",disabled:oe||Z===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>W("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,me(null),W("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),h.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>te("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return h.jsxs("div",{className:"space-y-3",children:[h.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),h.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),h.jsx("div",{className:"flex gap-2 pt-1",children:h.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{Me()},"data-testid":"wizard-done",children:"Done"})})]})}},[l,K,te,t,f,P,L,ie,H,oe,Z,n,r,a,W,re,ve,Me]);return h.jsx(ww,{open:i,onClose:et,title:"Mic check",children:h.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[h.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",l]}),a?h.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:a}):null,we]})})}const ak="sm.tour.completedAt",Wl=In((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:t=>{e().stepCount!==t&&i({stepCount:t})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:t,stepCount:n}=e();if(t>=n-1){e().complete();return}i({currentStep:t+1})},prev:()=>{const{currentStep:t}=e();t<=0||i({currentStep:t-1})},goTo:t=>{const{stepCount:n}=e();t<0||t>=n||i({currentStep:t})},complete:()=>{try{localStorage.setItem(ak,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function z3(){try{return!!localStorage.getItem(ak)}catch{return!1}}const X0={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function B3(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app",section:"session",run:()=>window.api.app.rebootApp()},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=Ct.getState(),t=xt.getState().activeTabId;e.isRecording?e.stopRecording():t&&e.startRecording(t)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>Ct.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>Ct.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{lt.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{lt.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Wl.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ei.getState().resetLayout()},{id:"nav:overview",label:"Home — this machine",section:"nav",emitOnly:!0},{id:"nav:project-home",label:"Go to Home",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0}]}function G3(i,e){if(!e)return 0;const t=i.toLowerCase(),n=e.toLowerCase();let r=0,l=-1,p=0;for(let a=0;a<t.length&&r<n.length;a++)t[a]===n[r]&&(p+=a-l,l=a,r++);return r!==n.length?null:p}function F3(i,e){if(!e)return i.map(n=>({...n,score:0}));const t=[];for(const n of i){const r=G3(n.label,e);r!==null&&t.push({...n,score:r})}return t.sort((n,r)=>n.score-r.score),t}function H3({open:i,onClose:e,onCommand:t}){const[n,r]=G.useState(""),[l,p]=G.useState(0),a=G.useRef(null),d=G.useRef(null),f=G.useRef(null),v=G.useRef(null),m=G.useMemo(()=>B3(),[]),y=G.useMemo(()=>F3(m,n),[m,n]);if(G.useEffect(()=>{if(i){const $=document.activeElement;v.current=$ instanceof HTMLElement?$:null,r(""),p(0);const P=setTimeout(()=>{var N;return(N=a.current)==null?void 0:N.focus()},0);return()=>{clearTimeout(P);const N=v.current;v.current=null,N&&requestAnimationFrame(()=>{try{N.focus()}catch{}})}}},[i]),G.useEffect(()=>{l>=y.length&&p(Math.max(0,y.length-1))},[y.length,l]),G.useEffect(()=>{if(!d.current)return;const $=d.current.querySelector(`[data-cmd-idx="${l}"]`);$&&$.scrollIntoView({block:"nearest"})},[l]),!i)return null;const D=async $=>{var P;if(e(),$.emitOnly){t($);return}try{await((P=$.run)==null?void 0:P.call($))}catch(N){console.error("[command-palette] run failed",$.id,N);const L=N instanceof Error?N.message:String(N);lt.error(`Command "${$.label}" failed: ${L}`)}t($)},E=$=>{var P,N,L,j;if($.key==="Escape"){$.preventDefault(),e();return}if($.key==="ArrowDown"){$.preventDefault(),p(H=>Math.min(y.length-1,H+1));return}if($.key==="ArrowUp"){$.preventDefault(),p(H=>Math.max(0,H-1));return}if($.key==="Home"){$.preventDefault(),p(0);return}if($.key==="End"){$.preventDefault(),p(Math.max(0,y.length-1));return}if($.key==="PageDown"){$.preventDefault(),p(H=>Math.min(y.length-1,H+5));return}if($.key==="PageUp"){$.preventDefault(),p(H=>Math.max(0,H-5));return}if($.key==="Tab"){$.preventDefault();const H=document.activeElement;$.shiftKey?H===a.current?(P=f.current)==null||P.focus():(N=a.current)==null||N.focus():H===a.current?(L=f.current)==null||L.focus():(j=a.current)==null||j.focus();return}if($.key==="Enter"){$.preventDefault();const H=y[l];H&&D(H);return}},T=[],b=new Map;y.forEach(($,P)=>{let N=b.get($.section);N===void 0&&(N=T.length,b.set($.section,N),T.push({section:$.section,items:[]})),T[N].items.push({cmd:$,absIdx:P})});const C=y[l],w=C?`cmdk-opt-${C.id}`:void 0,x=h.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-start justify-center bg-black/60 pt-[15vh]`,onClick:$=>{$.target===$.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:E,children:h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[h.jsxs("div",{className:"border-b border-line flex items-center",children:[h.jsx("input",{ref:a,id:"cmdk-title",type:"text",value:n,onChange:$=>{r($.target.value),p(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":w,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),h.jsx("button",{ref:f,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),h.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:y.length===0?h.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):T.map($=>h.jsxs("div",{role:"group","aria-label":X0[$.section],className:"py-1",children:[h.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:X0[$.section]}),$.items.map(({cmd:P,absIdx:N})=>{const L=N===l;return h.jsxs("button",{id:`cmdk-opt-${P.id}`,type:"button",role:"option","aria-selected":L,"data-cmd-idx":N,"data-cmd-id":P.id,tabIndex:-1,onMouseEnter:()=>p(N),onClick:()=>D(P),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${L?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[h.jsx("span",{className:"truncate flex-1",children:P.label}),P.hint&&h.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:P.hint})]},P.id)})]},$.section))}),h.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[h.jsx("span",{children:"↑↓ navigate"}),h.jsx("span",{children:"↵ run"}),h.jsx("span",{children:"esc close"}),h.jsxs("span",{className:"ml-auto",children:[y.length," of ",m.length]})]})]})});return typeof document<"u"&&document.body?Jf.createPortal(x,document.body):x}const W3={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function lk(){const i=ed(t=>t.toasts),e=ed(t=>t.dismiss);return i.length===0?null:h.jsx("div",{"data-testid":"toast-host",className:`fixed bottom-3 right-3 ${Cn.toast} flex flex-col gap-1.5 pointer-events-none`,children:i.map(t=>{const n=W3[t.kind];return h.jsxs("div",{"data-testid":"toast","data-kind":t.kind,role:t.kind==="error"?"alert":"status","aria-live":t.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${n.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[h.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${n.text}`,children:n.label}),h.jsx("span",{className:"flex-1 text-fg-dim break-words",children:t.message}),h.jsx("button",{type:"button",onClick:()=>e(t.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},t.id)})})}function U3(){const i=xt(r=>r.tabs),e=xt(r=>r.activeTabId),t=i.find(r=>r.id===e)??null,n=Ct(r=>r.isRecording);return h.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${n?"pt-7":""}`,children:[h.jsx(ok,{}),h.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[h.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),t&&h.jsxs("span",{className:"truncate",children:["· ",t.cwd]})]}),h.jsx("div",{className:"flex-1 min-h-0 relative",children:t?h.jsx(nk,{tabId:t.id,cwd:t.cwd},`${t.id}-${t.generation}`):h.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),h.jsx(lk,{})]})}const Zc=[{id:"welcome",title:"Welcome to Session Manager",body:"A 30-second tour so you know where everything lives. You can re-run this any time from the command palette.",position:"center"},{id:"tabs",title:"Session tabs",body:"Each tab is a separate Claude session with its own working directory. Click + new to open another, drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"Left navigation",body:"Switch between Terminal, Settings, Skills, MCP servers, History and more. Live dots show which sections are active right now.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"voice",title:"Push-to-talk dictation",body:"Hold the configured hotkey (F1 by default) to dictate into the terminal. You can also click the mic.",target:'[data-testid="mic-button"]',position:"right"},{id:"scheduler",title:"PRD scheduler",body:"Open a project tab and pick Scheduler in its sidebar: every PRD under that project's session-manager-operations/scheduler/ runs there as a token-budget-managed claude -p job. It is project-scoped — there is no machine-wide queue view.",position:"center"},{id:"mainpane-actions",title:"Session actions",body:"Press ⌘K / Ctrl+K to open the command palette — restart this session, broadcast a prompt to multiple tabs, or attach a long-running watcher command whose stdout streams back as toasts.",position:"center"},{id:"statusbar",title:"Status bar",body:"Model, 5-hour usage, branch, last activity, and the active working directory. Click restart-app to reload the whole app.",target:'[data-testid="tour-statusbar"]',position:"top"},{id:"new-session",title:"Start a new session",body:"Pick any project directory to spin up another claude session. Tabs persist across reboots — they auto-resume on next launch.",target:'[data-testid="tour-new-session"]',position:"top"}],Fl=360,Qc=220,Dn=16;function Gl(i,e,t){return Math.max(e,Math.min(t,i))}function V3(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const t=window.innerWidth,n=window.innerHeight;switch(e){case"top":return{position:"fixed",top:Gl(i.top-Qc-Dn,Dn,n-Qc-Dn),left:Gl(i.left+i.width/2-Fl/2,Dn,t-Fl-Dn)};case"bottom":return{position:"fixed",top:Gl(i.bottom+Dn,Dn,n-Qc-Dn),left:Gl(i.left+i.width/2-Fl/2,Dn,t-Fl-Dn)};case"left":return{position:"fixed",top:Gl(i.top+i.height/2-Qc/2,Dn,n-Qc-Dn),left:Gl(i.left-Fl-Dn,Dn,t-Fl-Dn)};case"right":return{position:"fixed",top:Gl(i.top+i.height/2-Qc/2,Dn,n-Qc-Dn),left:Gl(i.right+Dn,Dn,t-Fl-Dn)}}}function q3(){const i=Wl(T=>T.open),e=Wl(T=>T.currentStep),t=Wl(T=>T.next),n=Wl(T=>T.prev),r=Wl(T=>T.complete),l=Wl(T=>T.setStepCount);G.useEffect(()=>{l(Zc.length)},[l]);const[p,a]=G.useState(null),d=G.useRef(null),f=Zc[e]??Zc[0],v=e===0,m=e===Zc.length-1;if(G.useLayoutEffect(()=>{if(!i)return;let T=!1;const b=()=>{if(T)return;if(!f.target){a(null);return}const w=document.querySelector(f.target);if(!w){a(null);return}a(w.getBoundingClientRect())},C=requestAnimationFrame(b);return window.addEventListener("resize",b),()=>{T=!0,cancelAnimationFrame(C),window.removeEventListener("resize",b)}},[i,f.target,e]),G.useEffect(()=>{if(!i)return;const T=b=>{if(b.key==="Escape"){b.stopPropagation(),pt.info("tour","skipped",{step:f.id}),r();return}if(b.key==="ArrowRight"||b.key==="Enter"){b.preventDefault(),t();return}b.key==="ArrowLeft"&&(b.preventDefault(),n())};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[i,t,n,r,f.id]),G.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:f.id})},[i,e,f.id]),!i)return null;const y=V3(p,f.position),D=(e+1)/Zc.length*100,E=h.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:`fixed inset-0 ${Cn.tour}`,children:[p?h.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:p.top-6,left:p.left-6,width:p.width+12,height:p.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):h.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),h.jsxs("div",{ref:d,style:{...y,width:Fl},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[h.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[h.jsxs("div",{children:[h.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",Zc.length]}),h.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:f.title})]}),h.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),h.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:f.body}),h.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":Zc.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${D}%`}})}),h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),h.jsxs("div",{className:"flex items-center gap-2",children:[!v&&h.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),h.jsx("button",{type:"button",onClick:t,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:m?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?Jf.createPortal(E,document.body):E}function _f(i){return{path:i,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function A_(i,e,t){const n={...i,diskRaw:e.raw,diskData:e.data,exists:e.exists,parseError:e.parseError,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.raw,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}function I_(i,e,t){const n={...i,diskRaw:e.text,diskData:null,exists:e.exists,parseError:null,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.text,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}const K3=In((i,e)=>({files:{},watchRefs:{},loadJson:async t=>{const n=e().files[t];i({files:{...e().files,[t]:{...n??_f(t),busy:!0}}});const r=await window.api.config.readJson(t),l=e().files[t]??_f(t);i({files:{...e().files,[t]:A_(l,r,!1)}})},loadText:async(t,n=!1)=>{const r=e().files[t];i({files:{...e().files,[t]:{...r??_f(t),busy:!0}}});const l=await window.api.config.readText(t),p=e().files[t]??_f(t);i({files:{...e().files,[t]:I_(p,l,n)}})},setDraft:(t,n)=>{const r=e().files[t]??_f(t),l=n!==r.diskRaw;i({files:{...e().files,[t]:{...r,draftRaw:n,dirty:l}}})},revert:t=>{const n=e().files[t];n&&i({files:{...e().files,[t]:{...n,draftRaw:n.diskRaw,dirty:!1}}})},saveJson:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};let r;try{r=n.draftRaw.trim()===""?{}:JSON.parse(n.draftRaw)}catch(d){return{ok:!1,error:`invalid JSON: ${d.message}`}}i({files:{...e().files,[t]:{...n,busy:!0}}});const l=await window.api.config.writeJson(t,r);if(!l.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:l.error};const p=await window.api.config.readJson(t),a=A_({...n,busy:!1},p,!1);return i({files:{...e().files,[t]:{...a,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};i({files:{...e().files,[t]:{...n,busy:!0}}});const r=await window.api.config.writeText(t,n.draftRaw);if(!r.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:r.error};const l=await window.api.config.readText(t),p=I_({...n,busy:!1},l,!1);return i({files:{...e().files,[t]:{...p,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:t=>{const n={...e().watchRefs};n[t]=(n[t]??0)+1,i({watchRefs:n}),n[t]===1&&window.api.config.watch([t])},unwatchFile:t=>{const n={...e().watchRefs};n[t]&&(n[t]--,n[t]<=0&&(delete n[t],window.api.config.unwatch([t])),i({watchRefs:n}))},onExternalChange:t=>{e().files[t]&&(t.endsWith(".json")?window.api.config.readJson(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:A_(l,r,!0)}})}):window.api.config.readText(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:I_(l,r,!0)}})}))}}));function Y3(){return window.api.config.onChanged(({path:i})=>{K3.getState().onExternalChange(i)})}let P_=null;function X3(){return P_||(P_=os(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(uw.config({monaco:i}),i))),P_}function AL({value:i,onChange:e,path:t,readOnly:n}){const r=G.useRef(null),l=p=>{r.current=p};return h.jsx(tC,{path:`file://${t}`,defaultLanguage:"json",value:i,onChange:p=>e(p??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:n,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let J0=!1;async function J3(i){if(J0)return;const e=await X3(),t=await Promise.all(i.map(async r=>{let l=r.schema;if(!l){const p=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const a=new URL(r.uri).origin;if(!p.includes(a))throw new Error("untrusted origin");const d=await fetch(r.uri);d.ok&&(l=await d.json())}catch{}}return{uri:r.uri,fileMatch:r.fileMatch,schema:l}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:t.filter(r=>r.schema),enableSchemaRequest:!0}),J0=!0}const Z3=3e4,Q3=5e3,eL=In(()=>({teams:[],loaded:!1}));let Z0=!1,Q0=!1;async function ck(){try{const i=await Ob(window.api.teams.list(),Q3,"teams.list");eL.setState({teams:i.teams,loaded:!0})}catch(i){if(!Q0){Q0=!0;const e=i instanceof Error?i.message:String(i);lt.warn(`Teams list fetch failed: ${e}`)}}setTimeout(ck,Z3)}function tL(){Z0||(Z0=!0,ck())}async function e1(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return xt.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}async function iL(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=xt.getState(),t=e.tabs.find(r=>r.cwd===i);if(t)return e.setActive(t.id),t.id;const n=crypto.randomUUID();return e.addTab({id:n,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),n}function nL(i){const e=Ct(n=>n.ttsEnabled),t=Ct(n=>n.isRecording);G.useEffect(()=>{if(!i||!e)return;const n=l=>{const p=Ct.getState().lastBargeInAt;if(p!==null&&performance.now()-p<p2){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-p)});return}i2(l)};return window.api.transcripts.onEvent(i,l=>{for(const p of l){if(p.kind!=="message")continue;const a=p.data;if(typeof a!="object"||a===null)continue;const d=a;if(d.role!=="assistant"||Ct.getState().isRecording)continue;const f=d.content;if(typeof f=="string")n(f);else if(Array.isArray(f)){const v=f.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");v&&n(v)}}})},[i,e]),G.useEffect(()=>{t&&(O1(),Ct.setState({lastBargeInAt:performance.now()}))},[t])}const dk="sm.density",sL="roomy",t1="density-compact";function rL(){try{const i=localStorage.getItem(dk);if(i==="compact"||i==="roomy")return i}catch{}return sL}function uk(i){typeof document>"u"||(i==="compact"?document.body.classList.add(t1):document.body.classList.remove(t1))}let ch=rL();const Rb=new Set;uk(ch);function oL(i){if(i!==ch){ch=i;try{localStorage.setItem(dk,i)}catch{}uk(i),Rb.forEach(e=>e(i))}}function aL(){const[i,e]=G.useState(ch);G.useEffect(()=>{const n=r=>e(r);return Rb.add(n),ch!==i&&e(ch),()=>{Rb.delete(n)}},[]);const t=G.useCallback(n=>oL(n),[]);return{density:i,setDensity:t}}let i1=!1;function lL(){aL();const i=Ei(Z=>Z.focusedPanelId)??"overview",e=Ei(Z=>Z.navFace),[t,n]=G.useState(null),[r,l]=G.useState(!1),[p,a]=G.useState(!1),[d,f]=G.useState(!1),[v,m]=G.useState(null),y=G.useCallback(Z=>{Ei.getState().setEpicsWorkspaceOpen(Z==="terminal"),Ei.getState().openPanel(Z)},[]),D=G.useCallback(()=>y("voice"),[y]),E=G.useCallback(()=>y("scheduler"),[y]);G.useCallback(Z=>{$i.getState().openFile(Z),y("editor")},[y]),G.useEffect(()=>{Ei.getState().hydrateOpenToHomePref()},[]),G.useEffect(()=>{const Z=()=>y("editor");return window.addEventListener("sm:open-editor",Z),()=>window.removeEventListener("sm:open-editor",Z)},[y]),G.useEffect(()=>{const Z=me=>y(me.detail);return window.addEventListener("sm:navigate",Z),()=>window.removeEventListener("sm:navigate",Z)},[y]);const T=xt(Z=>Z.activeTabId),b=xt(Z=>Z.tabs),C=b.find(Z=>Z.id===T)??null,w=G.useRef(T),x=G.useRef(new Set(b.map(Z=>Z.id)));G.useEffect(()=>{const Z=w.current,me=x.current,ie=new Set(b.map(Ce=>Ce.id));w.current=T,x.current=ie,Z!==null&&T!==null&&T!==Z&&ie.size===me.size&&me.has(T)&&ie.has(Z)&&Ei.getState().openProjectPanel("terminal")},[T,b]),G.useEffect(()=>{AE(i,T,e)&&Ei.getState().openPanel("overview")},[i,T,e]),G.useEffect(()=>{if(!v)return;const Z=window.setTimeout(()=>m(null),2500);return()=>window.clearTimeout(Z)},[v]),G.useEffect(()=>C?window.api.watchers.onLine(me=>{if(me.tabId!==C.id)return;const ie=me.line.replace(/\x1b\[[0-9;]*m/g,"");ie.trim()&&m(ie.length>100?`${ie.slice(0,100)}…`:ie)}):void 0,[C==null?void 0:C.id]);const $=Ct(Z=>Z.isRecording),P=Ct(Z=>Z.wizardOpen),N=Ct(Z=>Z.closeWizard);nL(T);const L=G.useCallback(()=>{const{activeTabId:Z,restartTab:me}=xt.getState();Z&&me(Z)},[]);G.useCallback(()=>{window.api.app.rebootApp()},[]);const j=G.useCallback(()=>{a(Z=>(Z||Ei.getState().openPanel("terminal"),!Z))},[]),H=G.useCallback(()=>{f(Z=>(Z||Ei.getState().openPanel("terminal"),!Z))},[]),U=G.useRef(T);U.current=T;const oe=G.useRef("hold"),de=G.useCallback(()=>{iL().catch(()=>null).finally(()=>{Ei.getState().setEpicsWorkspaceOpen(!0),Ei.getState().openProjectPanel("terminal")})},[]);return G.useEffect(()=>{var ue;if(!vv()){i1||(pt.warn("voice","mic.gate.unsupported"),i1=!0);return}Ct.getState().initModel();let Z=null,me=!1;const ie=()=>{if(!Z)return;const Ce=Z.state;Ct.getState().setPermissionState(Ce)};return typeof navigator<"u"&&((ue=navigator.permissions)!=null&&ue.query)&&navigator.permissions.query({name:"microphone"}).then(Ce=>{me||(Z=Ce,Ct.getState().setPermissionState(Ce.state),Ce.addEventListener("change",ie))}).catch(Ce=>{pt.warn("voice","permission query unsupported",{error:Ce==null?void 0:Ce.message})}),()=>{me=!0,Z&&Z.removeEventListener("change",ie)}},[]),G.useEffect(()=>{var ve;const Z=a1[0],me=_e=>{if(!_e||xt.getState().tabs.length>0)return;const Me=crypto.randomUUID(),et=c1(Z,{sessionId:Me,cwd:_e});xt.setState(we=>({tabs:[...we.tabs,{id:Me,sessionId:Me,label:_e.split("/").filter(Boolean).pop()||_e,cwd:_e,pid:null,status:"spawning",exitCode:null,startupCommand:et,presetId:Z.id,generation:0}],activeTabId:Me}))},ie=_e=>{if(!_e||xt.getState().tabs.length>0)return;const Me=crypto.randomUUID();xt.setState(et=>({tabs:[...et.tabs,{id:Me,sessionId:Me,label:_e.split("/").filter(Boolean).pop()||_e,cwd:_e,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:Z.id,generation:0}],activeTabId:Me}))};window.api.app.launchMode().then(({simple:_e,cwd:Me})=>{if(_e){n(!0),me(Me);return}n(!1),O_().then(()=>{xt.getState().tabs.length>0||qw(Z).then(et=>ie(et||"")).catch(et=>{console.warn("[App] failed to create initial tab:",et),lt.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),O_().then(()=>{xt.getState().tabs.length>0||qw(Z).then(_e=>ie(_e||"")).catch(()=>{})})});const ue=window.api.app.onNewSession(()=>{e1().catch(_e=>{console.error("[App] new-session from menu failed:",_e),lt.error("Could not start new session. The directory picker failed.")})}),Ce=window.api.app.onRebootSession(()=>{const{activeTabId:_e}=xt.getState();_e&&xt.getState().restartTab(_e)});Tf.getState().init(),b2(),tL(),qk(),window.api.app.claudeBinStatus().then(_e=>{_e.foundOnDisk||lt.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(_e=>{_e.ok||lt.error(`Home-directory self-check failed: ${_e.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const Ee=Y3();J3([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]}]).catch(_e=>console.warn("[monaco] schema install failed:",_e)),window.api.voice.getHotkeyConfig().then(_e=>{oe.current=_e.mode}).catch(_e=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(_e)}));const W=window.api.voice.onHotkeyConfigChanged(_e=>{oe.current=_e.mode}),te=window.api.voice.onHotkey(({phase:_e,source:Me})=>{Ct.getState().armHotkey({phase:_e,source:Me,mode:oe.current,tabId:U.current})}),K=()=>Ct.getState().destroyHotkey();window.addEventListener("beforeunload",K);const re=async()=>{var _e;window.dispatchEvent(new Event("mic-device-change"));try{if(!((_e=navigator.mediaDevices)!=null&&_e.enumerateDevices))return;const et=(await navigator.mediaDevices.enumerateDevices()).filter(pe=>pe.kind==="audioinput"),we=Ct.getState();if(!we.isRecording)return;let X=null;try{X=await window.api.voice.getDevicePref()}catch{}if(!X||!X.selectedDeviceId||et.some(pe=>pe.deviceId===X.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:X.selectedDeviceId.slice(0,8)}),we.stopRecording(),Ct.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(Me){pt.warn("voice","devicechange handler failed",{error:Me instanceof Error?Me.message:String(Me)})}};return typeof navigator<"u"&&((ve=navigator.mediaDevices)!=null&&ve.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",re),()=>{var _e;Ee(),ue(),Ce(),W(),te(),window.removeEventListener("beforeunload",K),typeof navigator<"u"&&((_e=navigator.mediaDevices)!=null&&_e.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",re)}},[]),G.useEffect(()=>{try{window.api.voice.setRecording($)}catch{}},[$]),G.useEffect(()=>{const Z=ie=>{var W,te;const ue=ie.target,Ce=((W=ue==null?void 0:ue.tagName)==null?void 0:W.toLowerCase())??"",Ee=((te=ue==null?void 0:ue.classList)==null?void 0:te.contains("xterm-helper-textarea"))??!1;return!!((Ce==="input"||Ce==="textarea")&&!Ee||ue!=null&&ue.closest(".monaco-editor"))},me=ie=>{if((ie.metaKey||ie.ctrlKey)&&(ie.key==="k"||ie.key==="K")){if(Z(ie))return;ie.preventDefault(),ie.stopPropagation(),l(ue=>!ue)}else if(ie.key==="Escape"&&r)l(!1);else if(ie.altKey&&!ie.ctrlKey&&!ie.metaKey&&!ie.shiftKey){const ue=/^Digit([1-5])$/.exec(ie.code);if(!ue||Z(ie))return;const Ce=parseInt(ue[1],10)-1,{tabs:Ee,setActive:W}=xt.getState(),te=Ee[Ce];if(!te)return;ie.preventDefault(),ie.stopPropagation(),W(te.id),Ei.getState().setEpicsWorkspaceOpen(!1)}};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[r]),G.useEffect(()=>{let Z=!1,me=null;return(async()=>{var ie,ue;try{const Ce=await((ue=(ie=window.api.voice).getTurnDetector)==null?void 0:ue.call(ie));if(Z||!Ce||(Ct.setState({turnDetectorMode:Ce.mode,turnDetectorState:"disabled"}),Ce.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:Ce.mode}),Z))return;me=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),me.addEventListener("message",Ee=>{const W=Ee.data;if(!(!W||typeof W!="object")&&W.type==="status"){const te=W.status;te==="ready"?Ct.getState().setTurnDetectorRuntimeState("ok"):(te==="load_failed"||te==="runtime_error")&&Ct.getState().setTurnDetectorRuntimeState(te)}}),me.addEventListener("error",Ee=>{pt.error("voice-turn","turn-detector worker error",{message:Ee.message}),Ct.getState().setTurnDetectorRuntimeState("runtime_error")}),me.postMessage({type:"load"})}catch(Ce){pt.warn("voice-turn","mount.read-settings failed",{error:Ce instanceof Error?Ce.message:String(Ce)})}})(),()=>{if(Z=!0,me){try{me.terminate()}catch{}me=null}}},[]),G.useEffect(()=>{let Z=!1;return(async()=>{var me,ie;try{const ue=await((ie=(me=window.api.app).isE2E)==null?void 0:ie.call(me));if(Z||ue||z3()||Ct.getState().wizardOpen)return;Wl.getState().start()}catch{}})(),()=>{Z=!0}},[]),G.useEffect(()=>{let Z=!1;return(async()=>{var me,ie;try{const ue=await((ie=(me=window.api.app).isE2E)==null?void 0:ie.call(me));if(Z)return;if(ue){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const Ce=await window.api.voice.getWizardState();if(Z)return;Ce.completedSchema!==Ce.currentSchema&&(Ct.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:Ce.completedSchema,currentSchema:Ce.currentSchema}))}catch(ue){pt.warn("voice-wizard","auto-arm failed",{error:ue instanceof Error?ue.message:String(ue)})}})(),()=>{Z=!0}},[]),t===!0?h.jsx(U3,{}):h.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${$?"pt-7":""}`,children:[h.jsx(ok,{}),h.jsx(NE,{}),h.jsxs("div",{className:"flex-1 flex min-h-0",children:[h.jsx(D2,{active:i,onNavigate:y,onNewSession:de}),h.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&p&&h.jsx(B2,{onClose:()=>a(!1),onSent:Z=>{a(!1),m(`Sent to ${Z} tab${Z===1?"":"s"}`)}}),i==="terminal"&&C&&d&&h.jsx("div",{className:"absolute top-12 right-4 z-30",children:h.jsx(G2,{tabId:C.id,cwd:C.cwd,onClose:()=>f(!1)})}),h.jsx("div",{className:"flex-1 min-h-0 relative",children:h.jsx(M3,{onNavigate:y,onNewSession:de,onOpenVoice:D,onOpenScheduler:E})}),v&&h.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:v})]})]}),h.jsx(M2,{onNavigate:y}),h.jsx(L3,{open:P,onClose:N}),h.jsx(q3,{}),h.jsx(lk,{}),h.jsx(H3,{open:r,onClose:()=>l(!1),onCommand:Z=>{if(l(!1),Z.id.startsWith("nav:")){y(Z.id.slice(4));return}const me=xt.getState().tabs.find(ie=>ie.id===xt.getState().activeTabId)??null;switch(Z.id){case"new-tab-pick":e1().catch(ie=>{console.error("[App] new tab (pick) failed:",ie),lt.error("Could not start new session. The directory picker failed.")});return;case"new-tab-here":{if(!me)return;xt.getState().addTab({cwd:me.cwd,startupCommand:null,dormant:!0}),Ei.getState().openProjectPanel("terminal");return}case"close-tab":me&&xt.getState().closeTab(me.id);return;case"restart-session":L();return;case"broadcast":j();return;case"watchers":H();return;case"copy-cwd":me&&window.api.clipboard.writeText(me.cwd).catch(()=>lt.error("Copy failed"));return;case"copy-transcript":me&&window.api.transcripts.pathFor(me.cwd,me.sessionId).then(ie=>window.api.clipboard.writeText(ie)).catch(()=>lt.error("Copy failed"));return;case"open-transcript":me&&window.api.transcripts.pathFor(me.cwd,me.sessionId).then(ie=>window.api.shell.open({as:"openPath",path:ie})).catch(()=>lt.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const cL=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","teams","plugins","clipboard","memory"];function dL(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,t=[];for(const n of cL){const r=e[n];r==null?t.push({kind:"namespace-missing",name:n}):typeof r!="object"&&t.push({kind:"namespace-not-object",name:n,actualType:typeof r})}return t}function n1(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function uL(){const i=dL(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",n1(e));return setTimeout(()=>{os(async()=>{const{toast:e}=await Promise.resolve().then(()=>u1);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const t=i.length===1?n1(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(t)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");uL();Dk.createRoot(document.getElementById("root")).render(h.jsx(lL,{}));export{h as $,TN as A,DO as B,D_ as C,yL as D,hR as E,KN as F,Nr as G,el as H,yM as I,AL as J,vL as K,jj as L,pb as M,iA as N,bL as O,DL as P,OS as Q,jk as R,$L as S,Dv as T,_L as U,yf as V,nA as W,jb as X,qa as Y,Cn as Z,VS as _,rs as a,Hf as a0,CL as a1,hM as a2,Ub as a3,DS as a4,NC as a5,G as a6,C1 as a7,Nb as a8,mL as a9,yv as aa,AA as ab,TL as ac,EL as ad,Wk as ae,lt as af,LR as ag,di as ah,K3 as ai,$i as aj,Qu as ak,kS as al,hh as am,Ei as an,nw as ao,Yt as ap,fL as aq,jr as ar,PS as as,xt as at,uM as au,gL as av,$O as b,VI as c,xL as d,e0 as e,gb as f,dh as g,wL as h,tC as i,SL as j,Qx as k,ww as l,kL as m,OC as n,cM as o,Rt as p,LD as q,MO as r,$b as s,lM as t,Tj as u,ZR as v,NS as w,xv as x,In as y,IA as z};