claude-code-session-manager 0.122.0 → 0.122.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/assets/{AgentLibrary-BmJ8hIPw.js → AgentLibrary-C2qUX9WU.js} +1 -1
  2. package/dist/assets/{Button-BS4kmz4p.js → Button-ssBzvFha.js} +1 -1
  3. package/dist/assets/{DataModel-DZHBZrfL.js → DataModel-CENoTvc2.js} +1 -1
  4. package/dist/assets/{History-pg00b2Gd.js → History-BRdRp1J_.js} +1 -1
  5. package/dist/assets/{Hooks-BTEs0UZY.js → Hooks--hiGPBQy.js} +1 -1
  6. package/dist/assets/{Library-DuaJ-VSn.js → Library-0XYvkhh2.js} +1 -1
  7. package/dist/assets/{ListDetail-Cud72s-O.js → ListDetail-CkKXAM59.js} +1 -1
  8. package/dist/assets/{McpServers-Dy-wnG_X.js → McpServers-CCjHSwFm.js} +1 -1
  9. package/dist/assets/{Memory-Bs1T1Jo7.js → Memory-C7RXoVO4.js} +1 -1
  10. package/dist/assets/{Panel-8UhLXEOW.js → Panel-C92O_aAH.js} +1 -1
  11. package/dist/assets/{Permissions-BfwzvmBS.js → Permissions-DuTJ1FUb.js} +1 -1
  12. package/dist/assets/{Plugins-McjyvvKh.js → Plugins-DSXsP4hM.js} +2 -2
  13. package/dist/assets/{ProvenanceBadge-D0Ov_6WJ.js → ProvenanceBadge-CWdDkU1m.js} +1 -1
  14. package/dist/assets/{RemoteMachines-gOlFTvWq.js → RemoteMachines-BFmbIGpW.js} +1 -1
  15. package/dist/assets/{SaveBar-Cd6hJR6K.js → SaveBar-ob2dJJjH.js} +1 -1
  16. package/dist/assets/{Scheduler-BZXKqYJP.js → Scheduler-Du4HgPKY.js} +1 -1
  17. package/dist/assets/{ScopeSwitcher-C24ysV1K.js → ScopeSwitcher-Dv_6M_Ci.js} +1 -1
  18. package/dist/assets/{Settings-DWnN2qxn.js → Settings-DMoI0cqB.js} +1 -1
  19. package/dist/assets/{SkillReferenceGraph-BsWuiTbw.js → SkillReferenceGraph-Dx1Qs8Y0.js} +1 -1
  20. package/dist/assets/{Skills-6pHn6glu.js → Skills-DYWQTQB1.js} +1 -1
  21. package/dist/assets/{SystemPrompt-DT0LBH-K.js → SystemPrompt-Df0IfOuI.js} +1 -1
  22. package/dist/assets/{TagLibrary-DbJ0zbYL.js → TagLibrary-BuMsGx-2.js} +1 -1
  23. package/dist/assets/{TiptapBody-C4kIvIMH.js → TiptapBody-Cihe5er3.js} +1 -1
  24. package/dist/assets/{Toggle-pP19zlyk.js → Toggle-CpYVC8bF.js} +1 -1
  25. package/dist/assets/{ViewTabs-CpzN8e5I.js → ViewTabs-C3FN6P_C.js} +1 -1
  26. package/dist/assets/{historyTotals-Caq78bb5.js → historyTotals-C4Rs37Cd.js} +1 -1
  27. package/dist/assets/{index-Bjtguv6I.js → index-S-F5jp_h.js} +3 -3
  28. package/dist/assets/{settingsSchema-CC2ySu3d.js → settingsSchema-BZcdzHTQ.js} +1 -1
  29. package/dist/assets/{skillFrontmatter-hDhNo8jE.js → skillFrontmatter-EfNERt4b.js} +1 -1
  30. package/dist/assets/{useAgentsDirWatch-BuOtY25U.js → useAgentsDirWatch-BfbrFvB3.js} +1 -1
  31. package/dist/assets/{useRemotePeers-CNQmRBpt.js → useRemotePeers-CKVakQPc.js} +1 -1
  32. package/dist/index.html +1 -1
  33. package/package.json +1 -1
  34. package/plugins/session-manager-dev/skills/develop/SKILL.md +1 -0
  35. package/scripts/scheduler-mcp-server.cjs +18 -4
  36. package/src/main/build-info.json +4 -4
  37. package/src/main/lib/mcpToolCatalog.cjs +5 -7
  38. package/src/main/lib/prd/prdCreate.cjs +45 -0
  39. package/src/main/scheduler.cjs +13 -4
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-C4kIvIMH.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./Skills-6pHn6glu.js","./Panel-8UhLXEOW.js","./ListDetail-Cud72s-O.js","./skillFrontmatter-hDhNo8jE.js","./SaveBar-Cd6hJR6K.js","./ScopeSwitcher-C24ysV1K.js","./Toggle-pP19zlyk.js","./ProvenanceBadge-D0Ov_6WJ.js","./Library-DuaJ-VSn.js","./Button-BS4kmz4p.js","./listSkills-C1aWKf0T.js","./History-pg00b2Gd.js","./historyTotals-Caq78bb5.js","./RemoteMachines-gOlFTvWq.js","./useRemotePeers-CNQmRBpt.js","./Scheduler-BZXKqYJP.js","./Settings-DWnN2qxn.js","./settingsSchema-CC2ySu3d.js","./claude-settings-schema-COigsajx.js","./ViewTabs-CpzN8e5I.js","./Permissions-BfwzvmBS.js","./SystemPrompt-DT0LBH-K.js","./Memory-Bs1T1Jo7.js","./Plugins-McjyvvKh.js","./McpServers-Dy-wnG_X.js","./Hooks-BTEs0UZY.js","./AgentLibrary-BmJ8hIPw.js","./useAgentsDirWatch-BuOtY25U.js","./TagLibrary-DbJ0zbYL.js","./DataModel-DZHBZrfL.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-Cihe5er3.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./Skills-DYWQTQB1.js","./Panel-C92O_aAH.js","./ListDetail-CkKXAM59.js","./skillFrontmatter-EfNERt4b.js","./SaveBar-ob2dJJjH.js","./ScopeSwitcher-Dv_6M_Ci.js","./Toggle-CpYVC8bF.js","./ProvenanceBadge-CWdDkU1m.js","./Library-0XYvkhh2.js","./Button-ssBzvFha.js","./listSkills-C1aWKf0T.js","./History-BRdRp1J_.js","./historyTotals-C4Rs37Cd.js","./RemoteMachines-BFmbIGpW.js","./useRemotePeers-CKVakQPc.js","./Scheduler-Du4HgPKY.js","./Settings-DMoI0cqB.js","./settingsSchema-BZcdzHTQ.js","./claude-settings-schema-COigsajx.js","./ViewTabs-C3FN6P_C.js","./Permissions-DuTJ1FUb.js","./SystemPrompt-Df0IfOuI.js","./Memory-C7RXoVO4.js","./Plugins-DSXsP4hM.js","./McpServers-CCjHSwFm.js","./Hooks--hiGPBQy.js","./AgentLibrary-C2qUX9WU.js","./useAgentsDirWatch-BfbrFvB3.js","./TagLibrary-BuMsGx-2.js","./DataModel-CENoTvc2.js"])))=>i.map(i=>d[i]);
2
2
  var TT=Object.defineProperty;var DT=(i,e,t)=>e in i?TT(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Gi=(i,e,t)=>DT(i,typeof e!="symbol"?e+"":e,t);import{_ as mi}from"./monaco-editor-BsIlgG7c.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const l of s)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(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?l.credentials="include":s.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(s){if(s.ep)return;s.ep=!0;const l=t(s);fetch(s.href,l)}})();function Nw(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var b_={exports:{}},cf={},w_={exports:{}},wi={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -2927,7 +2927,7 @@ ${I}`,M=v.createShaderModule({code:P,label:r.name});li("verbose",()=>`[WebGPU] $
2927
2927
  * Licensed under the MIT License.
2928
2928
  */var Fx;function ED(){return Fx||(Fx=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof lo<"u"?lo:typeof Proxy<"u"?new Proxy(Y,{get:(re,pe)=>(typeof lo<"u"?lo:re)[pe]}):Y)(function(Y){if(typeof lo<"u")return lo.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),c=(Y,re)=>()=>(Y&&(re=Y(Y=0)),re),f=(Y,re)=>{for(var pe in re)n(Y,pe,{get:re[pe],enumerable:!0})},m=(Y,re,pe,Te)=>{if(re&&typeof re=="object"||typeof re=="function")for(let ye of l(re))!p.call(Y,ye)&&ye!==pe&&n(Y,ye,{get:()=>re[ye],enumerable:!(Te=s(re,ye))||Te.enumerable});return Y},g=Y=>m(n({},"__esModule",{value:!0}),Y),w,D,k,C,b,y=c(()=>{w=new Map,D=[],k=(Y,re,pe)=>{if(re&&typeof re.init=="function"&&typeof re.createInferenceSessionHandler=="function"){let Te=w.get(Y);if(Te===void 0)w.set(Y,{backend:re,priority:pe});else{if(Te.priority>pe)return;if(Te.priority===pe&&Te.backend!==re)throw new Error(`cannot register backend "${Y}" using priority ${pe}`)}if(pe>=0){let ye=D.indexOf(Y);ye!==-1&&D.splice(ye,1);for(let ze=0;ze<D.length;ze++)if(w.get(D[ze]).priority<=pe){D.splice(ze,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},C=async Y=>{let re=w.get(Y);if(!re)return"backend not found.";if(re.initialized)return re.backend;if(re.aborted)return re.error;{let pe=!!re.initPromise;try{return pe||(re.initPromise=re.backend.init(Y)),await re.initPromise,re.initialized=!0,re.backend}catch(Te){return pe||(re.error=`${Te}`,re.aborted=!0),re.error}finally{delete re.initPromise}}},b=async Y=>{let re=Y.executionProviders||[],pe=re.map(Be=>typeof Be=="string"?Be:Be.name),Te=pe.length===0?D:pe,ye,ze=[],$e=new Set;for(let Be of Te){let it=await C(Be);typeof it=="string"?ze.push({name:Be,err:it}):(ye||(ye=it),ye===it&&$e.add(Be))}if(!ye)throw new Error(`no available backend found. ERR: ${ze.map(Be=>`[${Be.name}] ${Be.err}`).join(", ")}`);for(let{name:Be,err:it}of ze)pe.includes(Be)&&console.warn(`removing requested execution provider "${Be}" from session options because it is not available: ${it}`);let Ae=re.filter(Be=>$e.has(typeof Be=="string"?Be:Be.name));return[ye,new Proxy(Y,{get:(Be,it)=>it==="executionProviders"?Ae:Reflect.get(Be,it)})]}}),x=c(()=>{y()}),S,T=c(()=>{S="1.26.0"}),j,N,L=c(()=>{T(),j="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:S},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}`);j=Y}},get logLevel(){return j}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),R,F=c(()=>{L(),R=N}),V,te,he=c(()=>{V=(Y,re)=>{let pe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);pe.width=Y.dims[3],pe.height=Y.dims[2];let Te=pe.getContext("2d");if(Te!=null){let ye,ze;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(ye=Y.dims[2],ze=Y.dims[3]):(ye=Y.dims[3],ze=Y.dims[2]);let $e=(re==null?void 0:re.format)!==void 0?re.format:"RGB",Ae=re==null?void 0:re.norm,Be,it;Ae===void 0||Ae.mean===void 0?Be=[255,255,255,255]:typeof Ae.mean=="number"?Be=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Be=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Be[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?it=[0,0,0,0]:typeof Ae.bias=="number"?it=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(it=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(it[3]=Ae.bias[3]));let ot=ze*ye,nt=0,Ke=ot,jt=ot*2,Le=-1;$e==="RGBA"?(nt=0,Ke=ot,jt=ot*2,Le=ot*3):$e==="RGB"?(nt=0,Ke=ot,jt=ot*2):$e==="RBG"&&(nt=0,jt=ot,Ke=ot*2);for(let dt=0;dt<ze;dt++)for(let Ii=0;Ii<ye;Ii++){let ei=(Y.data[nt++]-it[0])*Be[0],ti=(Y.data[Ke++]-it[1])*Be[1],Pi=(Y.data[jt++]-it[2])*Be[2],zt=Le===-1?255:(Y.data[Le++]-it[3])*Be[3];Te.fillStyle="rgba("+ei+","+ti+","+Pi+","+zt+")",Te.fillRect(Ii,dt,1,1)}if("toDataURL"in pe)return pe.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},te=(Y,re)=>{let pe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(pe!=null){let ye,ze,$e;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(ye=Y.dims[2],ze=Y.dims[1],$e=Y.dims[3]):(ye=Y.dims[3],ze=Y.dims[2],$e=Y.dims[1]);let Ae=re!==void 0&&re.format!==void 0?re.format:"RGB",Be=re==null?void 0:re.norm,it,ot;Be===void 0||Be.mean===void 0?it=[255,255,255,255]:typeof Be.mean=="number"?it=[Be.mean,Be.mean,Be.mean,Be.mean]:(it=[Be.mean[0],Be.mean[1],Be.mean[2],255],Be.mean[3]!==void 0&&(it[3]=Be.mean[3])),Be===void 0||Be.bias===void 0?ot=[0,0,0,0]:typeof Be.bias=="number"?ot=[Be.bias,Be.bias,Be.bias,Be.bias]:(ot=[Be.bias[0],Be.bias[1],Be.bias[2],0],Be.bias[3]!==void 0&&(ot[3]=Be.bias[3]));let nt=ze*ye;if(re!==void 0&&(re.format!==void 0&&$e===4&&re.format!=="RGBA"||$e===3&&re.format!=="RGB"&&re.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ke=4,jt=0,Le=1,dt=2,Ii=3,ei=0,ti=nt,Pi=nt*2,zt=-1;Ae==="RGBA"?(ei=0,ti=nt,Pi=nt*2,zt=nt*3):Ae==="RGB"?(ei=0,ti=nt,Pi=nt*2):Ae==="RBG"&&(ei=0,Pi=nt,ti=nt*2),Te=pe.createImageData(ye,ze);for(let Fi=0;Fi<ze*ye;jt+=Ke,Le+=Ke,dt+=Ke,Ii+=Ke,Fi++)Te.data[jt]=(Y.data[ei++]-ot[0])*it[0],Te.data[Le]=(Y.data[ti++]-ot[1])*it[1],Te.data[dt]=(Y.data[Pi++]-ot[2])*it[2],Te.data[Ii]=zt===-1?255:(Y.data[zt++]-ot[3])*it[3]}else throw new Error("Can not access image data");return Te}}),ee,we,ce,ve,Ee,fe,U=c(()=>{je(),ee=(Y,re)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(re.height===void 0||re.width===void 0)throw new Error("Image height and width must be defined");if(re.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:pe,width:Te}=re,ye=re.norm??{mean:255,bias:0},ze,$e;typeof ye.mean=="number"?ze=[ye.mean,ye.mean,ye.mean,ye.mean]:ze=[ye.mean[0],ye.mean[1],ye.mean[2],ye.mean[3]??255],typeof ye.bias=="number"?$e=[ye.bias,ye.bias,ye.bias,ye.bias]:$e=[ye.bias[0],ye.bias[1],ye.bias[2],ye.bias[3]??0];let Ae=re.format!==void 0?re.format:"RGBA",Be=re.tensorFormat!==void 0&&re.tensorFormat!==void 0?re.tensorFormat:"RGB",it=pe*Te,ot=Be==="RGBA"?new Float32Array(it*4):new Float32Array(it*3),nt=4,Ke=0,jt=1,Le=2,dt=3,Ii=0,ei=it,ti=it*2,Pi=-1;Ae==="RGB"&&(nt=3,Ke=0,jt=1,Le=2,dt=-1),Be==="RGBA"?Pi=it*3:Be==="RBG"?(Ii=0,ti=it,ei=it*2):Be==="BGR"&&(ti=0,ei=it,Ii=it*2);for(let zt=0;zt<it;zt++,Ke+=nt,Le+=nt,jt+=nt,dt+=nt)ot[Ii++]=(Y[Ke]+$e[0])/ze[0],ot[ei++]=(Y[jt]+$e[1])/ze[1],ot[ti++]=(Y[Le]+$e[2])/ze[2],Pi!==-1&&dt!==-1&&(ot[Pi++]=(Y[dt]+$e[3])/ze[3]);return Be==="RGBA"?new J("float32",ot,[1,4,pe,Te]):new J("float32",ot,[1,3,pe,Te])},we=async(Y,re)=>{let pe=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,ye=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,ze=typeof Y=="string",$e,Ae=re??{},Be=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},it=ot=>typeof HTMLCanvasElement<"u"&&ot instanceof HTMLCanvasElement||ot instanceof OffscreenCanvas?ot.getContext("2d"):null;if(pe){let ot=Be();ot.width=Y.width,ot.height=Y.height;let nt=it(ot);if(nt!=null){let Ke=Y.height,jt=Y.width;if(re!==void 0&&re.resizedHeight!==void 0&&re.resizedWidth!==void 0&&(Ke=re.resizedHeight,jt=re.resizedWidth),re!==void 0){if(Ae=re,re.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=Ke,Ae.width=jt}else Ae.tensorFormat="RGBA",Ae.height=Ke,Ae.width=jt;nt.drawImage(Y,0,0),$e=nt.getImageData(0,0,jt,Ke).data}else throw new Error("Can not access image data")}else if(Te){let ot,nt;if(re!==void 0&&re.resizedWidth!==void 0&&re.resizedHeight!==void 0?(ot=re.resizedHeight,nt=re.resizedWidth):(ot=Y.height,nt=Y.width),re!==void 0&&(Ae=re),Ae.format="RGBA",Ae.height=ot,Ae.width=nt,re!==void 0){let Ke=Be();Ke.width=nt,Ke.height=ot;let jt=it(Ke);if(jt!=null)jt.putImageData(Y,0,0),$e=jt.getImageData(0,0,nt,ot).data;else throw new Error("Can not access image data")}else $e=Y.data}else if(ye){if(re===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ot=Be();ot.width=Y.width,ot.height=Y.height;let nt=it(ot);if(nt!=null){let Ke=Y.height,jt=Y.width;return nt.drawImage(Y,0,0,jt,Ke),$e=nt.getImageData(0,0,jt,Ke).data,Ae.height=Ke,Ae.width=jt,ee($e,Ae)}else throw new Error("Can not access image data")}else{if(ze)return new Promise((ot,nt)=>{let Ke=Be(),jt=it(Ke);if(!Y||!jt)return nt();let Le=new Image;Le.crossOrigin="Anonymous",Le.src=Y,Le.onload=()=>{Ke.width=Le.width,Ke.height=Le.height,jt.drawImage(Le,0,0,Ke.width,Ke.height);let dt=jt.getImageData(0,0,Ke.width,Ke.height);Ae.height=Ke.height,Ae.width=Ke.width,ot(ee(dt.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return ee($e,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(Y,re)=>{let{width:pe,height:Te,download:ye,dispose:ze}=re,$e=[1,Te,pe,4];return new J({location:"texture",type:"float32",texture:Y,dims:$e,download:ye,dispose:ze})},ve=(Y,re)=>{let{dataType:pe,dims:Te,download:ye,dispose:ze}=re;return new J({location:"gpu-buffer",type:pe??"float32",gpuBuffer:Y,dims:Te,download:ye,dispose:ze})},Ee=(Y,re)=>{let{dataType:pe,dims:Te,download:ye,dispose:ze}=re;return new J({location:"ml-tensor",type:pe??"float32",mlTensor:Y,dims:Te,download:ye,dispose:ze})},fe=(Y,re,pe)=>new J({location:"cpu-pinned",type:Y,data:re,dims:pe??[re.length]})}),X,W,Q,oe,Ce=c(()=>{X=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),W=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Q=!1,oe=()=>{if(!Q){Q=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,re=typeof BigUint64Array<"u"&&BigUint64Array.from,pe=globalThis.Float16Array,Te=typeof pe<"u"&&pe.from;Y&&(X.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),re&&(X.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),Te?(X.set("float16",pe),W.set(pe,"float16")):X.set("float16",Uint16Array)}}}),Oe,Xe,ge=c(()=>{je(),Oe=Y=>{let re=1;for(let pe=0;pe<Y.length;pe++){let Te=Y[pe];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${pe}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${pe}] must be a non-negative integer, got: ${Te}`);re*=Te}return re},Xe=(Y,re)=>{switch(Y.location){case"cpu":return new J(Y.type,Y.data,re);case"cpu-pinned":return new J({location:"cpu-pinned",data:Y.data,type:Y.type,dims:re});case"texture":return new J({location:"texture",texture:Y.texture,type:Y.type,dims:re});case"gpu-buffer":return new J({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:re});case"ml-tensor":return new J({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:re});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),J,je=c(()=>{he(),U(),Ce(),ge(),J=class{constructor(Y,re,pe){oe();let Te,ye;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,ye=Y.dims,Y.location){case"cpu-pinned":{let $e=X.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=pe,Y==="string"){if(!Array.isArray(re))throw new TypeError("A string tensor's data must be a string array.");$e=re}else{let Be=X.get(Y);if(Be===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(re)){if(Y==="float16"&&Be===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Be.name} as data.`);Y==="uint64"||Y==="int64"?$e=Be.from(re,BigInt):$e=Be.from(re)}else if(re instanceof Be)$e=re;else if(re instanceof Uint8ClampedArray)if(Y==="uint8")$e=Uint8Array.from(re);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&re instanceof Uint16Array&&Be!==Uint16Array)$e=new globalThis.Float16Array(re.buffer,re.byteOffset,re.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Be}`)}else if(Ae=re,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Be=typeof Y[0];if(Be==="string")Te="string",$e=Y;else if(Be==="boolean")Te="bool",$e=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Be}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",$e=Uint8Array.from(Y);else{let Be=W.get(Y.constructor);if(Be===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Be,$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");ye=Ae,this.cpuData=$e,this.dataLocation="cpu"}let ze=Oe(ye);if(this.cpuData&&ze!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(ze/2)===this.cpuData.length))throw new Error(`Tensor's size(${ze}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=ye,this.size=ze}static async fromImage(Y,re){return we(Y,re)}static fromTexture(Y,re){return ce(Y,re)}static fromGpuBuffer(Y,re){return ve(Y,re)}static fromMLTensor(Y,re){return Ee(Y,re)}static fromPinnedBuffer(Y,re,pe){return fe(Y,re,pe)}toDataURL(Y){return V(this,Y)}toImageData(Y){return te(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 re=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=re,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),re}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 Xe(this,Y)}}}),de,Ie=c(()=>{je(),de=J}),Pe,Ye,ft,rt,Nt,mt,gi=c(()=>{L(),Pe=(Y,re)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${re}`)},Ye=(Y,re)=>{var ye;let pe=((ye=new Error().stack)==null?void 0:ye.split(/\r\n|\r|\n/g))||[],Te=!1;for(let ze=0;ze<pe.length;ze++){if(Te&&!pe[ze].includes("TRACE_FUNC")){let $e=`FUNC_${Y}::${pe[ze].trim().split(" ")[1]}`;re&&($e+=`::${re}`),Pe("CPU",$e);return}pe[ze].includes("TRACE_FUNC")&&(Te=!0)}},ft=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("BEGIN",Y)},rt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ye("END",Y)},Nt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},mt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),di,_i=c(()=>{y(),Ie(),gi(),di=class EC{constructor(re){this.handler=re}async run(re,pe,Te){ft(),Nt("InferenceSession.run");let ye={},ze={};if(typeof re!="object"||re===null||re instanceof de||Array.isArray(re))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof pe=="object"){if(pe===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(pe instanceof de)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(pe)){if(pe.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let it of pe){if(typeof it!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(it)===-1)throw new RangeError(`'fetches' contains invalid output name: ${it}.`);ye[it]=null}if(typeof Te=="object"&&Te!==null)ze=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let it=!1,ot=Object.getOwnPropertyNames(pe);for(let nt of this.outputNames)if(ot.indexOf(nt)!==-1){let Ke=pe[nt];(Ke===null||Ke instanceof de)&&(it=!0,$e=!1,ye[nt]=Ke)}if(it){if(typeof Te=="object"&&Te!==null)ze=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else ze=pe}}else if(typeof pe<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let it of this.inputNames)if(typeof re[it]>"u")throw new Error(`input '${it}' is missing in 'feeds'.`);if($e)for(let it of this.outputNames)ye[it]=null;let Ae=await this.handler.run(re,ye,ze),Be={};for(let it in Ae)if(Object.hasOwnProperty.call(Ae,it)){let ot=Ae[it];ot instanceof de?Be[it]=ot:Be[it]=new de(ot.type,ot.data,ot.dims)}return mt("InferenceSession.run"),rt(),Be}async release(){return this.handler.dispose()}static async create(re,pe,Te,ye){ft(),Nt("InferenceSession.create");let ze,$e={};if(typeof re=="string"){if(ze=re,typeof pe=="object"&&pe!==null)$e=pe;else if(typeof pe<"u")throw new TypeError("'options' must be an object.")}else if(re instanceof Uint8Array){if(ze=re,typeof pe=="object"&&pe!==null)$e=pe;else if(typeof pe<"u")throw new TypeError("'options' must be an object.")}else if(re instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&re instanceof SharedArrayBuffer){let ot=re,nt=0,Ke=re.byteLength;if(typeof pe=="object"&&pe!==null)$e=pe;else if(typeof pe=="number"){if(nt=pe,!Number.isSafeInteger(nt))throw new RangeError("'byteOffset' must be an integer.");if(nt<0||nt>=ot.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ot.byteLength}).`);if(Ke=re.byteLength-nt,typeof Te=="number"){if(Ke=Te,!Number.isSafeInteger(Ke))throw new RangeError("'byteLength' must be an integer.");if(Ke<=0||nt+Ke>ot.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ot.byteLength-nt}].`);if(typeof ye=="object"&&ye!==null)$e=ye;else if(typeof ye<"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 pe<"u")throw new TypeError("'options' must be an object.");ze=new Uint8Array(ot,nt,Ke)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Be]=await b($e),it=await Ae.createInferenceSessionHandler(ze,Be);return mt("InferenceSession.create"),rt(),new EC(it)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Je,Pt=c(()=>{_i(),Je=di}),_t=c(()=>{}),hi=c(()=>{}),Se=c(()=>{}),tt=c(()=>{}),ht={};f(ht,{InferenceSession:()=>Je,TRACE:()=>Pe,TRACE_EVENT_BEGIN:()=>Nt,TRACE_EVENT_END:()=>mt,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>rt,Tensor:()=>de,env:()=>R,registerBackend:()=>k});var Et=c(()=>{x(),F(),Pt(),Ie(),_t(),hi(),gi(),Se(),tt()}),vi=c(()=>{}),Jt={};f(Jt,{default:()=>un});var oi,Xt,un,wt=c(()=>{var Y;me(),Qn(),Zn(),oi="ort-wasm-proxy-worker",Xt=((Y=globalThis.self)==null?void 0:Y.name)===oi,Xt&&(self.onmessage=re=>{let{type:pe,in:Te}=re.data;try{switch(pe){case"init-wasm":ar(Te.wasm).then(()=>{Ko(Te).then(()=>{postMessage({type:pe})},ye=>{postMessage({type:pe,err:ye})})},ye=>{postMessage({type:pe,err:ye})});break;case"init-ep":{let{epName:ye,env:ze}=Te;Ir(ze,ye).then(()=>{postMessage({type:pe})},$e=>{postMessage({type:pe,err:$e})});break}case"copy-from":{let{buffer:ye}=Te,ze=li(ye);postMessage({type:pe,out:ze});break}case"create":{let{model:ye,options:ze}=Te;_s(ye,ze).then($e=>{postMessage({type:pe,out:$e})},$e=>{postMessage({type:pe,err:$e})});break}case"release":Kr(Te),postMessage({type:pe});break;case"run":{let{sessionId:ye,inputIndices:ze,inputs:$e,outputIndices:Ae,options:Be}=Te;qe(ye,ze,$e,Ae,new Array(Ae.length).fill(null),Be).then(it=>{it.some(ot=>ot[3]!=="cpu")?postMessage({type:pe,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:pe,out:it},gt([...$e,...it]))},it=>{postMessage({type:pe,err:it})});break}case"end-profiling":ts(Te),postMessage({type:pe});break;default:}}catch(ye){postMessage({type:pe,err:ye})}}),un=Xt?null:re=>new Worker(re??ai,{type:"classic",name:oi})}),Ri,Sn,ai,Ni,zi,fs,Rn,Nn,nr,Tr,Dr,Hs,Hn,Zn=c(()=>{vi(),Ri=typeof location>"u"?void 0:location.origin,Sn=()=>{var Y,re;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(re=self.location)==null?void 0:re.href:void 0},ai=Sn(),Ni=()=>{if(ai&&!ai.startsWith("blob:"))return ai.substring(0,ai.lastIndexOf("/")+1)},zi=(Y,re)=>{try{let pe=re??ai;return(pe?new URL(Y,pe):new URL(Y)).origin===Ri}catch{return!1}},fs=(Y,re)=>{let pe=re??ai;try{return(pe?new URL(Y,pe):new URL(Y)).href}catch{return}},Rn=(Y,re)=>`${re??"./"}${Y}`,Nn=async Y=>{let re=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(re)},nr=async Y=>(await import(Y)).default,Tr=(wt(),g(Jt)).default,Dr=async()=>{if(!ai)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zi(ai))return[void 0,Tr()];let Y=await Nn(ai);return[Y,Tr(Y)]},Hs=void 0,Hn=async(Y,re,pe,Te)=>{let ye=Hs&&!(Y||re);if(ye)if(ai)ye=zi(ai)||Te&&!pe;else if(Te&&!pe)ye=!0;else throw new Error("cannot determine the script source URL.");if(ye)return[void 0,Hs];{let ze="ort-wasm-simd-threaded.mjs",$e=Y??fs(ze,re),Ae=pe&&$e&&!zi($e,re),Be=Ae?await Nn($e):$e??Rn(ze,re);return[Ae?Be:void 0,await nr(Be)]}}}),sr,Wn,ms,Ns,ho,rr,or,ar,Gt,Qn=c(()=>{Zn(),Wn=!1,ms=!1,Ns=!1,ho=()=>{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}},rr=()=>{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}},or=()=>{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}},ar=async Y=>{if(Wn)return Promise.resolve();if(ms)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Ns)throw new Error("previous call to 'initializeWebAssembly()' failed.");ms=!0;let re=Y.initTimeout,pe=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!or())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!rr())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ho();pe>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+pe+", 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=pe=1);let ye=Y.wasmPaths,ze=typeof ye=="string"?ye:void 0,$e=ye==null?void 0:ye.mjs,Ae=($e==null?void 0:$e.href)??$e,Be=ye==null?void 0:ye.wasm,it=(Be==null?void 0:Be.href)??Be,ot=Y.wasmBinary,[nt,Ke]=await Hn(Ae,ze,pe>1,!!ot||!!it),jt=!1,Le=[];if(re>0&&Le.push(new Promise(dt=>{setTimeout(()=>{jt=!0,dt()},re)})),Le.push(new Promise((dt,Ii)=>{let ei={numThreads:pe};if(ot)ei.wasmBinary=ot,ei.locateFile=ti=>ti;else if(it||ze)ei.locateFile=ti=>it??ze+ti;else if(Ae&&Ae.indexOf("blob:")!==0)ei.locateFile=ti=>new URL(ti,Ae).href;else if(nt){let ti=Ni();ti&&(ei.locateFile=Pi=>ti+Pi)}Ke(ei).then(ti=>{ms=!1,Wn=!0,sr=ti,dt(),nt&&URL.revokeObjectURL(nt)},ti=>{ms=!1,Ns=!0,Ii(ti)})})),await Promise.race(Le),jt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${re}ms`)},Gt=()=>{if(Wn&&sr)return sr;throw new Error("WebAssembly is not initialized yet.")}}),Xi,Di,Tt,Vr=c(()=>{Qn(),Xi=(Y,re)=>{let pe=Gt(),Te=pe.lengthBytesUTF8(Y)+1,ye=pe._malloc(Te);return pe.stringToUTF8(Y,ye,Te),re.push(ye),ye},Di=(Y,re,pe,Te)=>{if(typeof Y=="object"&&Y!==null){if(pe.has(Y))throw new Error("Circular reference in options");pe.add(Y)}Object.entries(Y).forEach(([ye,ze])=>{let $e=re?re+ye:ye;if(typeof ze=="object")Di(ze,$e+".",pe,Te);else if(typeof ze=="string"||typeof ze=="number")Te($e,ze.toString());else if(typeof ze=="boolean")Te($e,ze?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof ze}`)})},Tt=Y=>{let re=Gt(),pe=re.stackSave();try{let Te=re.PTR_SIZE,ye=re.stackAlloc(2*Te);re._OrtGetLastError(ye,ye+Te);let ze=Number(re.getValue(ye,Te===4?"i32":"i64")),$e=re.getValue(ye+Te,"*"),Ae=$e?re.UTF8ToString($e):"";throw new Error(`${Y} ERROR_CODE: ${ze}, ERROR_MESSAGE: ${Ae}`)}finally{re.stackRestore(pe)}}}),po,Ta=c(()=>{Qn(),Vr(),po=Y=>{let re=Gt(),pe=0,Te=[],ye=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)ye.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)ye.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(ye.terminate=!1);let ze=0;return(Y==null?void 0:Y.tag)!==void 0&&(ze=Xi(Y.tag,Te)),pe=re._OrtCreateRunOptions(ye.logSeverityLevel,ye.logVerbosityLevel,!!ye.terminate,ze),pe===0&&Tt("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&Di(Y.extra,"",new WeakSet,($e,Ae)=>{let Be=Xi($e,Te),it=Xi(Ae,Te);re._OrtAddRunConfigEntry(pe,Be,it)!==0&&Tt(`Can't set a run config entry: ${$e} - ${Ae}.`)}),[pe,Te]}catch(ze){throw pe!==0&&re._OrtReleaseRunOptions(pe),Te.forEach($e=>re._free($e)),ze}}}),fo,mo,qo,Mn,Da,$a,$i=c(()=>{Qn(),Vr(),fo=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}`)}},mo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},qo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let re=Y.extra.session;re.use_ort_model_bytes_directly||(re.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(pe=>(typeof pe=="string"?pe:pe.name)==="webgpu")&&(Y.enableMemPattern=!1)},Mn=(Y,re,pe,Te)=>{let ye=Xi(re,Te),ze=Xi(pe,Te);Gt()._OrtAddSessionConfigEntry(Y,ye,ze)!==0&&Tt(`Can't set a session config entry: ${re} - ${pe}.`)},Da=async(Y,re,pe)=>{let Te=re.executionProviders;for(let ye of Te){let ze=typeof ye=="string"?ye:ye.name,$e=[];switch(ze){case"webnn":if(ze="WEBNN",Mn(Y,"session.disable_quant_qdq","1",pe),Mn(Y,"session.disable_qdq_constant_folding","1",pe),typeof ye!="string"){let nt=ye==null?void 0:ye.deviceType;nt&&Mn(Y,"deviceType",nt,pe)}break;case"webgpu":if(ze="JS",typeof ye!="string"){let nt=ye;if(nt!=null&&nt.preferredLayout){if(nt.preferredLayout!=="NCHW"&&nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${nt.preferredLayout}`);Mn(Y,"preferredLayout",nt.preferredLayout,pe)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${ze}`)}let Ae=Xi(ze,pe),Be=$e.length,it=0,ot=0;if(Be>0){it=Gt()._malloc(Be*Gt().PTR_SIZE),pe.push(it),ot=Gt()._malloc(Be*Gt().PTR_SIZE),pe.push(ot);for(let nt=0;nt<Be;nt++)Gt().setValue(it+nt*Gt().PTR_SIZE,$e[nt][0],"*"),Gt().setValue(ot+nt*Gt().PTR_SIZE,$e[nt][1],"*")}await Gt()._OrtAppendExecutionProvider(Y,Ae,it,ot,Be)!==0&&Tt(`Can't append execution provider: ${ze}.`)}},$a=async Y=>{let re=Gt(),pe=0,Te=[],ye=Y||{};qo(ye);try{let ze=fo(ye.graphOptimizationLevel??"all"),$e=mo(ye.executionMode??"sequential"),Ae=typeof ye.logId=="string"?Xi(ye.logId,Te):0,Be=ye.logSeverityLevel??2;if(!Number.isInteger(Be)||Be<0||Be>4)throw new Error(`log severity level is not valid: ${Be}`);let it=ye.logVerbosityLevel??0;if(!Number.isInteger(it)||it<0||it>4)throw new Error(`log verbosity level is not valid: ${it}`);let ot=typeof ye.optimizedModelFilePath=="string"?Xi(ye.optimizedModelFilePath,Te):0;if(pe=re._OrtCreateSessionOptions(ze,!!ye.enableCpuMemArena,!!ye.enableMemPattern,$e,!!ye.enableProfiling,0,Ae,Be,it,ot),pe===0&&Tt("Can't create session options."),ye.executionProviders&&await Da(pe,ye,Te),ye.enableGraphCapture!==void 0){if(typeof ye.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ye.enableGraphCapture}`);Mn(pe,"enableGraphCapture",ye.enableGraphCapture.toString(),Te)}if(ye.freeDimensionOverrides)for(let[nt,Ke]of Object.entries(ye.freeDimensionOverrides)){if(typeof nt!="string")throw new Error(`free dimension override name must be a string: ${nt}`);if(typeof Ke!="number"||!Number.isInteger(Ke)||Ke<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ke}`);let jt=Xi(nt,Te);re._OrtAddFreeDimensionOverride(pe,jt,Ke)!==0&&Tt(`Can't set a free dimension override: ${nt} - ${Ke}.`)}return ye.extra!==void 0&&Di(ye.extra,"",new WeakSet,(nt,Ke)=>{Mn(pe,nt,Ke,Te)}),[pe,Te]}catch(ze){throw pe!==0&&re._OrtReleaseSessionOptions(pe)!==0&&Tt("Can't release session options."),Te.forEach($e=>re._free($e)),ze}}}),Un,Zi,Vn,lr,qr,$r,gs,Cn,Ft=c(()=>{Un=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}`)}},Zi=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}`)}},Vn=(Y,re)=>{let pe=[-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 re=="number"?re:re.reduce((ye,ze)=>ye*ze,1);return pe>0?Math.ceil(Te*pe):void 0},lr=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}`)}},qr=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",gs=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",Cn=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,Ar=c(()=>{vi(),Qi=async Y=>{if(typeof Y=="string"){let re=await fetch(Y);if(!re.ok)throw new Error(`failed to load external data file: ${Y}`);let pe=re.headers.get("Content-Length"),Te=pe?parseInt(pe,10):0;if(Te<1073741824)return new Uint8Array(await re.arrayBuffer());{if(!re.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let ye=re.body.getReader(),ze;try{ze=new ArrayBuffer(Te)}catch(Ae){if(Ae instanceof RangeError){let Be=Math.ceil(Te/65536);ze=new WebAssembly.Memory({initial:Be,maximum:Be}).buffer}else throw Ae}let $e=0;for(;;){let{done:Ae,value:Be}=await ye.read();if(Ae)break;let it=Be.byteLength;new Uint8Array(ze,$e,it).set(Be),$e+=it}return new Uint8Array(ze,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),vs,Ko,Ir,es,Ws,Pr,li,_s,Kr,Ms,qe,ts,gt,me=c(()=>{Et(),Ta(),$i(),Ft(),Qn(),Vr(),Ar(),vs=(Y,re)=>{Gt()._OrtInit(Y,re)!==0&&Tt("Can't initialize onnxruntime.")},Ko=async Y=>{vs(Y.wasm.numThreads,qr(Y.logLevel))},Ir=async(Y,re)=>{var Te,ye;(ye=(Te=Gt()).asyncInit)==null||ye.call(Te);let pe=Y.webgpu.adapter;if(re==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(pe){if(typeof pe.limits!="object"||typeof pe.features!="object"||typeof pe.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let ze=Y.webgpu.powerPreference;if(ze!==void 0&&ze!=="low-power"&&ze!=="high-performance")throw new Error(`Invalid powerPreference setting: "${ze}"`);let $e=Y.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(pe=await navigator.gpu.requestAdapter({powerPreference:ze,forceFallbackAdapter:$e}),!pe)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(re==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},es=new Map,Ws=Y=>{let re=Gt(),pe=re.stackSave();try{let Te=re.PTR_SIZE,ye=re.stackAlloc(2*Te);re._OrtGetInputOutputCount(Y,ye,ye+Te)!==0&&Tt("Can't get session input/output count.");let ze=Te===4?"i32":"i64";return[Number(re.getValue(ye,ze)),Number(re.getValue(ye+Te,ze))]}finally{re.stackRestore(pe)}},Pr=(Y,re)=>{let pe=Gt(),Te=pe.stackSave(),ye=0;try{let ze=pe.PTR_SIZE,$e=pe.stackAlloc(2*ze);pe._OrtGetInputOutputMetadata(Y,re,$e,$e+ze)!==0&&Tt("Can't get session input/output metadata.");let Ae=Number(pe.getValue($e,"*"));ye=Number(pe.getValue($e+ze,"*"));let Be=pe.HEAP32[ye/4];if(Be===0)return[Ae,0];let it=pe.HEAPU32[ye/4+1],ot=[];for(let nt=0;nt<it;nt++){let Ke=Number(pe.getValue(ye+8+nt*ze,"*"));ot.push(Ke!==0?pe.UTF8ToString(Ke):Number(pe.getValue(ye+8+(nt+it)*ze,"*")))}return[Ae,Be,ot]}finally{pe.stackRestore(Te),ye!==0&&pe._OrtFree(ye)}},li=Y=>{let re=Gt(),pe=re._malloc(Y.byteLength);if(pe===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return re.HEAPU8.set(Y,pe),[pe,Y.byteLength]},_s=async(Y,re)=>{var ot,nt,Ke;let pe,Te,ye=Gt();Array.isArray(Y)?[pe,Te]=Y:Y.buffer===ye.HEAPU8.buffer?[pe,Te]=[Y.byteOffset,Y.byteLength]:[pe,Te]=li(Y);let ze=0,$e=0,Ae=[],Be=[],it=[];try{if([$e,Ae]=await $a(re),(re==null?void 0:re.externalData)&&ye.mountExternalData){let Fi=[];for(let fi of re.externalData){let kn=typeof fi=="string"?fi:fi.path;Fi.push(Qi(typeof fi=="string"?fi:fi.data).then(qn=>{ye.mountExternalData(kn,qn)}))}await Promise.all(Fi)}for(let Fi of(re==null?void 0:re.executionProviders)??[])if((typeof Fi=="string"?Fi:Fi.name)==="webnn"){if(ye.shouldTransferToMLTensor=!1,typeof Fi!="string"){let fi=Fi,kn=fi==null?void 0:fi.context,qn=fi==null?void 0:fi.gpuDevice,is=fi==null?void 0:fi.deviceType,Ia=fi==null?void 0:fi.powerPreference;kn?ye.currentContext=kn:qn?ye.currentContext=await ye.webnnCreateMLContext(qn):ye.currentContext=await ye.webnnCreateMLContext({deviceType:is,powerPreference:Ia})}else ye.currentContext=await ye.webnnCreateMLContext();break}ze=await ye._OrtCreateSession(pe,Te,$e),(ot=ye.webgpuOnCreateSession)==null||ot.call(ye,ze),ze===0&&Tt("Can't create a session."),(nt=ye.jsepOnCreateSession)==null||nt.call(ye),ye.currentContext&&(ye.webnnRegisterMLContext(ze,ye.currentContext),ye.currentContext=void 0,ye.shouldTransferToMLTensor=!0);let[jt,Le]=Ws(ze),dt=!!(re!=null&&re.enableGraphCapture),Ii=[],ei=[],ti=[],Pi=[],zt=[];for(let Fi=0;Fi<jt;Fi++){let[fi,kn,qn]=Pr(ze,Fi);fi===0&&Tt("Can't get an input name."),Be.push(fi);let is=ye.UTF8ToString(fi);Ii.push(is),ti.push(kn===0?{name:is,isTensor:!1}:{name:is,isTensor:!0,type:Zi(kn),shape:qn})}for(let Fi=0;Fi<Le;Fi++){let[fi,kn,qn]=Pr(ze,Fi+jt);fi===0&&Tt("Can't get an output name."),it.push(fi);let is=ye.UTF8ToString(fi);ei.push(is),Pi.push(kn===0?{name:is,isTensor:!1}:{name:is,isTensor:!0,type:Zi(kn),shape:qn})}return es.set(ze,[ze,Be,it,null,dt,!1]),[ze,Ii,ei,ti,Pi]}catch(jt){throw Be.forEach(Le=>ye._OrtFree(Le)),it.forEach(Le=>ye._OrtFree(Le)),ze!==0&&ye._OrtReleaseSession(ze)!==0&&Tt("Can't release session."),jt}finally{ye._free(pe),$e!==0&&ye._OrtReleaseSessionOptions($e)!==0&&Tt("Can't release session options."),Ae.forEach(jt=>ye._free(jt)),(Ke=ye.unmountExternalData)==null||Ke.call(ye)}},Kr=Y=>{var Be,it,ot;let re=Gt(),pe=es.get(Y);if(!pe)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,ye,ze,$e,Ae]=pe;$e&&(Ae&&re._OrtClearBoundOutputs($e.handle)!==0&&Tt("Can't clear bound outputs."),re._OrtReleaseBinding($e.handle)!==0&&Tt("Can't release IO binding.")),(Be=re.jsepOnReleaseSession)==null||Be.call(re,Y),(it=re.webnnOnReleaseSession)==null||it.call(re,Y),(ot=re.webgpuOnReleaseSession)==null||ot.call(re,Y),ye.forEach(nt=>re._OrtFree(nt)),ze.forEach(nt=>re._OrtFree(nt)),re._OrtReleaseSession(Te)!==0&&Tt("Can't release session."),es.delete(Y)},Ms=async(Y,re,pe,Te,ye,ze,$e=!1)=>{if(!Y){re.push(0);return}let Ae=Gt(),Be=Ae.PTR_SIZE,it=Y[0],ot=Y[1],nt=Y[3],Ke=nt,jt,Le;if(it==="string"&&(nt==="gpu-buffer"||nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${ze} when enableGraphCapture is true.`);if(nt==="gpu-buffer"){let ei=Y[2].gpuBuffer;Le=Vn(Un(it),ot);{let ti=Ae.jsepRegisterBuffer;if(!ti)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');jt=ti(Te,ze,ei,Le)}}else if(nt==="ml-tensor"){let ei=Y[2].mlTensor;Le=Vn(Un(it),ot);let ti=Ae.webnnRegisterMLTensor;if(!ti)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');jt=ti(Te,ei,Un(it),ot)}else{let ei=Y[2];if(Array.isArray(ei)){Le=Be*ei.length,jt=Ae._malloc(Le),pe.push(jt);for(let ti=0;ti<ei.length;ti++){if(typeof ei[ti]!="string")throw new TypeError(`tensor data at index ${ti} is not a string`);Ae.setValue(jt+ti*Be,Xi(ei[ti],pe),"*")}}else{let ti=Ae.webnnIsGraphInput,Pi=Ae.webnnIsGraphOutput;if(it!=="string"&&ti&&Pi){let zt=Ae.UTF8ToString(ye);if(ti(Te,zt)||Pi(Te,zt)){let Fi=Un(it);Le=Vn(Fi,ot),Ke="ml-tensor";let fi=Ae.webnnCreateTemporaryTensor,kn=Ae.webnnUploadTensor;if(!fi||!kn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let qn=await fi(Te,Fi,ot);kn(qn,new Uint8Array(ei.buffer,ei.byteOffset,ei.byteLength)),jt=qn}else Le=ei.byteLength,jt=Ae._malloc(Le),pe.push(jt),Ae.HEAPU8.set(new Uint8Array(ei.buffer,ei.byteOffset,Le),jt)}else Le=ei.byteLength,jt=Ae._malloc(Le),pe.push(jt),Ae.HEAPU8.set(new Uint8Array(ei.buffer,ei.byteOffset,Le),jt)}}let dt=Ae.stackSave(),Ii=Ae.stackAlloc(4*ot.length);try{ot.forEach((ti,Pi)=>Ae.setValue(Ii+Pi*Be,ti,Be===4?"i32":"i64"));let ei=Ae._OrtCreateTensor(Un(it),jt,Le,Ii,ot.length,Cn(Ke));ei===0&&Tt(`Can't create tensor for input/output. session=${Te}, index=${ze}.`),re.push(ei)}finally{Ae.stackRestore(dt)}},qe=async(Y,re,pe,Te,ye,ze)=>{var ns,ml,mc;let $e=Gt(),Ae=$e.PTR_SIZE,Be=es.get(Y);if(!Be)throw new Error(`cannot run inference. invalid session id: ${Y}`);let it=Be[0],ot=Be[1],nt=Be[2],Ke=Be[3],jt=Be[4];Be[5];let Le=re.length,dt=Te.length,Ii=0,ei=[],ti=[],Pi=[],zt=[],Fi=[],fi=$e.stackSave(),kn=$e.stackAlloc(Le*Ae),qn=$e.stackAlloc(Le*Ae),is=$e.stackAlloc(dt*Ae),Ia=$e.stackAlloc(dt*Ae);try{[Ii,ei]=po(ze),Nt("wasm prepareInputOutputTensor");for(let ui=0;ui<Le;ui++)await Ms(pe[ui],ti,zt,Y,ot[re[ui]],re[ui],jt);for(let ui=0;ui<dt;ui++)await Ms(ye[ui],Pi,zt,Y,nt[Te[ui]],Le+Te[ui],jt);mt("wasm prepareInputOutputTensor");for(let ui=0;ui<Le;ui++)$e.setValue(kn+ui*Ae,ti[ui],"*"),$e.setValue(qn+ui*Ae,ot[re[ui]],"*");for(let ui=0;ui<dt;ui++)$e.setValue(is+ui*Ae,Pi[ui],"*"),$e.setValue(Ia+ui*Ae,nt[Te[ui]],"*");(ns=$e.jsepOnRunStart)==null||ns.call($e,it),(ml=$e.webnnOnRunStart)==null||ml.call($e,it);let En;En=await $e._OrtRun(it,qn,kn,Le,Ia,dt,is,Ii),En!==0&&Tt("failed to call OrtRun().");let dr=[],gc=[];Nt("wasm ProcessOutputTensor");for(let ui=0;ui<dt;ui++){let Vs=Number($e.getValue(is+ui*Ae,"*"));if(Vs===Pi[ui]||Fi.includes(Pi[ui])){dr.push(ye[ui]),Vs!==Pi[ui]&&$e._OrtReleaseTensor(Vs)!==0&&Tt("Can't release tensor.");continue}let Td=$e.stackSave(),Nr=$e.stackAlloc(4*Ae),Yo=!1,pn,ss=0;try{$e._OrtGetTensorData(Vs,Nr,Nr+Ae,Nr+2*Ae,Nr+3*Ae)!==0&&Tt(`Can't access output tensor data on index ${ui}.`);let gl=Ae===4?"i32":"i64",rs=Number($e.getValue(Nr,gl));ss=$e.getValue(Nr+Ae,"*");let vc=$e.getValue(Nr+Ae*2,"*"),Dd=Number($e.getValue(Nr+Ae*3,gl)),Mr=[];for(let fn=0;fn<Dd;fn++)Mr.push(Number($e.getValue(vc+fn*Ae,gl)));$e._OrtFree(vc)!==0&&Tt("Can't free memory for tensor dims.");let qs=Mr.reduce((fn,Ji)=>fn*Ji,1);pn=Zi(rs);let ur=Ke==null?void 0:Ke.outputPreferredLocations[Te[ui]];if(pn==="string"){if(ur==="gpu-buffer"||ur==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let fn=[];for(let Ji=0;Ji<qs;Ji++){let Ks=$e.getValue(ss+Ji*Ae,"*"),_c=$e.getValue(ss+(Ji+1)*Ae,"*"),bc=Ji===qs-1?void 0:_c-Ks;fn.push($e.UTF8ToString(Ks,bc))}dr.push([pn,Mr,fn,"cpu"])}else if(ur==="gpu-buffer"&&qs>0){let fn=$e.jsepGetBuffer;if(!fn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Ji=fn(ss),Ks=Vn(rs,qs);if(Ks===void 0||!$r(pn))throw new Error(`Unsupported data type: ${pn}`);Yo=!0,dr.push([pn,Mr,{gpuBuffer:Ji,download:$e.jsepCreateDownloader(Ji,Ks,pn),dispose:()=>{$e._OrtReleaseTensor(Vs)!==0&&Tt("Can't release tensor.")}},"gpu-buffer"])}else if(ur==="ml-tensor"&&qs>0){let fn=$e.webnnEnsureTensor,Ji=$e.webnnIsGraphInputOutputTypeSupported;if(!fn||!Ji)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Vn(rs,qs)===void 0||!gs(pn))throw new Error(`Unsupported data type: ${pn}`);if(!Ji(Y,pn,!1))throw new Error(`preferredLocation "ml-tensor" for ${pn} output is not supported by current WebNN Context.`);let Ks=await fn(Y,ss,rs,Mr,!1);Yo=!0,dr.push([pn,Mr,{mlTensor:Ks,download:$e.webnnCreateMLTensorDownloader(ss,pn),dispose:()=>{$e.webnnReleaseTensorId(ss),$e._OrtReleaseTensor(Vs)}},"ml-tensor"])}else if(ur==="ml-tensor-cpu-output"&&qs>0){let fn=$e.webnnCreateMLTensorDownloader(ss,pn)(),Ji=dr.length;Yo=!0,gc.push((async()=>{let Ks=[Ji,await fn];return $e.webnnReleaseTensorId(ss),$e._OrtReleaseTensor(Vs),Ks})()),dr.push([pn,Mr,[],"cpu"])}else{let fn=lr(pn),Ji=new fn(qs);new Uint8Array(Ji.buffer,Ji.byteOffset,Ji.byteLength).set($e.HEAPU8.subarray(ss,ss+Ji.byteLength)),dr.push([pn,Mr,Ji,"cpu"])}}finally{$e.stackRestore(Td),pn==="string"&&ss&&$e._free(ss),Yo||$e._OrtReleaseTensor(Vs)}}Ke&&!jt&&($e._OrtClearBoundOutputs(Ke.handle)!==0&&Tt("Can't clear bound outputs."),es.set(Y,[it,ot,nt,Ke,jt,!1]));for(let[ui,Vs]of await Promise.all(gc))dr[ui][2]=Vs;return mt("wasm ProcessOutputTensor"),dr}finally{(mc=$e.webnnOnRunEnd)==null||mc.call($e,it),$e.stackRestore(fi),ti.forEach(En=>$e._OrtReleaseTensor(En)),Pi.forEach(En=>$e._OrtReleaseTensor(En)),zt.forEach(En=>$e._free(En)),Ii!==0&&$e._OrtReleaseRunOptions(Ii),ei.forEach(En=>$e._free(En))}},ts=Y=>{let re=Gt(),pe=es.get(Y);if(!pe)throw new Error("invalid session id");let Te=pe[0],ye=re._OrtEndProfiling(Te);ye===0&&Tt("Can't get an profile file name."),re._OrtFree(ye)},gt=Y=>{let re=[];for(let pe of Y){let Te=pe[2];!Array.isArray(Te)&&"buffer"in Te&&re.push(Te.buffer)}return re}}),Ne,Ze,$t,ni,ci,Bi,Mi,ln,Vi,hn,Oi,Us,Yr,go,cr,Ed,vo,_o,hc=c(()=>{Et(),me(),Qn(),Zn(),Ne=()=>!!R.wasm.proxy&&typeof document<"u",$t=!1,ni=!1,ci=!1,ln=new Map,Vi=(Y,re)=>{let pe=ln.get(Y);pe?pe.push(re):ln.set(Y,[re])},hn=()=>{if($t||!ni||ci||!Ze)throw new Error("worker not ready")},Oi=Y=>{switch(Y.data.type){case"init-wasm":$t=!1,Y.data.err?(ci=!0,Mi[1](Y.data.err)):(ni=!0,Mi[0]()),Bi&&(URL.revokeObjectURL(Bi),Bi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let re=ln.get(Y.data.type);Y.data.err?re.shift()[1](Y.data.err):re.shift()[0](Y.data.out);break}}},Us=async()=>{if(!ni){if($t)throw new Error("multiple calls to 'initWasm()' detected.");if(ci)throw new Error("previous call to 'initWasm()' failed.");if($t=!0,Ne())return new Promise((Y,re)=>{Ze==null||Ze.terminate(),Dr().then(([pe,Te])=>{try{Ze=Te,Ze.onerror=ze=>re(ze),Ze.onmessage=Oi,Mi=[Y,re];let ye={type:"init-wasm",in:R};if(!ye.in.wasm.wasmPaths&&pe){let ze=Ni();ze&&(ye.in.wasm.wasmPaths=ze)}Ze.postMessage(ye),Bi=pe}catch(ye){re(ye)}},re)});try{await ar(R.wasm),await Ko(R),ni=!0}catch(Y){throw ci=!0,Y}finally{$t=!1}}},Yr=async Y=>{if(Ne())return hn(),new Promise((re,pe)=>{Vi("init-ep",[re,pe]);let Te={type:"init-ep",in:{epName:Y,env:R}};Ze.postMessage(Te)});await Ir(R,Y)},go=async Y=>Ne()?(hn(),new Promise((re,pe)=>{Vi("copy-from",[re,pe]);let Te={type:"copy-from",in:{buffer:Y}};Ze.postMessage(Te,[Y.buffer])})):li(Y),cr=async(Y,re)=>{if(Ne()){if(re!=null&&re.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return hn(),new Promise((pe,Te)=>{Vi("create",[pe,Te]);let ye={type:"create",in:{model:Y,options:{...re}}},ze=[];Y instanceof Uint8Array&&ze.push(Y.buffer),Ze.postMessage(ye,ze)})}else return _s(Y,re)},Ed=async Y=>{if(Ne())return hn(),new Promise((re,pe)=>{Vi("release",[re,pe]);let Te={type:"release",in:Y};Ze.postMessage(Te)});Kr(Y)},vo=async(Y,re,pe,Te,ye,ze)=>{if(Ne()){if(pe.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ye.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return hn(),new Promise(($e,Ae)=>{Vi("run",[$e,Ae]);let Be=pe,it={type:"run",in:{sessionId:Y,inputIndices:re,inputs:Be,outputIndices:Te,options:ze}};Ze.postMessage(it,gt(Be))})}else return qe(Y,re,pe,Te,ye,ze)},_o=async Y=>{if(Ne())return hn(),new Promise((re,pe)=>{Vi("end-profiling",[re,pe]);let Te={type:"end-profiling",in:Y};Ze.postMessage(Te)});ts(Y)}}),ul,bo,Aa,hl=c(()=>{Et(),hc(),Ft(),vi(),Ar(),ul=(Y,re)=>{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 ${re()}`)}},bo=Y=>{switch(Y[3]){case"cpu":return new de(Y[0],Y[2],Y[1]);case"gpu-buffer":{let re=Y[0];if(!$r(re))throw new Error(`not supported data type: ${re} for deserializing GPU tensor`);let{gpuBuffer:pe,download:Te,dispose:ye}=Y[2];return de.fromGpuBuffer(pe,{dataType:re,dims:Y[1],download:Te,dispose:ye})}case"ml-tensor":{let re=Y[0];if(!gs(re))throw new Error(`not supported data type: ${re} for deserializing MLTensor tensor`);let{mlTensor:pe,download:Te,dispose:ye}=Y[2];return de.fromMLTensor(pe,{dataType:re,dims:Y[1],download:Te,dispose:ye})}default:throw new Error(`invalid data location: ${Y[3]}`)}},Aa=class{async fetchModelAndCopyToWasmMemory(Y){return go(await Qi(Y))}async loadModel(Y,re){ft();let pe;typeof Y=="string"?pe=await this.fetchModelAndCopyToWasmMemory(Y):pe=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await cr(pe,re),rt()}async dispose(){return Ed(this.sessionId)}async run(Y,re,pe){ft();let Te=[],ye=[];Object.entries(Y).forEach(nt=>{let Ke=nt[0],jt=nt[1],Le=this.inputNames.indexOf(Ke);if(Le===-1)throw new Error(`invalid input '${Ke}'`);Te.push(jt),ye.push(Le)});let ze=[],$e=[];Object.entries(re).forEach(nt=>{let Ke=nt[0],jt=nt[1],Le=this.outputNames.indexOf(Ke);if(Le===-1)throw new Error(`invalid output '${Ke}'`);ze.push(jt),$e.push(Le)});let Ae=Te.map((nt,Ke)=>ul(nt,()=>`input "${this.inputNames[ye[Ke]]}"`)),Be=ze.map((nt,Ke)=>nt?ul(nt,()=>`output "${this.outputNames[$e[Ke]]}"`):null),it=await vo(this.sessionId,ye,Ae,$e,Be,pe),ot={};for(let nt=0;nt<it.length;nt++)ot[this.outputNames[$e[nt]]]=ze[nt]??bo(it[nt]);return rt(),ot}startProfiling(){}endProfiling(){_o(this.sessionId)}}}),jr={};f(jr,{OnnxruntimeWebAssemblyBackend:()=>Rr,initializeFlags:()=>Xr,wasmBackend:()=>wo});var Xr,Rr,wo,pc=c(()=>{Et(),hc(),hl(),Xr=()=>{(typeof R.wasm.initTimeout!="number"||R.wasm.initTimeout<0)&&(R.wasm.initTimeout=0);let Y=R.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.`),R.wasm.simd=!1),typeof R.wasm.proxy!="boolean"&&(R.wasm.proxy=!1),typeof R.wasm.trace!="boolean"&&(R.wasm.trace=!1),typeof R.wasm.numThreads!="number"||!Number.isInteger(R.wasm.numThreads)||R.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)R.wasm.numThreads=1;else{let re=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;R.wasm.numThreads=Math.min(4,Math.ceil((re||1)/2))}},Rr=class{async init(Y){Xr(),await Us(),await Yr(Y)}async createInferenceSessionHandler(Y,re){let pe=new Aa;return await pe.loadModel(Y,re),pe}},wo=new Rr}),fc={};f(fc,{InferenceSession:()=>Je,TRACE:()=>Pe,TRACE_EVENT_BEGIN:()=>Nt,TRACE_EVENT_END:()=>mt,TRACE_FUNC_BEGIN:()=>ft,TRACE_FUNC_END:()=>rt,Tensor:()=>de,default:()=>fl,env:()=>R,registerBackend:()=>k}),Et(),Et(),Et();var pl="1.26.0",fl=ht;{let Y=(pc(),g(jr)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(R.versions,"web",{value:pl,enumerable:!0}),g(fc)})();i.exports=t})(A_)),A_.exports}var Hx;function TD(){return Hx||(Hx=1,(function(i){var e=el&&el.__createBinding||(Object.create?(function(S,T,j,N){N===void 0&&(N=j);var L=Object.getOwnPropertyDescriptor(T,j);(!L||("get"in L?!T.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return T[j]}}),Object.defineProperty(S,N,L)}):(function(S,T,j,N){N===void 0&&(N=j),S[N]=T[j]})),t=el&&el.__setModuleDefault||(Object.create?(function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}):function(S,T){S.default=T}),n=el&&el.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var j in S)j!=="default"&&Object.prototype.hasOwnProperty.call(S,j)&&e(T,S,j);return t(T,S),T};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const s=n(ED()),l=Ww(),p=Uw(),a=vm(),c=Xv(),f=CC(),m=kC();i.DEFAULT_MODEL="legacy",i.ort=s;const g="vad.worklet.bundle.min.js",w="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",k=S=>({...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:S,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async T=>{T.getTracks().forEach(j=>{j.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:T=>{T.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const C=S=>"audioWorklet"in S&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(S,T,j,N,L){await j.audioWorklet.addModule(S),T.processorOptions={...T.processorOptions??{},frameSamples:N};const R=new AudioWorkletNode(j,"vad-helper-worklet",T);return R.port.onmessage=async F=>{const V=F.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case c.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const te=new Float32Array(V.data);await L(te);break}}},R}async function y(S,T,j){const N=new m.Resampler({nativeSampleRate:S.sampleRate,targetSampleRate:16e3,targetFrameSize:T});a.log.debug("using script processor");const R=S.createScriptProcessor(4096,1,1);let F=!1;return R.onaudioprocess=async V=>{if(!F){F=!0;try{const te=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const ee=N.process(te);for(const we of ee)await j(we)}catch(te){console.error("Error processing audio:",te)}finally{F=!1}}},R.connect(S.destination),R}class x{constructor(T,j,N,L,R=!1,F=null,V=null,te=null,he=null,ee=null,we=null,ce="uninitialized",ve=!1){this.options=T,this.frameProcessor=j,this.model=N,this.frameSamples=L,this.listening=R,this.errored=F,this._stream=V,this._audioContext=te,this._vadNode=he,this._mediaStreamAudioSourceNode=ee,this._audioProcessorAdapterType=we,this.initializationState=ce,this.ownsAudioContext=ve,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=Ee=>{this.initializationState="errored",this.errored=Ee},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(Ee){throw Ee instanceof Error?this.setErrored(Ee.message):this.setErrored(String(Ee)),Ee}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?C(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await y(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),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:Ee,audioContext:fe,vadNode:U}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ee);const X=new MediaStreamAudioSourceNode(fe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=X,X.connect(U);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ee,mediaStreamAudioSourceNode:fe}=this.getAudioInstances();await this.options.pauseStream(Ee),fe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var fe;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ee}=this.getAudioInstances();Ee instanceof AudioWorkletNode&&Ee.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((fe=this._audioContext)==null?void 0:fe.close())},this.setOptions=Ee=>{this.frameProcessor.setOptions(Ee)},this.processFrame=async Ee=>{await this.frameProcessor.process(Ee,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ee=>{switch(Ee.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(Ee.probs,Ee.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(Ee.audio);break}}}static async new(T={}){const j={...(0,i.getDefaultRealTimeVADOptions)(T.model??i.DEFAULT_MODEL),...T};(0,p.validateOptions)(j),i.ort.env.wasm.wasmPaths=j.onnxWASMBasePath,j.ortConfig!==void 0&&j.ortConfig(i.ort);const N=j.model==="v5"?w:D,L=j.baseAssetPath+N,R=j.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let F;try{F=await R(i.ort,()=>(0,l.defaultModelFetcher)(L))}catch(we){throw console.error(`Encountered an error while loading model file ${L}`),we}const V=j.model==="v5"?512:1536,te=V/16,he=new p.FrameProcessor(F.process,F.reset_state,{positiveSpeechThreshold:j.positiveSpeechThreshold,negativeSpeechThreshold:j.negativeSpeechThreshold,redemptionMs:j.redemptionMs,preSpeechPadMs:j.preSpeechPadMs,minSpeechMs:j.minSpeechMs,submitUserSpeechOnPause:j.submitUserSpeechOnPause},te),ee=new x(j,he,F,V);if(j.startOnLoad)try{await ee.start()}catch(we){throw console.error("Error starting micVad",we),we}return ee}}i.MicVAD=x})(el)),el}var Wx;function DD(){return Wx||(Wx=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=yC();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=Ww();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Uw();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var s=Xv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return s.Message}});var l=CD();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=kD();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=TD();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}})})(T_)),T_}var $D=DD();function $g(i,e,t,n,s){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,s)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const ut={debug:(i,e,t)=>$g(i,"debug",e,t),info:(i,e,t)=>$g(i,"info",e,t),warn:(i,e,t)=>$g(i,"warn",e,t),error:(i,e,t,n)=>$g(i,"error",e,t,n)},TC=16e3,AD=6,dh=TC*AD,ID=400,PD=TC*ID/1e3,Ux=300,Vx=2e3,qx=1500,Kx=3e3,jD=600,DC=.5,$C=.35,Yx=.85,Xx=.7;let As=null,Ho=!1,Fs=!1;const Pb=new Set;function Ag(i){for(const e of Array.from(Pb))try{e(i)}catch(t){ut.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let I_=0;const Jx=2;let wh=!1,AC=!1;function IC(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";ut[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{ut.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),RD(`error:${e.message||"unknown"}`)})}function Av(){return As||(As=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),IC(As),ut.info("speech","worker spawned"),As)}let Ig=!1;function RD(i){if(!wh){if(Ig){ut.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(Ig=!0,I_+=1,AC=!0,ut.warn("speech","respawnWorker: starting",{reason:i,attempt:I_}),Ag({reason:i,respawned:!1,finalOnly:!0}),I_>Jx){if(wh=!0,ut.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Jx}),As)try{As.terminate()}catch{}As=null,Ho=!1,Fs=!1,Ag({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Ig=!1;return}if(As)try{As.terminate()}catch{}As=null,Ho=!1,Fs=!1;try{As=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),IC(As),Fs=!0,As.postMessage({type:"load"}),ut.info("speech","respawnWorker: new worker spawned, load posted"),Ag({reason:i,respawned:!0,finalOnly:!0})}catch(e){wh=!0,ut.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Ag({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Ig=!1}}}function ND(i,e){if(Ho||Fs)return;Fs=!0;const t=Av();ut.info("speech","preloadModel: posting load");const n=s=>{s.data.type==="status"?(i==null||i(s.data.status,s.data.message),s.data.status==="ready"&&(Ho=!0,Fs=!1,ut.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(Fs=!1,ut.error("speech","preloadModel: worker reported error",{error:s.data.error}),i==null||i("error",s.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function MD(){ut.info("speech","resetModel: clearing load flags"),Ho=!1,Fs=!1}function OD(){if(ut.info("speech","releaseModel: terminating worker"),As)try{As.terminate()}catch{}As=null,Ho=!1,Fs=!1}function Jv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function LD(i){const e=Av();return!Ho&&!Fs&&(Fs=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const s=l=>{var p,a,c;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",s),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",s),n(new Error(String(l.data.error??"Transcription failed")))):((c=l.data)==null?void 0:c.type)==="status"&&l.data.status==="ready"&&(Ho=!0,Fs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function PC(i){let e=Av(),t=!1,n=null,s=null,l=null,p=null,a=null;const c=[],f=new Set;let m=null,g=0,w=!1,D=0,k=!1,C=!1,b=0,y=0,x=0,S=-1,T=Ux,j=0,N=null,L="",R="",F=!1,V=0;function te(oe,Ce){const Oe=Math.min(oe.length,Ce.length);let Xe=0;for(;Xe<Oe&&oe.charCodeAt(Xe)===Ce.charCodeAt(Xe);)Xe++;return Xe}function he(oe){const Ce=te(L,oe);return L=oe,Ce>R.length&&(R=oe.slice(0,Ce)),R.length>oe.length&&(R=oe),R}const ee=()=>(m||(m=new Float32Array(dh)),m),we=()=>{g=0},ce=oe=>{const Ce=ee(),Oe=oe.length;if(Oe>=dh){Ce.set(oe.subarray(Oe-dh)),g=dh;return}if(g+Oe<=dh){Ce.set(oe,g),g+=Oe;return}const Xe=g+Oe-dh;Ce.copyWithin(0,Xe,g),g-=Xe,Ce.set(oe,g),g+=Oe},ve=()=>{N&&(clearTimeout(N),N=null)},Ee=()=>{ve(),w=!1,k=!1,C=!1,T=Ux,L="",R="",F=!1,V=0,we()},fe=()=>{if(t||!w||C||k||N)return;if(g<PD){N=setTimeout(()=>{N=null,fe()},T);return}const oe=performance.now()-b;if(oe<T&&b!==0){N=setTimeout(()=>{N=null,fe()},T-oe);return}if(AC||wh||i.partialsEnabled&&!i.partialsEnabled())return;const Ce=ee(),Oe=new Float32Array(g);Oe.set(Ce.subarray(0,g)),y+=1,x=y,k=!0,j=performance.now(),b=j,e.postMessage({type:"transcribe-partial",audio:Oe,seq:y},[Oe.buffer])},U=oe=>oe.length===0?Promise.resolve():wh?(ut.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Ce=>{c.push(Ce),y+=1;const Oe=y;S=Oe,e.postMessage({type:"transcribe",audio:oe,seq:Oe},[oe.buffer])}),X=oe=>{const Ce=U(oe);return f.add(Ce),Ce.finally(()=>{f.delete(Ce)}),Ce},W=oe=>{var Ce,Oe,Xe,ge,J;if(oe.data.type==="result"){const je=oe.data.text,de=oe.data.seq??0;de&&de<S&&ut.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:de,latestFinalSeq:S}),!t&&je&&i.onFinal(je),(Ce=c.shift())==null||Ce()}else if(oe.data.type==="partial"){const je=oe.data.seq??0,de=oe.data.text??"",Ie=performance.now()-j;k=!1,Ie>=Kx?(C=!0,ut.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ie),seq:je})):Ie>=qx&&(T=Math.min(T*2,Vx),ut.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ie),newIntervalMs:T,seq:je})),F||(F=!0,Ie>jD&&T<500&&(T=500,ut.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ie),newIntervalMs:500})));const Pe=je!==x||je<=S;if(!t&&!Pe&&de){const Ye=he(de);Ye&&((Oe=i.onPartial)==null||Oe.call(i,Ye),V===0&&(V=performance.now(),ut.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-D)})))}fe()}else if(oe.data.type==="partial-error"){const je=performance.now()-j;k=!1,je>=Kx?(C=!0,ut.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(je),seq:oe.data.seq})):je>=qx&&(T=Math.min(T*2,Vx),ut.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(je),newIntervalMs:T,seq:oe.data.seq})),ut.warn("speech","partial encode failed",{error:oe.data.error,seq:oe.data.seq}),fe()}else oe.data.type==="error"?(t||i.onError(oe.data.error),(Xe=c.shift())==null||Xe()):oe.data.type==="status"?(t||(ge=i.onModelStatus)==null||ge.call(i,oe.data.status,oe.data.message),oe.data.status==="ready"&&(Ho=!0,Fs=!1)):oe.data.type==="progress"&&(t||(J=i.onProgress)==null||J.call(i,oe.data.pct))};e.addEventListener("message",W);const Q=oe=>{var Ce,Oe;if(!t){for(ut.warn("speech","createRecognition: worker death event",oe),(Ce=i.onStatusChange)==null||Ce.call(i,"restarting");c.length;)(Oe=c.shift())==null||Oe();if(f.clear(),ve(),k=!1,oe.respawned){try{e.removeEventListener("message",W)}catch{}e=Av(),e.addEventListener("message",W)}}};return Pb.add(Q),{start:async()=>{if(!t){if(wh){i.onError("Speech recognition disabled — please reload the app.");return}!Ho&&!Fs&&(Fs=!0,ut.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ut.info("speech","createRecognition.start: initializing VAD",{modelReady:Ho,modelLoading:Fs});try{const oe=new URL("vad/",document.baseURI).href;ut.info("speech","vad: asset base resolved",{vadBase:oe}),bD();const Ce=i.inputDeviceId||null,Oe={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Ce&&(Oe.deviceId={exact:Ce}),ut.info("speech","getUserMedia",{hasDeviceId:!!Ce,deviceIdPrefix:Ce?Ce.slice(0,8):null});const Xe=await navigator.mediaDevices.getUserMedia({audio:Oe});s=Xe,l=new AudioContext;for(const ge of Xe.getAudioTracks())ge.addEventListener("ended",()=>{t||(ut.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(s),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ge){ut.warn("speech","analyser init failed",{error:ge instanceof Error?ge.message:String(ge)}),a=null,p=null}n=await $D.MicVAD.new({audioContext:l,getStream:async()=>Xe,resumeStream:async()=>Xe,pauseStream:async()=>{},baseAssetPath:oe,onnxWASMBasePath:oe,model:"v5",positiveSpeechThreshold:DC,negativeSpeechThreshold:$C,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ge,J)=>{var je;t||((je=i.onFrame)==null||je.call(i,ge),w&&(ce(J),fe()))},onSpeechStart:()=>{var ge;t||(Ee(),w=!0,D=performance.now(),(ge=i.onSpeechStart)==null||ge.call(i))},onSpeechEnd:ge=>{var J;t||((J=i.onStatusChange)==null||J.call(i,"transcribing"),Ee(),X(ge))},onVADMisfire:()=>{var ge,J;t||((ge=i.onStatusChange)==null||ge.call(i,"idle"),Ee(),(J=i.onMisfire)==null||J.call(i))}}),ut.info("speech","vad: ort wasm files loaded",{files:_D()}),n.start()}catch(oe){const Ce=oe instanceof Error?oe.message:"Microphone access denied",Oe=oe instanceof Error?oe.stack:"";if(ut.error("speech","createRecognition.start: VAD init failed",{error:Ce,stack:Oe}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(s){try{s.getTracks().forEach(Xe=>Xe.stop())}catch{}s=null}if(l){try{await l.close()}catch{}l=null}i.onError(Ce)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(Ee();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(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(oe,Ce)=>{if(n)try{n.setOptions({positiveSpeechThreshold:oe,negativeSpeechThreshold:Ce})}catch(Oe){ut.warn("speech","setVadThresholds failed",{error:Oe instanceof Error?Oe.message:String(Oe)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,Ee(),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(s){try{s.getTracks().forEach(oe=>oe.stop())}catch{}s=null}Pb.delete(Q),e.removeEventListener("message",W)}}}let Uf=null;const jb=new Set,Rb=new Set;function zD(){for(const i of jb)try{i()}catch{}}function Nb(){for(const i of Rb)try{i()}catch{}}function BD(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 GD(i){if(!window.speechSynthesis)return;const e=BD(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Uf=performance.now(),zD()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Uf=null,Nb())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Uf=null,Nb())},window.speechSynthesis.speak(t)}function jC(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Uf=null,Nb())}function RC(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function FD(){return Uf}function HD(i){return jb.add(i),()=>{jb.delete(i)}}function WD(i){return Rb.add(i),()=>{Rb.delete(i)}}function UD(i){RC()&&(i.setVadThresholds(Yx,Xx),ut.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=HD(()=>{i.setVadThresholds(Yx,Xx),ut.info("voice","tts.duck.on")}),t=WD(()=>{i.setVadThresholds(DC,$C),ut.info("voice","tts.duck.off")});return()=>{e(),t()}}const VD=[{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 qD(i){const e=i.trim();return VD.find(t=>t.match.test(e))??null}const KD=4e4;let vd=null;function yh(){vd&&clearTimeout(vd),vd=setTimeout(()=>{vd=null,kt.getState().stopRecording()},KD)}function Pg(){vd&&(clearTimeout(vd),vd=null)}let oc=null,ec=null;const YD=.04,XD=.3;let Iv=0,Mb=0;function JD(i){ec!==null&&cancelAnimationFrame(ec);const e=()=>{if(oc===null||kt.getState().submitCountdownStartAt===null){ec=null;return}const t=performance.now();if(t-Mb<200&&Iv>XD){const s=t-i;ut.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Iv.toFixed(2),msIntoCountdown:Math.round(s)}),Jl(),yh();return}const n=NC();if(n){const s=new Uint8Array(n.fftSize);n.getByteTimeDomainData(s);let l=0;for(let a=0;a<s.length;a++){const c=(s[a]-128)/128;l+=c*c}const p=Math.sqrt(l/s.length);if(p>YD){const a=t-i;ut.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Jl(),yh();return}}ec=requestAnimationFrame(e)};ec=requestAnimationFrame(e)}function Zx(i){oc&&clearTimeout(oc);const e=kt.getState().submitDelayMs,t=performance.now();kt.setState({submitCountdownStartAt:t}),oc=setTimeout(()=>{var s;oc=null,kt.setState({submitCountdownStartAt:null});const n=Ct.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(s=pi.getState().chats[i])==null?void 0:s.pendingVoiceText;l&&(pi.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),pi.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){ut.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}yh()},e),JD(t)}function Jl(){ec!==null&&(cancelAnimationFrame(ec),ec=null),oc&&(clearTimeout(oc),oc=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let Bn=null,Bs=null,vf=null;function NC(){var i;return((i=Bn==null?void 0:Bn.getAnalyser)==null?void 0:i.call(Bn))??null}const jg=1e4;let Vf=null;function Rg(){Vf&&(clearTimeout(Vf),Vf=null)}let hv=null,pv=null;function Ng(){hv=null,pv&&(pv(),pv=null)}const ZD=1500,QD=9e4;let _f=0,fv=null,Ob=-1;function bf(){fv&&(clearTimeout(fv),fv=null,Ob=-1)}const e$=1800*1e3;let qf=null,Mg=!1;function Qx(){qf&&(clearTimeout(qf),qf=null)}const t$=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=jn((i,e)=>{function t(){Qx(),qf=setTimeout(()=>{if(qf=null,e().isRecording||Bn){t();return}ut.info("voice","model idle timeout: releasing worker"),bf(),_f++,OD(),i({modelStatus:"idle",loadingProgress:0,error:null,errorKind:null})},e$)}function n(){return e().modelStatus==="error"?e().resetAndRetryModel():e().initModel(),new Promise((s,l)=>{let p=()=>{};const a=c=>c.modelStatus==="ready"?(p(),s(),!0):c.modelStatus==="error"?(p(),l(new Error(c.error??"Model load failed")),!0):!1;a(e())||(p=kt.subscribe(c=>{a(c)}))})}return{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;ut.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const s=++_f,l=()=>{s===_f&&(bf(),Ob=s,fv=setTimeout(()=>{Ob===s&&e().modelStatus==="loading"&&(ut.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},QD))};l(),ND((p,a)=>{s===_f&&(p==="ready"?(bf(),ut.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null}),!e().isRecording&&!Bn&&t()):p==="error"?(bf(),ut.error("voice","modelStatus -> error",{msg:a}),i({modelStatus:"error",error:a,errorKind:"load"})):(l(),i({modelStatus:"loading"})))},p=>{s===_f&&(l(),i({loadingProgress:Math.round(p)}))})},resetAndRetryModel:()=>{ut.info("voice","mic.gate.retry"),bf(),MD(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(s,l)=>{if(e().isRecording)return;if(Bn){ut.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Jv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}if(e().modelStatus!=="ready"){if(Mg)return;Mg=!0,n().then(()=>{Mg=!1,e().startRecording(s,l)}).catch(a=>{Mg=!1;const c=a instanceof Error?a.message:String(a);ut.error("voice","startRecording: model load failed",{error:c}),Qe.error(`Could not load speech model: ${c}`)});return}Qx();const p=a=>{try{const c=PC({inputDeviceId:a,onStatusChange:f=>{i(f==="transcribing"?{statusPill:"transcribing"}:f==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:f=>{e().partialsEnabled&&i({lastPartial:f})},partialsEnabled:()=>e().partialsEnabled,onFrame:f=>{Iv=f.isSpeech,Mb=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),Pg(),Jl(),RC()){const m=FD(),g=m!==null?performance.now()-m:null;jC(),i({lastBargeInAt:performance.now()}),ut.info("voice","barge-in",{tabId:s,utteranceOffsetMs:g})}else ut.debug("voice","barge-in.no-op",{tabId:s})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),yh();const f=e().lastBargeInAt;f!==null&&performance.now()-f<600&&ut.warn("voice","barge-in.misfire",{tabId:s,sinceBargeInMs:Math.round(performance.now()-f)})},onFinal:f=>{var k;yh();const m=f.trim();if(!m||t$.has(m)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(vf){vf(m),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((k=Ct.getState().tabs.find(C=>C.id===s))==null?void 0:k.status)==="dormant"){pi.getState().setPendingVoiceText(s,m),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Zx(s);const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}const w=qD(m);if(w){ut.info("voice","voice-command",{tabId:s,label:w.label,transcript:m}),window.api.pty.write({tabId:s,data:w.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Jl();const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}window.api.pty.write({tabId:s,data:m}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Zx(s);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:s,text:m}),D.__transcripts.length>500&&D.__transcripts.shift())},onError:f=>{ut.error("voice","recognition error",{err:f}),Jl(),i({error:f,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Bs==null||Bs(),Bs=null,Pg(),Bn==null||Bn.destroy(),Bn=null,vf=null,Qe.error(`Microphone error: ${f}`)},onModelStatus:f=>{f==="ready"?i({modelStatus:"ready",loadingProgress:100}):f==="loading"&&i({modelStatus:"loading"})},onProgress:f=>i({loadingProgress:Math.round(f)})});Bn=c,vf=(l==null?void 0:l.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),yh(),c.start().then(()=>{Bn===c&&(Bs==null||Bs(),Bs=UD(c))}).catch(f=>{const m=f instanceof Error?f.message:String(f);ut.error("voice","handle.start() failed",{error:m}),Qe.error(`Could not start mic: ${m}`)})}catch(c){i({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,c,f;return((f=(c=(a=window.api)==null?void 0:a.voice)==null?void 0:c.getDevicePref)==null?void 0:f.call(c))??Promise.resolve(null)}).then(a=>p((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ut.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),p(null)})},stopRecording:()=>{const s=Bn;s&&(Pg(),Jl(),Iv=0,Mb=0,Bs==null||Bs(),Bs=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t(),s.stop().finally(()=>{s.destroy(),Bn===s&&(Bn=null,vf=null),e().hotkeyState==="stopping"&&(Rg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const s=Bn;if(!s)return;Pg(),Bs==null||Bs(),Bs=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await s.stop()}catch(a){ut.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}s.destroy(),Bn===s&&(Bn=null);const{useSessions:l}=await mi(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>N2);return{useSessions:a}},[],import.meta.url),p=l.getState().activeTabId;p&&e().startRecording(p)},setExternalRecording:s=>i({externalRecording:s}),toggleTTS:()=>i(s=>({ttsEnabled:!s.ttsEnabled})),setAutoSubmit:s=>i({autoSubmit:s}),setSubmitDelayMs:s=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(s)))}),cancelSubmit:()=>Jl(),setPartialsEnabled:s=>{e().partialsEnabled!==s&&(i({partialsEnabled:s}),s||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:s=>{e().permissionState!==s&&(ut.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:s}),i({permissionState:s}))},setLevelMeterEnabled:s=>{e().levelMeterEnabled!==s&&i({levelMeterEnabled:s})},setTurnDetectorRuntimeState:s=>{e().turnDetectorState!==s&&(i({turnDetectorState:s}),s==="load_failed"?ut.warn("voice-turn","voice-turn.load_failed"):s==="runtime_error"?ut.warn("voice-turn","voice-turn.runtime_error"):s==="disabled"&&ut.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:s=>{e().wizardArmed!==s&&i({wizardArmed:s})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:s,source:l,mode:p,tabId:a})=>{const c=e(),{canRecord:f,reason:m}=Pv(c);if(s==="down"){if(m==="error"||m==="load-timeout"){c.resetAndRetryModel(),ut.info("voice-hotkey","down.retry",{source:l,reason:m});return}if(!f&&m!=="loading"){ut.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:m});return}if(c.hotkeyState==="recording"||c.isRecording){(p==="toggle"||l==="global")&&(i({hotkeyState:"stopping"}),Rg(),Vf=setTimeout(()=>{e().hotkeyState==="stopping"&&(ut.warn("voice-hotkey","drain-timeout",{durationMs:jg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},jg),c.stopRecording());return}if(m==="loading"){c.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),ut.info("voice-hotkey","armed",{source:l,modelStatus:c.modelStatus})),Ng(),hv={tabId:a,source:l,mode:p},pv=kt.subscribe((g,w)=>{if(hv&&g.modelStatus==="ready"&&w.modelStatus!=="ready"&&g.hotkeyState==="armed"){const D=hv;if(Ng(),!D.tabId){ut.warn("voice-hotkey","armed-promote-no-tab",{source:D.source}),i({hotkeyState:"idle"});return}ut.info("voice-hotkey","armed-promote",D),i({hotkeyState:"recording"}),kt.getState().startRecording(D.tabId)}});return}if(!a){ut.warn("voice-hotkey","no-active-tab",{source:l});return}ut.info("voice-hotkey","start",{source:l,mode:p,tabId:a}),c.startRecording(a),e().isRecording?i({hotkeyState:"recording"}):(ut.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(p!=="hold"||l==="global")){if(c.hotkeyState==="armed"){Ng(),ut.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),Rg(),Vf=setTimeout(()=>{e().hotkeyState==="stopping"&&(ut.warn("voice-hotkey","drain-timeout",{durationMs:jg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},jg),c.stopRecording())}},destroyHotkey:()=>{const s=e();if(Ng(),Jl(),s.hotkeyState==="recording"){ut.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{s.stopRecording()}catch{}}else(s.hotkeyState==="armed"||s.hotkeyState==="stopping")&&(Rg(),i({hotkeyState:"destroyed"}))}}}),i$=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),Pv=i=>Jv()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=kt,i.__transcripts=[]}const nm=6e4,n$=3e5,s$=.25,r$=5e3,sm=jn(()=>({data:null,refreshing:!1}));let e0=!1,mv=null,P_=nm,Og=!1,sl=null;function o$(i,e){if(i.kind==="ok")return{delayMs:nm,nextBackoffMs:nm};const t=Math.min(e*2,n$),n=t*s$;let s=t+(Math.random()*2-1)*n;const l=i.kind==="meter_rate_limited"?i.retryAfterMs:void 0;return typeof l=="number"&&Number.isFinite(l)&&l>s&&(s=l),{delayMs:s,nextBackoffMs:t}}function t0(){return X1(window.api.billing.fetch(),r$,"billing.fetch")}function i0(i){sm.setState({data:i,refreshing:!1})}async function Vw(){sm.setState({refreshing:!0});let i=nm;try{const e=await t0();sl&&(sl.cancel(),sl=null),i0(e);const{delayMs:t,nextBackoffMs:n}=o$(e,P_);P_=n,i=t}catch(e){P_=nm,sm.setState({refreshing:!1});const t=J1({error:e,retry:t0,onRetrySuccess:n=>{sl=null,i0(n)},onStillFailing:n=>{sl=null,Og||(Og=!0,Qe.warn(`Billing usage fetch: ${n}`))}});if(t)sl=t;else if(!Og){Og=!0;const n=e instanceof Error?e.message:String(e);Qe.warn(`Billing usage fetch failed: ${n}`)}}mv=setTimeout(Vw,i)}function a$(){e0||(e0=!0,Vw())}function MC(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 l$(){mv!==null&&(clearTimeout(mv),mv=null),sl&&(sl.cancel(),sl=null),Vw()}function rm(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),s=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${s} ${e[1]}`:`${n} ${s}`}function om(i){const e=/(opus|sonnet|haiku|fable)/i.exec(i);return e?e[1].toLowerCase():null}const Lg=new Map,c$=3e4;function qw(i){const[e,t]=z.useState(()=>{var n;return i?((n=Lg.get(i))==null?void 0:n.value)??null:null});return z.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=Lg.get(i);if(l&&Date.now()-l.ts<c$){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;Lg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;Lg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}const OC="~/.claude/session-manager/ui-chrome-prefs.json",d$=180,u$=480,Lb=252,ld={sidebarWidth:Lb,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function zb(i){return Math.min(u$,Math.max(d$,i))}let tc=null,gv={};function h$(i){const e=()=>{const t=i(),n={sidebarWidth:t.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed,collapsedGroups:t.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed,tourCompletedAt:t.tourCompletedAt,density:t.density};window.api.config.writeJson(OC,n).catch(()=>{})};i().hydrated||!tc?e():tc.then(e)}function uh(i,e,t){i(t),!e().hydrated&&tc&&Object.assign(gv,t),h$(e)}const Pn=jn((i,e)=>({...ld,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():tc||(tc=(async()=>{try{const t=await window.api.config.readJson(OC);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({sidebarWidth:typeof n.sidebarWidth=="number"?zb(n.sidebarWidth):ld.sidebarWidth,sidebarCollapsed:n.sidebarCollapsed??ld.sidebarCollapsed,collapsedGroups:Array.isArray(n.collapsedGroups)?n.collapsedGroups:ld.collapsedGroups,learningPanelCollapsed:n.learningPanelCollapsed??ld.learningPanelCollapsed,tourCompletedAt:typeof n.tourCompletedAt=="number"?n.tourCompletedAt:ld.tourCompletedAt,density:n.density==="compact"?"compact":ld.density,...gv,hydrated:!0});return}}catch{}i({...gv,hydrated:!0})})().finally(()=>{tc=null,gv={}}),tc),setSidebarWidth:t=>uh(i,e,{sidebarWidth:zb(t)}),setSidebarCollapsed:t=>uh(i,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>uh(i,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>uh(i,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>uh(i,e,{tourCompletedAt:t}),setDensity:t=>uh(i,e,{density:t})}));function p$(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:s})=>({key:e,label:t,icon:n,hint:s}))}const f$=52;function m$(i){return new Set(i.filter(e=>e==="Workspace"||e==="Configure"||e==="Tools"))}function g$(){const i=Ct(t=>{var n;return((n=t.tabs.find(s=>s.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Wr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(s=>s.status==="running"&&(!i||s.cwd===i))})}}function v$({active:i,onNavigate:e,onNewSession:t}){const n=Pn(ee=>ee.hydrated),s=Pn(ee=>ee.hydrate);z.useEffect(()=>{n||s()},[n,s]);const l=Pn(ee=>ee.collapsedGroups),p=Pn(ee=>ee.setCollapsedGroups),a=z.useMemo(()=>m$(l),[l]),c=z.useCallback(ee=>{const we=new Set(a);we.has(ee)?we.delete(ee):we.add(ee),p(Array.from(we))},[a,p]),f=Pn(ee=>ee.sidebarCollapsed),m=Pn(ee=>ee.setSidebarCollapsed),g=z.useCallback(()=>{m(!f)},[f,m]),w=Ct(ee=>ee.tabs),D=Ct(ee=>ee.activeTabId),k=w.find(ee=>ee.id===D)??null,C=g$(),b=ji(ee=>ee.navFace),y=z2(b),x=y.filter(ee=>ee.group==="Workspace"),S=y.filter(ee=>ee.group==="Configure"),T=p$(y),j=b==="home"&&!f,N=Pn(ee=>ee.sidebarWidth),L=Pn(ee=>ee.setSidebarWidth),[R,F]=z.useState(N),V=z.useRef(R);V.current=R,z.useEffect(()=>{F(N)},[N]);const te=z.useCallback(ee=>{ee.preventDefault();const we=ee.clientX,ce=V.current;let ve=ce;const Ee=U=>{ve=zb(ce+(U.clientX-we)),F(ve)},fe=()=>{window.removeEventListener("pointermove",Ee),window.removeEventListener("pointerup",fe),document.body.style.cursor="",document.body.style.userSelect="",L(ve)};window.addEventListener("pointermove",Ee),window.addEventListener("pointerup",fe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[L]),he=z.useCallback(()=>{F(Lb),L(Lb)},[L]);return d.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:f?f$:R},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[d.jsx(_$,{tab:k,navFace:b,onNewSession:t,rail:f,onToggleRail:g}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:f?"4px":"8px"},children:j?d.jsxs(d.Fragment,{children:[d.jsx(j_,{label:"Workspace",desc:k_.Workspace,collapsed:a.has("Workspace"),count:x.length,onToggle:()=>c("Workspace")}),!a.has("Workspace")&&x.map(ee=>d.jsx(R_,{item:ee,active:i===ee.key,live:ee.liveKind?C[ee.liveKind]:!1,onClick:()=>e(ee.key),rail:!1},ee.key)),d.jsx(j_,{label:"Configure",desc:k_.Configure,collapsed:a.has("Configure"),count:S.length,onToggle:()=>c("Configure")}),!a.has("Configure")&&S.map(ee=>d.jsx(R_,{item:ee,active:i===ee.key,live:!1,onClick:()=>e(ee.key),rail:!1},ee.key)),T.length>0&&d.jsx(j_,{label:"Tools",desc:k_.Tools,collapsed:a.has("Tools"),count:T.length,onToggle:()=>c("Tools")}),T.length>0&&!a.has("Tools")&&T.map(ee=>d.jsx(n0,{tool:ee,active:i===ee.key,onClick:()=>e(ee.key),rail:!1},ee.key))]}):d.jsx("div",{className:"pt-2",children:y.map(ee=>ee.group==="Tools"?d.jsx(n0,{tool:{key:ee.key,label:ee.label,icon:ee.icon,hint:ee.hint},active:i===ee.key,onClick:()=>e(ee.key),rail:f},ee.key):d.jsx(R_,{item:ee,active:i===ee.key,live:ee.liveKind?C[ee.liveKind]:!1,onClick:()=>e(ee.key),rail:f},ee.key))})}),d.jsx(b$,{rail:f,navFace:b}),!f&&d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:te,onDoubleClick:he,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 _$({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:s}){const l=(i==null?void 0:i.label)??"no session",p=qw((i==null?void 0:i.cwd)??null);return n?d.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[d.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:d.jsx(Cr,{name:"plus",size:15,stroke:1.8})}),d.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:d.jsx(Cr,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?d.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),d.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(Cr,{name:"chevron",size:13,stroke:1.8})})})]}),d.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:d.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:[d.jsx(Cr,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):d.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),d.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(Cr,{name:"chevron",size:13,stroke:1.8})})})]}),d.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[d.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),d.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),d.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),d.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:d.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:[d.jsx(Cr,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function j_({label:i,desc:e,collapsed:t,count:n,onToggle:s}){return d.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[d.jsxs("button",{onClick:s,"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:[d.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),d.jsx("span",{className:"flex-1",children:i}),t&&d.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&d.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 R_({item:i,active:e,live:t,onClick:n,rail:s}){return d.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&d.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),d.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:d.jsx(Cr,{name:i.icon,size:17,stroke:1.6})}),!s&&d.jsxs("span",{className:"flex-1 min-w-0",children:[d.jsx("span",{className:"block truncate",children:i.label}),i.hint&&d.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!s&&t&&d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&t&&d.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 n0({tool:i,active:e,onClick:t,rail:n}){return d.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&&d.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),d.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:d.jsx(Cr,{name:i.icon,size:15,stroke:1.6})}),!n&&d.jsxs("span",{className:"flex-1 min-w-0",children:[d.jsx("span",{className:"block truncate",children:i.label}),i.hint&&d.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function b$({rail:i,navFace:e}){const t=kt(c=>c.isRecording),n=Ct(c=>c.tabs),s=Ct(c=>c.activeTabId),l=n.find(c=>c.id===s)??null,[p,a]=z.useState(null);return z.useEffect(()=>{let c=!1;if(!(l!=null&&l.presetId)){a(null);return}return H1(l.presetId).then(f=>{c||a((f==null?void 0:f.model)??null)}).catch(()=>{c||a(null)}),()=>{c=!0}},[l==null?void 0:l.presetId]),i?d.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):d.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:[d.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")&&d.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${rm(p)}`:"Claude Code"})]})}function w$(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function y$(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 x$(i,e,t){const n=Date.now(),s={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,c)=>a.length>c?a.slice(0,c-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];s.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,c=a.input,f={};for(const m of["command","file_path","pattern","url","query","subagent_type","description"])c&&m in c&&(f[m]=c[m]);if(s.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const m=a.input,g=["Edit","Write","NotebookEdit"].includes(a.name),w=typeof(m==null?void 0:m.file_path)=="string"?m.file_path:void 0,D=typeof(m==null?void 0:m.command)=="string"?m.command:void 0,k=w?w.split("/").pop()??w:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:w??D,toolName:a.name}),g&&w&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(w.split("/").pop()??w,34)}`,target:w,toolName:a.name})}break}case"plan":{const a=e.data,c=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);s.plans=[{at:n,content:c??""},...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;s.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,c=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,m=a.output_tokens??a.outputTokens??0,g=c+f+m;s.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+m,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(g/1e3)>Math.floor(c/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(g/1e3)}k tokens`});break}case"tool_result":{const a=e.data;s.agents=w$(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:s,newActivity:l}}const vv=jn((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,s)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:y$(t,n,s)}});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:s}).then(async a=>{const c=e().tabs[t];if(!c)return;if(!a.ok){const{toast:m}=await mi(async()=>{const{toast:g}=await Promise.resolve().then(()=>V1);return{toast:g}},void 0,import.meta.url);m.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...c,path:null}}});return}i({tabs:{...e().tabs,[t]:{...c,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 s=e().unsubs[t];s==null||s();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,s)=>{e().ingestBatch(t,[n],s)},ingestBatch:(t,n,s)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const c of n){const{next:f,newActivity:m}=x$(p,c,s);p=f,a=a.concat(m)}if(a.length>0){let c=l.activitySeq;const f=a.map(m=>({...m,id:++c}));p={...p,activitySeq:c,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function S$(i){const e=vv(s=>s.subscribe),t=vv(s=>s.unsubscribe),n=vv(s=>i?s.tabs[i.id]:void 0);return z.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 LC(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),s=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${s}h`:s>0?`${s}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 Bb(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function s0(i,e){const t=Bb(e);if(t==null)return`${i} — usage unavailable`;const n=LC((e==null?void 0:e.resets_at)??null),s=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${s} — click to open Home`}function fB(i,e){return i?i==="session"||i==="five_hour"?"Session · 5h":i==="weekly_all"?"Weekly · all models":i==="weekly_scoped"?"Weekly · scoped":i:null}const zC=z.createContext(null);function C$({panelId:i,children:e}){return d.jsx(zC.Provider,{value:i,children:e})}function Zv(i){const e=z.useContext(zC),t=i??e;return ji(n=>t==null||n.focusedPanelId===t)}function Kw(i){const e=Zv(i),t=z.useRef(e);return t.current=e,t}const k$=5e3;let md=null;const Gb=new Set;let N_=0,Kf=null;function E$(){Gb.forEach(i=>i())}async function jv(){try{md=await window.api.schedule.sessionSlots(),E$()}catch{}}const T$=0,D$=10;async function $$(i){md||await jv();const e=md?md.min:T$,t=md?md.max:D$,n=Math.min(t,Math.max(e,Math.round(i)));await window.api.schedule.setSessionSlots(n),await jv()}function A$(){Kf==null&&(jv(),Kf=setInterval(()=>{jv()},k$))}function I$(){Kf!=null&&(clearInterval(Kf),Kf=null)}function Yw(i){const e=Zv(i),[,t]=z.useState(0);return z.useEffect(()=>{const n=()=>t(s=>s+1);return Gb.add(n),()=>{Gb.delete(n)}},[]),z.useEffect(()=>{if(e)return N_+=1,A$(),()=>{N_-=1,N_<=0&&I$()}},[e]),md}const P$=360*60*1e3;let BC=null;const Fb=new Set;let M_=0,Yf=null;async function r0(){try{BC=await window.api.app.updateStatus(),Fb.forEach(i=>i())}catch{}}function j$(){Yf==null&&(r0(),Yf=setInterval(()=>{r0()},P$))}function R$(){Yf!=null&&(clearInterval(Yf),Yf=null)}function N$(){const[,i]=z.useState(0);return z.useEffect(()=>{const e=()=>i(t=>t+1);return Fb.add(e),M_+=1,j$(),()=>{Fb.delete(e),M_-=1,M_<=0&&R$()}},[]),BC}let GC=null;const Hb=new Set;let O_=0,_v=null,Wb=!1;function o0(i){GC=i,Hb.forEach(e=>e())}function M$(){Wb||(Wb=!0,_v=window.api.updater.onStatus(o0),window.api.updater.status().then(o0).catch(()=>{}))}function O$(){Wb=!1,_v&&(_v(),_v=null)}function L$(){const[,i]=z.useState(0);return z.useEffect(()=>{const e=()=>i(t=>t+1);return Hb.add(e),O_+=1,M$(),()=>{Hb.delete(e),O_-=1,O_<=0&&O$()}},[]),GC}function z$({total:i,inUse:e,size:t}){const n=Math.min(Math.max(e,0),i),s=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return d.jsx(d.Fragment,{children:Array.from({length:i},(l,p)=>d.jsx("span",{"data-testid":"slot-dot","data-filled":p<n?"true":"false",className:`${s} ${p<n?"bg-accent border-accent":"bg-bg border-line"}`},p))})}function B$({onNavigate:i}){const e=Ct(ce=>ce.tabs),t=Ct(ce=>ce.activeTabId),n=e.find(ce=>ce.id===t)??null,s=S$(n),l=(s==null?void 0:s.lastEventAt)??0,p=sm(ce=>ce.data),a=Wr(ce=>{var ve;return((ve=ce.snapshot)==null?void 0:ve.paused)??null}),c=qw((n==null?void 0:n.cwd)??null),f=Yw(),m=N$(),g=L$(),w=Ps(ce=>ce.show),[,D]=z.useState(0);z.useEffect(()=>{const ce=setInterval(()=>D(ve=>ve+1),6e4);return()=>clearInterval(ce)},[]);const k=async()=>{const ce=(g==null?void 0:g.latest)??"";try{const ve=await window.api.updater.install(!1),Ee=(ve==null?void 0:ve.status)??await window.api.updater.status();(Ee==null?void 0:Ee.state)==="deferred"&&w("info",`Update v${ce} will install when ${Ee.busyReason??"running jobs"} finish`)}catch(ve){w("error",ve instanceof Error?ve.message:String(ve))}},C=(s==null?void 0:s.todos)??[],[b,y]=z.useState(!1),x=z.useRef(null);z.useEffect(()=>{if(!b)return;const ce=ve=>{x.current&&!x.current.contains(ve.target)&&y(!1)};return document.addEventListener("mousedown",ce),()=>document.removeEventListener("mousedown",ce)},[b]),z.useEffect(()=>{C.length===0&&y(!1)},[C.length]);const S=MC(p),T=(S==null?void 0:S.usage.five_hour)??null,j=(S==null?void 0:S.usage.seven_day)??null,N=Bb(T),L=Bb(j),R=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",F=l>0?H$(Date.now()-l):"—",V=(f==null?void 0:f.total)??5,te=f?Math.min(Math.max(f.inUse,0),f.total):0,he=f?`${te} / ${V}`:`— / ${V}`,ee=f&&f.holders.length>0?`
2929
2929
  `+f.holders.slice(0,5).map(ce=>ce.owner).join(`
2930
- `):"",we=`${he} Claude sessions running${ee}`;return d.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:[d.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:R?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:R?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:s0("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:N!=null?`${N}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:s0("Weekly window (all models)",j),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:L!=null?`${L}%`:"—"})]}),a&&d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&d.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,c&&d.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),d.jsxs("span",{className:"text-fg-faint",children:["last activity: ",d.jsx("span",{className:"text-fg-dim",children:F})]}),C.length>0&&d.jsx(G$,{ref:x,todos:C,open:b,onToggle:()=>y(ce=>!ce)}),d.jsx("span",{className:"flex-1"}),d.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:we,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(z$,{total:V,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),(g==null?void 0:g.state)==="ready"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",g.latest]}):(g==null?void 0:g.state)==="deferred"?d.jsxs("span",{className:"text-amber-300",title:`Waiting for ${g.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",g.latest," installs when idle"]}):(g==null?void 0:g.state)==="downloading"?d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",g.latest,"…"]}):m!=null&&m.behind&&m.latest&&m.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${m.current} → v${m.latest}`,"data-testid":"footer-version",onClick:()=>{const ce=m.downloadUrl;ce&&window.api.shell.open({as:"external",url:ce}).catch(()=>{w("error",`Couldn't open URL: ${ce}`)})},children:["Download v",m.latest]}):m!=null&&m.behind&&m.latest?d.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",m.current," → v",m.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(m==null?void 0:m.current)??"0.122.0"]})]})}const G$=z.forwardRef(function({todos:e,open:t,onToggle:n},s){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 d.jsxs("div",{ref:s,className:"relative",children:[d.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:[d.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),d.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),d.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),d.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&d.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 ${dn.dialog}`,"data-testid":"footer-todos-popover",children:d.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>d.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[d.jsx(F$,{status:p.status}),d.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 F$({status:i}){return i==="completed"?d.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?d.jsx("span",{className:"w-3 shrink-0",children:d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):d.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function H$(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function W$({onClose:i,onSent:e}){const t=Ct(L=>L.tabs),[n,s]=z.useState(""),[l,p]=z.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,c]=z.useState(!1),[f,m]=z.useState({}),g=z.useRef(null),w=z.useRef(e);z.useEffect(()=>{w.current=e},[e]),z.useEffect(()=>{p(L=>{const R={};for(const F of t)R[F.id]=L[F.id]??!0;return R})},[t]),z.useEffect(()=>{var L;(L=g.current)==null||L.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(R=>{m(F=>R.tabId in F?{...F,[R.tabId]:"skipped"}:F)}),[]),z.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(F=>F==="sent").length,R=window.setTimeout(()=>w.current(L),1500);return()=>window.clearTimeout(R)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,C=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!C,y=()=>{if(!b)return;c(!0);const L=Ct.getState().tabs,R=new Set(L.map(V=>V.id)),F={};for(const V of D)R.has(V)?(window.api.pty.write({tabId:V,data:n+"\r"}),F[V]="sent"):F[V]="skipped";m(F),c(!1)},x=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),y())},S=t.length>0&&t.every(L=>l[L.id]),T=()=>{const L=!S;p(Object.fromEntries(t.map(R=>[R.id,L])))},j=Object.values(f).some(L=>L==="skipped"),N=C?j?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return d.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),d.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),d.jsx("textarea",{ref:g,value:n,onChange:L=>s(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"}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:S,onChange:T,className:"accent-accent"}),d.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),d.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>d.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:R=>p(F=>({...F,[L.id]:R.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),d.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[d.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"}),d.jsx("button",{onClick:y,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 U$({tabId:i,cwd:e,onClose:t}){const n=Wf(k=>k.watchersForTab(i)),s=Wf(k=>k.add),l=Wf(k=>k.remove),p=z.useRef(null),[a,c]=z.useState(""),[f,m]=z.useState(""),[g,w]=z.useState(!1);z.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),z.useEffect(()=>{const k=C=>{p.current&&!p.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||g)return;w(!0);const C=await s({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),C&&(c(""),m(""))};return d.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:[d.jsxs("div",{className:"flex items-center mb-2",children:[d.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),d.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),d.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[d.jsx("input",{value:a,onChange:k=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("input",{value:f,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),d.jsx("button",{onClick:D,disabled:!f.trim()||g,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"})]}),d.jsxs("span",{className:"text-fg-faint",children:["cwd: ",d.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?d.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):d.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const C=k.lines[k.lines.length-1];return d.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),d.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),d.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),d.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:d.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
2930
+ `):"",we=`${he} Claude sessions running${ee}`;return d.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:[d.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:R?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:R?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:s0("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:N!=null?`${N}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:s0("Weekly window (all models)",j),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:L!=null?`${L}%`:"—"})]}),a&&d.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:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&d.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,c&&d.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),d.jsxs("span",{className:"text-fg-faint",children:["last activity: ",d.jsx("span",{className:"text-fg-dim",children:F})]}),C.length>0&&d.jsx(G$,{ref:x,todos:C,open:b,onToggle:()=>y(ce=>!ce)}),d.jsx("span",{className:"flex-1"}),d.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:we,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(z$,{total:V,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),(g==null?void 0:g.state)==="ready"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",g.latest]}):(g==null?void 0:g.state)==="deferred"?d.jsxs("span",{className:"text-amber-300",title:`Waiting for ${g.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",g.latest," installs when idle"]}):(g==null?void 0:g.state)==="downloading"?d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",g.latest,"…"]}):m!=null&&m.behind&&m.latest&&m.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${m.current} → v${m.latest}`,"data-testid":"footer-version",onClick:()=>{const ce=m.downloadUrl;ce&&window.api.shell.open({as:"external",url:ce}).catch(()=>{w("error",`Couldn't open URL: ${ce}`)})},children:["Download v",m.latest]}):m!=null&&m.behind&&m.latest?d.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",m.current," → v",m.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(m==null?void 0:m.current)??"0.122.1"]})]})}const G$=z.forwardRef(function({todos:e,open:t,onToggle:n},s){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 d.jsxs("div",{ref:s,className:"relative",children:[d.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:[d.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),d.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),d.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),d.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&d.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 ${dn.dialog}`,"data-testid":"footer-todos-popover",children:d.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>d.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[d.jsx(F$,{status:p.status}),d.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 F$({status:i}){return i==="completed"?d.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?d.jsx("span",{className:"w-3 shrink-0",children:d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):d.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function H$(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function W$({onClose:i,onSent:e}){const t=Ct(L=>L.tabs),[n,s]=z.useState(""),[l,p]=z.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,c]=z.useState(!1),[f,m]=z.useState({}),g=z.useRef(null),w=z.useRef(e);z.useEffect(()=>{w.current=e},[e]),z.useEffect(()=>{p(L=>{const R={};for(const F of t)R[F.id]=L[F.id]??!0;return R})},[t]),z.useEffect(()=>{var L;(L=g.current)==null||L.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(R=>{m(F=>R.tabId in F?{...F,[R.tabId]:"skipped"}:F)}),[]),z.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(F=>F==="sent").length,R=window.setTimeout(()=>w.current(L),1500);return()=>window.clearTimeout(R)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,C=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!C,y=()=>{if(!b)return;c(!0);const L=Ct.getState().tabs,R=new Set(L.map(V=>V.id)),F={};for(const V of D)R.has(V)?(window.api.pty.write({tabId:V,data:n+"\r"}),F[V]="sent"):F[V]="skipped";m(F),c(!1)},x=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),y())},S=t.length>0&&t.every(L=>l[L.id]),T=()=>{const L=!S;p(Object.fromEntries(t.map(R=>[R.id,L])))},j=Object.values(f).some(L=>L==="skipped"),N=C?j?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return d.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),d.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),d.jsx("textarea",{ref:g,value:n,onChange:L=>s(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"}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:S,onChange:T,className:"accent-accent"}),d.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),d.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>d.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:R=>p(F=>({...F,[L.id]:R.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),d.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[d.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"}),d.jsx("button",{onClick:y,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 U$({tabId:i,cwd:e,onClose:t}){const n=Wf(k=>k.watchersForTab(i)),s=Wf(k=>k.add),l=Wf(k=>k.remove),p=z.useRef(null),[a,c]=z.useState(""),[f,m]=z.useState(""),[g,w]=z.useState(!1);z.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),z.useEffect(()=>{const k=C=>{p.current&&!p.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||g)return;w(!0);const C=await s({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),C&&(c(""),m(""))};return d.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:[d.jsxs("div",{className:"flex items-center mb-2",children:[d.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),d.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),d.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[d.jsx("input",{value:a,onChange:k=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("input",{value:f,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),d.jsx("button",{onClick:D,disabled:!f.trim()||g,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"})]}),d.jsxs("span",{className:"text-fg-faint",children:["cwd: ",d.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?d.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):d.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const C=k.lines[k.lines.length-1];return d.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),d.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),d.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),d.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:d.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
2931
2931
  * dockview-core
2932
2932
  * @version 6.6.1
2933
2933
  * @link https://github.com/mathuo/dockview
@@ -3032,7 +3032,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3032
3032
 
3033
3033
  ${t}`}const Ff={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},qM=["popover","review","diff"],EE=["popover","review"];function KM(i,e){switch(e.type){case"SELECT":return{...Ff,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Ff,editCount:i.editCount};case"LISTEN":return EE.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 qM.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:{...Ff,editCount:i.editCount+1};case"RESET_FILE":return{...Ff,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function YM(i,e){let t=null;for(const n of e){const s=n.cwd;!s||!(i===s||i.startsWith(s.endsWith("/")?s:`${s}/`))||(t===null||s.length>t.length)&&(t=s)}return t}function XM(i,e,t){var l;let n=null,s=-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>s)&&(n=p,s=a)}return n}const JM="sonnet";function ZM(i,e){const[t,n]=z.useReducer(KM,Ff),s=z.useRef(0),l=z.useRef(null),p=z.useRef(i),a=z.useRef(new Map);z.useEffect(()=>window.api.docEdit.onSessionResult(S=>{const T=a.current.get(S.requestId);T&&(a.current.delete(S.requestId),T(S))}),[]),z.useEffect(()=>{p.current!==i&&(p.current=i,s.current+=1,c(),n({type:"RESET_FILE"}))},[i]);function c(){const S=l.current;S&&(l.current=null,S.stop().catch(()=>{}),S.destroy(),kt.setState({externalRecording:!1}))}const f=z.useCallback(S=>{s.current+=1,c(),n({type:"SELECT",selection:S})},[]),m=z.useCallback(()=>{s.current+=1,c(),n({type:"CANCEL"})},[]),g=z.useCallback(()=>{if(!EE.includes(t.phase))return;if(kt.getState().isRecording){Qe.error("Microphone is already in use");return}if(!Jv()){Qe.error("Microphone or Web Worker not available");return}const S=++s.current;n({type:"LISTEN"}),kt.setState({externalRecording:!0});const T=()=>{l.current===j&&(l.current=null),kt.setState({externalRecording:!1})},j=PC({onFinal:N=>{if(s.current!==S)return;j.stop().catch(()=>{}),j.destroy(),T();const L=N.trim();if(!L){n({type:"CANCEL"});return}n({type:"HEARD",transcript:L})},onError:N=>{s.current===S&&(j.destroy(),T(),Qe.error(`Microphone error: ${N}`),n({type:"CANCEL"}))},onModelStatus:(N,L)=>{s.current===S&&n({type:"MODEL_STATUS",status:N,message:L})},onProgress:N=>{s.current===S&&n({type:"MODEL_STATUS",status:"loading",message:`${N}%`})}});l.current=j,j.start().catch(N=>{s.current===S&&(j.destroy(),T(),Qe.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),w=z.useCallback(()=>{const S=YM(i,Ct.getState().tabs);if(!S)return null;const T=XM(S,Ct.getState().tabs,vv.getState().tabs);return!T||pi.getState().get(T.id).running?null:T},[i]),D=z.useCallback((S,T,j,N,L,R)=>{const F=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(V=>{a.current.set(F,V),window.api.docEdit.runInSession({tabId:S,sessionId:T,cwd:j,before:N,instruction:L,documentText:R,requestId:F})})},[]),k=z.useCallback(async(S,T)=>{const j=t.selection;if(!j)return;const N=++s.current;n({type:"RUN",instruction:S,recordInstruction:T});const L=VM(e);try{const R=w(),F=R?await D(R.id,R.sessionId,R.cwd,j.text,S,L):await window.api.docEdit.run({path:i,before:j.text,instruction:S,documentText:L});if(s.current!==N)return;if(!F.ok){Qe.error(F.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:j.text,after:F.after??""}})}catch(R){if(s.current!==N)return;Qe.error(R instanceof Error?R.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,w,D]),C=z.useCallback(S=>{k(S,!0)},[k]),b=z.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),y=z.useCallback(()=>{const S=t.instruction;S&&k(`${S}
3034
3034
 
3035
- (Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),x=z.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const j=WM(S,T.before,T.after);return j.ok?(s.current+=1,n({type:"ACCEPT"})):Qe.error(j.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),j},[t.diff]);return{state:t,select:f,cancel:m,listen:g,sendHeard:b,run:C,retry:y,accept:x}}async function Ca(i){try{const e=await window.api.clipboard.writeText(i);return(e==null?void 0:e.ok)===!0}catch{return!1}}const QM=[{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."}],kS=320,Af=8;function eO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function tO(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Af),Math.max(Af,e-kS-Af)),n=Math.max(i.top-Af,Af);return{position:"fixed",left:t,top:n,width:kS,transform:"translateY(-100%)",zIndex:Z2.dialog}}function iO({phase:i,rect:e,selectedText:t,diff:n,transcript:s,modelStatus:l,onQuickAction:p,onRunCustom:a,onListen:c,onSendHeard:f,onCancel:m,onAccept:g,onReject:w,onRetry:D}){const[k,C]=z.useState(""),[b,y]=z.useState(!1),x=Ps(N=>N.show),S=z.useRef(null);z.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await Ca(t)){x("error","Copy failed");return}y(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>y(!1),1500)},j=()=>{const N=k.trim();N&&(a(N),C(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:tO(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&d.jsxs("div",{className:"p-2",children:[d.jsxs("div",{className:"flex items-center justify-between mb-2",children:[d.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:b?"Copied":"Copy"}),d.jsx("button",{onClick:c,"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"}),QM.map(N=>d.jsx("button",{onClick:()=>p(N.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:N.label},N.label))]}),d.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{value:k,onChange:N=>C(N.target.value),onKeyDown:N=>{N.key==="Enter"?j():N.key==="Escape"&&m()},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"&&d.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[d.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(eO,{}),"Listening…"]}),l&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:l})]}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsxs("div",{className:"p-3 flex items-center justify-between",children:[d.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&d.jsxs("div",{className:"p-3",children:[d.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:D,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function nO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function ES({phase:i,transcript:e,diff:t,editCount:n,modelStatus:s,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:m}){return d.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[d.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[d.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),d.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:rm(JM)})]}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&d.jsxs("div",{className:"text-fg-faint",children:[d.jsx("p",{children:"Select text in the doc…"}),d.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&d.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&d.jsxs("div",{children:[d.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[d.jsx(nO,{}),"Listening…"]}),s&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),d.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"&&d.jsxs("div",{children:[d.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&d.jsxs("div",{children:[d.jsxs("div",{className:"mb-3 space-y-2",children:[d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function sO(){const i=Ct(t=>t.tabs),e=Ct(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function rO({path:i,onRenamed:e,onDeleted:t}){const[n,s]=z.useState(!1),[l,p]=z.useState(!1),[a,c]=z.useState(""),[f,m]=z.useState(!1),g=Ci(V=>V.buffers[i]),w=Ci(V=>V.openFile),D=Ci(V=>V.renameOpenFile),k=Ci(V=>V.closeFile),C=sO(),b=wa(i),y=()=>s(!1),x=()=>{c(b),p(!0),y()},S=async()=>{const V=a.trim();if(!V||V===b){p(!1);return}try{const te=await window.api.files.rename(i,V);if(te.ok){const he=i.slice(0,i.lastIndexOf("/")),ee=te.newPath??`${he}/${V}`;D(i,ee),e==null||e(i,ee),Qe.info(`Renamed to ${V}`)}else Qe.error(te.error??`Couldn't rename ${b}`)}catch(te){Qe.error(te instanceof Error?te.message:`Couldn't rename ${b}`)}p(!1)},T=async()=>{y();try{const V=await window.api.files.duplicate(i);V.ok&&V.path?(w(V.path),Qe.info(`Duplicated as ${wa(V.path)}`)):Qe.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Qe.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},j=async()=>{try{const V=await window.api.files.delete(i);V.ok?(k(i),t==null||t(i),Qe.info(`Deleted ${b}`)):Qe.error(V.error??`Couldn't delete ${b}`)}catch(V){Qe.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},N=async()=>{y();const V=g??"";await Ca(V)?Qe.info(`Copied ${V.length} chars`):Qe.error(`Couldn't copy ${b}`)},L=()=>{if(y(),!C){Qe.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Qe.info(`Added ${b} to Claude context`)},R=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(V=>{V.ok||Qe.error(V.error??`Couldn't open ${b}`)}).catch(V=>Qe.error(V instanceof Error?V.message:`Couldn't open ${b}`))},F=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(V=>{V.ok||Qe.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Qe.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>s(V=>!V),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&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuScrim}`,onMouseDown:y}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${dn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(ib,{children:"Edit"}),d.jsx(ud,{label:"Rename",onClick:x}),d.jsx(ud,{label:"Duplicate",onClick:T}),d.jsx(ud,{label:"Delete document",danger:!0,onClick:()=>{y(),m(!0)}}),d.jsx(TS,{}),d.jsx(ib,{children:"Open"}),d.jsx(ud,{label:"Open in default app",onClick:R}),d.jsx(ud,{label:"Reveal in OS",onClick:F}),d.jsx(TS,{}),d.jsx(ib,{children:"Export"}),d.jsx(ud,{label:"Copy as Markdown",onClick:N}),d.jsx(ud,{label:"Add to Claude context",onClick:L,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(oO,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void S()}),f&&d.jsx(aO,{name:b,onCancel:()=>m(!1),onConfirm:()=>void j()})]})}function ib({children:i}){return d.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function ud({label:i,onClick:e,danger:t,disabled:n,title:s}){return d.jsx("button",{onClick:e,disabled:n,title:s,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 TS(){return d.jsx("div",{className:"my-1 border-t border-line"})}function oO({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),d.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?n():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function aO({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function lO(){const[i,e]=z.useState(!1),t=_d();return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.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&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${dn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(mh,{label:"Text size",children:d.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[d.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−"}),d.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),d.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+"})]})}),d.jsx(mh,{label:"Word wrap",children:d.jsx(iv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(mh,{label:"Minimap",children:d.jsx(iv,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(mh,{label:"Theme",children:d.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"})}),d.jsx(mh,{label:"Autosave",children:d.jsx(iv,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(mh,{label:"Wide measure",children:d.jsx(iv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function mh({label:i,children:e}){return d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-fg-faint",children:i}),e]})}function iv({on:i,onClick:e}){return d.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 cO=z.lazy(()=>mi(()=>import("./TiptapBody-C4kIvIMH.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function nv(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[s,l]of Object.entries(i))t.has(s)||(n[s]=l);return n}function sv(i){return Xk(i)||Jk(i)}function dO(){const i=Kw(),e=Ci(Je=>Je.openFiles),t=Ci(Je=>Je.activeFilePath),n=Ci(Je=>Je.dirty),s=Ci(Je=>Je.viewMode),l=Ci(Je=>Je.buffers),p=Ci(Je=>Je.setActive),a=Ci(Je=>Je.closeFile),c=Ci(Je=>Je.closeOthers),f=Ci(Je=>Je.closeToTheRight),m=Ci(Je=>Je.closeAll),g=Ci(Je=>Je.loadBuffer),w=Ci(Je=>Je.setBuffer),D=Ci(Je=>Je.markSaved),k=Ci(Je=>Je.setViewMode),C=_d(),[b,y]=z.useState({}),[x,S]=z.useState({}),[T,j]=z.useState(null),[N,L]=z.useState(null),[R,F]=z.useState(!1),[V,te]=z.useState(!1),[he,ee]=z.useState(!0),we=z.useRef(null),ce=z.useRef(null),ve=z.useRef(void 0),Ee=z.useRef(null),fe=z.useRef(null),U=ZM(t??"",l[t??""]??""),X=z.useCallback(Je=>{we.current=Je},[]),W=z.useCallback(()=>we.current,[]);z.useEffect(()=>{Fj()},[]),z.useEffect(()=>{const Je=t;if(!Je||sv(Je))return;if(Ci.getState().hasBuffer(Je)){y(_t=>_t[Je]==="ready"?_t:{..._t,[Je]:"ready"});return}let Pt=!1;return y(_t=>({..._t,[Je]:"loading"})),window.api.files.read(Je).then(_t=>{Pt||(_t.binary?y(hi=>({...hi,[Je]:{binary:!0,size:_t.size??0,mime:_t.mime??"application/octet-stream",reason:_t.error??"Binary file"}})):_t.ok?(g(Je,_t.text),y(hi=>({...hi,[Je]:"ready"}))):y(hi=>({...hi,[Je]:{error:_t.error??"failed to read"}})))}),()=>{Pt=!0}},[t,g]),z.useEffect(()=>{L(null)},[t]);const Q=z.useCallback(async(Je,Pt=!1)=>{const _t=Ci.getState().buffers[Je];if(_t==null)return;Pt&&F(!0);const hi=await window.api.files.write(Je,_t);hi.ok?(D(Je),S(Se=>({...Se,[Je]:(Se[Je]??0)+1})),Pt||Qe.info(`Saved ${wa(Je)}`)):Qe.error(hi.error??`Couldn't save ${wa(Je)}`),Pt&&F(!1)},[D]);z.useEffect(()=>{if(!C.autosave)return;const Je=t;if(!(!Je||sv(Je)||!n[Je]))return window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{Q(Je,!0)},1200),()=>window.clearTimeout(ve.current)},[C.autosave,t,n,l,Q]);const oe=z.useCallback(Je=>{Je.length&&(y(Pt=>nv(Pt,Je)),S(Pt=>nv(Pt,Je)))},[]),Ce=z.useCallback((Je,Pt)=>{y(_t=>Je in _t?{...nv(_t,[Je]),[Pt]:_t[Je]}:_t),S(_t=>Je in _t?{...nv(_t,[Je]),[Pt]:_t[Je]}:_t)},[]),Oe=z.useCallback(Je=>{n[Je]?j({kind:"one",path:Je}):(a(Je),oe([Je]))},[n,a,oe]),Xe=z.useCallback(Je=>{e.some(_t=>_t.path!==Je&&n[_t.path])?j({kind:"others",path:Je}):(c(Je),oe(e.filter(_t=>_t.path!==Je).map(_t=>_t.path)))},[e,n,c,oe]),ge=z.useCallback(Je=>{const Pt=e.findIndex(hi=>hi.path===Je);Pt!==-1&&e.slice(Pt+1).some(hi=>n[hi.path])?j({kind:"right",path:Je}):(f(Je),oe(Pt!==-1?e.slice(Pt+1).map(hi=>hi.path):[]))},[e,n,f,oe]);z.useEffect(()=>{const Je=Pt=>{if(i.current)if((Pt.metaKey||Pt.ctrlKey)&&(Pt.key==="s"||Pt.key==="S")){const _t=Ci.getState().activeFilePath;_t&&!sv(_t)&&(Pt.preventDefault(),Q(_t))}else if((Pt.metaKey||Pt.ctrlKey)&&Pt.shiftKey&&(Pt.key==="f"||Pt.key==="F"))Pt.preventDefault(),te(_t=>!_t);else if((Pt.metaKey||Pt.ctrlKey)&&Pt.shiftKey&&(Pt.key==="w"||Pt.key==="W")){const _t=Ci.getState().activeFilePath;_t&&Ci.getState().openFiles.length>1&&(Pt.preventDefault(),Xe(_t))}else Pt.key==="Escape"&&U.state.phase!=="idle"?U.cancel():Pt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[Q,V,Xe,U.state.phase,U.cancel]),z.useEffect(()=>{if(U.state.phase==="idle")return;const Je=Pt=>{var hi,Se;const _t=Pt.target;(hi=fe.current)!=null&&hi.contains(_t)||(Se=Ee.current)!=null&&Se.contains(_t)||U.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[U.state.phase,U.cancel]),z.useEffect(()=>{U.cancel()},[t,U.cancel]);const J=z.useCallback(()=>{e.some(Pt=>n[Pt.path])?j({kind:"all",path:""}):(m(),y({}),S({}))},[e,n,m]),je=()=>{if(T){if(T.kind==="one")a(T.path),oe([T.path]);else if(T.kind==="others"){const Je=e.filter(Pt=>Pt.path!==T.path).map(Pt=>Pt.path);c(T.path),oe(Je)}else if(T.kind==="right"){const Je=e.findIndex(_t=>_t.path===T.path),Pt=Je!==-1?e.slice(Je+1).map(_t=>_t.path):[];f(T.path),oe(Pt)}else m(),y({}),S({});j(null)}};if(e.length===0)return d.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:d.jsxs("div",{className:"text-center",children:[d.jsx("div",{className:"mb-2",children:"no file open"}),d.jsxs("div",{children:["open the ",d.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const de=t,Ie=de?wa(de):"",Pe=de?b[de]:void 0,Ye=de?eE(de):!1,ft=de?Lj(de):!1,rt=de&&Ye?s[de]??zj(de):"edit",Nt=!!de&&!sv(de)&&Pe==="ready",mt=Nt,gi=ft?["edit","wysiwyg","preview","split"]:Ye?["edit","preview"]:[],di=de&&d.jsx(pN,{path:de,name:Ie,value:l[de]??"",onChange:Je=>w(de,Je),onSave:()=>void Q(de),onReady:X,onCursor:L}),_i=R?"Saving…":de&&n[de]?C.autosave?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&d.jsx(tR,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Oe,onCloseOthers:Xe,onCloseToTheRight:ge,onCloseAll:J}),de&&!V&&d.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[d.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ie}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:de}),Nt&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",_i]}),nl(de)&&(rt==="preview"||rt==="split")&&d.jsx("button",{onClick:()=>ee(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${he?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),nl(de)&&(rt==="preview"||rt==="split")&&d.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),gi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:gi.map(Je=>d.jsx("button",{onClick:()=>k(de,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${rt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),d.jsx("div",{className:"flex-1"}),d.jsx(rO,{path:de,onRenamed:Ce,onDeleted:Je=>oe([Je])}),Nt&&d.jsx(lO,{}),d.jsx("button",{onClick:()=>te(!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"})]}),V&&d.jsx("button",{onClick:()=>te(!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"}),d.jsx("div",{className:"flex-1 min-h-0",children:de?Xk(de)?d.jsx(MM,{path:de,name:Ie}):Jk(de)?d.jsx(OM,{path:de}):Pe&&typeof Pe=="object"&&"binary"in Pe?d.jsx(HM,{path:de,name:Ie,size:Pe.size,mime:Pe.mime,reason:Pe.reason}):Pe&&typeof Pe=="object"&&"error"in Pe?d.jsx("div",{className:"p-6 text-xs text-red-400",children:Pe.error}):Pe!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):rt==="wysiwyg"&&nl(de)?d.jsx(z.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(cO,{value:l[de]??"",onChange:Je=>w(de,Je)},de)}):rt==="split"&&nl(de)?d.jsxs("div",{className:"flex h-full",children:[he&&d.jsx(xS,{text:l[de]??"",scrollRef:ce}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(yS,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:di})]}),d.jsx("div",{ref:Ee,className:"flex-1 min-w-0",children:d.jsx(fw,{ref:ce,text:l[de]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!V&&C.assistantRail&&d.jsx(ES,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)},onReject:U.cancel,onRetry:U.retry})]}):rt==="preview"&&nl(de)?d.jsxs("div",{className:"flex h-full",children:[he&&d.jsx(xS,{text:l[de]??"",scrollRef:ce}),d.jsx("div",{ref:Ee,className:"flex-1 min-w-0",children:d.jsx(fw,{ref:ce,text:l[de]??"",wideMeasure:C.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!V&&C.assistantRail&&d.jsx(ES,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)},onReject:U.cancel,onRetry:U.retry})]}):rt==="preview"&&Yk(de)?d.jsx(RM,{path:de,dirty:!!n[de],reloadToken:x[de]??0}):rt==="preview"&&Zk(de)?d.jsx(zM,{path:de,text:l[de]??""}):rt==="preview"&&Qk(de)?d.jsx(FM,{path:de,text:l[de]??""}):nl(de)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(yS,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:di})]}):di:null}),mt&&d.jsx(jM,{text:l[de]??"",cursor:N,language:Ur(de)||void 0}),de&&nl(de)&&(rt==="preview"||rt==="split")&&U.state.phase!=="idle"&&U.state.selection&&d.jsx("div",{ref:fe,children:d.jsx(iO,{phase:U.state.phase,rect:U.state.selection.rect,selectedText:U.state.selection.text,diff:U.state.diff,transcript:U.state.transcript,modelStatus:U.state.modelStatus,onQuickAction:U.run,onRunCustom:U.run,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onReject:U.cancel,onRetry:U.retry,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)}})}),T&&d.jsx(uO,{message:T.kind==="one"?`Discard unsaved changes to ${wa(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>j(null),onConfirm:je})]})}const vw=z.memo(dO);function uO({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const hO={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},DS='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function a_({open:i,onClose:e,children:t,title:n,size:s="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&d.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),d.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const c=z.useRef(null),f=z.useRef(null),m=z.useRef(e);if(m.current=e,z.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=c.current;if(!b)return;const y=b.querySelector(DS);y?y.focus():b.focus()},0),C=b=>{if(b.key==="Escape"){b.stopPropagation(),m.current();return}if(b.key==="Tab"){const y=c.current;if(!y)return;const x=Array.from(y.querySelectorAll(DS)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(x.length===0){b.preventDefault(),y.focus();return}const S=x[0],T=x[x.length-1],j=document.activeElement;b.shiftKey?(j===S||!y.contains(j))&&(b.preventDefault(),T.focus()):(j===T||!y.contains(j))&&(b.preventDefault(),S.focus())}};return document.addEventListener("keydown",C),()=>{clearTimeout(k),document.removeEventListener("keydown",C);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const g=D=>{D.target===D.currentTarget&&e()},w=d.jsx("div",{className:`fixed inset-0 ${dn.dialog} flex items-center justify-center bg-black/60`,onClick:g,"data-testid":"modal-backdrop",children:d.jsxs("div",{ref:c,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 ${hO[s]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?d.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?d.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Dh.createPortal(w,document.body):w}class TE extends z.Component{constructor(){super(...arguments);Gi(this,"state",{error:null});Gi(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):d.jsxs("div",{className:"p-6 text-xs",children:[d.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),d.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),d.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 pO({open:i,onClose:e,title:t,children:n,variant:s="overlay"}){return d.jsxs(a_,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&d.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[d.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),d.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:"✕"})]}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(TE,{children:n})})]})}function DE(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (on-device, 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 $S=i=>Symbol.iterator in i,AS=i=>"entries"in i,IS=(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[s,l]of t)if(!n.has(s)||!Object.is(l,n.get(s)))return!1;return!0},fO=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let s=t.next(),l=n.next();for(;!s.done&&!l.done;){if(!Object.is(s.value,l.value))return!1;s=t.next(),l=n.next()}return!!s.done&&!!l.done};function mO(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:$S(i)&&$S(e)?AS(i)&&AS(e)?IS(i,e):fO(i,e):IS({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function xy(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return mO(e.current,n)?e.current:e.current=n}}let PS=0;const gO=1e3;function vO(i){const e=performance.now();e-PS<gO||(PS=e,ut.debug("voice","mic.gate.click_rejected",{reason:i}))}function _O(){const i=kt(f=>f.isRecording),e=kt(f=>f.error),t=kt(f=>f.loadingProgress),n=kt(xy(Pv)),s=()=>{const f=kt.getState(),{canRecord:m,reason:g}=Pv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(g==="error"||g==="load-timeout"){f.resetAndRetryModel();return}if(!m)return vO(g);const w=Ct.getState().activeTabId;w&&f.startRecording(w)},l=DE(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,c=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 d.jsx("button",{onClick:s,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 ${c}`,children:d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),d.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),d.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),d.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function bO(){const i=kt(t=>t.ttsEnabled),e=kt(t=>t.toggleTTS);return d.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:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?d.jsxs(d.Fragment,{children:[d.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),d.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),d.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),d.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function wO(i){return/^monitor of /i.test(i.trim())}function jS(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function RS(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 s=jS(e),l=t.filter(p=>p.label&&jS(p.label)===s);return l.length===1?l[0]:null}async function NS(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&wO(n.label))):[]}const MS=!1;function $E(){const i=kt(f=>f.isRecording);kt(f=>f.startRecording),kt(f=>f.stopRecording);const[e,t]=z.useState([]),[n,s]=z.useState(null),[l,p]=z.useState(null);z.useEffect(()=>{let f=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(f)return;const g=await NS(MS);if(f)return;t(g),p(m.selectedLabel);const w=RS(m.selectedDeviceId,m.selectedLabel,g);w?(s(w.deviceId),m.selectedDeviceId&&w.deviceId!==m.selectedDeviceId&&(ut.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ut.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ut.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{f=!0}},[]);const a=z.useCallback(async()=>{try{const f=await NS(MS);if(t(f),n&&!f.some(m=>m.deviceId===n)){const m=RS(null,l,f);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||l}).catch(()=>{})):s(null)}}catch(f){ut.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);z.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const c=async f=>{var D;const m=f.target.value,g=m===""?null:m,w=g?((D=e.find(k=>k.deviceId===g))==null?void 0:D.label)??null:null;s(g),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:w}),ut.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(k){ut.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await kt.getState().restartWithDevice()}catch(k){ut.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return d.jsxs("select",{value:n??"",onChange:c,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:[d.jsx("option",{value:"",children:"Default"}),e.map(f=>d.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function yO(){const i=kt(D=>D.isRecording),e=kt(D=>D.levelMeterEnabled),[t,n]=z.useState(0),[s,l]=z.useState(0),p=z.useRef(0);p.current=s;const[a,c]=z.useState(0),[f,m]=z.useState(!1),g=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,C=null,b=null;const y=()=>{if(k)return;const S=b??NC();if(!S){D=requestAnimationFrame(y);return}b!==S&&(b=S,C=new Uint8Array(new ArrayBuffer(S.fftSize)));const T=C;S.getByteTimeDomainData(T);let j=0;for(let F=0;F<T.length;F++){const V=T[F]-128;j+=V*V}const N=Math.sqrt(j/T.length)/128,L=N>0?20*Math.log10(N):-60,R=Math.max(0,Math.min(1,(L+60)/60));l(N),n(R),N>=.95&&(m(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>m(!1),150)),D=requestAnimationFrame(y)};D=requestAnimationFrame(y);const x=setInterval(()=>{k||c(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(x),g.current&&(clearTimeout(g.current),g.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return d.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:d.jsx("div",{className:`h-full ${w} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function AE(){const i=kt(f=>f.submitCountdownStartAt),e=kt(f=>f.submitDelayMs),[t,n]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let f;const m=()=>{n(performance.now()),f=requestAnimationFrame(m)};return f=requestAnimationFrame(m),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const s=t-i,l=Math.max(0,e-s),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,c=kt.getState().cancelSubmit;return d.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:d.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:d.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function xO({open:i,onClose:e,variant:t="overlay"}){return d.jsx(pO,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:d.jsxs("div",{className:"p-4 space-y-4",children:[d.jsx(EO,{}),d.jsx(AE,{}),d.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[d.jsx(_O,{}),d.jsx($E,{}),d.jsx(bO,{})]}),d.jsx(SO,{}),d.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[d.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),d.jsx(kO,{})]}),d.jsx(yO,{})]})})}function SO(){const i=kt(l=>l.isRecording),[e,t]=z.useState(null);if(z.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",s=CO(e.accelerator);return d.jsxs("div",{className:"text-[11px] text-fg-faint",children:[d.jsxs("span",{children:[n," "]}),d.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),d.jsx("span",{children:" to record"})]})}function CO(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 kO(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>ut.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const s=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,s()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const s={...i,mode:n};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(l){ut.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return d.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:[d.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[d.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),d.jsx("span",{children:"Tap on/off"})]}),d.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[d.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),d.jsx("span",{children:"Hold to talk"})]})]})}function EO(){const i=kt(l=>l.isRecording),e=kt(l=>l.lastTranscript),t=kt(l=>l.error),n=kt(l=>l.modelStatus),s=kt(l=>l.loadingProgress);return t?d.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?d.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[d.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),d.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?d.jsxs("div",{className:"text-[11px] text-fg-faint",children:[d.jsxs("div",{className:"flex items-center justify-between mb-1",children:[d.jsx("span",{children:"Loading speech model"}),d.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),d.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:d.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}const IE="~/.claude/session-manager/projects-prefs.json";let OS=Promise.resolve(),rv=null;function LS(i){const e=OS.then(i);return OS=e.catch(()=>{}),e}async function zS(){const i=await window.api.config.readJson(IE);if(i.exists&&i.data&&typeof i.data=="object"){const e=i.data.pinned;if(e&&typeof e=="object")return{...e}}return{}}const nb=jn(i=>({pinned:{},hydrated:!1,hydrate:()=>rv||(rv=LS(async()=>{try{i({pinned:await zS(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),i({hydrated:!0})}}),rv),togglePin:e=>{LS(async()=>{let t;try{t=await zS()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Qe.error("Could not update pinned projects: the preferences file is unreadable.");return}const n={...t};n[e]?delete n[e]:n[e]=!0;try{await window.api.config.writeJson(IE,{pinned:n}),i({pinned:n})}catch(s){i({pinned:t}),Qe.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function TO(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function DO(i,e,t){const n=z.useRef(e);n.current=e;const s=Array.from(new Set(i.filter(p=>!!p).map(TO))),l=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;z.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const p=window.api.config.onChanged(a=>{s.includes(a.path)&&n.current(a.path)});return()=>{p(),window.api.config.unwatch(s,t)}},[l])}async function $O(i){const e=await ym(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function AO(i,e){return xd(i,{fileTreeExpanded:[...e].slice(0,500)})}async function IO(){const i=await Th();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function PO(i){mm({fileTreeShowHidden:i}).catch(()=>{})}function sb(i,e){const t=e+"/";let n=!1;const s=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}s.add(l)}return n?s:i}const rb={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:"!"}},jO=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 RO(i){const e=Ur(i);return jO.has(e)||Kk.has(e)||e==="pdf"}function NO(i,e){if(e)return"#d97757";switch(Ur(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 If(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}const BS=64,MO=250,OO={depth:0};function ob(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function LO({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const s=Kw(),l=Zv(),[p,a]=z.useState([]),[c,f]=z.useState(new Set),m=z.useRef(c);m.current=c;const g=z.useRef(!1),[w,D]=z.useState(""),[k,C]=z.useState(!0),b=z.useRef(!1);z.useEffect(()=>{let Se=!1;return IO().then(tt=>{!Se&&!b.current&&C(tt)}),()=>{Se=!0}},[]);const y=z.useCallback(Se=>{b.current=!0,C(tt=>{const ht=typeof Se=="function"?Se(tt):Se;return PO(ht),ht})},[]),[x,S]=z.useState(!1),[T,j]=z.useState(null),[N,L]=z.useState({}),[R,F]=z.useState(null),[V,te]=z.useState(null),[he,ee]=z.useState(""),[we,ce]=z.useState(null),[ve,Ee]=z.useState(""),[fe,U]=z.useState(null),X=z.useRef(null),W=z.useRef(null),Q=z.useRef(0),oe=z.useCallback(async()=>{if(!i)return;const Se=++Q.current;S(!0),j(null);const tt=await window.api.files.list(i,k);Q.current===Se&&(tt.ok?a(tt.entries.map(ht=>({...ht}))):(j(tt.error??"failed to list"),a([])),S(!1))},[i,k]),Ce=z.useCallback(async Se=>{const tt=Q.current,ht=new Map;for(const vi of Se){const Jt=vi.split("/").length,oi=ht.get(Jt);oi?oi.push(vi):ht.set(Jt,[vi])}const Et=[];for(const vi of[...ht.keys()].sort((Jt,oi)=>Jt-oi)){const Jt=ht.get(vi),oi=await Promise.all(Jt.map(async Xt=>({p:Xt,result:await window.api.files.list(Xt,k)})));if(Q.current!==tt)return Et;for(const{p:Xt,result:un}of oi)un.ok?a(wt=>wv(wt,Xt,un.entries.map(Ri=>({...Ri})))):Et.push(Xt)}return Et},[k]),Oe=z.useCallback(async Se=>(await oe(),Se.length?Ce(Se):[]),[oe,Ce]);z.useEffect(()=>{D(""),te(null),F(null),ce(null),U(null),L({});let Se=!1;return g.current=!1,(async()=>{const[tt]=await Promise.all([$O(i),oe()]);if(Se)return;if(!g.current){const Et=new Set(tt);m.current=Et,f(Et)}if(!tt.length)return;const ht=await Ce(tt);Se||!ht.length||Ye(Et=>{const vi=new Set;let Jt=!1;for(const oi of Et){if(ht.some(Xt=>oi===Xt||oi.startsWith(Xt+"/"))){Jt=!0;continue}vi.add(oi)}return Jt?vi:Et})})(),If(i).then(tt=>{Se||L(tt)}),()=>{Se=!0}},[i]);const Xe=z.useRef(!0);z.useEffect(()=>{if(Xe.current){Xe.current=!1;return}Oe([...m.current])},[k]),z.useEffect(()=>{if(!i||!l)return;If(i).then(L);const Se=window.setInterval(()=>{If(i).then(L)},5e3);return()=>window.clearInterval(Se)},[i,l]);const ge=z.useMemo(()=>{if(!i)return[];const Se=[...c].filter(tt=>tt!==i);return[i,...Se.slice(-63)]},[i,c]),J=z.useRef(!1);z.useEffect(()=>{!i||c.size+1<=BS||J.current||(J.current=!0,console.warn(`FileTree: watching only ${BS} of ${c.size+1} folders (cap reached)`))},[i,c]);const je=z.useRef(new Map),de=z.useRef(new Set),Ie=z.useRef(!1);Ie.current=V!==null||we!==null;const Pe=z.useRef(()=>{});Pe.current=Se=>{if(!(Se!==ob(i)&&!m.current.has(Se))){if(Ie.current){de.current.add(Se);return}Se===ob(i)?Oe([...m.current]):rt(Se)}},DO(ge,Se=>{if(Se!==ob(i)&&!m.current.has(Se))return;const tt=je.current,ht=tt.get(Se);ht&&clearTimeout(ht),tt.set(Se,setTimeout(()=>{tt.delete(Se),Pe.current(Se)},MO))},OO),z.useEffect(()=>{if(V!==null||we!==null)return;const Se=[...de.current];de.current.clear();for(const tt of Se)Pe.current(tt)},[V,we]),z.useEffect(()=>{const Se=je.current,tt=de.current;return()=>{for(const ht of Se.values())clearTimeout(ht);Se.clear(),tt.clear()}},[i]),z.useEffect(()=>{if(!R)return;const Se=()=>F(null),tt=ht=>{s.current&&ht.key==="Escape"&&F(null)};return window.addEventListener("mousedown",Se),window.addEventListener("keydown",tt),()=>{window.removeEventListener("mousedown",Se),window.removeEventListener("keydown",tt)}},[R]),z.useEffect(()=>{V&&setTimeout(()=>{var Se;return(Se=X.current)==null?void 0:Se.select()},30)},[V]),z.useEffect(()=>{we&&setTimeout(()=>{var Se;return(Se=W.current)==null?void 0:Se.focus()},30)},[we]);const Ye=z.useCallback(Se=>{const tt=m.current,ht=Se(tt);ht!==tt&&(g.current=!0,m.current=ht,f(ht),AO(i,ht).catch(()=>{m.current===ht&&(m.current=tt,f(tt),Qe.error("Couldn't save folder expansion — reverted."))}))},[i]),ft=z.useCallback(async Se=>{if(c.has(Se.path)){Ye(ht=>sb(ht,Se.path));return}if(Ye(ht=>new Set(ht).add(Se.path)),Se.children)return;const tt=await window.api.files.list(Se.path,k);tt.ok&&a(ht=>wv(ht,Se.path,tt.entries.map(Et=>({...Et}))))},[c,k,Ye]),rt=z.useCallback(async Se=>{if(Se===i){await oe();return}const tt=await window.api.files.list(Se,k);tt.ok&&a(ht=>wv(ht,Se,tt.entries.map(Et=>({...Et}))))},[i,oe,k]),Nt=z.useCallback(Se=>{if(Se.isDirectory){ft(Se);return}RO(Se.name)&&e?e(Se.path):window.api.shell.open({as:"openPath",path:Se.path})},[ft,e]),mt=z.useCallback(Se=>{if(t){t(Se);return}if(n){const tt=Se.startsWith(i+"/")?Se.slice(i.length+1):Se;window.api.pty.write({tabId:n,data:`@${tt} `})}},[t,n,i]),gi=z.useCallback((Se,tt)=>{Se.preventDefault(),Se.stopPropagation(),F({x:Se.clientX,y:Se.clientY,node:tt})},[]),di=Se=>{te(Se.path),ee(Se.name)},_i=async()=>{if(!V)return;const Se=he.trim();if(!Se){te(null);return}const tt=await window.api.files.rename(V,Se);if(te(null),tt.ok){const ht=V.slice(0,V.lastIndexOf("/"));Ye(Et=>sb(Et,V)),await rt(ht||i),If(i).then(L)}else{const ht=tt.error??"rename failed";j(ht),Qe.error(ht)}},Je=async()=>{if(!we)return;const Se=ve.trim();if(!Se){ce(null),Ee("");return}const tt=await window.api.files.create(we.parent,Se,we.kind);if(ce(null),Ee(""),tt.ok)await rt(we.parent),we.kind==="folder"&&Ye(ht=>new Set(ht).add(we.parent));else{const ht=tt.error??"create failed";j(ht),Qe.error(ht)}},Pt=async()=>{if(!fe)return;const Se=await window.api.files.delete(fe.path),tt=fe.path.slice(0,fe.path.lastIndexOf("/"));if(U(null),Se.ok)Ye(ht=>sb(ht,fe.path)),await rt(tt||i),If(i).then(L);else{const ht=Se.error??"delete failed";j(ht),Qe.error(ht)}},_t=z.useMemo(()=>{if(!w.trim())return p;const Se=w.toLowerCase();return p.filter(tt=>tt.name.toLowerCase().includes(Se))},[p,w]),hi=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return d.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[d.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[d.jsx(jE,{size:14,className:"shrink-0 text-accent"}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("p",{className:"text-xs font-medium text-fg truncate",children:hi}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:oe,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:x,children:d.jsx(WO,{size:12,className:x?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:Se=>D(Se.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"})})]}),d.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[d.jsx("button",{onClick:()=>ce({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:d.jsx(UO,{size:12})}),d.jsx("button",{onClick:()=>ce({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:d.jsx(VO,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>y(Se=>!Se),className:`p-1.5 rounded transition-colors ${k?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:k?"Hide hidden files":"Show hidden files",children:k?d.jsx(qO,{size:12}):d.jsx(KO,{size:12})})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[T&&d.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:T}),!T&&_t.length===0&&!x&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!T&&d.jsx(PE,{nodes:_t,depth:0,expanded:c,gitStatus:N,renaming:V,renameValue:he,renameInputRef:X,onRenameChange:ee,onRenameCommit:_i,onRenameCancel:()=>te(null),onToggleDir:ft,onFileClick:Nt,onSendToChat:mt,onContextMenu:gi})]}),d.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"}),R&&d.jsx(zO,{x:R.x,y:R.y,node:R.node,onClose:()=>F(null),onRename:()=>{di(R.node),F(null)},onDelete:()=>{U(R.node),F(null)},onNewFile:()=>{ce({parent:R.node.path,kind:"file"}),F(null)},onNewFolder:()=>{ce({parent:R.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:R.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:R.node.path}),F(null)},onCopyPath:()=>{const Se=R.node.path;Ca(Se).then(tt=>{tt||Qe.error("Couldn't copy path")}),F(null)},onSendToChat:()=>{mt(R.node.path),F(null)}}),we&&d.jsx(GS,{title:`New ${we.kind}`,subtitle:`in ${BO(we.parent)}`,onCancel:()=>{ce(null),Ee("")},onConfirm:Je,confirmLabel:"Create",confirmDisabled:!ve.trim(),children:d.jsx("input",{ref:W,value:ve,onChange:Se=>Ee(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&Je(),Se.key==="Escape"&&(ce(null),Ee(""))},placeholder:we.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"})}),fe&&d.jsx(GS,{title:`Delete ${fe.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>U(null),onConfirm:Pt,confirmLabel:"Delete",danger:!0,children:d.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",d.jsxs("span",{className:"text-fg font-medium",children:['"',fe.name,'"']})," to the trash?",fe.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function PE(i){const{nodes:e,depth:t,expanded:n,gitStatus:s,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,m=s[a.path],g=NO(a.name,a.isDirectory);return d.jsxs("div",{children:[d.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?d.jsx(HO,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):d.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?c?d.jsx(GO,{size:12,color:g}):d.jsx(jE,{size:12,color:g}):d.jsx(FO,{size:12,color:g}),f?d.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):d.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),m&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:rb[m].color,backgroundColor:`${rb[m].color}20`},title:m,children:rb[m].label}),!a.isDirectory&&d.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:d.jsx(YO,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(PE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function zO(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${dn.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&&d.jsx(Kl,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(Kl,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(Kl,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(ab,{}),d.jsx(Kl,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(Kl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(ab,{}),d.jsx(Kl,{label:"New file",onClick:i.onNewFile}),d.jsx(Kl,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(ab,{}),d.jsx(Kl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Kl({label:i,onClick:e,danger:t}){return d.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 ab(){return d.jsx("div",{className:"my-1 border-t border-line"})}function GS(i){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&d.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),d.jsx("div",{className:"mb-4",children:i.children}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.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"}),d.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 BO(i){return i.split("/").filter(Boolean).pop()||i}function wv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:wv(n.children,e,t)}:n)}function Ea({size:i,children:e,className:t,color:n}){return d.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 jE({size:i,className:e,color:t}){return d.jsx(Ea,{size:i,className:e,color:t,children:d.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 GO({size:i,className:e,color:t}){return d.jsx(Ea,{size:i,className:e,color:t,children:d.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 FO({size:i,className:e,color:t}){return d.jsxs(Ea,{size:i,className:e,color:t,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function HO({size:i,className:e}){return d.jsx(Ea,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function WO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("polyline",{points:"1 20 1 14 7 14"}),d.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 UO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"}),d.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),d.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function VO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.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"}),d.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),d.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function qO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function KO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.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"}),d.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function YO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),d.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function RE({content:i,children:e,align:t="bottom-right"}){const[n,s]=z.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return d.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${dn.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 em(i,e){if(!e)return i;const t=e.length>1?e.replace(/\/+$/,""):e;if(i===t)return"~";const n=t.endsWith("/")?t:`${t}/`;return i.startsWith(n)?`~/${i.slice(n.length)}`:i}function lb(i){mm(i).catch(()=>Qe.error("Couldn't save File Explorer layout."))}const cb=33,XO=20,JO=60,ZO=32;function FS(i){return Math.min(JO,Math.max(XO,i))}function QO(){const i=Ct(te=>te.tabs),e=Ct(te=>te.activeTabId),t=i.find(te=>te.id===e)??null,n=ji(te=>te.navFace),s=n_(),l=n==="home"?s:(t==null?void 0:t.cwd)??null,[p,a]=z.useState(cb),[c,f]=z.useState(!1),m=z.useRef(!1),[g,w]=z.useState(!1),D=z.useRef(p);D.current=p;const k=z.useRef(c);k.current=c;const C=z.useRef(null),b=z.useRef(null),{projects:y,openProject:x,archiveProjectByCwd:S}=Cd(),T=nb(te=>te.pinned),j=nb(te=>te.togglePin);z.useEffect(()=>{nb.getState().hydrate()},[]),z.useEffect(()=>{let te=!1;return Th().then(he=>{te||m.current||(typeof he.projectsSplitPct=="number"&&Number.isFinite(he.projectsSplitPct)&&a(FS(he.projectsSplitPct)),typeof he.projectsFileTreeCollapsed=="boolean"&&f(he.projectsFileTreeCollapsed))}),()=>{te=!0}},[]);const N=[...y].sort((te,he)=>(T[he.cwd]?1:0)-(T[te.cwd]?1:0));z.useEffect(()=>{if(!g)return;const te=he=>{b.current&&!b.current.contains(he.target)&&w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[g]);const L=z.useCallback(te=>{Ci.getState().openFile(te)},[]),R=z.useCallback(te=>{te.preventDefault(),m.current=!0;const he=te.clientX,ee=D.current;let we=ee;const ce=Ee=>{const fe=C.current;if(!fe)return;const U=fe.getBoundingClientRect(),X=Ee.clientX-he;we=FS(ee+X/U.width*100),a(we)},ve=()=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",ve),document.body.style.cursor="",document.body.style.userSelect="",lb({projectsSplitPct:we})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",ve),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),F=z.useCallback(()=>{m.current=!0,a(cb),lb({projectsSplitPct:cb})},[]),V=z.useCallback(()=>{m.current=!0;const te=!k.current;f(te),lb({projectsFileTreeCollapsed:te})},[]);return c?d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:V,"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:ZO},children:[d.jsx("span",{className:"text-[11px]",children:"▸"}),d.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(vw,{})})]}):d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${p}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:b,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(te=>!te),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:[d.jsx("span",{className:"flex-1 truncate text-left",children:l?em(l,s):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),d.jsx("button",{onClick:V,"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:"◂"}),g&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${dn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:N.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):N.map(te=>{const he=em(te.cwd,s);return d.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[d.jsx(RE,{content:T[te.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>j(te.cwd),className:`shrink-0 text-sm leading-none transition-colors ${T[te.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:T[te.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{x(te.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:he}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${he}?`)&&await S(te)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},te.cwd)})})]}),l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:l,children:em(l,s)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(LO,{cwd:l,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:L})})]}):d.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:R,onDoubleClick:F,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(vw,{})})]})}const e3=z.memo(QO),t3={"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:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},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."]},remote:{headline:"Session Managers on your other computers",intro:"Pick a paired machine to browse its projects and active sessions, or open a terminal on it. Pairing and revoking machines happens in Settings → Phone remote.",sections:[{title:"Using it",items:[{term:"Machines",body:"The switcher lists every paired computer with its OS and whether it is online right now."},{term:"Sessions / Terminal",body:"Sessions shows what the selected machine is running; Terminal opens a shell there."}]}]},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 (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},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 Moonshine 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."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}};function i3({content:i}){return d.jsxs(d.Fragment,{children:[d.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>d.jsxs("div",{className:"mb-3 last:mb-0",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),d.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>d.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&d.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",d.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&d.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),d.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>d.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function n3({active:i}){const e=Pn(g=>g.learningPanelCollapsed),t=Pn(g=>g.setLearningPanelCollapsed),n=Pn(g=>g.hydrated),s=Pn(g=>g.hydrate);z.useEffect(()=>{n||s()},[n,s]);const[l,p]=z.useState(()=>!e),a=z.useRef(null);z.useEffect(()=>{n&&p(!e)},[n]);const c=z.useCallback(()=>{p(g=>{const w=!g;return t(!w),w})},[t]);z.useEffect(()=>{if(!l)return;const g=w=>{var D;(D=a.current)!=null&&D.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l,t]);const f=z.useRef(!1);z.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const m=t3[i];return m?d.jsxs("span",{ref:a,className:"relative inline-block",children:[d.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":l,title:l?"Close learning panel":"What is this?",children:"Learn"}),l&&d.jsx("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:d.jsx(i3,{content:m})})]}):null}function s3({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:s,children:l}){const p=n&&(i||e||t);return d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&d.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[d.jsxs("div",{className:"max-w-[820px]",children:[i&&d.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&d.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&d.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),s&&d.jsx(n3,{active:s})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const r3=z.lazy(()=>mi(()=>import("./Skills-6pHn6glu.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),o3=z.lazy(()=>mi(()=>import("./History-pg00b2Gd.js"),__vite__mapDeps([14,4,15,1,2]),import.meta.url).then(i=>({default:i.History}))),a3=z.lazy(()=>mi(()=>import("./RemoteMachines-gOlFTvWq.js"),__vite__mapDeps([16,17,1,2]),import.meta.url).then(i=>({default:i.RemoteMachines}))),l3=z.lazy(()=>mi(()=>import("./Scheduler-BZXKqYJP.js"),__vite__mapDeps([18,15,13,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),c3=z.lazy(()=>mi(()=>import("./Settings-DWnN2qxn.js"),__vite__mapDeps([19,4,8,7,20,21,22,9,17,1,2]),import.meta.url).then(i=>({default:i.Settings}))),d3=z.lazy(()=>mi(()=>import("./Permissions-BfwzvmBS.js"),__vite__mapDeps([23,4,8,7,11,12,13,20,21,22,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),u3=z.lazy(()=>mi(()=>import("./SystemPrompt-DT0LBH-K.js"),__vite__mapDeps([24,4,7,11,12,13,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),h3=z.lazy(()=>mi(()=>import("./Memory-Bs1T1Jo7.js"),__vite__mapDeps([25,1,2]),import.meta.url).then(i=>({default:i.Memory}))),p3=z.lazy(()=>mi(()=>import("./Plugins-McjyvvKh.js"),__vite__mapDeps([26,4,10,11,12,13,6,1,2,5]),import.meta.url).then(i=>({default:i.Plugins}))),f3=z.lazy(()=>mi(()=>import("./McpServers-Dy-wnG_X.js"),__vite__mapDeps([27,4,5,7,8,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),m3=z.lazy(()=>mi(()=>import("./Hooks-BTEs0UZY.js"),__vite__mapDeps([28,4,5,7,8,10,11,12,13,20,21,22,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),g3=z.lazy(()=>mi(()=>import("./AgentLibrary-BmJ8hIPw.js"),__vite__mapDeps([29,4,5,12,30,21,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),v3=z.lazy(()=>mi(()=>import("./TagLibrary-DbJ0zbYL.js"),__vite__mapDeps([31,4,5,30,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),_3=z.lazy(()=>mi(()=>import("./DataModel-DZHBZrfL.js"),__vite__mapDeps([32,4,22,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),b3=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Sr({children:i}){return d.jsx(z.Suspense,{fallback:b3,children:i})}const w3={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."},remote:{title:"Remote machines",intro:"Open a Session Manager running on another computer — its projects, active sessions and a terminal. Pair or revoke machines in Settings → Phone remote."},history:{title:"Spend, tokens and time",intro:"Estimated spend, tokens, prompts and active time across every project — by project, model and day. Export any range to CSV."},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:"Claude Code's own memory files for this project and its subagents — a MEMORY.md index plus topic files. 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."},voice:{title:"Voice & microphone",intro:"On-device transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},y3=()=>{},HS=new Map;function x3(i,e){const t=HS.get(i);if(t&&t.ctx===e)return t.node;const n=S3(i,e);return HS.set(i,{ctx:e,node:n}),n}function S3(i,e){switch(i){case"overview":return d.jsx(cj,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return d.jsx(Zj,{});case"editor":return d.jsx(vw,{});case"projects":return d.jsx(e3,{})}const t=w3[i],n=(()=>{switch(i){case"skills":return d.jsx(Sr,{children:d.jsx(r3,{})});case"history":return d.jsx(Sr,{children:d.jsx(o3,{})});case"remote":return d.jsx(Sr,{children:d.jsx(a3,{onOpenSettings:()=>{var l;return(l=e.onNavigate)==null?void 0:l.call(e,"settings")}})});case"scheduler":return d.jsx(Sr,{children:d.jsx(l3,{navigate:e.onNavigate})});case"plugins":return d.jsx(Sr,{children:d.jsx(p3,{})});case"mcp":return d.jsx(Sr,{children:d.jsx(f3,{})});case"hooks":return d.jsx(Sr,{children:d.jsx(m3,{})});case"memory":return d.jsx(Sr,{children:d.jsx(h3,{})});case"system-prompt":return d.jsx(Sr,{children:d.jsx(u3,{})});case"permissions":return d.jsx(Sr,{children:d.jsx(d3,{})});case"settings":return d.jsx(Sr,{children:d.jsx(c3,{})});case"agent-library":return d.jsx(Sr,{children:d.jsx(g3,{})});case"tag-library":return d.jsx(Sr,{children:d.jsx(v3,{})});case"data-model":return d.jsx(Sr,{children:d.jsx(_3,{})});case"voice":return d.jsx(xO,{open:!0,onClose:y3,variant:"page"});default:return null}})();if(!n)return null;const s=B2[i];return t&&s?d.jsx(s3,{eyebrow:s,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var db={exports:{}},WS;function C3(){return WS||(WS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(x,S,T,j){var N,L=arguments.length,R=L<3?S:j===null?j=Object.getOwnPropertyDescriptor(S,T):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(x,S,T,j);else for(var F=x.length-1;F>=0;F--)(N=x[F])&&(R=(L<3?N(R):L>3?N(S,T,R):N(S,T))||R);return L>3&&R&&Object.defineProperty(S,T,R),R},m=this&&this.__param||function(x,S){return function(T,j){S(T,j,x)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const g=c(9042),w=c(9924),D=c(844),k=c(4725),C=c(2585),b=c(3656);let y=a.AccessibilityManager=class extends D.Disposable{constructor(x,S,T,j){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=j,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
3035
+ (Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),x=z.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const j=WM(S,T.before,T.after);return j.ok?(s.current+=1,n({type:"ACCEPT"})):Qe.error(j.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),j},[t.diff]);return{state:t,select:f,cancel:m,listen:g,sendHeard:b,run:C,retry:y,accept:x}}async function Ca(i){try{const e=await window.api.clipboard.writeText(i);return(e==null?void 0:e.ok)===!0}catch{return!1}}const QM=[{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."}],kS=320,Af=8;function eO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function tO(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Af),Math.max(Af,e-kS-Af)),n=Math.max(i.top-Af,Af);return{position:"fixed",left:t,top:n,width:kS,transform:"translateY(-100%)",zIndex:Z2.dialog}}function iO({phase:i,rect:e,selectedText:t,diff:n,transcript:s,modelStatus:l,onQuickAction:p,onRunCustom:a,onListen:c,onSendHeard:f,onCancel:m,onAccept:g,onReject:w,onRetry:D}){const[k,C]=z.useState(""),[b,y]=z.useState(!1),x=Ps(N=>N.show),S=z.useRef(null);z.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await Ca(t)){x("error","Copy failed");return}y(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>y(!1),1500)},j=()=>{const N=k.trim();N&&(a(N),C(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:tO(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&d.jsxs("div",{className:"p-2",children:[d.jsxs("div",{className:"flex items-center justify-between mb-2",children:[d.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:b?"Copied":"Copy"}),d.jsx("button",{onClick:c,"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"}),QM.map(N=>d.jsx("button",{onClick:()=>p(N.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:N.label},N.label))]}),d.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{value:k,onChange:N=>C(N.target.value),onKeyDown:N=>{N.key==="Enter"?j():N.key==="Escape"&&m()},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"&&d.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[d.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(eO,{}),"Listening…"]}),l&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:l})]}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsxs("div",{className:"p-3 flex items-center justify-between",children:[d.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&d.jsxs("div",{className:"p-3",children:[d.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:D,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function nO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function ES({phase:i,transcript:e,diff:t,editCount:n,modelStatus:s,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:m}){return d.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[d.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[d.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),d.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:rm(JM)})]}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&d.jsxs("div",{className:"text-fg-faint",children:[d.jsx("p",{children:"Select text in the doc…"}),d.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&d.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&d.jsxs("div",{children:[d.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[d.jsx(nO,{}),"Listening…"]}),s&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),d.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"&&d.jsxs("div",{children:[d.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&d.jsxs("div",{children:[d.jsxs("div",{className:"mb-3 space-y-2",children:[d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function sO(){const i=Ct(t=>t.tabs),e=Ct(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function rO({path:i,onRenamed:e,onDeleted:t}){const[n,s]=z.useState(!1),[l,p]=z.useState(!1),[a,c]=z.useState(""),[f,m]=z.useState(!1),g=Ci(V=>V.buffers[i]),w=Ci(V=>V.openFile),D=Ci(V=>V.renameOpenFile),k=Ci(V=>V.closeFile),C=sO(),b=wa(i),y=()=>s(!1),x=()=>{c(b),p(!0),y()},S=async()=>{const V=a.trim();if(!V||V===b){p(!1);return}try{const te=await window.api.files.rename(i,V);if(te.ok){const he=i.slice(0,i.lastIndexOf("/")),ee=te.newPath??`${he}/${V}`;D(i,ee),e==null||e(i,ee),Qe.info(`Renamed to ${V}`)}else Qe.error(te.error??`Couldn't rename ${b}`)}catch(te){Qe.error(te instanceof Error?te.message:`Couldn't rename ${b}`)}p(!1)},T=async()=>{y();try{const V=await window.api.files.duplicate(i);V.ok&&V.path?(w(V.path),Qe.info(`Duplicated as ${wa(V.path)}`)):Qe.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Qe.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},j=async()=>{try{const V=await window.api.files.delete(i);V.ok?(k(i),t==null||t(i),Qe.info(`Deleted ${b}`)):Qe.error(V.error??`Couldn't delete ${b}`)}catch(V){Qe.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},N=async()=>{y();const V=g??"";await Ca(V)?Qe.info(`Copied ${V.length} chars`):Qe.error(`Couldn't copy ${b}`)},L=()=>{if(y(),!C){Qe.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Qe.info(`Added ${b} to Claude context`)},R=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(V=>{V.ok||Qe.error(V.error??`Couldn't open ${b}`)}).catch(V=>Qe.error(V instanceof Error?V.message:`Couldn't open ${b}`))},F=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(V=>{V.ok||Qe.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Qe.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>s(V=>!V),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&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuScrim}`,onMouseDown:y}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${dn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(ib,{children:"Edit"}),d.jsx(ud,{label:"Rename",onClick:x}),d.jsx(ud,{label:"Duplicate",onClick:T}),d.jsx(ud,{label:"Delete document",danger:!0,onClick:()=>{y(),m(!0)}}),d.jsx(TS,{}),d.jsx(ib,{children:"Open"}),d.jsx(ud,{label:"Open in default app",onClick:R}),d.jsx(ud,{label:"Reveal in OS",onClick:F}),d.jsx(TS,{}),d.jsx(ib,{children:"Export"}),d.jsx(ud,{label:"Copy as Markdown",onClick:N}),d.jsx(ud,{label:"Add to Claude context",onClick:L,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(oO,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void S()}),f&&d.jsx(aO,{name:b,onCancel:()=>m(!1),onConfirm:()=>void j()})]})}function ib({children:i}){return d.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function ud({label:i,onClick:e,danger:t,disabled:n,title:s}){return d.jsx("button",{onClick:e,disabled:n,title:s,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 TS(){return d.jsx("div",{className:"my-1 border-t border-line"})}function oO({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),d.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?n():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function aO({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function lO(){const[i,e]=z.useState(!1),t=_d();return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.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&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${dn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(mh,{label:"Text size",children:d.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[d.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−"}),d.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),d.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+"})]})}),d.jsx(mh,{label:"Word wrap",children:d.jsx(iv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(mh,{label:"Minimap",children:d.jsx(iv,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(mh,{label:"Theme",children:d.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"})}),d.jsx(mh,{label:"Autosave",children:d.jsx(iv,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(mh,{label:"Wide measure",children:d.jsx(iv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function mh({label:i,children:e}){return d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-fg-faint",children:i}),e]})}function iv({on:i,onClick:e}){return d.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 cO=z.lazy(()=>mi(()=>import("./TiptapBody-Cihe5er3.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function nv(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[s,l]of Object.entries(i))t.has(s)||(n[s]=l);return n}function sv(i){return Xk(i)||Jk(i)}function dO(){const i=Kw(),e=Ci(Je=>Je.openFiles),t=Ci(Je=>Je.activeFilePath),n=Ci(Je=>Je.dirty),s=Ci(Je=>Je.viewMode),l=Ci(Je=>Je.buffers),p=Ci(Je=>Je.setActive),a=Ci(Je=>Je.closeFile),c=Ci(Je=>Je.closeOthers),f=Ci(Je=>Je.closeToTheRight),m=Ci(Je=>Je.closeAll),g=Ci(Je=>Je.loadBuffer),w=Ci(Je=>Je.setBuffer),D=Ci(Je=>Je.markSaved),k=Ci(Je=>Je.setViewMode),C=_d(),[b,y]=z.useState({}),[x,S]=z.useState({}),[T,j]=z.useState(null),[N,L]=z.useState(null),[R,F]=z.useState(!1),[V,te]=z.useState(!1),[he,ee]=z.useState(!0),we=z.useRef(null),ce=z.useRef(null),ve=z.useRef(void 0),Ee=z.useRef(null),fe=z.useRef(null),U=ZM(t??"",l[t??""]??""),X=z.useCallback(Je=>{we.current=Je},[]),W=z.useCallback(()=>we.current,[]);z.useEffect(()=>{Fj()},[]),z.useEffect(()=>{const Je=t;if(!Je||sv(Je))return;if(Ci.getState().hasBuffer(Je)){y(_t=>_t[Je]==="ready"?_t:{..._t,[Je]:"ready"});return}let Pt=!1;return y(_t=>({..._t,[Je]:"loading"})),window.api.files.read(Je).then(_t=>{Pt||(_t.binary?y(hi=>({...hi,[Je]:{binary:!0,size:_t.size??0,mime:_t.mime??"application/octet-stream",reason:_t.error??"Binary file"}})):_t.ok?(g(Je,_t.text),y(hi=>({...hi,[Je]:"ready"}))):y(hi=>({...hi,[Je]:{error:_t.error??"failed to read"}})))}),()=>{Pt=!0}},[t,g]),z.useEffect(()=>{L(null)},[t]);const Q=z.useCallback(async(Je,Pt=!1)=>{const _t=Ci.getState().buffers[Je];if(_t==null)return;Pt&&F(!0);const hi=await window.api.files.write(Je,_t);hi.ok?(D(Je),S(Se=>({...Se,[Je]:(Se[Je]??0)+1})),Pt||Qe.info(`Saved ${wa(Je)}`)):Qe.error(hi.error??`Couldn't save ${wa(Je)}`),Pt&&F(!1)},[D]);z.useEffect(()=>{if(!C.autosave)return;const Je=t;if(!(!Je||sv(Je)||!n[Je]))return window.clearTimeout(ve.current),ve.current=window.setTimeout(()=>{Q(Je,!0)},1200),()=>window.clearTimeout(ve.current)},[C.autosave,t,n,l,Q]);const oe=z.useCallback(Je=>{Je.length&&(y(Pt=>nv(Pt,Je)),S(Pt=>nv(Pt,Je)))},[]),Ce=z.useCallback((Je,Pt)=>{y(_t=>Je in _t?{...nv(_t,[Je]),[Pt]:_t[Je]}:_t),S(_t=>Je in _t?{...nv(_t,[Je]),[Pt]:_t[Je]}:_t)},[]),Oe=z.useCallback(Je=>{n[Je]?j({kind:"one",path:Je}):(a(Je),oe([Je]))},[n,a,oe]),Xe=z.useCallback(Je=>{e.some(_t=>_t.path!==Je&&n[_t.path])?j({kind:"others",path:Je}):(c(Je),oe(e.filter(_t=>_t.path!==Je).map(_t=>_t.path)))},[e,n,c,oe]),ge=z.useCallback(Je=>{const Pt=e.findIndex(hi=>hi.path===Je);Pt!==-1&&e.slice(Pt+1).some(hi=>n[hi.path])?j({kind:"right",path:Je}):(f(Je),oe(Pt!==-1?e.slice(Pt+1).map(hi=>hi.path):[]))},[e,n,f,oe]);z.useEffect(()=>{const Je=Pt=>{if(i.current)if((Pt.metaKey||Pt.ctrlKey)&&(Pt.key==="s"||Pt.key==="S")){const _t=Ci.getState().activeFilePath;_t&&!sv(_t)&&(Pt.preventDefault(),Q(_t))}else if((Pt.metaKey||Pt.ctrlKey)&&Pt.shiftKey&&(Pt.key==="f"||Pt.key==="F"))Pt.preventDefault(),te(_t=>!_t);else if((Pt.metaKey||Pt.ctrlKey)&&Pt.shiftKey&&(Pt.key==="w"||Pt.key==="W")){const _t=Ci.getState().activeFilePath;_t&&Ci.getState().openFiles.length>1&&(Pt.preventDefault(),Xe(_t))}else Pt.key==="Escape"&&U.state.phase!=="idle"?U.cancel():Pt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[Q,V,Xe,U.state.phase,U.cancel]),z.useEffect(()=>{if(U.state.phase==="idle")return;const Je=Pt=>{var hi,Se;const _t=Pt.target;(hi=fe.current)!=null&&hi.contains(_t)||(Se=Ee.current)!=null&&Se.contains(_t)||U.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[U.state.phase,U.cancel]),z.useEffect(()=>{U.cancel()},[t,U.cancel]);const J=z.useCallback(()=>{e.some(Pt=>n[Pt.path])?j({kind:"all",path:""}):(m(),y({}),S({}))},[e,n,m]),je=()=>{if(T){if(T.kind==="one")a(T.path),oe([T.path]);else if(T.kind==="others"){const Je=e.filter(Pt=>Pt.path!==T.path).map(Pt=>Pt.path);c(T.path),oe(Je)}else if(T.kind==="right"){const Je=e.findIndex(_t=>_t.path===T.path),Pt=Je!==-1?e.slice(Je+1).map(_t=>_t.path):[];f(T.path),oe(Pt)}else m(),y({}),S({});j(null)}};if(e.length===0)return d.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:d.jsxs("div",{className:"text-center",children:[d.jsx("div",{className:"mb-2",children:"no file open"}),d.jsxs("div",{children:["open the ",d.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const de=t,Ie=de?wa(de):"",Pe=de?b[de]:void 0,Ye=de?eE(de):!1,ft=de?Lj(de):!1,rt=de&&Ye?s[de]??zj(de):"edit",Nt=!!de&&!sv(de)&&Pe==="ready",mt=Nt,gi=ft?["edit","wysiwyg","preview","split"]:Ye?["edit","preview"]:[],di=de&&d.jsx(pN,{path:de,name:Ie,value:l[de]??"",onChange:Je=>w(de,Je),onSave:()=>void Q(de),onReady:X,onCursor:L}),_i=R?"Saving…":de&&n[de]?C.autosave?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&d.jsx(tR,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Oe,onCloseOthers:Xe,onCloseToTheRight:ge,onCloseAll:J}),de&&!V&&d.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[d.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ie}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:de}),Nt&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",_i]}),nl(de)&&(rt==="preview"||rt==="split")&&d.jsx("button",{onClick:()=>ee(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${he?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),nl(de)&&(rt==="preview"||rt==="split")&&d.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),gi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:gi.map(Je=>d.jsx("button",{onClick:()=>k(de,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${rt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),d.jsx("div",{className:"flex-1"}),d.jsx(rO,{path:de,onRenamed:Ce,onDeleted:Je=>oe([Je])}),Nt&&d.jsx(lO,{}),d.jsx("button",{onClick:()=>te(!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"})]}),V&&d.jsx("button",{onClick:()=>te(!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"}),d.jsx("div",{className:"flex-1 min-h-0",children:de?Xk(de)?d.jsx(MM,{path:de,name:Ie}):Jk(de)?d.jsx(OM,{path:de}):Pe&&typeof Pe=="object"&&"binary"in Pe?d.jsx(HM,{path:de,name:Ie,size:Pe.size,mime:Pe.mime,reason:Pe.reason}):Pe&&typeof Pe=="object"&&"error"in Pe?d.jsx("div",{className:"p-6 text-xs text-red-400",children:Pe.error}):Pe!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):rt==="wysiwyg"&&nl(de)?d.jsx(z.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(cO,{value:l[de]??"",onChange:Je=>w(de,Je)},de)}):rt==="split"&&nl(de)?d.jsxs("div",{className:"flex h-full",children:[he&&d.jsx(xS,{text:l[de]??"",scrollRef:ce}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(yS,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:di})]}),d.jsx("div",{ref:Ee,className:"flex-1 min-w-0",children:d.jsx(fw,{ref:ce,text:l[de]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!V&&C.assistantRail&&d.jsx(ES,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)},onReject:U.cancel,onRetry:U.retry})]}):rt==="preview"&&nl(de)?d.jsxs("div",{className:"flex h-full",children:[he&&d.jsx(xS,{text:l[de]??"",scrollRef:ce}),d.jsx("div",{ref:Ee,className:"flex-1 min-w-0",children:d.jsx(fw,{ref:ce,text:l[de]??"",wideMeasure:C.wideMeasure,onSelect:U.select,onDismissSelection:U.cancel})}),!V&&C.assistantRail&&d.jsx(ES,{phase:U.state.phase,transcript:U.state.transcript,diff:U.state.diff,editCount:U.state.editCount,modelStatus:U.state.modelStatus,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)},onReject:U.cancel,onRetry:U.retry})]}):rt==="preview"&&Yk(de)?d.jsx(RM,{path:de,dirty:!!n[de],reloadToken:x[de]??0}):rt==="preview"&&Zk(de)?d.jsx(zM,{path:de,text:l[de]??""}):rt==="preview"&&Qk(de)?d.jsx(FM,{path:de,text:l[de]??""}):nl(de)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(yS,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:di})]}):di:null}),mt&&d.jsx(jM,{text:l[de]??"",cursor:N,language:Ur(de)||void 0}),de&&nl(de)&&(rt==="preview"||rt==="split")&&U.state.phase!=="idle"&&U.state.selection&&d.jsx("div",{ref:fe,children:d.jsx(iO,{phase:U.state.phase,rect:U.state.selection.rect,selectedText:U.state.selection.text,diff:U.state.diff,transcript:U.state.transcript,modelStatus:U.state.modelStatus,onQuickAction:U.run,onRunCustom:U.run,onListen:U.listen,onSendHeard:U.sendHeard,onCancel:U.cancel,onReject:U.cancel,onRetry:U.retry,onAccept:()=>{const Je=U.accept(l[de]??"");Je.ok&&w(de,Je.next)}})}),T&&d.jsx(uO,{message:T.kind==="one"?`Discard unsaved changes to ${wa(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>j(null),onConfirm:je})]})}const vw=z.memo(dO);function uO({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const hO={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},DS='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function a_({open:i,onClose:e,children:t,title:n,size:s="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&d.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),d.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const c=z.useRef(null),f=z.useRef(null),m=z.useRef(e);if(m.current=e,z.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=c.current;if(!b)return;const y=b.querySelector(DS);y?y.focus():b.focus()},0),C=b=>{if(b.key==="Escape"){b.stopPropagation(),m.current();return}if(b.key==="Tab"){const y=c.current;if(!y)return;const x=Array.from(y.querySelectorAll(DS)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(x.length===0){b.preventDefault(),y.focus();return}const S=x[0],T=x[x.length-1],j=document.activeElement;b.shiftKey?(j===S||!y.contains(j))&&(b.preventDefault(),T.focus()):(j===T||!y.contains(j))&&(b.preventDefault(),S.focus())}};return document.addEventListener("keydown",C),()=>{clearTimeout(k),document.removeEventListener("keydown",C);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const g=D=>{D.target===D.currentTarget&&e()},w=d.jsx("div",{className:`fixed inset-0 ${dn.dialog} flex items-center justify-center bg-black/60`,onClick:g,"data-testid":"modal-backdrop",children:d.jsxs("div",{ref:c,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 ${hO[s]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?d.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?d.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Dh.createPortal(w,document.body):w}class TE extends z.Component{constructor(){super(...arguments);Gi(this,"state",{error:null});Gi(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):d.jsxs("div",{className:"p-6 text-xs",children:[d.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),d.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),d.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 pO({open:i,onClose:e,title:t,children:n,variant:s="overlay"}){return d.jsxs(a_,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&d.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[d.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),d.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:"✕"})]}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(TE,{children:n})})]})}function DE(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (on-device, 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 $S=i=>Symbol.iterator in i,AS=i=>"entries"in i,IS=(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[s,l]of t)if(!n.has(s)||!Object.is(l,n.get(s)))return!1;return!0},fO=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let s=t.next(),l=n.next();for(;!s.done&&!l.done;){if(!Object.is(s.value,l.value))return!1;s=t.next(),l=n.next()}return!!s.done&&!!l.done};function mO(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:$S(i)&&$S(e)?AS(i)&&AS(e)?IS(i,e):fO(i,e):IS({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function xy(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return mO(e.current,n)?e.current:e.current=n}}let PS=0;const gO=1e3;function vO(i){const e=performance.now();e-PS<gO||(PS=e,ut.debug("voice","mic.gate.click_rejected",{reason:i}))}function _O(){const i=kt(f=>f.isRecording),e=kt(f=>f.error),t=kt(f=>f.loadingProgress),n=kt(xy(Pv)),s=()=>{const f=kt.getState(),{canRecord:m,reason:g}=Pv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(g==="error"||g==="load-timeout"){f.resetAndRetryModel();return}if(!m)return vO(g);const w=Ct.getState().activeTabId;w&&f.startRecording(w)},l=DE(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,c=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 d.jsx("button",{onClick:s,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 ${c}`,children:d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),d.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),d.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),d.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function bO(){const i=kt(t=>t.ttsEnabled),e=kt(t=>t.toggleTTS);return d.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:[d.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[d.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?d.jsxs(d.Fragment,{children:[d.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),d.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):d.jsxs(d.Fragment,{children:[d.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),d.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),d.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function wO(i){return/^monitor of /i.test(i.trim())}function jS(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function RS(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 s=jS(e),l=t.filter(p=>p.label&&jS(p.label)===s);return l.length===1?l[0]:null}async function NS(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&wO(n.label))):[]}const MS=!1;function $E(){const i=kt(f=>f.isRecording);kt(f=>f.startRecording),kt(f=>f.stopRecording);const[e,t]=z.useState([]),[n,s]=z.useState(null),[l,p]=z.useState(null);z.useEffect(()=>{let f=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(f)return;const g=await NS(MS);if(f)return;t(g),p(m.selectedLabel);const w=RS(m.selectedDeviceId,m.selectedLabel,g);w?(s(w.deviceId),m.selectedDeviceId&&w.deviceId!==m.selectedDeviceId&&(ut.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ut.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ut.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{f=!0}},[]);const a=z.useCallback(async()=>{try{const f=await NS(MS);if(t(f),n&&!f.some(m=>m.deviceId===n)){const m=RS(null,l,f);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||l}).catch(()=>{})):s(null)}}catch(f){ut.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);z.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const c=async f=>{var D;const m=f.target.value,g=m===""?null:m,w=g?((D=e.find(k=>k.deviceId===g))==null?void 0:D.label)??null:null;s(g),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:w}),ut.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(k){ut.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await kt.getState().restartWithDevice()}catch(k){ut.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return d.jsxs("select",{value:n??"",onChange:c,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:[d.jsx("option",{value:"",children:"Default"}),e.map(f=>d.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function yO(){const i=kt(D=>D.isRecording),e=kt(D=>D.levelMeterEnabled),[t,n]=z.useState(0),[s,l]=z.useState(0),p=z.useRef(0);p.current=s;const[a,c]=z.useState(0),[f,m]=z.useState(!1),g=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,C=null,b=null;const y=()=>{if(k)return;const S=b??NC();if(!S){D=requestAnimationFrame(y);return}b!==S&&(b=S,C=new Uint8Array(new ArrayBuffer(S.fftSize)));const T=C;S.getByteTimeDomainData(T);let j=0;for(let F=0;F<T.length;F++){const V=T[F]-128;j+=V*V}const N=Math.sqrt(j/T.length)/128,L=N>0?20*Math.log10(N):-60,R=Math.max(0,Math.min(1,(L+60)/60));l(N),n(R),N>=.95&&(m(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>m(!1),150)),D=requestAnimationFrame(y)};D=requestAnimationFrame(y);const x=setInterval(()=>{k||c(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(x),g.current&&(clearTimeout(g.current),g.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return d.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:d.jsx("div",{className:`h-full ${w} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function AE(){const i=kt(f=>f.submitCountdownStartAt),e=kt(f=>f.submitDelayMs),[t,n]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let f;const m=()=>{n(performance.now()),f=requestAnimationFrame(m)};return f=requestAnimationFrame(m),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const s=t-i,l=Math.max(0,e-s),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,c=kt.getState().cancelSubmit;return d.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:d.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:d.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function xO({open:i,onClose:e,variant:t="overlay"}){return d.jsx(pO,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:d.jsxs("div",{className:"p-4 space-y-4",children:[d.jsx(EO,{}),d.jsx(AE,{}),d.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[d.jsx(_O,{}),d.jsx($E,{}),d.jsx(bO,{})]}),d.jsx(SO,{}),d.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[d.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),d.jsx(kO,{})]}),d.jsx(yO,{})]})})}function SO(){const i=kt(l=>l.isRecording),[e,t]=z.useState(null);if(z.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",s=CO(e.accelerator);return d.jsxs("div",{className:"text-[11px] text-fg-faint",children:[d.jsxs("span",{children:[n," "]}),d.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),d.jsx("span",{children:" to record"})]})}function CO(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 kO(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>ut.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const s=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,s()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const s={...i,mode:n};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(l){ut.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return d.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:[d.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[d.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),d.jsx("span",{children:"Tap on/off"})]}),d.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[d.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),d.jsx("span",{children:"Hold to talk"})]})]})}function EO(){const i=kt(l=>l.isRecording),e=kt(l=>l.lastTranscript),t=kt(l=>l.error),n=kt(l=>l.modelStatus),s=kt(l=>l.loadingProgress);return t?d.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?d.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[d.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),d.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?d.jsxs("div",{className:"text-[11px] text-fg-faint",children:[d.jsxs("div",{className:"flex items-center justify-between mb-1",children:[d.jsx("span",{children:"Loading speech model"}),d.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),d.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:d.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}const IE="~/.claude/session-manager/projects-prefs.json";let OS=Promise.resolve(),rv=null;function LS(i){const e=OS.then(i);return OS=e.catch(()=>{}),e}async function zS(){const i=await window.api.config.readJson(IE);if(i.exists&&i.data&&typeof i.data=="object"){const e=i.data.pinned;if(e&&typeof e=="object")return{...e}}return{}}const nb=jn(i=>({pinned:{},hydrated:!1,hydrate:()=>rv||(rv=LS(async()=>{try{i({pinned:await zS(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),i({hydrated:!0})}}),rv),togglePin:e=>{LS(async()=>{let t;try{t=await zS()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Qe.error("Could not update pinned projects: the preferences file is unreadable.");return}const n={...t};n[e]?delete n[e]:n[e]=!0;try{await window.api.config.writeJson(IE,{pinned:n}),i({pinned:n})}catch(s){i({pinned:t}),Qe.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function TO(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function DO(i,e,t){const n=z.useRef(e);n.current=e;const s=Array.from(new Set(i.filter(p=>!!p).map(TO))),l=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;z.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const p=window.api.config.onChanged(a=>{s.includes(a.path)&&n.current(a.path)});return()=>{p(),window.api.config.unwatch(s,t)}},[l])}async function $O(i){const e=await ym(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function AO(i,e){return xd(i,{fileTreeExpanded:[...e].slice(0,500)})}async function IO(){const i=await Th();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function PO(i){mm({fileTreeShowHidden:i}).catch(()=>{})}function sb(i,e){const t=e+"/";let n=!1;const s=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}s.add(l)}return n?s:i}const rb={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:"!"}},jO=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 RO(i){const e=Ur(i);return jO.has(e)||Kk.has(e)||e==="pdf"}function NO(i,e){if(e)return"#d97757";switch(Ur(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 If(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}const BS=64,MO=250,OO={depth:0};function ob(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function LO({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const s=Kw(),l=Zv(),[p,a]=z.useState([]),[c,f]=z.useState(new Set),m=z.useRef(c);m.current=c;const g=z.useRef(!1),[w,D]=z.useState(""),[k,C]=z.useState(!0),b=z.useRef(!1);z.useEffect(()=>{let Se=!1;return IO().then(tt=>{!Se&&!b.current&&C(tt)}),()=>{Se=!0}},[]);const y=z.useCallback(Se=>{b.current=!0,C(tt=>{const ht=typeof Se=="function"?Se(tt):Se;return PO(ht),ht})},[]),[x,S]=z.useState(!1),[T,j]=z.useState(null),[N,L]=z.useState({}),[R,F]=z.useState(null),[V,te]=z.useState(null),[he,ee]=z.useState(""),[we,ce]=z.useState(null),[ve,Ee]=z.useState(""),[fe,U]=z.useState(null),X=z.useRef(null),W=z.useRef(null),Q=z.useRef(0),oe=z.useCallback(async()=>{if(!i)return;const Se=++Q.current;S(!0),j(null);const tt=await window.api.files.list(i,k);Q.current===Se&&(tt.ok?a(tt.entries.map(ht=>({...ht}))):(j(tt.error??"failed to list"),a([])),S(!1))},[i,k]),Ce=z.useCallback(async Se=>{const tt=Q.current,ht=new Map;for(const vi of Se){const Jt=vi.split("/").length,oi=ht.get(Jt);oi?oi.push(vi):ht.set(Jt,[vi])}const Et=[];for(const vi of[...ht.keys()].sort((Jt,oi)=>Jt-oi)){const Jt=ht.get(vi),oi=await Promise.all(Jt.map(async Xt=>({p:Xt,result:await window.api.files.list(Xt,k)})));if(Q.current!==tt)return Et;for(const{p:Xt,result:un}of oi)un.ok?a(wt=>wv(wt,Xt,un.entries.map(Ri=>({...Ri})))):Et.push(Xt)}return Et},[k]),Oe=z.useCallback(async Se=>(await oe(),Se.length?Ce(Se):[]),[oe,Ce]);z.useEffect(()=>{D(""),te(null),F(null),ce(null),U(null),L({});let Se=!1;return g.current=!1,(async()=>{const[tt]=await Promise.all([$O(i),oe()]);if(Se)return;if(!g.current){const Et=new Set(tt);m.current=Et,f(Et)}if(!tt.length)return;const ht=await Ce(tt);Se||!ht.length||Ye(Et=>{const vi=new Set;let Jt=!1;for(const oi of Et){if(ht.some(Xt=>oi===Xt||oi.startsWith(Xt+"/"))){Jt=!0;continue}vi.add(oi)}return Jt?vi:Et})})(),If(i).then(tt=>{Se||L(tt)}),()=>{Se=!0}},[i]);const Xe=z.useRef(!0);z.useEffect(()=>{if(Xe.current){Xe.current=!1;return}Oe([...m.current])},[k]),z.useEffect(()=>{if(!i||!l)return;If(i).then(L);const Se=window.setInterval(()=>{If(i).then(L)},5e3);return()=>window.clearInterval(Se)},[i,l]);const ge=z.useMemo(()=>{if(!i)return[];const Se=[...c].filter(tt=>tt!==i);return[i,...Se.slice(-63)]},[i,c]),J=z.useRef(!1);z.useEffect(()=>{!i||c.size+1<=BS||J.current||(J.current=!0,console.warn(`FileTree: watching only ${BS} of ${c.size+1} folders (cap reached)`))},[i,c]);const je=z.useRef(new Map),de=z.useRef(new Set),Ie=z.useRef(!1);Ie.current=V!==null||we!==null;const Pe=z.useRef(()=>{});Pe.current=Se=>{if(!(Se!==ob(i)&&!m.current.has(Se))){if(Ie.current){de.current.add(Se);return}Se===ob(i)?Oe([...m.current]):rt(Se)}},DO(ge,Se=>{if(Se!==ob(i)&&!m.current.has(Se))return;const tt=je.current,ht=tt.get(Se);ht&&clearTimeout(ht),tt.set(Se,setTimeout(()=>{tt.delete(Se),Pe.current(Se)},MO))},OO),z.useEffect(()=>{if(V!==null||we!==null)return;const Se=[...de.current];de.current.clear();for(const tt of Se)Pe.current(tt)},[V,we]),z.useEffect(()=>{const Se=je.current,tt=de.current;return()=>{for(const ht of Se.values())clearTimeout(ht);Se.clear(),tt.clear()}},[i]),z.useEffect(()=>{if(!R)return;const Se=()=>F(null),tt=ht=>{s.current&&ht.key==="Escape"&&F(null)};return window.addEventListener("mousedown",Se),window.addEventListener("keydown",tt),()=>{window.removeEventListener("mousedown",Se),window.removeEventListener("keydown",tt)}},[R]),z.useEffect(()=>{V&&setTimeout(()=>{var Se;return(Se=X.current)==null?void 0:Se.select()},30)},[V]),z.useEffect(()=>{we&&setTimeout(()=>{var Se;return(Se=W.current)==null?void 0:Se.focus()},30)},[we]);const Ye=z.useCallback(Se=>{const tt=m.current,ht=Se(tt);ht!==tt&&(g.current=!0,m.current=ht,f(ht),AO(i,ht).catch(()=>{m.current===ht&&(m.current=tt,f(tt),Qe.error("Couldn't save folder expansion — reverted."))}))},[i]),ft=z.useCallback(async Se=>{if(c.has(Se.path)){Ye(ht=>sb(ht,Se.path));return}if(Ye(ht=>new Set(ht).add(Se.path)),Se.children)return;const tt=await window.api.files.list(Se.path,k);tt.ok&&a(ht=>wv(ht,Se.path,tt.entries.map(Et=>({...Et}))))},[c,k,Ye]),rt=z.useCallback(async Se=>{if(Se===i){await oe();return}const tt=await window.api.files.list(Se,k);tt.ok&&a(ht=>wv(ht,Se,tt.entries.map(Et=>({...Et}))))},[i,oe,k]),Nt=z.useCallback(Se=>{if(Se.isDirectory){ft(Se);return}RO(Se.name)&&e?e(Se.path):window.api.shell.open({as:"openPath",path:Se.path})},[ft,e]),mt=z.useCallback(Se=>{if(t){t(Se);return}if(n){const tt=Se.startsWith(i+"/")?Se.slice(i.length+1):Se;window.api.pty.write({tabId:n,data:`@${tt} `})}},[t,n,i]),gi=z.useCallback((Se,tt)=>{Se.preventDefault(),Se.stopPropagation(),F({x:Se.clientX,y:Se.clientY,node:tt})},[]),di=Se=>{te(Se.path),ee(Se.name)},_i=async()=>{if(!V)return;const Se=he.trim();if(!Se){te(null);return}const tt=await window.api.files.rename(V,Se);if(te(null),tt.ok){const ht=V.slice(0,V.lastIndexOf("/"));Ye(Et=>sb(Et,V)),await rt(ht||i),If(i).then(L)}else{const ht=tt.error??"rename failed";j(ht),Qe.error(ht)}},Je=async()=>{if(!we)return;const Se=ve.trim();if(!Se){ce(null),Ee("");return}const tt=await window.api.files.create(we.parent,Se,we.kind);if(ce(null),Ee(""),tt.ok)await rt(we.parent),we.kind==="folder"&&Ye(ht=>new Set(ht).add(we.parent));else{const ht=tt.error??"create failed";j(ht),Qe.error(ht)}},Pt=async()=>{if(!fe)return;const Se=await window.api.files.delete(fe.path),tt=fe.path.slice(0,fe.path.lastIndexOf("/"));if(U(null),Se.ok)Ye(ht=>sb(ht,fe.path)),await rt(tt||i),If(i).then(L);else{const ht=Se.error??"delete failed";j(ht),Qe.error(ht)}},_t=z.useMemo(()=>{if(!w.trim())return p;const Se=w.toLowerCase();return p.filter(tt=>tt.name.toLowerCase().includes(Se))},[p,w]),hi=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return d.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[d.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[d.jsx(jE,{size:14,className:"shrink-0 text-accent"}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("p",{className:"text-xs font-medium text-fg truncate",children:hi}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:oe,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:x,children:d.jsx(WO,{size:12,className:x?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:Se=>D(Se.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"})})]}),d.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[d.jsx("button",{onClick:()=>ce({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:d.jsx(UO,{size:12})}),d.jsx("button",{onClick:()=>ce({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:d.jsx(VO,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>y(Se=>!Se),className:`p-1.5 rounded transition-colors ${k?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:k?"Hide hidden files":"Show hidden files",children:k?d.jsx(qO,{size:12}):d.jsx(KO,{size:12})})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[T&&d.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:T}),!T&&_t.length===0&&!x&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!T&&d.jsx(PE,{nodes:_t,depth:0,expanded:c,gitStatus:N,renaming:V,renameValue:he,renameInputRef:X,onRenameChange:ee,onRenameCommit:_i,onRenameCancel:()=>te(null),onToggleDir:ft,onFileClick:Nt,onSendToChat:mt,onContextMenu:gi})]}),d.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"}),R&&d.jsx(zO,{x:R.x,y:R.y,node:R.node,onClose:()=>F(null),onRename:()=>{di(R.node),F(null)},onDelete:()=>{U(R.node),F(null)},onNewFile:()=>{ce({parent:R.node.path,kind:"file"}),F(null)},onNewFolder:()=>{ce({parent:R.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:R.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:R.node.path}),F(null)},onCopyPath:()=>{const Se=R.node.path;Ca(Se).then(tt=>{tt||Qe.error("Couldn't copy path")}),F(null)},onSendToChat:()=>{mt(R.node.path),F(null)}}),we&&d.jsx(GS,{title:`New ${we.kind}`,subtitle:`in ${BO(we.parent)}`,onCancel:()=>{ce(null),Ee("")},onConfirm:Je,confirmLabel:"Create",confirmDisabled:!ve.trim(),children:d.jsx("input",{ref:W,value:ve,onChange:Se=>Ee(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&Je(),Se.key==="Escape"&&(ce(null),Ee(""))},placeholder:we.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"})}),fe&&d.jsx(GS,{title:`Delete ${fe.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>U(null),onConfirm:Pt,confirmLabel:"Delete",danger:!0,children:d.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",d.jsxs("span",{className:"text-fg font-medium",children:['"',fe.name,'"']})," to the trash?",fe.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function PE(i){const{nodes:e,depth:t,expanded:n,gitStatus:s,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,m=s[a.path],g=NO(a.name,a.isDirectory);return d.jsxs("div",{children:[d.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?d.jsx(HO,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):d.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?c?d.jsx(GO,{size:12,color:g}):d.jsx(jE,{size:12,color:g}):d.jsx(FO,{size:12,color:g}),f?d.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):d.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),m&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:rb[m].color,backgroundColor:`${rb[m].color}20`},title:m,children:rb[m].label}),!a.isDirectory&&d.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:d.jsx(YO,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(PE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function zO(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${dn.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&&d.jsx(Kl,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(Kl,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(Kl,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(ab,{}),d.jsx(Kl,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(Kl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(ab,{}),d.jsx(Kl,{label:"New file",onClick:i.onNewFile}),d.jsx(Kl,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(ab,{}),d.jsx(Kl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Kl({label:i,onClick:e,danger:t}){return d.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 ab(){return d.jsx("div",{className:"my-1 border-t border-line"})}function GS(i){return d.jsx("div",{className:`fixed inset-0 ${dn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&d.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),d.jsx("div",{className:"mb-4",children:i.children}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.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"}),d.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 BO(i){return i.split("/").filter(Boolean).pop()||i}function wv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:wv(n.children,e,t)}:n)}function Ea({size:i,children:e,className:t,color:n}){return d.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 jE({size:i,className:e,color:t}){return d.jsx(Ea,{size:i,className:e,color:t,children:d.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 GO({size:i,className:e,color:t}){return d.jsx(Ea,{size:i,className:e,color:t,children:d.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 FO({size:i,className:e,color:t}){return d.jsxs(Ea,{size:i,className:e,color:t,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function HO({size:i,className:e}){return d.jsx(Ea,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function WO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("polyline",{points:"1 20 1 14 7 14"}),d.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 UO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"}),d.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),d.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function VO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.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"}),d.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),d.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function qO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function KO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.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"}),d.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function YO({size:i,className:e}){return d.jsxs(Ea,{size:i,className:e,children:[d.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),d.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function RE({content:i,children:e,align:t="bottom-right"}){const[n,s]=z.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return d.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${dn.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 em(i,e){if(!e)return i;const t=e.length>1?e.replace(/\/+$/,""):e;if(i===t)return"~";const n=t.endsWith("/")?t:`${t}/`;return i.startsWith(n)?`~/${i.slice(n.length)}`:i}function lb(i){mm(i).catch(()=>Qe.error("Couldn't save File Explorer layout."))}const cb=33,XO=20,JO=60,ZO=32;function FS(i){return Math.min(JO,Math.max(XO,i))}function QO(){const i=Ct(te=>te.tabs),e=Ct(te=>te.activeTabId),t=i.find(te=>te.id===e)??null,n=ji(te=>te.navFace),s=n_(),l=n==="home"?s:(t==null?void 0:t.cwd)??null,[p,a]=z.useState(cb),[c,f]=z.useState(!1),m=z.useRef(!1),[g,w]=z.useState(!1),D=z.useRef(p);D.current=p;const k=z.useRef(c);k.current=c;const C=z.useRef(null),b=z.useRef(null),{projects:y,openProject:x,archiveProjectByCwd:S}=Cd(),T=nb(te=>te.pinned),j=nb(te=>te.togglePin);z.useEffect(()=>{nb.getState().hydrate()},[]),z.useEffect(()=>{let te=!1;return Th().then(he=>{te||m.current||(typeof he.projectsSplitPct=="number"&&Number.isFinite(he.projectsSplitPct)&&a(FS(he.projectsSplitPct)),typeof he.projectsFileTreeCollapsed=="boolean"&&f(he.projectsFileTreeCollapsed))}),()=>{te=!0}},[]);const N=[...y].sort((te,he)=>(T[he.cwd]?1:0)-(T[te.cwd]?1:0));z.useEffect(()=>{if(!g)return;const te=he=>{b.current&&!b.current.contains(he.target)&&w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[g]);const L=z.useCallback(te=>{Ci.getState().openFile(te)},[]),R=z.useCallback(te=>{te.preventDefault(),m.current=!0;const he=te.clientX,ee=D.current;let we=ee;const ce=Ee=>{const fe=C.current;if(!fe)return;const U=fe.getBoundingClientRect(),X=Ee.clientX-he;we=FS(ee+X/U.width*100),a(we)},ve=()=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",ve),document.body.style.cursor="",document.body.style.userSelect="",lb({projectsSplitPct:we})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",ve),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),F=z.useCallback(()=>{m.current=!0,a(cb),lb({projectsSplitPct:cb})},[]),V=z.useCallback(()=>{m.current=!0;const te=!k.current;f(te),lb({projectsFileTreeCollapsed:te})},[]);return c?d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:V,"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:ZO},children:[d.jsx("span",{className:"text-[11px]",children:"▸"}),d.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(vw,{})})]}):d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${p}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:b,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(te=>!te),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:[d.jsx("span",{className:"flex-1 truncate text-left",children:l?em(l,s):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),d.jsx("button",{onClick:V,"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:"◂"}),g&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${dn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:N.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):N.map(te=>{const he=em(te.cwd,s);return d.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[d.jsx(RE,{content:T[te.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>j(te.cwd),className:`shrink-0 text-sm leading-none transition-colors ${T[te.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:T[te.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{x(te.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:he}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${he}?`)&&await S(te)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},te.cwd)})})]}),l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:l,children:em(l,s)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(LO,{cwd:l,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:L})})]}):d.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:R,onDoubleClick:F,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(vw,{})})]})}const e3=z.memo(QO),t3={"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:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},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."]},remote:{headline:"Session Managers on your other computers",intro:"Pick a paired machine to browse its projects and active sessions, or open a terminal on it. Pairing and revoking machines happens in Settings → Phone remote.",sections:[{title:"Using it",items:[{term:"Machines",body:"The switcher lists every paired computer with its OS and whether it is online right now."},{term:"Sessions / Terminal",body:"Sessions shows what the selected machine is running; Terminal opens a shell there."}]}]},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 (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},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 Moonshine 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."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}};function i3({content:i}){return d.jsxs(d.Fragment,{children:[d.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>d.jsxs("div",{className:"mb-3 last:mb-0",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),d.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>d.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&d.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",d.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&d.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),d.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>d.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function n3({active:i}){const e=Pn(g=>g.learningPanelCollapsed),t=Pn(g=>g.setLearningPanelCollapsed),n=Pn(g=>g.hydrated),s=Pn(g=>g.hydrate);z.useEffect(()=>{n||s()},[n,s]);const[l,p]=z.useState(()=>!e),a=z.useRef(null);z.useEffect(()=>{n&&p(!e)},[n]);const c=z.useCallback(()=>{p(g=>{const w=!g;return t(!w),w})},[t]);z.useEffect(()=>{if(!l)return;const g=w=>{var D;(D=a.current)!=null&&D.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l,t]);const f=z.useRef(!1);z.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const m=t3[i];return m?d.jsxs("span",{ref:a,className:"relative inline-block",children:[d.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":l,title:l?"Close learning panel":"What is this?",children:"Learn"}),l&&d.jsx("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:d.jsx(i3,{content:m})})]}):null}function s3({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:s,children:l}){const p=n&&(i||e||t);return d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&d.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[d.jsxs("div",{className:"max-w-[820px]",children:[i&&d.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&d.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&d.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),s&&d.jsx(n3,{active:s})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const r3=z.lazy(()=>mi(()=>import("./Skills-DYWQTQB1.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),o3=z.lazy(()=>mi(()=>import("./History-BRdRp1J_.js"),__vite__mapDeps([14,4,15,1,2]),import.meta.url).then(i=>({default:i.History}))),a3=z.lazy(()=>mi(()=>import("./RemoteMachines-BFmbIGpW.js"),__vite__mapDeps([16,17,1,2]),import.meta.url).then(i=>({default:i.RemoteMachines}))),l3=z.lazy(()=>mi(()=>import("./Scheduler-Du4HgPKY.js"),__vite__mapDeps([18,15,13,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),c3=z.lazy(()=>mi(()=>import("./Settings-DMoI0cqB.js"),__vite__mapDeps([19,4,8,7,20,21,22,9,17,1,2]),import.meta.url).then(i=>({default:i.Settings}))),d3=z.lazy(()=>mi(()=>import("./Permissions-DuTJ1FUb.js"),__vite__mapDeps([23,4,8,7,11,12,13,20,21,22,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),u3=z.lazy(()=>mi(()=>import("./SystemPrompt-Df0IfOuI.js"),__vite__mapDeps([24,4,7,11,12,13,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),h3=z.lazy(()=>mi(()=>import("./Memory-C7RXoVO4.js"),__vite__mapDeps([25,1,2]),import.meta.url).then(i=>({default:i.Memory}))),p3=z.lazy(()=>mi(()=>import("./Plugins-DSXsP4hM.js"),__vite__mapDeps([26,4,10,11,12,13,6,1,2,5]),import.meta.url).then(i=>({default:i.Plugins}))),f3=z.lazy(()=>mi(()=>import("./McpServers-CCjHSwFm.js"),__vite__mapDeps([27,4,5,7,8,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),m3=z.lazy(()=>mi(()=>import("./Hooks--hiGPBQy.js"),__vite__mapDeps([28,4,5,7,8,10,11,12,13,20,21,22,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),g3=z.lazy(()=>mi(()=>import("./AgentLibrary-C2qUX9WU.js"),__vite__mapDeps([29,4,5,12,30,21,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),v3=z.lazy(()=>mi(()=>import("./TagLibrary-BuMsGx-2.js"),__vite__mapDeps([31,4,5,30,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),_3=z.lazy(()=>mi(()=>import("./DataModel-CENoTvc2.js"),__vite__mapDeps([32,4,22,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),b3=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Sr({children:i}){return d.jsx(z.Suspense,{fallback:b3,children:i})}const w3={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."},remote:{title:"Remote machines",intro:"Open a Session Manager running on another computer — its projects, active sessions and a terminal. Pair or revoke machines in Settings → Phone remote."},history:{title:"Spend, tokens and time",intro:"Estimated spend, tokens, prompts and active time across every project — by project, model and day. Export any range to CSV."},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:"Claude Code's own memory files for this project and its subagents — a MEMORY.md index plus topic files. 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."},voice:{title:"Voice & microphone",intro:"On-device transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},y3=()=>{},HS=new Map;function x3(i,e){const t=HS.get(i);if(t&&t.ctx===e)return t.node;const n=S3(i,e);return HS.set(i,{ctx:e,node:n}),n}function S3(i,e){switch(i){case"overview":return d.jsx(cj,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return d.jsx(Zj,{});case"editor":return d.jsx(vw,{});case"projects":return d.jsx(e3,{})}const t=w3[i],n=(()=>{switch(i){case"skills":return d.jsx(Sr,{children:d.jsx(r3,{})});case"history":return d.jsx(Sr,{children:d.jsx(o3,{})});case"remote":return d.jsx(Sr,{children:d.jsx(a3,{onOpenSettings:()=>{var l;return(l=e.onNavigate)==null?void 0:l.call(e,"settings")}})});case"scheduler":return d.jsx(Sr,{children:d.jsx(l3,{navigate:e.onNavigate})});case"plugins":return d.jsx(Sr,{children:d.jsx(p3,{})});case"mcp":return d.jsx(Sr,{children:d.jsx(f3,{})});case"hooks":return d.jsx(Sr,{children:d.jsx(m3,{})});case"memory":return d.jsx(Sr,{children:d.jsx(h3,{})});case"system-prompt":return d.jsx(Sr,{children:d.jsx(u3,{})});case"permissions":return d.jsx(Sr,{children:d.jsx(d3,{})});case"settings":return d.jsx(Sr,{children:d.jsx(c3,{})});case"agent-library":return d.jsx(Sr,{children:d.jsx(g3,{})});case"tag-library":return d.jsx(Sr,{children:d.jsx(v3,{})});case"data-model":return d.jsx(Sr,{children:d.jsx(_3,{})});case"voice":return d.jsx(xO,{open:!0,onClose:y3,variant:"page"});default:return null}})();if(!n)return null;const s=B2[i];return t&&s?d.jsx(s3,{eyebrow:s,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var db={exports:{}},WS;function C3(){return WS||(WS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(x,S,T,j){var N,L=arguments.length,R=L<3?S:j===null?j=Object.getOwnPropertyDescriptor(S,T):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(x,S,T,j);else for(var F=x.length-1;F>=0;F--)(N=x[F])&&(R=(L<3?N(R):L>3?N(S,T,R):N(S,T))||R);return L>3&&R&&Object.defineProperty(S,T,R),R},m=this&&this.__param||function(x,S){return function(T,j){S(T,j,x)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const g=c(9042),w=c(9924),D=c(844),k=c(4725),C=c(2585),b=c(3656);let y=a.AccessibilityManager=class extends D.Disposable{constructor(x,S,T,j){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=j,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
3036
3036
  `)))),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(x){for(let S=0;S<x;S++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
3037
3037
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,S){this._liveRegionDebouncer.refresh(x,S,this._terminal.rows)}_renderRows(x,S){const T=this._terminal.buffer,j=T.lines.length.toString();for(let N=x;N<=S;N++){const L=T.lines.get(T.ydisp+N),R=[],F=(L==null?void 0:L.translateToString(!0,void 0,void 0,R))||"",V=(T.ydisp+N+1).toString(),te=this._rowElements[N];te&&(F.length===0?(te.innerText=" ",this._rowColumns.set(te,[0,1])):(te.textContent=F,this._rowColumns.set(te,R)),te.setAttribute("aria-posinset",V),te.setAttribute("aria-setsize",j))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,S){const T=x.target,j=this._rowElements[S===0?1:this._rowElements.length-2];if(T.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==j)return;let N,L;if(S===0?(N=T,L=this._rowElements.pop(),this._rowContainer.removeChild(L)):(N=this._rowElements.shift(),L=T,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),L.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const R=this._createAccessibilityTreeNode();this._rowElements.unshift(R),this._rowContainer.insertAdjacentElement("afterbegin",R)}else{const R=this._createAccessibilityTreeNode();this._rowElements.push(R),this._rowContainer.appendChild(R)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var F;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:x.anchorNode,offset:x.anchorOffset},T={node:x.focusNode,offset:x.focusOffset};if((S.node.compareDocumentPosition(T.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===T.node&&S.offset>T.offset)&&([S,T]=[T,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const j=this._rowElements.slice(-1)[0];if(T.node.compareDocumentPosition(j)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(T={node:j,offset:((F=j.textContent)==null?void 0:F.length)??0}),!this._rowContainer.contains(T.node))return;const N=({node:V,offset:te})=>{const he=V instanceof Text?V.parentNode:V;let ee=parseInt(he==null?void 0:he.getAttribute("aria-posinset"),10)-1;if(isNaN(ee))return console.warn("row is invalid. Race condition?"),null;const we=this._rowColumns.get(he);if(!we)return console.warn("columns is null. Race condition?"),null;let ce=te<we.length?we[te]:we.slice(-1)[0]+1;return ce>=this._terminal.cols&&(++ee,ce=0),{row:ee,column:ce}},L=N(S),R=N(T);if(L&&R){if(L.row>R.row||L.row===R.row&&L.column>=R.column)throw new Error("invalid range");this._terminal.select(L.column,L.row,(R.row-L.row)*this._terminal.cols-L.column+R.column)}}_handleResize(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_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 x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=y=f([m(1,C.IInstantiationService),m(2,k.ICoreBrowserService),m(3,k.IRenderService)],y)},3614:(p,a)=>{function c(w){return w.replace(/\r?\n/g,"\r")}function f(w,D){return D?"\x1B[200~"+w+"\x1B[201~":w}function m(w,D,k,C){w=f(w=c(w),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(w,!0),D.value=""}function g(w,D,k){const C=k.getBoundingClientRect(),b=w.clientX-C.left-10,y=w.clientY-C.top-10;D.style.width="20px",D.style.height="20px",D.style.left=`${b}px`,D.style.top=`${y}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=c,a.bracketTextForPaste=f,a.copyHandler=function(w,D){w.clipboardData&&w.clipboardData.setData("text/plain",D.selectionText),w.preventDefault()},a.handlePasteEvent=function(w,D,k,C){w.stopPropagation(),w.clipboardData&&m(w.clipboardData.getData("text/plain"),D,k,C)},a.paste=m,a.moveTextAreaUnderMouseCursor=g,a.rightClickHandler=function(w,D,k,C,b){g(w,D,k),b&&C.rightClickSelect(w),D.value=C.selectionText,D.select()}},7239:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorContrastCache=void 0;const f=c(1505);a.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(m,g,w){this._css.set(m,g,w)}getCss(m,g){return this._css.get(m,g)}setColor(m,g,w){this._color.set(m,g,w)}getColor(m,g){return this._color.get(m,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(c,f,m,g){c.addEventListener(f,m,g);let w=!1;return{dispose:()=>{w||(w=!0,c.removeEventListener(f,m,g))}}}},3551:function(p,a,c){var f=this&&this.__decorate||function(y,x,S,T){var j,N=arguments.length,L=N<3?x:T===null?T=Object.getOwnPropertyDescriptor(x,S):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(y,x,S,T);else for(var R=y.length-1;R>=0;R--)(j=y[R])&&(L=(N<3?j(L):N>3?j(x,S,L):j(x,S))||L);return N>3&&L&&Object.defineProperty(x,S,L),L},m=this&&this.__param||function(y,x){return function(S,T){x(S,T,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const g=c(3656),w=c(8460),D=c(844),k=c(2585),C=c(4725);let b=a.Linkifier=class extends D.Disposable{get currentLink(){return this._currentLink}constructor(y,x,S,T,j){super(),this._element=y,this._mouseService=x,this._renderService=S,this._bufferService=T,this._linkProviderService=j,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new w.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new w.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,D.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,D.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(y){this._lastMouseEvent=y;const x=this._positionFromMouseEvent(y,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const S=y.composedPath();for(let T=0;T<S.length;T++){const j=S[T];if(j.classList.contains("xterm"))break;if(j.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(y){if(this._activeLine!==y.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(y,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,y)||(this._clearCurrentLink(),this._askForLink(y,!0))}_askForLink(y,x){var T,j;this._activeProviderReplies&&x||((T=this._activeProviderReplies)==null||T.forEach((N=>{N==null||N.forEach((L=>{L.link.dispose&&L.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=y.y);let S=!1;for(const[N,L]of this._linkProviderService.linkProviders.entries())x?(j=this._activeProviderReplies)!=null&&j.get(N)&&(S=this._checkLinkProviderResult(N,y,S)):L.provideLinks(y.y,(R=>{var V,te;if(this._isMouseOut)return;const F=R==null?void 0:R.map((he=>({link:he})));(V=this._activeProviderReplies)==null||V.set(N,F),S=this._checkLinkProviderResult(N,y,S),((te=this._activeProviderReplies)==null?void 0:te.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(y.y,this._activeProviderReplies)}))}_removeIntersectingLinks(y,x){const S=new Set;for(let T=0;T<x.size;T++){const j=x.get(T);if(j)for(let N=0;N<j.length;N++){const L=j[N],R=L.link.range.start.y<y?0:L.link.range.start.x,F=L.link.range.end.y>y?this._bufferService.cols:L.link.range.end.x;for(let V=R;V<=F;V++){if(S.has(V)){j.splice(N--,1);break}S.add(V)}}}}_checkLinkProviderResult(y,x,S){var N;if(!this._activeProviderReplies)return S;const T=this._activeProviderReplies.get(y);let j=!1;for(let L=0;L<y;L++)this._activeProviderReplies.has(L)&&!this._activeProviderReplies.get(L)||(j=!0);if(!j&&T){const L=T.find((R=>this._linkAtPosition(R.link,x)));L&&(S=!0,this._handleNewLink(L))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let L=0;L<this._activeProviderReplies.size;L++){const R=(N=this._activeProviderReplies.get(L))==null?void 0:N.find((F=>this._linkAtPosition(F.link,x)));if(R){S=!0,this._handleNewLink(R);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(y){if(!this._currentLink)return;const x=this._positionFromMouseEvent(y,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(y,this._currentLink.link.text)}_clearCurrentLink(y,x){this._currentLink&&this._lastMouseEvent&&(!y||!x||this._currentLink.link.range.start.y>=y&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,D.disposeArray)(this._linkCacheDisposables))}_handleNewLink(y){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(y.link,x)&&(this._currentLink=y,this._currentLink.state={decorations:{underline:y.link.decorations===void 0||y.link.decorations.underline,pointerCursor:y.link.decorations===void 0||y.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,y.link,this._lastMouseEvent),y.link.decorations={},Object.defineProperties(y.link.decorations,{pointerCursor:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.pointerCursor},set:S=>{var T;(T=this._currentLink)!=null&&T.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.underline},set:S=>{var T,j,N;(T=this._currentLink)!=null&&T.state&&((N=(j=this._currentLink)==null?void 0:j.state)==null?void 0:N.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(y.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const T=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,j=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=T&&this._currentLink.link.range.end.y<=j&&(this._clearCurrentLink(T,j),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(y,x,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&y.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(S,x.text)}_fireUnderlineEvent(y,x){const S=y.range,T=this._bufferService.buffer.ydisp,j=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-T-1,S.end.x,S.end.y-T-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(j)}_linkLeave(y,x,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&y.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(S,x.text)}_linkAtPosition(y,x){const S=y.range.start.y*this._bufferService.cols+y.range.start.x,T=y.range.end.y*this._bufferService.cols+y.range.end.x,j=x.y*this._bufferService.cols+x.x;return S<=j&&j<=T}_positionFromMouseEvent(y,x,S){const T=S.getCoords(y,x,this._bufferService.cols,this._bufferService.rows);if(T)return{x:T[0],y:T[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(y,x,S,T,j){return{x1:y,y1:x,x2:S,y2:T,cols:this._bufferService.cols,fg:j}}};a.Linkifier=b=f([m(1,C.IMouseService),m(2,C.IRenderService),m(3,k.IBufferService),m(4,C.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,c){var f=this&&this.__decorate||function(C,b,y,x){var S,T=arguments.length,j=T<3?b:x===null?x=Object.getOwnPropertyDescriptor(b,y):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(C,b,y,x);else for(var N=C.length-1;N>=0;N--)(S=C[N])&&(j=(T<3?S(j):T>3?S(b,y,j):S(b,y))||j);return T>3&&j&&Object.defineProperty(b,y,j),j},m=this&&this.__param||function(C,b){return function(y,x){b(y,x,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const g=c(511),w=c(2585);let D=a.OscLinkProvider=class{constructor(C,b,y){this._bufferService=C,this._optionsService=b,this._oscLinkService=y}provideLinks(C,b){var F;const y=this._bufferService.buffer.lines.get(C-1);if(!y)return void b(void 0);const x=[],S=this._optionsService.rawOptions.linkHandler,T=new g.CellData,j=y.getTrimmedLength();let N=-1,L=-1,R=!1;for(let V=0;V<j;V++)if(L!==-1||y.hasContent(V)){if(y.loadCell(V,T),T.hasExtendedAttrs()&&T.extended.urlId){if(L===-1){L=V,N=T.extended.urlId;continue}R=T.extended.urlId!==N}else L!==-1&&(R=!0);if(R||L!==-1&&V===j-1){const te=(F=this._oscLinkService.getLinkData(N))==null?void 0:F.uri;if(te){const he={start:{x:L+1,y:C},end:{x:V+(R||V!==j-1?0:1),y:C}};let ee=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const we=new URL(te);["http:","https:"].includes(we.protocol)||(ee=!0)}catch{ee=!0}ee||x.push({text:te,range:he,activate:(we,ce)=>S?S.activate(we,ce,he):k(0,ce),hover:(we,ce)=>{var ve;return(ve=S==null?void 0:S.hover)==null?void 0:ve.call(S,we,ce,he)},leave:(we,ce)=>{var ve;return(ve=S==null?void 0:S.leave)==null?void 0:ve.call(S,we,ce,he)}})}R=!1,T.hasExtendedAttrs()&&T.extended.urlId?(L=V,N=T.extended.urlId):(L=-1,N=-1)}}b(x)}};function k(C,b){if(confirm(`Do you want to navigate to ${b}?
3038
3038