claude-code-session-manager 0.107.0 → 0.108.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentLibrary-Bjeq2-kp.js → AgentLibrary-Co54GThg.js} +1 -1
- package/dist/assets/{Button-CRLhoI2K.js → Button-DC6VzovQ.js} +1 -1
- package/dist/assets/{DataModel-iPJw5jcG.js → DataModel-DZ0vyJau.js} +1 -1
- package/dist/assets/{History-DfPR3_6N.js → History-Df3YwpPe.js} +1 -1
- package/dist/assets/{Hooks-Bw7H_DmC.js → Hooks-DplG6roH.js} +1 -1
- package/dist/assets/{Library-rqaJJJ1b.js → Library-DLmnlfQt.js} +1 -1
- package/dist/assets/{ListDetail-qI27OYfy.js → ListDetail-YylbvUj_.js} +1 -1
- package/dist/assets/{MarkdownEditor-BEFuHVNz.js → MarkdownEditor-DMPKWHTF.js} +1 -1
- package/dist/assets/{McpServers-Bz9O79rz.js → McpServers-Da-Ty5nc.js} +1 -1
- package/dist/assets/{Memory-DobxIoZ-.js → Memory-C3rUQ_cg.js} +1 -1
- package/dist/assets/{Panel-Cyt1wpUf.js → Panel-CC3JTnOI.js} +1 -1
- package/dist/assets/{Permissions-ChSNRUJJ.js → Permissions-XvBiMj1-.js} +1 -1
- package/dist/assets/{Plugins-CII221R2.js → Plugins-CzHY1mgS.js} +2 -2
- package/dist/assets/{ProvenanceBadge-C_sk5-v3.js → ProvenanceBadge-DaJIWVcg.js} +1 -1
- package/dist/assets/{SaveBar-BuYrg5E9.js → SaveBar-C06rFT34.js} +1 -1
- package/dist/assets/{Scheduler-eixbMGEk.js → Scheduler-BehadU-0.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BM0gLPhd.js → ScopeSwitcher-Cp5mxblN.js} +1 -1
- package/dist/assets/{Settings-qD-0W-Ut.js → Settings-Cg9LIni0.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-D0Hgdfxq.js → SkillReferenceGraph-DuWRmT_f.js} +1 -1
- package/dist/assets/{Skills-C3T_2_2o.js → Skills-CMmCZfIv.js} +1 -1
- package/dist/assets/{SystemPrompt-B-xTy9Qn.js → SystemPrompt-D_-MV025.js} +1 -1
- package/dist/assets/{TagLibrary-BH67tR5z.js → TagLibrary-D9Tv3yOJ.js} +1 -1
- package/dist/assets/{TiptapBody-CP_F_mwb.js → TiptapBody-1r4ODLJ7.js} +1 -1
- package/dist/assets/{Toggle-haRPHS5N.js → Toggle-BGT68XHP.js} +1 -1
- package/dist/assets/{ViewTabs-BHV3MA5u.js → ViewTabs-T0NBc8uv.js} +1 -1
- package/dist/assets/{index-v_3LvhMx.js → index-3_AtCAyd.js} +3 -3
- package/dist/assets/{settingsSchema-CE46TA3V.js → settingsSchema-CvoNk3Ye.js} +1 -1
- package/dist/assets/useAgentsDirWatch-1C2CBBya.js +1 -0
- package/dist/assets/{useConfigDirWatch-CjcswsWR.js → useConfigDirWatch-Cd5PnTkB.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/scripts/scheduler-mcp-server.cjs +38 -5
- package/src/main/build-info.json +4 -4
- package/src/main/lib/builtinMacros.cjs +2 -2
- package/src/main/lib/mcpToolCatalog.cjs +3 -1
- package/src/main/lib/shippedPersonaSeeds.cjs +11 -0
- package/src/seed/agents/demo-video-builder.md +69 -48
- package/dist/assets/useAgentsDirWatch-BZTi2K2e.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-1r4ODLJ7.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./Skills-CMmCZfIv.js","./Panel-CC3JTnOI.js","./ListDetail-YylbvUj_.js","./MarkdownEditor-DMPKWHTF.js","./SaveBar-C06rFT34.js","./ScopeSwitcher-Cp5mxblN.js","./Toggle-BGT68XHP.js","./ProvenanceBadge-DaJIWVcg.js","./Library-DLmnlfQt.js","./Button-DC6VzovQ.js","./listSkills-QORduPIk.js","./useConfigDirWatch-Cd5PnTkB.js","./skillFrontmatter-Dif5JIg7.js","./History-Df3YwpPe.js","./Scheduler-BehadU-0.js","./Settings-Cg9LIni0.js","./settingsSchema-CvoNk3Ye.js","./claude-settings-schema-COigsajx.js","./ViewTabs-T0NBc8uv.js","./Permissions-XvBiMj1-.js","./SystemPrompt-D_-MV025.js","./Memory-C3rUQ_cg.js","./Plugins-CzHY1mgS.js","./McpServers-Da-Ty5nc.js","./Hooks-DplG6roH.js","./AgentLibrary-Co54GThg.js","./useAgentsDirWatch-1C2CBBya.js","./TagLibrary-D9Tv3yOJ.js","./DataModel-DZ0vyJau.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var LE=Object.defineProperty;var zE=(i,e,t)=>e in i?LE(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Li=(i,e,t)=>zE(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 r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const l of r)if(l.type==="childList")for(const p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&n(p)}).observe(document,{childList:!0,subtree:!0});function t(r){const l={};return r.integrity&&(l.integrity=r.integrity),r.referrerPolicy&&(l.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?l.credentials="include":r.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(r){if(r.ep)return;r.ep=!0;const l=t(r);fetch(r.href,l)}})();function hw(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var o_={exports:{}},rf={},a_={exports:{}},vi={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -2927,7 +2927,7 @@ ${I}`,M=v.createShaderModule({code:P,label:s.name});oi("verbose",()=>`[WebGPU] $
|
|
|
2927
2927
|
* Licensed under the MIT License.
|
|
2928
2928
|
*/var gx;function j2(){return gx||(gx=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(X=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(X,{get:(se,he)=>(typeof oo<"u"?oo:se)[he]}):X)(function(X){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+X+'" is not supported')}),c=(X,se)=>()=>(X&&(se=X(X=0)),se),f=(X,se)=>{for(var he in se)n(X,he,{get:se[he],enumerable:!0})},g=(X,se,he,Te)=>{if(se&&typeof se=="object"||typeof se=="function")for(let xe of l(se))!p.call(X,xe)&&xe!==he&&n(X,xe,{get:()=>se[xe],enumerable:!(Te=r(se,xe))||Te.enumerable});return X},m=X=>g(n({},"__esModule",{value:!0}),X),w,$,k,E,b,y=c(()=>{w=new Map,$=[],k=(X,se,he)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Te=w.get(X);if(Te===void 0)w.set(X,{backend:se,priority:he});else{if(Te.priority>he)return;if(Te.priority===he&&Te.backend!==se)throw new Error(`cannot register backend "${X}" using priority ${he}`)}if(he>=0){let xe=$.indexOf(X);xe!==-1&&$.splice(xe,1);for(let Le=0;Le<$.length;Le++)if(w.get($[Le]).priority<=he){$.splice(Le,0,X);return}$.push(X)}return}throw new TypeError("not a valid backend")},E=async X=>{let se=w.get(X);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let he=!!se.initPromise;try{return he||(se.initPromise=se.backend.init(X)),await se.initPromise,se.initialized=!0,se.backend}catch(Te){return he||(se.error=`${Te}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async X=>{let se=X.executionProviders||[],he=se.map(ze=>typeof ze=="string"?ze:ze.name),Te=he.length===0?$:he,xe,Le=[],Ie=new Set;for(let ze of Te){let Qe=await E(ze);typeof Qe=="string"?Le.push({name:ze,err:Qe}):(xe||(xe=Qe),xe===Qe&&Ie.add(ze))}if(!xe)throw new Error(`no available backend found. ERR: ${Le.map(ze=>`[${ze.name}] ${ze.err}`).join(", ")}`);for(let{name:ze,err:Qe}of Le)he.includes(ze)&&console.warn(`removing requested execution provider "${ze}" from session options because it is not available: ${Qe}`);let Pe=se.filter(ze=>Ie.has(typeof ze=="string"?ze:ze.name));return[xe,new Proxy(X,{get:(ze,Qe)=>Qe==="executionProviders"?Pe:Reflect.get(ze,Qe)})]}}),S=c(()=>{y()}),x,T=c(()=>{x="1.26.0"}),R,N,O=c(()=>{T(),R="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(X){if(X!==void 0){if(typeof X!="string"||["verbose","info","warning","error","fatal"].indexOf(X)===-1)throw new Error(`Unsupported logging level: ${X}`);R=X}},get logLevel(){return R}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,F=c(()=>{O(),j=N}),U,re,de=c(()=>{U=(X,se)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=X.dims[3],he.height=X.dims[2];let Te=he.getContext("2d");if(Te!=null){let xe,Le;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=X.dims[2],Le=X.dims[3]):(xe=X.dims[3],Le=X.dims[2]);let Ie=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Pe=se==null?void 0:se.norm,ze,Qe;Pe===void 0||Pe.mean===void 0?ze=[255,255,255,255]:typeof Pe.mean=="number"?ze=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(ze=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(ze[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?Qe=[0,0,0,0]:typeof Pe.bias=="number"?Qe=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(Qe=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(Qe[3]=Pe.bias[3]));let at=Le*xe,tt=0,Ke=at,Rt=at*2,Me=-1;Ie==="RGBA"?(tt=0,Ke=at,Rt=at*2,Me=at*3):Ie==="RGB"?(tt=0,Ke=at,Rt=at*2):Ie==="RBG"&&(tt=0,Rt=at,Ke=at*2);for(let ht=0;ht<Le;ht++)for(let Ii=0;Ii<xe;Ii++){let Qt=(X.data[tt++]-Qe[0])*ze[0],ei=(X.data[Ke++]-Qe[1])*ze[1],Pi=(X.data[Rt++]-Qe[2])*ze[2],zt=Me===-1?255:(X.data[Me++]-Qe[3])*ze[3];Te.fillStyle="rgba("+Qt+","+ei+","+Pi+","+zt+")",Te.fillRect(Ii,ht,1,1)}if("toDataURL"in he)return he.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},re=(X,se)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(he!=null){let xe,Le,Ie;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=X.dims[2],Le=X.dims[1],Ie=X.dims[3]):(xe=X.dims[3],Le=X.dims[2],Ie=X.dims[1]);let Pe=se!==void 0&&se.format!==void 0?se.format:"RGB",ze=se==null?void 0:se.norm,Qe,at;ze===void 0||ze.mean===void 0?Qe=[255,255,255,255]:typeof ze.mean=="number"?Qe=[ze.mean,ze.mean,ze.mean,ze.mean]:(Qe=[ze.mean[0],ze.mean[1],ze.mean[2],255],ze.mean[3]!==void 0&&(Qe[3]=ze.mean[3])),ze===void 0||ze.bias===void 0?at=[0,0,0,0]:typeof ze.bias=="number"?at=[ze.bias,ze.bias,ze.bias,ze.bias]:(at=[ze.bias[0],ze.bias[1],ze.bias[2],0],ze.bias[3]!==void 0&&(at[3]=ze.bias[3]));let tt=Le*xe;if(se!==void 0&&(se.format!==void 0&&Ie===4&&se.format!=="RGBA"||Ie===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ke=4,Rt=0,Me=1,ht=2,Ii=3,Qt=0,ei=tt,Pi=tt*2,zt=-1;Pe==="RGBA"?(Qt=0,ei=tt,Pi=tt*2,zt=tt*3):Pe==="RGB"?(Qt=0,ei=tt,Pi=tt*2):Pe==="RBG"&&(Qt=0,Pi=tt,ei=tt*2),Te=he.createImageData(xe,Le);for(let Bi=0;Bi<Le*xe;Rt+=Ke,Me+=Ke,ht+=Ke,Ii+=Ke,Bi++)Te.data[Rt]=(X.data[Qt++]-at[0])*Qe[0],Te.data[Me]=(X.data[ei++]-at[1])*Qe[1],Te.data[ht]=(X.data[Pi++]-at[2])*Qe[2],Te.data[Ii]=zt===-1?255:(X.data[zt++]-at[3])*Qe[3]}else throw new Error("Can not access image data");return Te}}),J,pe,ce,ye,$e,me,V=c(()=>{we(),J=(X,se)=>{if(X===void 0)throw new Error("Image buffer must be defined");if(se.height===void 0||se.width===void 0)throw new Error("Image height and width must be defined");if(se.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:he,width:Te}=se,xe=se.norm??{mean:255,bias:0},Le,Ie;typeof xe.mean=="number"?Le=[xe.mean,xe.mean,xe.mean,xe.mean]:Le=[xe.mean[0],xe.mean[1],xe.mean[2],xe.mean[3]??255],typeof xe.bias=="number"?Ie=[xe.bias,xe.bias,xe.bias,xe.bias]:Ie=[xe.bias[0],xe.bias[1],xe.bias[2],xe.bias[3]??0];let Pe=se.format!==void 0?se.format:"RGBA",ze=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",Qe=he*Te,at=ze==="RGBA"?new Float32Array(Qe*4):new Float32Array(Qe*3),tt=4,Ke=0,Rt=1,Me=2,ht=3,Ii=0,Qt=Qe,ei=Qe*2,Pi=-1;Pe==="RGB"&&(tt=3,Ke=0,Rt=1,Me=2,ht=-1),ze==="RGBA"?Pi=Qe*3:ze==="RBG"?(Ii=0,ei=Qe,Qt=Qe*2):ze==="BGR"&&(ei=0,Qt=Qe,Ii=Qe*2);for(let zt=0;zt<Qe;zt++,Ke+=tt,Me+=tt,Rt+=tt,ht+=tt)at[Ii++]=(X[Ke]+Ie[0])/Le[0],at[Qt++]=(X[Rt]+Ie[1])/Le[1],at[ei++]=(X[Me]+Ie[2])/Le[2],Pi!==-1&&ht!==-1&&(at[Pi++]=(X[ht]+Ie[3])/Le[3]);return ze==="RGBA"?new Z("float32",at,[1,4,he,Te]):new Z("float32",at,[1,3,he,Te])},pe=async(X,se)=>{let he=typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement,Te=typeof ImageData<"u"&&X instanceof ImageData,xe=typeof ImageBitmap<"u"&&X instanceof ImageBitmap,Le=typeof X=="string",Ie,Pe=se??{},ze=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Qe=at=>typeof HTMLCanvasElement<"u"&&at instanceof HTMLCanvasElement||at instanceof OffscreenCanvas?at.getContext("2d"):null;if(he){let at=ze();at.width=X.width,at.height=X.height;let tt=Qe(at);if(tt!=null){let Ke=X.height,Rt=X.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(Ke=se.resizedHeight,Rt=se.resizedWidth),se!==void 0){if(Pe=se,se.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Ke,Pe.width=Rt}else Pe.tensorFormat="RGBA",Pe.height=Ke,Pe.width=Rt;tt.drawImage(X,0,0),Ie=tt.getImageData(0,0,Rt,Ke).data}else throw new Error("Can not access image data")}else if(Te){let at,tt;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(at=se.resizedHeight,tt=se.resizedWidth):(at=X.height,tt=X.width),se!==void 0&&(Pe=se),Pe.format="RGBA",Pe.height=at,Pe.width=tt,se!==void 0){let Ke=ze();Ke.width=tt,Ke.height=at;let Rt=Qe(Ke);if(Rt!=null)Rt.putImageData(X,0,0),Ie=Rt.getImageData(0,0,tt,at).data;else throw new Error("Can not access image data")}else Ie=X.data}else if(xe){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let at=ze();at.width=X.width,at.height=X.height;let tt=Qe(at);if(tt!=null){let Ke=X.height,Rt=X.width;return tt.drawImage(X,0,0,Rt,Ke),Ie=tt.getImageData(0,0,Rt,Ke).data,Pe.height=Ke,Pe.width=Rt,J(Ie,Pe)}else throw new Error("Can not access image data")}else{if(Le)return new Promise((at,tt)=>{let Ke=ze(),Rt=Qe(Ke);if(!X||!Rt)return tt();let Me=new Image;Me.crossOrigin="Anonymous",Me.src=X,Me.onload=()=>{Ke.width=Me.width,Ke.height=Me.height,Rt.drawImage(Me,0,0,Ke.width,Ke.height);let ht=Rt.getImageData(0,0,Ke.width,Ke.height);Pe.height=Ke.height,Pe.width=Ke.width,at(J(ht.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ie!==void 0)return J(Ie,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},ce=(X,se)=>{let{width:he,height:Te,download:xe,dispose:Le}=se,Ie=[1,Te,he,4];return new Z({location:"texture",type:"float32",texture:X,dims:Ie,download:xe,dispose:Le})},ye=(X,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Le}=se;return new Z({location:"gpu-buffer",type:he??"float32",gpuBuffer:X,dims:Te,download:xe,dispose:Le})},$e=(X,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Le}=se;return new Z({location:"ml-tensor",type:he??"float32",mlTensor:X,dims:Te,download:xe,dispose:Le})},me=(X,se,he)=>new Z({location:"cpu-pinned",type:X,data:se,dims:he??[se.length]})}),Y,W,ee,ue,Ee=c(()=>{Y=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"]]),ee=!1,ue=()=>{if(!ee){ee=!0;let X=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,Te=typeof he<"u"&&he.from;X&&(Y.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),se&&(Y.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),Te?(Y.set("float16",he),W.set(he,"float16")):Y.set("float16",Uint16Array)}}}),Ge,Je,ve=c(()=>{we(),Ge=X=>{let se=1;for(let he=0;he<X.length;he++){let Te=X[he];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${he}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${Te}`);se*=Te}return se},Je=(X,se)=>{switch(X.location){case"cpu":return new Z(X.type,X.data,se);case"cpu-pinned":return new Z({location:"cpu-pinned",data:X.data,type:X.type,dims:se});case"texture":return new Z({location:"texture",texture:X.texture,type:X.type,dims:se});case"gpu-buffer":return new Z({location:"gpu-buffer",gpuBuffer:X.gpuBuffer,type:X.type,dims:se});case"ml-tensor":return new Z({location:"ml-tensor",mlTensor:X.mlTensor,type:X.type,dims:se});default:throw new Error(`tensorReshape: tensor location ${X.location} is not supported`)}}}),Z,we=c(()=>{de(),V(),Ee(),ve(),Z=class{constructor(X,se,he){ue();let Te,xe;if(typeof X=="object"&&"location"in X)switch(this.dataLocation=X.location,Te=X.type,xe=X.dims,X.location){case"cpu-pinned":{let Ie=Y.get(Te);if(!Ie)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(X.data instanceof Ie))throw new TypeError(`buffer should be of type ${Ie.name}`);this.cpuData=X.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=X.texture,this.downloader=X.download,this.disposer=X.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=X.gpuBuffer,this.downloader=X.download,this.disposer=X.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=X.mlTensor,this.downloader=X.download,this.disposer=X.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ie,Pe;if(typeof X=="string")if(Te=X,Pe=he,X==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");Ie=se}else{let ze=Y.get(X);if(ze===void 0)throw new TypeError(`Unsupported tensor type: ${X}.`);if(Array.isArray(se)){if(X==="float16"&&ze===Uint16Array||X==="uint4"||X==="int4")throw new TypeError(`Creating a ${X} tensor from number array is not supported. Please use ${ze.name} as data.`);X==="uint64"||X==="int64"?Ie=ze.from(se,BigInt):Ie=ze.from(se)}else if(se instanceof ze)Ie=se;else if(se instanceof Uint8ClampedArray)if(X==="uint8")Ie=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(X==="float16"&&se instanceof Uint16Array&&ze!==Uint16Array)Ie=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${ze}`)}else if(Pe=se,Array.isArray(X)){if(X.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let ze=typeof X[0];if(ze==="string")Te="string",Ie=X;else if(ze==="boolean")Te="bool",Ie=Uint8Array.from(X);else throw new TypeError(`Invalid element type of data array: ${ze}.`)}else if(X instanceof Uint8ClampedArray)Te="uint8",Ie=Uint8Array.from(X);else{let ze=W.get(X.constructor);if(ze===void 0)throw new TypeError(`Unsupported type for tensor data: ${X.constructor}.`);Te=ze,Ie=X}if(Pe===void 0)Pe=[Ie.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");xe=Pe,this.cpuData=Ie,this.dataLocation="cpu"}let Le=Ge(xe);if(this.cpuData&&Le!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Le/2)===this.cpuData.length))throw new Error(`Tensor's size(${Le}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=xe,this.size=Le}static async fromImage(X,se){return pe(X,se)}static fromTexture(X,se){return ce(X,se)}static fromGpuBuffer(X,se){return ye(X,se)}static fromMLTensor(X,se){return $e(X,se)}static fromPinnedBuffer(X,se,he){return me(X,se,he)}toDataURL(X){return U(this,X)}toImageData(X){return re(this,X)}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(X){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let se=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=se,X&&this.disposer&&(this.disposer(),this.disposer=void 0),se}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(X){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Je(this,X)}}}),fe,Ae=c(()=>{we(),fe=Z}),ke,st,yt,ot,Nt,gt,pi=c(()=>{O(),ke=(X,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${X}::ORT::${se}`)},st=(X,se)=>{var xe;let he=((xe=new Error().stack)==null?void 0:xe.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Le=0;Le<he.length;Le++){if(Te&&!he[Le].includes("TRACE_FUNC")){let Ie=`FUNC_${X}::${he[Le].trim().split(" ")[1]}`;se&&(Ie+=`::${se}`),ke("CPU",Ie);return}he[Le].includes("TRACE_FUNC")&&(Te=!0)}},yt=X=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||st("BEGIN",X)},ot=X=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||st("END",X)},Nt=X=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${X}`)},gt=X=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${X}`)}}),it,Tt=c(()=>{y(),Ae(),pi(),it=class L1{constructor(se){this.handler=se}async run(se,he,Te){yt(),Nt("InferenceSession.run");let xe={},Le={};if(typeof se!="object"||se===null||se instanceof fe||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ie=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof fe)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(he)){if(he.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ie=!1;for(let Qe of he){if(typeof Qe!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Qe)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Qe}.`);xe[Qe]=null}if(typeof Te=="object"&&Te!==null)Le=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let Qe=!1,at=Object.getOwnPropertyNames(he);for(let tt of this.outputNames)if(at.indexOf(tt)!==-1){let Ke=he[tt];(Ke===null||Ke instanceof fe)&&(Qe=!0,Ie=!1,xe[tt]=Ke)}if(Qe){if(typeof Te=="object"&&Te!==null)Le=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Le=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Qe of this.inputNames)if(typeof se[Qe]>"u")throw new Error(`input '${Qe}' is missing in 'feeds'.`);if(Ie)for(let Qe of this.outputNames)xe[Qe]=null;let Pe=await this.handler.run(se,xe,Le),ze={};for(let Qe in Pe)if(Object.hasOwnProperty.call(Pe,Qe)){let at=Pe[Qe];at instanceof fe?ze[Qe]=at:ze[Qe]=new fe(at.type,at.data,at.dims)}return gt("InferenceSession.run"),ot(),ze}async release(){return this.handler.dispose()}static async create(se,he,Te,xe){yt(),Nt("InferenceSession.create");let Le,Ie={};if(typeof se=="string"){if(Le=se,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Le=se,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let at=se,tt=0,Ke=se.byteLength;if(typeof he=="object"&&he!==null)Ie=he;else if(typeof he=="number"){if(tt=he,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=at.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${at.byteLength}).`);if(Ke=se.byteLength-tt,typeof Te=="number"){if(Ke=Te,!Number.isSafeInteger(Ke))throw new RangeError("'byteLength' must be an integer.");if(Ke<=0||tt+Ke>at.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${at.byteLength-tt}].`);if(typeof xe=="object"&&xe!==null)Ie=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Le=new Uint8Array(at,tt,Ke)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,ze]=await b(Ie),Qe=await Pe.createInferenceSessionHandler(Le,ze);return gt("InferenceSession.create"),ot(),new L1(Qe)}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}}}),Oe,wt=c(()=>{Tt(),Oe=it}),ft=c(()=>{}),Xe=c(()=>{}),ct=c(()=>{}),Zt=c(()=>{}),ci={};f(ci,{InferenceSession:()=>Oe,TRACE:()=>ke,TRACE_EVENT_BEGIN:()=>Nt,TRACE_EVENT_END:()=>gt,TRACE_FUNC_BEGIN:()=>yt,TRACE_FUNC_END:()=>ot,Tensor:()=>fe,env:()=>j,registerBackend:()=>k});var ii=c(()=>{S(),F(),wt(),Ae(),ft(),Xe(),pi(),ct(),Zt()}),fi=c(()=>{}),ui={};f(ui,{default:()=>Ai});var Si,rt,Ai,us=c(()=>{var X;ge(),Xn(),Kn(),Si="ort-wasm-proxy-worker",rt=((X=globalThis.self)==null?void 0:X.name)===Si,rt&&(self.onmessage=se=>{let{type:he,in:Te}=se.data;try{switch(he){case"init-wasm":sr(Te.wasm).then(()=>{Vo(Te).then(()=>{postMessage({type:he})},xe=>{postMessage({type:he,err:xe})})},xe=>{postMessage({type:he,err:xe})});break;case"init-ep":{let{epName:xe,env:Le}=Te;Er(Le,xe).then(()=>{postMessage({type:he})},Ie=>{postMessage({type:he,err:Ie})});break}case"copy-from":{let{buffer:xe}=Te,Le=oi(xe);postMessage({type:he,out:Le});break}case"create":{let{model:xe,options:Le}=Te;vs(xe,Le).then(Ie=>{postMessage({type:he,out:Ie})},Ie=>{postMessage({type:he,err:Ie})});break}case"release":Vr(Te),postMessage({type:he});break;case"run":{let{sessionId:xe,inputIndices:Le,inputs:Ie,outputIndices:Pe,options:ze}=Te;qe(xe,Le,Ie,Pe,new Array(Pe.length).fill(null),ze).then(Qe=>{Qe.some(at=>at[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:Qe},vt([...Ie,...Qe]))},Qe=>{postMessage({type:he,err:Qe})});break}case"end-profiling":Jn(Te),postMessage({type:he});break;default:}}catch(xe){postMessage({type:he,err:xe})}}),Ai=rt?null:se=>new Worker(se??di,{type:"classic",name:Si})}),cn,Yi,di,gn,zi,Ps,hs,ps,Hr,xr,Sr,Gs,zn,Kn=c(()=>{fi(),cn=typeof location>"u"?void 0:location.origin,Yi=()=>{var X,se;return typeof document<"u"?(X=document.currentScript)==null?void 0:X.src:typeof self<"u"?(se=self.location)==null?void 0:se.href:void 0},di=Yi(),gn=()=>{if(di&&!di.startsWith("blob:"))return di.substring(0,di.lastIndexOf("/")+1)},zi=(X,se)=>{try{let he=se??di;return(he?new URL(X,he):new URL(X)).origin===cn}catch{return!1}},Ps=(X,se)=>{let he=se??di;try{return(he?new URL(X,he):new URL(X)).href}catch{return}},hs=(X,se)=>`${se??"./"}${X}`,ps=async X=>{let se=await(await fetch(X,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},Hr=async X=>(await import(X)).default,xr=(us(),m(ui)).default,Sr=async()=>{if(!di)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(zi(di))return[void 0,xr()];let X=await ps(di);return[X,xr(X)]},Gs=void 0,zn=async(X,se,he,Te)=>{let xe=Gs&&!(X||se);if(xe)if(di)xe=zi(di)||Te&&!he;else if(Te&&!he)xe=!0;else throw new Error("cannot determine the script source URL.");if(xe)return[void 0,Gs];{let Le="ort-wasm-simd-threaded.mjs",Ie=X??Ps(Le,se),Pe=he&&Ie&&!zi(Ie,se),ze=Pe?await ps(Ie):Ie??hs(Le,se);return[Pe?ze:void 0,await Hr(ze)]}}}),tr,Bn,fs,Rs,co,ir,nr,sr,Gt,Xn=c(()=>{Kn(),Bn=!1,fs=!1,Rs=!1,co=()=>{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}},ir=()=>{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}},nr=()=>{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}},sr=async X=>{if(Bn)return Promise.resolve();if(fs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Rs)throw new Error("previous call to 'initializeWebAssembly()' failed.");fs=!0;let se=X.initTimeout,he=X.numThreads;if(X.simd!==!1){if(X.simd==="relaxed"){if(!nr())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ir())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=co();he>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+he+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),X.numThreads=he=1);let xe=X.wasmPaths,Le=typeof xe=="string"?xe:void 0,Ie=xe==null?void 0:xe.mjs,Pe=(Ie==null?void 0:Ie.href)??Ie,ze=xe==null?void 0:xe.wasm,Qe=(ze==null?void 0:ze.href)??ze,at=X.wasmBinary,[tt,Ke]=await zn(Pe,Le,he>1,!!at||!!Qe),Rt=!1,Me=[];if(se>0&&Me.push(new Promise(ht=>{setTimeout(()=>{Rt=!0,ht()},se)})),Me.push(new Promise((ht,Ii)=>{let Qt={numThreads:he};if(at)Qt.wasmBinary=at,Qt.locateFile=ei=>ei;else if(Qe||Le)Qt.locateFile=ei=>Qe??Le+ei;else if(Pe&&Pe.indexOf("blob:")!==0)Qt.locateFile=ei=>new URL(ei,Pe).href;else if(tt){let ei=gn();ei&&(Qt.locateFile=Pi=>ei+Pi)}Ke(Qt).then(ei=>{fs=!1,Bn=!0,tr=ei,ht(),tt&&URL.revokeObjectURL(tt)},ei=>{fs=!1,Rs=!0,Ii(ei)})})),await Promise.race(Me),Rt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},Gt=()=>{if(Bn&&tr)return tr;throw new Error("WebAssembly is not initialized yet.")}}),Ki,Ti,Dt,Wr=c(()=>{Xn(),Ki=(X,se)=>{let he=Gt(),Te=he.lengthBytesUTF8(X)+1,xe=he._malloc(Te);return he.stringToUTF8(X,xe,Te),se.push(xe),xe},Ti=(X,se,he,Te)=>{if(typeof X=="object"&&X!==null){if(he.has(X))throw new Error("Circular reference in options");he.add(X)}Object.entries(X).forEach(([xe,Le])=>{let Ie=se?se+xe:xe;if(typeof Le=="object")Ti(Le,Ie+".",he,Te);else if(typeof Le=="string"||typeof Le=="number")Te(Ie,Le.toString());else if(typeof Le=="boolean")Te(Ie,Le?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Le}`)})},Dt=X=>{let se=Gt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetLastError(xe,xe+Te);let Le=Number(se.getValue(xe,Te===4?"i32":"i64")),Ie=se.getValue(xe+Te,"*"),Pe=Ie?se.UTF8ToString(Ie):"";throw new Error(`${X} ERROR_CODE: ${Le}, ERROR_MESSAGE: ${Pe}`)}finally{se.stackRestore(he)}}}),uo,Ca=c(()=>{Xn(),Wr(),uo=X=>{let se=Gt(),he=0,Te=[],xe=X||{};try{if((X==null?void 0:X.logSeverityLevel)===void 0)xe.logSeverityLevel=2;else if(typeof X.logSeverityLevel!="number"||!Number.isInteger(X.logSeverityLevel)||X.logSeverityLevel<0||X.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${X.logSeverityLevel}`);if((X==null?void 0:X.logVerbosityLevel)===void 0)xe.logVerbosityLevel=0;else if(typeof X.logVerbosityLevel!="number"||!Number.isInteger(X.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${X.logVerbosityLevel}`);(X==null?void 0:X.terminate)===void 0&&(xe.terminate=!1);let Le=0;return(X==null?void 0:X.tag)!==void 0&&(Le=Ki(X.tag,Te)),he=se._OrtCreateRunOptions(xe.logSeverityLevel,xe.logVerbosityLevel,!!xe.terminate,Le),he===0&&Dt("Can't create run options."),(X==null?void 0:X.extra)!==void 0&&Ti(X.extra,"",new WeakSet,(Ie,Pe)=>{let ze=Ki(Ie,Te),Qe=Ki(Pe,Te);se._OrtAddRunConfigEntry(he,ze,Qe)!==0&&Dt(`Can't set a run config entry: ${Ie} - ${Pe}.`)}),[he,Te]}catch(Le){throw he!==0&&se._OrtReleaseRunOptions(he),Te.forEach(Ie=>se._free(Ie)),Le}}}),ho,po,Uo,Rn,ka,Ea,Di=c(()=>{Xn(),Wr(),ho=X=>{switch(X){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: ${X}`)}},po=X=>{switch(X){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${X}`)}},Uo=X=>{X.extra||(X.extra={}),X.extra.session||(X.extra.session={});let se=X.extra.session;se.use_ort_model_bytes_directly||(se.use_ort_model_bytes_directly="1"),X.executionProviders&&X.executionProviders.some(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(X.enableMemPattern=!1)},Rn=(X,se,he,Te)=>{let xe=Ki(se,Te),Le=Ki(he,Te);Gt()._OrtAddSessionConfigEntry(X,xe,Le)!==0&&Dt(`Can't set a session config entry: ${se} - ${he}.`)},ka=async(X,se,he)=>{let Te=se.executionProviders;for(let xe of Te){let Le=typeof xe=="string"?xe:xe.name,Ie=[];switch(Le){case"webnn":if(Le="WEBNN",Rn(X,"session.disable_quant_qdq","1",he),Rn(X,"session.disable_qdq_constant_folding","1",he),typeof xe!="string"){let tt=xe==null?void 0:xe.deviceType;tt&&Rn(X,"deviceType",tt,he)}break;case"webgpu":if(Le="JS",typeof xe!="string"){let tt=xe;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Rn(X,"preferredLayout",tt.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Le}`)}let Pe=Ki(Le,he),ze=Ie.length,Qe=0,at=0;if(ze>0){Qe=Gt()._malloc(ze*Gt().PTR_SIZE),he.push(Qe),at=Gt()._malloc(ze*Gt().PTR_SIZE),he.push(at);for(let tt=0;tt<ze;tt++)Gt().setValue(Qe+tt*Gt().PTR_SIZE,Ie[tt][0],"*"),Gt().setValue(at+tt*Gt().PTR_SIZE,Ie[tt][1],"*")}await Gt()._OrtAppendExecutionProvider(X,Pe,Qe,at,ze)!==0&&Dt(`Can't append execution provider: ${Le}.`)}},Ea=async X=>{let se=Gt(),he=0,Te=[],xe=X||{};Uo(xe);try{let Le=ho(xe.graphOptimizationLevel??"all"),Ie=po(xe.executionMode??"sequential"),Pe=typeof xe.logId=="string"?Ki(xe.logId,Te):0,ze=xe.logSeverityLevel??2;if(!Number.isInteger(ze)||ze<0||ze>4)throw new Error(`log severity level is not valid: ${ze}`);let Qe=xe.logVerbosityLevel??0;if(!Number.isInteger(Qe)||Qe<0||Qe>4)throw new Error(`log verbosity level is not valid: ${Qe}`);let at=typeof xe.optimizedModelFilePath=="string"?Ki(xe.optimizedModelFilePath,Te):0;if(he=se._OrtCreateSessionOptions(Le,!!xe.enableCpuMemArena,!!xe.enableMemPattern,Ie,!!xe.enableProfiling,0,Pe,ze,Qe,at),he===0&&Dt("Can't create session options."),xe.executionProviders&&await ka(he,xe,Te),xe.enableGraphCapture!==void 0){if(typeof xe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${xe.enableGraphCapture}`);Rn(he,"enableGraphCapture",xe.enableGraphCapture.toString(),Te)}if(xe.freeDimensionOverrides)for(let[tt,Ke]of Object.entries(xe.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Ke!="number"||!Number.isInteger(Ke)||Ke<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ke}`);let Rt=Ki(tt,Te);se._OrtAddFreeDimensionOverride(he,Rt,Ke)!==0&&Dt(`Can't set a free dimension override: ${tt} - ${Ke}.`)}return xe.extra!==void 0&&Ti(xe.extra,"",new WeakSet,(tt,Ke)=>{Rn(he,tt,Ke,Te)}),[he,Te]}catch(Le){throw he!==0&&se._OrtReleaseSessionOptions(he)!==0&&Dt("Can't release session options."),Te.forEach(Ie=>se._free(Ie)),Le}}}),Gn,Ji,Fn,rr,Ur,Cr,ms,Sn,Ft=c(()=>{Gn=X=>{switch(X){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: ${X}`)}},Ji=X=>{switch(X){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: ${X}`)}},Fn=(X,se)=>{let he=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][X],Te=typeof se=="number"?se:se.reduce((xe,Le)=>xe*Le,1);return he>0?Math.ceil(Te*he):void 0},rr=X=>{switch(X){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: ${X}`)}},Ur=X=>{switch(X){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: ${X}`)}},Cr=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",ms=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint64"||X==="int8"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",Sn=X=>{switch(X){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: ${X}`)}}}),Zi,kr=c(()=>{fi(),Zi=async X=>{if(typeof X=="string"){let se=await fetch(X);if(!se.ok)throw new Error(`failed to load external data file: ${X}`);let he=se.headers.get("Content-Length"),Te=he?parseInt(he,10):0;if(Te<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${X}, no response body.`);let xe=se.body.getReader(),Le;try{Le=new ArrayBuffer(Te)}catch(Pe){if(Pe instanceof RangeError){let ze=Math.ceil(Te/65536);Le=new WebAssembly.Memory({initial:ze,maximum:ze}).buffer}else throw Pe}let Ie=0;for(;;){let{done:Pe,value:ze}=await xe.read();if(Pe)break;let Qe=ze.byteLength;new Uint8Array(Le,Ie,Qe).set(ze),Ie+=Qe}return new Uint8Array(Le,0,Te)}}else return X instanceof Blob?new Uint8Array(await X.arrayBuffer()):X instanceof Uint8Array?X:new Uint8Array(X)}}),gs,Vo,Er,Yn,Fs,Tr,oi,vs,Vr,js,qe,Jn,vt,ge=c(()=>{ii(),Ca(),Di(),Ft(),Xn(),Wr(),kr(),gs=(X,se)=>{Gt()._OrtInit(X,se)!==0&&Dt("Can't initialize onnxruntime.")},Vo=async X=>{gs(X.wasm.numThreads,Ur(X.logLevel))},Er=async(X,se)=>{var Te,xe;(xe=(Te=Gt()).asyncInit)==null||xe.call(Te);let he=X.webgpu.adapter;if(se==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(he){if(typeof he.limits!="object"||typeof he.features!="object"||typeof he.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Le=X.webgpu.powerPreference;if(Le!==void 0&&Le!=="low-power"&&Le!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Le}"`);let Ie=X.webgpu.forceFallbackAdapter;if(Ie!==void 0&&typeof Ie!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ie}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Le,forceFallbackAdapter:Ie}),!he)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(se==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Yn=new Map,Fs=X=>{let se=Gt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetInputOutputCount(X,xe,xe+Te)!==0&&Dt("Can't get session input/output count.");let Le=Te===4?"i32":"i64";return[Number(se.getValue(xe,Le)),Number(se.getValue(xe+Te,Le))]}finally{se.stackRestore(he)}},Tr=(X,se)=>{let he=Gt(),Te=he.stackSave(),xe=0;try{let Le=he.PTR_SIZE,Ie=he.stackAlloc(2*Le);he._OrtGetInputOutputMetadata(X,se,Ie,Ie+Le)!==0&&Dt("Can't get session input/output metadata.");let Pe=Number(he.getValue(Ie,"*"));xe=Number(he.getValue(Ie+Le,"*"));let ze=he.HEAP32[xe/4];if(ze===0)return[Pe,0];let Qe=he.HEAPU32[xe/4+1],at=[];for(let tt=0;tt<Qe;tt++){let Ke=Number(he.getValue(xe+8+tt*Le,"*"));at.push(Ke!==0?he.UTF8ToString(Ke):Number(he.getValue(xe+8+(tt+Qe)*Le,"*")))}return[Pe,ze,at]}finally{he.stackRestore(Te),xe!==0&&he._OrtFree(xe)}},oi=X=>{let se=Gt(),he=se._malloc(X.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${X.byteLength}.`);return se.HEAPU8.set(X,he),[he,X.byteLength]},vs=async(X,se)=>{var at,tt,Ke;let he,Te,xe=Gt();Array.isArray(X)?[he,Te]=X:X.buffer===xe.HEAPU8.buffer?[he,Te]=[X.byteOffset,X.byteLength]:[he,Te]=oi(X);let Le=0,Ie=0,Pe=[],ze=[],Qe=[];try{if([Ie,Pe]=await Ea(se),(se==null?void 0:se.externalData)&&xe.mountExternalData){let Bi=[];for(let hi of se.externalData){let Cn=typeof hi=="string"?hi:hi.path;Bi.push(Zi(typeof hi=="string"?hi:hi.data).then(Hn=>{xe.mountExternalData(Cn,Hn)}))}await Promise.all(Bi)}for(let Bi of(se==null?void 0:se.executionProviders)??[])if((typeof Bi=="string"?Bi:Bi.name)==="webnn"){if(xe.shouldTransferToMLTensor=!1,typeof Bi!="string"){let hi=Bi,Cn=hi==null?void 0:hi.context,Hn=hi==null?void 0:hi.gpuDevice,Zn=hi==null?void 0:hi.deviceType,Da=hi==null?void 0:hi.powerPreference;Cn?xe.currentContext=Cn:Hn?xe.currentContext=await xe.webnnCreateMLContext(Hn):xe.currentContext=await xe.webnnCreateMLContext({deviceType:Zn,powerPreference:Da})}else xe.currentContext=await xe.webnnCreateMLContext();break}Le=await xe._OrtCreateSession(he,Te,Ie),(at=xe.webgpuOnCreateSession)==null||at.call(xe,Le),Le===0&&Dt("Can't create a session."),(tt=xe.jsepOnCreateSession)==null||tt.call(xe),xe.currentContext&&(xe.webnnRegisterMLContext(Le,xe.currentContext),xe.currentContext=void 0,xe.shouldTransferToMLTensor=!0);let[Rt,Me]=Fs(Le),ht=!!(se!=null&&se.enableGraphCapture),Ii=[],Qt=[],ei=[],Pi=[],zt=[];for(let Bi=0;Bi<Rt;Bi++){let[hi,Cn,Hn]=Tr(Le,Bi);hi===0&&Dt("Can't get an input name."),ze.push(hi);let Zn=xe.UTF8ToString(hi);Ii.push(Zn),ei.push(Cn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ji(Cn),shape:Hn})}for(let Bi=0;Bi<Me;Bi++){let[hi,Cn,Hn]=Tr(Le,Bi+Rt);hi===0&&Dt("Can't get an output name."),Qe.push(hi);let Zn=xe.UTF8ToString(hi);Qt.push(Zn),Pi.push(Cn===0?{name:Zn,isTensor:!1}:{name:Zn,isTensor:!0,type:Ji(Cn),shape:Hn})}return Yn.set(Le,[Le,ze,Qe,null,ht,!1]),[Le,Ii,Qt,ei,Pi]}catch(Rt){throw ze.forEach(Me=>xe._OrtFree(Me)),Qe.forEach(Me=>xe._OrtFree(Me)),Le!==0&&xe._OrtReleaseSession(Le)!==0&&Dt("Can't release session."),Rt}finally{xe._free(he),Ie!==0&&xe._OrtReleaseSessionOptions(Ie)!==0&&Dt("Can't release session options."),Pe.forEach(Rt=>xe._free(Rt)),(Ke=xe.unmountExternalData)==null||Ke.call(xe)}},Vr=X=>{var ze,Qe,at;let se=Gt(),he=Yn.get(X);if(!he)throw new Error(`cannot release session. invalid session id: ${X}`);let[Te,xe,Le,Ie,Pe]=he;Ie&&(Pe&&se._OrtClearBoundOutputs(Ie.handle)!==0&&Dt("Can't clear bound outputs."),se._OrtReleaseBinding(Ie.handle)!==0&&Dt("Can't release IO binding.")),(ze=se.jsepOnReleaseSession)==null||ze.call(se,X),(Qe=se.webnnOnReleaseSession)==null||Qe.call(se,X),(at=se.webgpuOnReleaseSession)==null||at.call(se,X),xe.forEach(tt=>se._OrtFree(tt)),Le.forEach(tt=>se._OrtFree(tt)),se._OrtReleaseSession(Te)!==0&&Dt("Can't release session."),Yn.delete(X)},js=async(X,se,he,Te,xe,Le,Ie=!1)=>{if(!X){se.push(0);return}let Pe=Gt(),ze=Pe.PTR_SIZE,Qe=X[0],at=X[1],tt=X[3],Ke=tt,Rt,Me;if(Qe==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ie&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Le} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Qt=X[2].gpuBuffer;Me=Fn(Gn(Qe),at);{let ei=Pe.jsepRegisterBuffer;if(!ei)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Rt=ei(Te,Le,Qt,Me)}}else if(tt==="ml-tensor"){let Qt=X[2].mlTensor;Me=Fn(Gn(Qe),at);let ei=Pe.webnnRegisterMLTensor;if(!ei)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Rt=ei(Te,Qt,Gn(Qe),at)}else{let Qt=X[2];if(Array.isArray(Qt)){Me=ze*Qt.length,Rt=Pe._malloc(Me),he.push(Rt);for(let ei=0;ei<Qt.length;ei++){if(typeof Qt[ei]!="string")throw new TypeError(`tensor data at index ${ei} is not a string`);Pe.setValue(Rt+ei*ze,Ki(Qt[ei],he),"*")}}else{let ei=Pe.webnnIsGraphInput,Pi=Pe.webnnIsGraphOutput;if(Qe!=="string"&&ei&&Pi){let zt=Pe.UTF8ToString(xe);if(ei(Te,zt)||Pi(Te,zt)){let Bi=Gn(Qe);Me=Fn(Bi,at),Ke="ml-tensor";let hi=Pe.webnnCreateTemporaryTensor,Cn=Pe.webnnUploadTensor;if(!hi||!Cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Hn=await hi(Te,Bi,at);Cn(Hn,new Uint8Array(Qt.buffer,Qt.byteOffset,Qt.byteLength)),Rt=Hn}else Me=Qt.byteLength,Rt=Pe._malloc(Me),he.push(Rt),Pe.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Me),Rt)}else Me=Qt.byteLength,Rt=Pe._malloc(Me),he.push(Rt),Pe.HEAPU8.set(new Uint8Array(Qt.buffer,Qt.byteOffset,Me),Rt)}}let ht=Pe.stackSave(),Ii=Pe.stackAlloc(4*at.length);try{at.forEach((ei,Pi)=>Pe.setValue(Ii+Pi*ze,ei,ze===4?"i32":"i64"));let Qt=Pe._OrtCreateTensor(Gn(Qe),Rt,Me,Ii,at.length,Sn(Ke));Qt===0&&Dt(`Can't create tensor for input/output. session=${Te}, index=${Le}.`),se.push(Qt)}finally{Pe.stackRestore(ht)}},qe=async(X,se,he,Te,xe,Le)=>{var Qn,pl,pc;let Ie=Gt(),Pe=Ie.PTR_SIZE,ze=Yn.get(X);if(!ze)throw new Error(`cannot run inference. invalid session id: ${X}`);let Qe=ze[0],at=ze[1],tt=ze[2],Ke=ze[3],Rt=ze[4];ze[5];let Me=se.length,ht=Te.length,Ii=0,Qt=[],ei=[],Pi=[],zt=[],Bi=[],hi=Ie.stackSave(),Cn=Ie.stackAlloc(Me*Pe),Hn=Ie.stackAlloc(Me*Pe),Zn=Ie.stackAlloc(ht*Pe),Da=Ie.stackAlloc(ht*Pe);try{[Ii,Qt]=uo(Le),Nt("wasm prepareInputOutputTensor");for(let li=0;li<Me;li++)await js(he[li],ei,zt,X,at[se[li]],se[li],Rt);for(let li=0;li<ht;li++)await js(xe[li],Pi,zt,X,tt[Te[li]],Me+Te[li],Rt);gt("wasm prepareInputOutputTensor");for(let li=0;li<Me;li++)Ie.setValue(Cn+li*Pe,ei[li],"*"),Ie.setValue(Hn+li*Pe,at[se[li]],"*");for(let li=0;li<ht;li++)Ie.setValue(Zn+li*Pe,Pi[li],"*"),Ie.setValue(Da+li*Pe,tt[Te[li]],"*");(Qn=Ie.jsepOnRunStart)==null||Qn.call(Ie,Qe),(pl=Ie.webnnOnRunStart)==null||pl.call(Ie,Qe);let kn;kn=await Ie._OrtRun(Qe,Hn,Cn,Me,Da,ht,Zn,Ii),kn!==0&&Dt("failed to call OrtRun().");let ar=[],fc=[];Nt("wasm ProcessOutputTensor");for(let li=0;li<ht;li++){let Ws=Number(Ie.getValue(Zn+li*Pe,"*"));if(Ws===Pi[li]||Bi.includes(Pi[li])){ar.push(xe[li]),Ws!==Pi[li]&&Ie._OrtReleaseTensor(Ws)!==0&&Dt("Can't release tensor.");continue}let Cd=Ie.stackSave(),Ar=Ie.stackAlloc(4*Pe),qo=!1,un,es=0;try{Ie._OrtGetTensorData(Ws,Ar,Ar+Pe,Ar+2*Pe,Ar+3*Pe)!==0&&Dt(`Can't access output tensor data on index ${li}.`);let fl=Pe===4?"i32":"i64",ts=Number(Ie.getValue(Ar,fl));es=Ie.getValue(Ar+Pe,"*");let mc=Ie.getValue(Ar+Pe*2,"*"),kd=Number(Ie.getValue(Ar+Pe*3,fl)),Ir=[];for(let hn=0;hn<kd;hn++)Ir.push(Number(Ie.getValue(mc+hn*Pe,fl)));Ie._OrtFree(mc)!==0&&Dt("Can't free memory for tensor dims.");let Us=Ir.reduce((hn,Xi)=>hn*Xi,1);un=Ji(ts);let lr=Ke==null?void 0:Ke.outputPreferredLocations[Te[li]];if(un==="string"){if(lr==="gpu-buffer"||lr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let hn=[];for(let Xi=0;Xi<Us;Xi++){let Vs=Ie.getValue(es+Xi*Pe,"*"),gc=Ie.getValue(es+(Xi+1)*Pe,"*"),vc=Xi===Us-1?void 0:gc-Vs;hn.push(Ie.UTF8ToString(Vs,vc))}ar.push([un,Ir,hn,"cpu"])}else if(lr==="gpu-buffer"&&Us>0){let hn=Ie.jsepGetBuffer;if(!hn)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Xi=hn(es),Vs=Fn(ts,Us);if(Vs===void 0||!Cr(un))throw new Error(`Unsupported data type: ${un}`);qo=!0,ar.push([un,Ir,{gpuBuffer:Xi,download:Ie.jsepCreateDownloader(Xi,Vs,un),dispose:()=>{Ie._OrtReleaseTensor(Ws)!==0&&Dt("Can't release tensor.")}},"gpu-buffer"])}else if(lr==="ml-tensor"&&Us>0){let hn=Ie.webnnEnsureTensor,Xi=Ie.webnnIsGraphInputOutputTypeSupported;if(!hn||!Xi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Fn(ts,Us)===void 0||!ms(un))throw new Error(`Unsupported data type: ${un}`);if(!Xi(X,un,!1))throw new Error(`preferredLocation "ml-tensor" for ${un} output is not supported by current WebNN Context.`);let Vs=await hn(X,es,ts,Ir,!1);qo=!0,ar.push([un,Ir,{mlTensor:Vs,download:Ie.webnnCreateMLTensorDownloader(es,un),dispose:()=>{Ie.webnnReleaseTensorId(es),Ie._OrtReleaseTensor(Ws)}},"ml-tensor"])}else if(lr==="ml-tensor-cpu-output"&&Us>0){let hn=Ie.webnnCreateMLTensorDownloader(es,un)(),Xi=ar.length;qo=!0,fc.push((async()=>{let Vs=[Xi,await hn];return Ie.webnnReleaseTensorId(es),Ie._OrtReleaseTensor(Ws),Vs})()),ar.push([un,Ir,[],"cpu"])}else{let hn=rr(un),Xi=new hn(Us);new Uint8Array(Xi.buffer,Xi.byteOffset,Xi.byteLength).set(Ie.HEAPU8.subarray(es,es+Xi.byteLength)),ar.push([un,Ir,Xi,"cpu"])}}finally{Ie.stackRestore(Cd),un==="string"&&es&&Ie._free(es),qo||Ie._OrtReleaseTensor(Ws)}}Ke&&!Rt&&(Ie._OrtClearBoundOutputs(Ke.handle)!==0&&Dt("Can't clear bound outputs."),Yn.set(X,[Qe,at,tt,Ke,Rt,!1]));for(let[li,Ws]of await Promise.all(fc))ar[li][2]=Ws;return gt("wasm ProcessOutputTensor"),ar}finally{(pc=Ie.webnnOnRunEnd)==null||pc.call(Ie,Qe),Ie.stackRestore(hi),ei.forEach(kn=>Ie._OrtReleaseTensor(kn)),Pi.forEach(kn=>Ie._OrtReleaseTensor(kn)),zt.forEach(kn=>Ie._free(kn)),Ii!==0&&Ie._OrtReleaseRunOptions(Ii),Qt.forEach(kn=>Ie._free(kn))}},Jn=X=>{let se=Gt(),he=Yn.get(X);if(!he)throw new Error("invalid session id");let Te=he[0],xe=se._OrtEndProfiling(Te);xe===0&&Dt("Can't get an profile file name."),se._OrtFree(xe)},vt=X=>{let se=[];for(let he of X){let Te=he[2];!Array.isArray(Te)&&"buffer"in Te&&se.push(Te.buffer)}return se}}),je,Ye,At,ni,ai,Oi,ji,an,Wi,dn,Ni,Hs,qr,fo,or,Sd,mo,go,dc=c(()=>{ii(),ge(),Xn(),Kn(),je=()=>!!j.wasm.proxy&&typeof document<"u",At=!1,ni=!1,ai=!1,an=new Map,Wi=(X,se)=>{let he=an.get(X);he?he.push(se):an.set(X,[se])},dn=()=>{if(At||!ni||ai||!Ye)throw new Error("worker not ready")},Ni=X=>{switch(X.data.type){case"init-wasm":At=!1,X.data.err?(ai=!0,ji[1](X.data.err)):(ni=!0,ji[0]()),Oi&&(URL.revokeObjectURL(Oi),Oi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=an.get(X.data.type);X.data.err?se.shift()[1](X.data.err):se.shift()[0](X.data.out);break}}},Hs=async()=>{if(!ni){if(At)throw new Error("multiple calls to 'initWasm()' detected.");if(ai)throw new Error("previous call to 'initWasm()' failed.");if(At=!0,je())return new Promise((X,se)=>{Ye==null||Ye.terminate(),Sr().then(([he,Te])=>{try{Ye=Te,Ye.onerror=Le=>se(Le),Ye.onmessage=Ni,ji=[X,se];let xe={type:"init-wasm",in:j};if(!xe.in.wasm.wasmPaths&&he){let Le=gn();Le&&(xe.in.wasm.wasmPaths=Le)}Ye.postMessage(xe),Oi=he}catch(xe){se(xe)}},se)});try{await sr(j.wasm),await Vo(j),ni=!0}catch(X){throw ai=!0,X}finally{At=!1}}},qr=async X=>{if(je())return dn(),new Promise((se,he)=>{Wi("init-ep",[se,he]);let Te={type:"init-ep",in:{epName:X,env:j}};Ye.postMessage(Te)});await Er(j,X)},fo=async X=>je()?(dn(),new Promise((se,he)=>{Wi("copy-from",[se,he]);let Te={type:"copy-from",in:{buffer:X}};Ye.postMessage(Te,[X.buffer])})):oi(X),or=async(X,se)=>{if(je()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return dn(),new Promise((he,Te)=>{Wi("create",[he,Te]);let xe={type:"create",in:{model:X,options:{...se}}},Le=[];X instanceof Uint8Array&&Le.push(X.buffer),Ye.postMessage(xe,Le)})}else return vs(X,se)},Sd=async X=>{if(je())return dn(),new Promise((se,he)=>{Wi("release",[se,he]);let Te={type:"release",in:X};Ye.postMessage(Te)});Vr(X)},mo=async(X,se,he,Te,xe,Le)=>{if(je()){if(he.some(Ie=>Ie[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(xe.some(Ie=>Ie))throw new Error("pre-allocated output tensor is not supported for proxy.");return dn(),new Promise((Ie,Pe)=>{Wi("run",[Ie,Pe]);let ze=he,Qe={type:"run",in:{sessionId:X,inputIndices:se,inputs:ze,outputIndices:Te,options:Le}};Ye.postMessage(Qe,vt(ze))})}else return qe(X,se,he,Te,xe,Le)},go=async X=>{if(je())return dn(),new Promise((se,he)=>{Wi("end-profiling",[se,he]);let Te={type:"end-profiling",in:X};Ye.postMessage(Te)});Jn(X)}}),cl,vo,Ta,dl=c(()=>{ii(),dc(),Ft(),fi(),kr(),cl=(X,se)=>{switch(X.location){case"cpu":return[X.type,X.dims,X.data,"cpu"];case"gpu-buffer":return[X.type,X.dims,{gpuBuffer:X.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[X.type,X.dims,{mlTensor:X.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${X.location} for ${se()}`)}},vo=X=>{switch(X[3]){case"cpu":return new fe(X[0],X[2],X[1]);case"gpu-buffer":{let se=X[0];if(!Cr(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:he,download:Te,dispose:xe}=X[2];return fe.fromGpuBuffer(he,{dataType:se,dims:X[1],download:Te,dispose:xe})}case"ml-tensor":{let se=X[0];if(!ms(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:he,download:Te,dispose:xe}=X[2];return fe.fromMLTensor(he,{dataType:se,dims:X[1],download:Te,dispose:xe})}default:throw new Error(`invalid data location: ${X[3]}`)}},Ta=class{async fetchModelAndCopyToWasmMemory(X){return fo(await Zi(X))}async loadModel(X,se){yt();let he;typeof X=="string"?he=await this.fetchModelAndCopyToWasmMemory(X):he=X,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await or(he,se),ot()}async dispose(){return Sd(this.sessionId)}async run(X,se,he){yt();let Te=[],xe=[];Object.entries(X).forEach(tt=>{let Ke=tt[0],Rt=tt[1],Me=this.inputNames.indexOf(Ke);if(Me===-1)throw new Error(`invalid input '${Ke}'`);Te.push(Rt),xe.push(Me)});let Le=[],Ie=[];Object.entries(se).forEach(tt=>{let Ke=tt[0],Rt=tt[1],Me=this.outputNames.indexOf(Ke);if(Me===-1)throw new Error(`invalid output '${Ke}'`);Le.push(Rt),Ie.push(Me)});let Pe=Te.map((tt,Ke)=>cl(tt,()=>`input "${this.inputNames[xe[Ke]]}"`)),ze=Le.map((tt,Ke)=>tt?cl(tt,()=>`output "${this.outputNames[Ie[Ke]]}"`):null),Qe=await mo(this.sessionId,xe,Pe,Ie,ze,he),at={};for(let tt=0;tt<Qe.length;tt++)at[this.outputNames[Ie[tt]]]=Le[tt]??vo(Qe[tt]);return ot(),at}startProfiling(){}endProfiling(){go(this.sessionId)}}}),Dr={};f(Dr,{OnnxruntimeWebAssemblyBackend:()=>$r,initializeFlags:()=>Kr,wasmBackend:()=>_o});var Kr,$r,_o,uc=c(()=>{ii(),dc(),dl(),Kr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let X=j.wasm.simd;if(typeof X!="boolean"&&X!==void 0&&X!=="fixed"&&X!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${X}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let se=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((se||1)/2))}},$r=class{async init(X){Kr(),await Hs(),await qr(X)}async createInferenceSessionHandler(X,se){let he=new Ta;return await he.loadModel(X,se),he}},_o=new $r}),hc={};f(hc,{InferenceSession:()=>Oe,TRACE:()=>ke,TRACE_EVENT_BEGIN:()=>Nt,TRACE_EVENT_END:()=>gt,TRACE_FUNC_BEGIN:()=>yt,TRACE_FUNC_END:()=>ot,Tensor:()=>fe,default:()=>hl,env:()=>j,registerBackend:()=>k}),ii(),ii(),ii();var ul="1.26.0",hl=ci;{let X=(uc(),m(Dr)).wasmBackend;k("cpu",X,10),k("wasm",X,10)}return Object.defineProperty(j.versions,"web",{value:ul,enumerable:!0}),m(hc)})();i.exports=t})(v_)),v_.exports}var vx;function N2(){return vx||(vx=1,(function(i){var e=Ja&&Ja.__createBinding||(Object.create?(function(x,T,R,N){N===void 0&&(N=R);var O=Object.getOwnPropertyDescriptor(T,R);(!O||("get"in O?!T.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return T[R]}}),Object.defineProperty(x,N,O)}):(function(x,T,R,N){N===void 0&&(N=R),x[N]=T[R]})),t=Ja&&Ja.__setModuleDefault||(Object.create?(function(x,T){Object.defineProperty(x,"default",{enumerable:!0,value:T})}):function(x,T){x.default=T}),n=Ja&&Ja.__importStar||function(x){if(x&&x.__esModule)return x;var T={};if(x!=null)for(var R in x)R!=="default"&&Object.prototype.hasOwnProperty.call(x,R)&&e(T,x,R);return t(T,x),T};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(j2()),l=yw(),p=xw(),a=cm(),c=zv(),f=M1(),g=O1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",w="silero_vad_v5.onnx",$="silero_vad_legacy.onnx",k=x=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async T=>{T.getTracks().forEach(R=>{R.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 E=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,T,R,N,O){await R.audioWorklet.addModule(x),T.processorOptions={...T.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(R,"vad-helper-worklet",T);return j.port.onmessage=async F=>{const U=F.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case c.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const re=new Float32Array(U.data);await O(re);break}}},j}async function y(x,T,R){const N=new g.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:T});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let F=!1;return j.onaudioprocess=async U=>{if(!F){F=!0;try{const re=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const J=N.process(re);for(const pe of J)await R(pe)}catch(re){console.error("Error processing audio:",re)}finally{F=!1}}},j.connect(x.destination),j}class S{constructor(T,R,N,O,j=!1,F=null,U=null,re=null,de=null,J=null,pe=null,ce="uninitialized",ye=!1){this.options=T,this.frameProcessor=R,this.model=N,this.frameSamples=O,this.listening=j,this.errored=F,this._stream=U,this._audioContext=re,this._vadNode=de,this._mediaStreamAudioSourceNode=J,this._audioProcessorAdapterType=pe,this.initializationState=ce,this.ownsAudioContext=ye,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=$e=>{this.initializationState="errored",this.errored=$e},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch($e){throw $e instanceof Error?this.setErrored($e.message):this.setErrored(String($e)),$e}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?E(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await 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:$e,audioContext:me,vadNode:V}=this.getAudioInstances();this._stream=await this.options.resumeStream($e);const Y=new MediaStreamAudioSourceNode(me,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Y,Y.connect(V);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:$e,mediaStreamAudioSourceNode:me}=this.getAudioInstances();await this.options.pauseStream($e),me.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var me;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:$e}=this.getAudioInstances();$e instanceof AudioWorkletNode&&$e.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((me=this._audioContext)==null?void 0:me.close())},this.setOptions=$e=>{this.frameProcessor.setOptions($e)},this.processFrame=async $e=>{await this.frameProcessor.process($e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=$e=>{switch($e.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed($e.probs,$e.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($e.audio);break}}}static async new(T={}){const R={...(0,i.getDefaultRealTimeVADOptions)(T.model??i.DEFAULT_MODEL),...T};(0,p.validateOptions)(R),i.ort.env.wasm.wasmPaths=R.onnxWASMBasePath,R.ortConfig!==void 0&&R.ortConfig(i.ort);const N=R.model==="v5"?w:$,O=R.baseAssetPath+N,j=R.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let F;try{F=await j(i.ort,()=>(0,l.defaultModelFetcher)(O))}catch(pe){throw console.error(`Encountered an error while loading model file ${O}`),pe}const U=R.model==="v5"?512:1536,re=U/16,de=new p.FrameProcessor(F.process,F.reset_state,{positiveSpeechThreshold:R.positiveSpeechThreshold,negativeSpeechThreshold:R.negativeSpeechThreshold,redemptionMs:R.redemptionMs,preSpeechPadMs:R.preSpeechPadMs,minSpeechMs:R.minSpeechMs,submitUserSpeechOnPause:R.submitUserSpeechOnPause},re),J=new S(R,de,F,U);if(R.startOnLoad)try{await J.start()}catch(pe){throw console.error("Error starting micVad",pe),pe}return J}}i.MicVAD=S})(Ja)),Ja}var _x;function M2(){return _x||(_x=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=R1();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=yw();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=xw();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=zv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=P2();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=R2();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=N2();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}})})(f_)),f_}var O2=M2();function bg(i,e,t,n,r){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,r)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const pt={debug:(i,e,t)=>bg(i,"debug",e,t),info:(i,e,t)=>bg(i,"info",e,t),warn:(i,e,t)=>bg(i,"warn",e,t),error:(i,e,t,n)=>bg(i,"error",e,t,n)},z1=16e3,L2=6,oh=z1*L2,z2=400,B2=z1*z2/1e3,bx=300,wx=2e3,yx=1500,xx=3e3,G2=600,B1=.5,G1=.35,Sx=.85,Cx=.7;let br=null,ya=!1,er=!1;const hb=new Set;function wg(i){for(const e of Array.from(hb))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let __=0;const kx=2;let gh=!1,F1=!1;function H1(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";pt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),F2(`error:${e.message||"unknown"}`)})}function bv(){return br||(br=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),H1(br),pt.info("speech","worker spawned"),br)}let yg=!1;function F2(i){if(!gh){if(yg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(yg=!0,__+=1,F1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:__}),wg({reason:i,respawned:!1,finalOnly:!0}),__>kx){if(gh=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:kx}),br)try{br.terminate()}catch{}br=null,ya=!1,er=!1,wg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),yg=!1;return}if(br)try{br.terminate()}catch{}br=null,ya=!1,er=!1;try{br=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),H1(br),er=!0,br.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),wg({reason:i,respawned:!0,finalOnly:!0})}catch(e){gh=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),wg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{yg=!1}}}function H2(i,e){if(ya||er)return;er=!0;const t=bv();pt.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(i==null||i(r.data.status,r.data.message),r.data.status==="ready"&&(ya=!0,er=!1,pt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(er=!1,pt.error("speech","preloadModel: worker reported error",{error:r.data.error}),i==null||i("error",r.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function W2(){pt.info("speech","resetModel: clearing load flags"),ya=!1,er=!1}function Bv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function U2(i){const e=bv();return!ya&&!er&&(er=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const r=l=>{var p,a,c;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",r),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(l.data.error??"Transcription failed")))):((c=l.data)==null?void 0:c.type)==="status"&&l.data.status==="ready"&&(ya=!0,er=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function W1(i){let e=bv(),t=!1,n=null,r=null,l=null,p=null,a=null;const c=[],f=new Set;let g=null,m=0,w=!1,$=0,k=!1,E=!1,b=0,y=0,S=0,x=-1,T=bx,R=0,N=null,O="",j="",F=!1,U=0;function re(ue,Ee){const Ge=Math.min(ue.length,Ee.length);let Je=0;for(;Je<Ge&&ue.charCodeAt(Je)===Ee.charCodeAt(Je);)Je++;return Je}function de(ue){const Ee=re(O,ue);return O=ue,Ee>j.length&&(j=ue.slice(0,Ee)),j.length>ue.length&&(j=ue),j}const J=()=>(g||(g=new Float32Array(oh)),g),pe=()=>{m=0},ce=ue=>{const Ee=J(),Ge=ue.length;if(Ge>=oh){Ee.set(ue.subarray(Ge-oh)),m=oh;return}if(m+Ge<=oh){Ee.set(ue,m),m+=Ge;return}const Je=m+Ge-oh;Ee.copyWithin(0,Je,m),m-=Je,Ee.set(ue,m),m+=Ge},ye=()=>{N&&(clearTimeout(N),N=null)},$e=()=>{ye(),w=!1,k=!1,E=!1,T=bx,O="",j="",F=!1,U=0,pe()},me=()=>{if(t||!w||E||k||N)return;if(m<B2){N=setTimeout(()=>{N=null,me()},T);return}const ue=performance.now()-b;if(ue<T&&b!==0){N=setTimeout(()=>{N=null,me()},T-ue);return}if(F1||gh||i.partialsEnabled&&!i.partialsEnabled())return;const Ee=J(),Ge=new Float32Array(m);Ge.set(Ee.subarray(0,m)),y+=1,S=y,k=!0,R=performance.now(),b=R,e.postMessage({type:"transcribe-partial",audio:Ge,seq:y},[Ge.buffer])},V=ue=>ue.length===0?Promise.resolve():gh?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Ee=>{c.push(Ee),y+=1;const Ge=y;x=Ge,e.postMessage({type:"transcribe",audio:ue,seq:Ge},[ue.buffer])}),Y=ue=>{const Ee=V(ue);return f.add(Ee),Ee.finally(()=>{f.delete(Ee)}),Ee},W=ue=>{var Ee,Ge,Je,ve,Z;if(ue.data.type==="result"){const we=ue.data.text,fe=ue.data.seq??0;fe&&fe<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:fe,latestFinalSeq:x}),!t&&we&&i.onFinal(we),(Ee=c.shift())==null||Ee()}else if(ue.data.type==="partial"){const we=ue.data.seq??0,fe=ue.data.text??"",Ae=performance.now()-R;k=!1,Ae>=xx?(E=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ae),seq:we})):Ae>=yx&&(T=Math.min(T*2,wx),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ae),newIntervalMs:T,seq:we})),F||(F=!0,Ae>G2&&T<500&&(T=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ae),newIntervalMs:500})));const ke=we!==S||we<=x;if(!t&&!ke&&fe){const st=de(fe);st&&((Ge=i.onPartial)==null||Ge.call(i,st),U===0&&(U=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-$)})))}me()}else if(ue.data.type==="partial-error"){const we=performance.now()-R;k=!1,we>=xx?(E=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ue.data.seq})):we>=yx&&(T=Math.min(T*2,wx),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:T,seq:ue.data.seq})),pt.warn("speech","partial encode failed",{error:ue.data.error,seq:ue.data.seq}),me()}else ue.data.type==="error"?(t||i.onError(ue.data.error),(Je=c.shift())==null||Je()):ue.data.type==="status"?(t||(ve=i.onModelStatus)==null||ve.call(i,ue.data.status,ue.data.message),ue.data.status==="ready"&&(ya=!0,er=!1)):ue.data.type==="progress"&&(t||(Z=i.onProgress)==null||Z.call(i,ue.data.pct))};e.addEventListener("message",W);const ee=ue=>{var Ee,Ge;if(!t){for(pt.warn("speech","createRecognition: worker death event",ue),(Ee=i.onStatusChange)==null||Ee.call(i,"restarting");c.length;)(Ge=c.shift())==null||Ge();if(f.clear(),ye(),k=!1,ue.respawned){try{e.removeEventListener("message",W)}catch{}e=bv(),e.addEventListener("message",W)}}};return hb.add(ee),{start:async()=>{if(!t){if(gh){i.onError("Speech recognition disabled — please reload the app.");return}!ya&&!er&&(er=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:ya,modelLoading:er});try{const ue=new URL("vad/",document.baseURI).href;pt.info("speech","vad: asset base resolved",{vadBase:ue}),T2();const Ee=i.inputDeviceId||null,Ge={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Ee&&(Ge.deviceId={exact:Ee}),pt.info("speech","getUserMedia",{hasDeviceId:!!Ee,deviceIdPrefix:Ee?Ee.slice(0,8):null});const Je=await navigator.mediaDevices.getUserMedia({audio:Ge});r=Je,l=new AudioContext;for(const ve of Je.getAudioTracks())ve.addEventListener("ended",()=>{t||(pt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(r),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ve){pt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),a=null,p=null}n=await O2.MicVAD.new({audioContext:l,getStream:async()=>Je,resumeStream:async()=>Je,pauseStream:async()=>{},baseAssetPath:ue,onnxWASMBasePath:ue,model:"v5",positiveSpeechThreshold:B1,negativeSpeechThreshold:G1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,Z)=>{var we;t||((we=i.onFrame)==null||we.call(i,ve),w&&(ce(Z),me()))},onSpeechStart:()=>{var ve;t||($e(),w=!0,$=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var Z;t||((Z=i.onStatusChange)==null||Z.call(i,"transcribing"),$e(),Y(ve))},onVADMisfire:()=>{var ve,Z;t||((ve=i.onStatusChange)==null||ve.call(i,"idle"),$e(),(Z=i.onMisfire)==null||Z.call(i))}}),pt.info("speech","vad: ort wasm files loaded",{files:E2()}),n.start()}catch(ue){const Ee=ue instanceof Error?ue.message:"Microphone access denied",Ge=ue instanceof Error?ue.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:Ee,stack:Ge}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(Je=>Je.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(Ee)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for($e();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(ue=>ue.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ue,Ee)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ue,negativeSpeechThreshold:Ee})}catch(Ge){pt.warn("speech","setVadThresholds failed",{error:Ge instanceof Error?Ge.message:String(Ge)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,$e(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(r){try{r.getTracks().forEach(ue=>ue.stop())}catch{}r=null}hb.delete(ee),e.removeEventListener("message",W)}}}let Of=null;const pb=new Set,fb=new Set;function V2(){for(const i of pb)try{i()}catch{}}function mb(){for(const i of fb)try{i()}catch{}}function q2(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 K2(i){if(!window.speechSynthesis)return;const e=q2(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Of=performance.now(),V2()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Of=null,mb())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Of=null,mb())},window.speechSynthesis.speak(t)}function U1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Of=null,mb())}function V1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function X2(){return Of}function Y2(i){return pb.add(i),()=>{pb.delete(i)}}function J2(i){return fb.add(i),()=>{fb.delete(i)}}function Z2(i){V1()&&(i.setVadThresholds(Sx,Cx),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=Y2(()=>{i.setVadThresholds(Sx,Cx),pt.info("voice","tts.duck.on")}),t=J2(()=>{i.setVadThresholds(B1,G1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const Q2=[{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 eD(i){const e=i.trim();return Q2.find(t=>t.match.test(e))??null}const tD=4e4;let md=null;function vh(){md&&clearTimeout(md),md=setTimeout(()=>{md=null,Et.getState().stopRecording()},tD)}function xg(){md&&(clearTimeout(md),md=null)}let sc=null,Ql=null;const iD=.04,nD=.3;let wv=0,gb=0;function sD(i){Ql!==null&&cancelAnimationFrame(Ql);const e=()=>{if(sc===null||Et.getState().submitCountdownStartAt===null){Ql=null;return}const t=performance.now();if(t-gb<200&&wv>nD){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:wv.toFixed(2),msIntoCountdown:Math.round(r)}),Yl(),vh();return}const n=q1();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let l=0;for(let a=0;a<r.length;a++){const c=(r[a]-128)/128;l+=c*c}const p=Math.sqrt(l/r.length);if(p>iD){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Yl(),vh();return}}Ql=requestAnimationFrame(e)};Ql=requestAnimationFrame(e)}function Ex(i){sc&&clearTimeout(sc);const e=Et.getState().submitDelayMs,t=performance.now();Et.setState({submitCountdownStartAt:t}),sc=setTimeout(()=>{var r;sc=null,Et.setState({submitCountdownStartAt:null});const n=kt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=_i.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(_i.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),_i.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){pt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}vh()},e),sD(t)}function Yl(){Ql!==null&&(cancelAnimationFrame(Ql),Ql=null),sc&&(clearTimeout(sc),sc=null),Et.getState().submitCountdownStartAt!==null&&Et.setState({submitCountdownStartAt:null})}let ds=null,Ls=null,pf=null;function q1(){var i;return((i=ds==null?void 0:ds.getAnalyser)==null?void 0:i.call(ds))??null}const Sg=1e4;let Lf=null;function Cg(){Lf&&(clearTimeout(Lf),Lf=null)}let nv=null,sv=null;function kg(){nv=null,sv&&(sv(),sv=null)}const rD=1500,oD=9e4;let Eg=0,rv=null,vb=-1;function Tg(){rv&&(clearTimeout(rv),rv=null,vb=-1)}const aD=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Et=Pn((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++Eg,n=()=>{t===Eg&&(Tg(),vb=t,rv=setTimeout(()=>{vb===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},oD))};n(),H2((r,l)=>{t===Eg&&(r==="ready"?(Tg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(Tg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===Eg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),Tg(),W2(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ds){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Bv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=W1({inputDeviceId:l,onStatusChange:a=>{i(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&i({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{wv=a.isSpeech,gb=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),xg(),Yl(),V1()){const c=X2(),f=c!==null?performance.now()-c:null;U1(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else pt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),vh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&pt.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var w;vh();const c=a.trim();if(!c||aD.has(c)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(pf){pf(c),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((w=kt.getState().tabs.find($=>$.id===t))==null?void 0:w.status)==="dormant"){_i.getState().setPendingVoiceText(t,c),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Ex(t);const $=window;$.__transcripts&&($.__transcripts.push({tabId:t,text:c}),$.__transcripts.length>500&&$.__transcripts.shift());return}const g=eD(c);if(g){pt.info("voice","voice-command",{tabId:t,label:g.label,transcript:c}),window.api.pty.write({tabId:t,data:g.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Yl();const $=window;$.__transcripts&&($.__transcripts.push({tabId:t,text:c}),$.__transcripts.length>500&&$.__transcripts.shift());return}window.api.pty.write({tabId:t,data:c}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&Ex(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:c}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{pt.error("voice","recognition error",{err:a}),Yl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Ls==null||Ls(),Ls=null,xg(),ds==null||ds.destroy(),ds=null,pf=null,et.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?i({modelStatus:"ready",loadingProgress:100}):a==="loading"&&i({modelStatus:"loading"})},onProgress:a=>i({loadingProgress:Math.round(a)})});ds=p,pf=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),vh(),p.start().then(()=>{ds===p&&(Ls==null||Ls(),Ls=Z2(p))}).catch(a=>{const c=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:c}),et.error(`Could not start mic: ${c}`)})}catch(p){i({error:p instanceof Error?p.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,p,a;return((a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.getDevicePref)==null?void 0:a.call(p))??Promise.resolve(null)}).then(l=>r((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{pt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=ds;t&&(xg(),Yl(),wv=0,gb=0,Ls==null||Ls(),Ls=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ds===t&&(ds=null,pf=null),e().hotkeyState==="stopping"&&(Cg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ds;if(!t)return;xg(),Ls==null||Ls(),Ls=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){pt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),ds===t&&(ds=null);const{useSessions:n}=await mi(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>WT);return{useSessions:l}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},setExternalRecording:t=>i({externalRecording:t}),toggleTTS:()=>i(t=>({ttsEnabled:!t.ttsEnabled})),setAutoSubmit:t=>i({autoSubmit:t}),setSubmitDelayMs:t=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(t)))}),cancelSubmit:()=>Yl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(pt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:t}),i({permissionState:t}))},setLevelMeterEnabled:t=>{e().levelMeterEnabled!==t&&i({levelMeterEnabled:t})},setTurnDetectorRuntimeState:t=>{e().turnDetectorState!==t&&(i({turnDetectorState:t}),t==="load_failed"?pt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&&pt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:t=>{e().wizardArmed!==t&&i({wizardArmed:t})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:t,source:n,mode:r,tabId:l})=>{const p=e(),{canRecord:a,reason:c}=yv(p);if(t==="down"){if(c==="error"||c==="load-timeout"){p.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:n,reason:c});return}if(!a&&c!=="loading"){pt.warn("voice-hotkey","miss-model-loading",{modelStatus:p.modelStatus,reason:c});return}if(p.hotkeyState==="recording"||p.isRecording){(r==="toggle"||n==="global")&&(i({hotkeyState:"stopping"}),Cg(),Lf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Sg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Sg),p.stopRecording());return}if(c==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),kg(),nv={tabId:l,source:n,mode:r},sv=Et.subscribe((f,g)=>{if(nv&&f.modelStatus==="ready"&&g.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=nv;if(kg(),!m.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),Et.getState().startRecording(m.tabId)}});return}if(!l){pt.warn("voice-hotkey","no-active-tab",{source:n});return}pt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){kg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),Cg(),Lf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:Sg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Sg),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(kg(),Yl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(Cg(),i({hotkeyState:"destroyed"}))}})),lD=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),yv=i=>Bv()?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=Et,i.__transcripts=[]}const Kf=6e4,cD=3e5,dD=.25,uD=5e3,Xf=Pn(()=>({data:null,refreshing:!1}));let Tx=!1,ov=null,b_=Kf,Dg=!1,tl=null;function hD(i,e){if(i.kind==="ok")return{delayMs:Kf,nextBackoffMs:Kf};const t=Math.min(e*2,cD),n=t*dD;let r=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>r&&(r=l),{delayMs:r,nextBackoffMs:t}}function Dx(){return h1(window.api.billing.fetch(),uD,"billing.fetch")}function $x(i){Xf.setState({data:i,refreshing:!1})}async function Sw(){Xf.setState({refreshing:!0});let i=Kf;try{const e=await Dx();tl&&(tl.cancel(),tl=null),$x(e);const{delayMs:t,nextBackoffMs:n}=hD(e,b_);b_=n,i=t}catch(e){b_=Kf,Xf.setState({refreshing:!1});const t=p1({error:e,retry:Dx,onRetrySuccess:n=>{tl=null,$x(n)},onStillFailing:n=>{tl=null,Dg||(Dg=!0,et.warn(`Billing usage fetch: ${n}`))}});if(t)tl=t;else if(!Dg){Dg=!0;const n=e instanceof Error?e.message:String(e);et.warn(`Billing usage fetch failed: ${n}`)}}ov=setTimeout(Sw,i)}function pD(){Tx||(Tx=!0,Sw())}function K1(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 fD(){ov!==null&&(clearTimeout(ov),ov=null),tl&&(tl.cancel(),tl=null),Sw()}function Yf(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(),r=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${r} ${e[1]}`:`${n} ${r}`}function Jf(i){const e=/(opus|sonnet|haiku|fable)/i.exec(i);return e?e[1].toLowerCase():null}const $g=new Map,mD=3e4;function Cw(i){const[e,t]=z.useState(()=>{var n;return i?((n=$g.get(i))==null?void 0:n.value)??null:null});return z.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=$g.get(i);if(l&&Date.now()-l.ts<mD){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;$g.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;$g.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}const X1="~/.claude/session-manager/ui-chrome-prefs.json",gD=180,vD=480,_b=252,od={sidebarWidth:_b,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function bb(i){return Math.min(vD,Math.max(gD,i))}let ec=null,av={};function _D(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(X1,n).catch(()=>{})};i().hydrated||!ec?e():ec.then(e)}function ah(i,e,t){i(t),!e().hydrated&&ec&&Object.assign(av,t),_D(e)}const In=Pn((i,e)=>({...od,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():ec||(ec=(async()=>{try{const t=await window.api.config.readJson(X1);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({sidebarWidth:typeof n.sidebarWidth=="number"?bb(n.sidebarWidth):od.sidebarWidth,sidebarCollapsed:n.sidebarCollapsed??od.sidebarCollapsed,collapsedGroups:Array.isArray(n.collapsedGroups)?n.collapsedGroups:od.collapsedGroups,learningPanelCollapsed:n.learningPanelCollapsed??od.learningPanelCollapsed,tourCompletedAt:typeof n.tourCompletedAt=="number"?n.tourCompletedAt:od.tourCompletedAt,density:n.density==="compact"?"compact":od.density,...av,hydrated:!0});return}}catch{}i({...av,hydrated:!0})})().finally(()=>{ec=null,av={}}),ec),setSidebarWidth:t=>ah(i,e,{sidebarWidth:bb(t)}),setSidebarCollapsed:t=>ah(i,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>ah(i,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>ah(i,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>ah(i,e,{tourCompletedAt:t}),setDensity:t=>ah(i,e,{density:t})}));function bD(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:r})=>({key:e,label:t,icon:n,hint:r}))}const wD=52;function yD(i){return new Set(i.filter(e=>e==="Workspace"||e==="Configure"||e==="Tools"))}function xD(){const i=kt(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Gr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function SD({active:i,onNavigate:e,onNewSession:t}){const n=In(J=>J.hydrated),r=In(J=>J.hydrate);z.useEffect(()=>{n||r()},[n,r]);const l=In(J=>J.collapsedGroups),p=In(J=>J.setCollapsedGroups),a=z.useMemo(()=>yD(l),[l]),c=z.useCallback(J=>{const pe=new Set(a);pe.has(J)?pe.delete(J):pe.add(J),p(Array.from(pe))},[a,p]),f=In(J=>J.sidebarCollapsed),g=In(J=>J.setSidebarCollapsed),m=z.useCallback(()=>{g(!f)},[f,g]),w=kt(J=>J.tabs),$=kt(J=>J.activeTabId),k=w.find(J=>J.id===$)??null,E=xD(),b=Ri(J=>J.navFace),y=KT(b),S=y.filter(J=>J.group==="Workspace"),x=y.filter(J=>J.group==="Configure"),T=bD(y),R=b==="home"&&!f,N=In(J=>J.sidebarWidth),O=In(J=>J.setSidebarWidth),[j,F]=z.useState(N),U=z.useRef(j);U.current=j,z.useEffect(()=>{F(N)},[N]);const re=z.useCallback(J=>{J.preventDefault();const pe=J.clientX,ce=U.current;let ye=ce;const $e=V=>{ye=bb(ce+(V.clientX-pe)),F(ye)},me=()=>{window.removeEventListener("pointermove",$e),window.removeEventListener("pointerup",me),document.body.style.cursor="",document.body.style.userSelect="",O(ye)};window.addEventListener("pointermove",$e),window.addEventListener("pointerup",me),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[O]),de=z.useCallback(()=>{F(_b),O(_b)},[O]);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?wD:j},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[d.jsx(CD,{tab:k,navFace:b,onNewSession:t,rail:f,onToggleRail:m}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:f?"4px":"8px"},children:R?d.jsxs(d.Fragment,{children:[d.jsx(w_,{label:"Workspace",desc:h_.Workspace,collapsed:a.has("Workspace"),count:S.length,onToggle:()=>c("Workspace")}),!a.has("Workspace")&&S.map(J=>d.jsx(y_,{item:J,active:i===J.key,live:J.liveKind?E[J.liveKind]:!1,onClick:()=>e(J.key),rail:!1},J.key)),d.jsx(w_,{label:"Configure",desc:h_.Configure,collapsed:a.has("Configure"),count:x.length,onToggle:()=>c("Configure")}),!a.has("Configure")&&x.map(J=>d.jsx(y_,{item:J,active:i===J.key,live:!1,onClick:()=>e(J.key),rail:!1},J.key)),T.length>0&&d.jsx(w_,{label:"Tools",desc:h_.Tools,collapsed:a.has("Tools"),count:T.length,onToggle:()=>c("Tools")}),T.length>0&&!a.has("Tools")&&T.map(J=>d.jsx(Ax,{tool:J,active:i===J.key,onClick:()=>e(J.key),rail:!1},J.key))]}):d.jsx("div",{className:"pt-2",children:y.map(J=>J.group==="Tools"?d.jsx(Ax,{tool:{key:J.key,label:J.label,icon:J.icon,hint:J.hint},active:i===J.key,onClick:()=>e(J.key),rail:f},J.key):d.jsx(y_,{item:J,active:i===J.key,live:J.liveKind?E[J.liveKind]:!1,onClick:()=>e(J.key),rail:f},J.key))})}),d.jsx(kD,{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:re,onDoubleClick:de,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 CD({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Cw((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(wr,{name:"plus",size:15,stroke:1.8})}),d.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:d.jsx(wr,{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:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(wr,{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(wr,{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:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(wr,{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(wr,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function w_({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return d.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[d.jsxs("button",{onClick:r,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[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 y_({item:i,active:e,live:t,onClick:n,rail:r}){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 ${r?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&d.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),d.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:d.jsx(wr,{name:i.icon,size:17,stroke:1.6})}),!r&&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})]}),!r&&t&&d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&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 Ax({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(wr,{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 kD({rail:i,navFace:e}){const t=Et(c=>c.isRecording),n=kt(c=>c.tabs),r=kt(c=>c.activeTabId),l=n.find(c=>c.id===r)??null,[p,a]=z.useState(null);return z.useEffect(()=>{let c=!1;if(!(l!=null&&l.presetId)){a(null);return}return r1(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 · ${Yf(p)}`:"Claude Code"})]})}function ED(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function TD(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 DD(i,e,t){const n=Date.now(),r={...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:[];r.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,c=a.input,f={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])c&&g in c&&(f[g]=c[g]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),w=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,$=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,k=w?w.split("/").pop()??w:$?p($,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:w??$,toolName:a.name}),m&&w&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(w.split("/").pop()??w,34)}`,target:w,toolName:a.name})}break}case"plan":{const a=e.data,c=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);r.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;r.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,c=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,g=a.output_tokens??a.outputTokens??0,m=c+f+g;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+g,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(c/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const a=e.data;r.agents=ED(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const lv=Pn((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,r)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:TD(t,n,r)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:r}).then(async a=>{const c=e().tabs[t];if(!c)return;if(!a.ok){const{toast:g}=await mi(async()=>{const{toast:m}=await Promise.resolve().then(()=>l1);return{toast:m}},void 0,import.meta.url);g.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 r=e().unsubs[t];r==null||r();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,r)=>{e().ingestBatch(t,[n],r)},ingestBatch:(t,n,r)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const c of n){const{next:f,newActivity:g}=DD(p,c,r);p=f,a=a.concat(g)}if(a.length>0){let c=l.activitySeq;const f=a.map(g=>({...g,id:++c}));p={...p,activitySeq:c,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function $D(i){const e=lv(r=>r.subscribe),t=lv(r=>r.unsubscribe),n=lv(r=>i?r.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 Y1(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${r}h`:r>0?`${r}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function wb(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function Ix(i,e){const t=wb(e);if(t==null)return`${i} — usage unavailable`;const n=Y1((e==null?void 0:e.resets_at)??null),r=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${r} — click to open Home`}function e4(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 J1=z.createContext(null);function AD({panelId:i,children:e}){return d.jsx(J1.Provider,{value:i,children:e})}function Gv(i){const e=z.useContext(J1),t=i??e;return Ri(n=>t==null||n.focusedPanelId===t)}function kw(i){const e=Gv(i),t=z.useRef(e);return t.current=e,t}const ID=5e3;let Z1=null;const yb=new Set;let x_=0,zf=null;function PD(){yb.forEach(i=>i())}async function Px(){try{Z1=await window.api.schedule.sessionSlots(),PD()}catch{}}function RD(){zf==null&&(Px(),zf=setInterval(()=>{Px()},ID))}function jD(){zf!=null&&(clearInterval(zf),zf=null)}function Ew(i){const e=Gv(i),[,t]=z.useState(0);return z.useEffect(()=>{const n=()=>t(r=>r+1);return yb.add(n),()=>{yb.delete(n)}},[]),z.useEffect(()=>{if(e)return x_+=1,RD(),()=>{x_-=1,x_<=0&&jD()}},[e]),Z1}const ND=360*60*1e3;let Q1=null;const xb=new Set;let S_=0,Bf=null;async function Rx(){try{Q1=await window.api.app.updateStatus(),xb.forEach(i=>i())}catch{}}function MD(){Bf==null&&(Rx(),Bf=setInterval(()=>{Rx()},ND))}function OD(){Bf!=null&&(clearInterval(Bf),Bf=null)}function LD(){const[,i]=z.useState(0);return z.useEffect(()=>{const e=()=>i(t=>t+1);return xb.add(e),S_+=1,MD(),()=>{xb.delete(e),S_-=1,S_<=0&&OD()}},[]),Q1}function zD({total:i,inUse:e,size:t}){const n=Math.min(Math.max(e,0),i),r=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:`${r} ${p<n?"bg-accent border-accent":"bg-bg border-line"}`},p))})}function BD({onNavigate:i}){const e=kt(J=>J.tabs),t=kt(J=>J.activeTabId),n=e.find(J=>J.id===t)??null,r=$D(n),l=(r==null?void 0:r.lastEventAt)??0,p=Xf(J=>J.data),a=Gr(J=>{var pe;return((pe=J.snapshot)==null?void 0:pe.paused)??null}),c=Cw((n==null?void 0:n.cwd)??null),f=Ew(),g=LD(),m=Bs(J=>J.show),[,w]=z.useState(0);z.useEffect(()=>{const J=setInterval(()=>w(pe=>pe+1),6e4);return()=>clearInterval(J)},[]);const $=(r==null?void 0:r.todos)??[],[k,E]=z.useState(!1),b=z.useRef(null);z.useEffect(()=>{if(!k)return;const J=pe=>{b.current&&!b.current.contains(pe.target)&&E(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[k]),z.useEffect(()=>{$.length===0&&E(!1)},[$.length]);const y=K1(p),S=(y==null?void 0:y.usage.five_hour)??null,x=(y==null?void 0:y.usage.seven_day)??null,T=wb(S),R=wb(x),N=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",O=l>0?HD(Date.now()-l):"—",j=(f==null?void 0:f.total)??5,F=f?Math.min(Math.max(f.inUse,0),f.total):0,U=f?`${F} / ${j}`:`— / ${j}`,re=f&&f.holders.length>0?`
|
|
2929
2929
|
`+f.holders.slice(0,5).map(J=>J.owner).join(`
|
|
2930
|
-
`):"",de=`${U} Claude sessions running${re}`;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:N?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:N?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Ix("Session (5h window)",S),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:T!=null?`${T}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Ix("Weekly window (all models)",x),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:R!=null?`${R}%`:"—"})]}),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:O})]}),$.length>0&&d.jsx(GD,{ref:b,todos:$,open:k,onToggle:()=>E(J=>!J)}),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:de,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(zD,{total:j,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),g!=null&&g.behind&&g.latest&&g.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${g.current} → v${g.latest}`,"data-testid":"footer-version",onClick:()=>{const J=g.downloadUrl;J&&window.api.shell.open({as:"external",url:J}).catch(()=>{m("error",`Couldn't open URL: ${J}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.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",g.current," → v",g.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.107.0"]})]})}const GD=z.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return d.jsxs("div",{ref:r,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 ${mn.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(FD,{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 FD({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 HD(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 WD({onClose:i,onSent:e}){const t=kt(O=>O.tabs),[n,r]=z.useState(""),[l,p]=z.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[a,c]=z.useState(!1),[f,g]=z.useState({}),m=z.useRef(null),w=z.useRef(e);z.useEffect(()=>{w.current=e},[e]),z.useEffect(()=>{p(O=>{const j={};for(const F of t)j[F.id]=O[F.id]??!0;return j})},[t]),z.useEffect(()=>{var O;(O=m.current)==null||O.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(j=>{g(F=>j.tabId in F?{...F,[j.tabId]:"skipped"}:F)}),[]),z.useEffect(()=>{if(Object.keys(f).length===0)return;const O=Object.values(f).filter(F=>F==="sent").length,j=window.setTimeout(()=>w.current(O),1500);return()=>window.clearTimeout(j)},[f]);const $=t.filter(O=>l[O.id]).map(O=>O.id),k=$.length,E=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!E,y=()=>{if(!b)return;c(!0);const O=kt.getState().tabs,j=new Set(O.map(U=>U.id)),F={};for(const U of $)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),F[U]="sent"):F[U]="skipped";g(F),c(!1)},S=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),i();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),y())},x=t.length>0&&t.every(O=>l[O.id]),T=()=>{const O=!x;p(Object.fromEntries(t.map(j=>[j.id,O])))},R=Object.values(f).some(O=>O==="skipped"),N=E?R?"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:S,"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:m,value:n,onChange:O=>r(O.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:x,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(O=>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[O.id],onChange:j=>p(F=>({...F,[O.id]:j.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),f[O.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[O.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.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 UD({tabId:i,cwd:e,onClose:t}){const n=Mf(k=>k.watchersForTab(i)),r=Mf(k=>k.add),l=Mf(k=>k.remove),p=z.useRef(null),[a,c]=z.useState(""),[f,g]=z.useState(""),[m,w]=z.useState(!1);z.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),z.useEffect(()=>{const k=E=>{p.current&&!p.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const $=async()=>{const k=f.trim();if(!k||m)return;w(!0);const E=await r({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),E&&(c(""),g(""))};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=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"&&$()},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:$,disabled:!f.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),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 E=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:(E==null?void 0:E.line)??"",children:E?E.line:d.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2930
|
+
`):"",de=`${U} Claude sessions running${re}`;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:N?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:N?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Ix("Session (5h window)",S),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:T!=null?`${T}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:Ix("Weekly window (all models)",x),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:R!=null?`${R}%`:"—"})]}),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:O})]}),$.length>0&&d.jsx(GD,{ref:b,todos:$,open:k,onToggle:()=>E(J=>!J)}),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:de,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(zD,{total:j,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),g!=null&&g.behind&&g.latest&&g.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${g.current} → v${g.latest}`,"data-testid":"footer-version",onClick:()=>{const J=g.downloadUrl;J&&window.api.shell.open({as:"external",url:J}).catch(()=>{m("error",`Couldn't open URL: ${J}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.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",g.current," → v",g.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.108.0"]})]})}const GD=z.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return d.jsxs("div",{ref:r,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 ${mn.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(FD,{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 FD({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 HD(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 WD({onClose:i,onSent:e}){const t=kt(O=>O.tabs),[n,r]=z.useState(""),[l,p]=z.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[a,c]=z.useState(!1),[f,g]=z.useState({}),m=z.useRef(null),w=z.useRef(e);z.useEffect(()=>{w.current=e},[e]),z.useEffect(()=>{p(O=>{const j={};for(const F of t)j[F.id]=O[F.id]??!0;return j})},[t]),z.useEffect(()=>{var O;(O=m.current)==null||O.focus()},[]),z.useEffect(()=>window.api.pty.onWriteError(j=>{g(F=>j.tabId in F?{...F,[j.tabId]:"skipped"}:F)}),[]),z.useEffect(()=>{if(Object.keys(f).length===0)return;const O=Object.values(f).filter(F=>F==="sent").length,j=window.setTimeout(()=>w.current(O),1500);return()=>window.clearTimeout(j)},[f]);const $=t.filter(O=>l[O.id]).map(O=>O.id),k=$.length,E=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!E,y=()=>{if(!b)return;c(!0);const O=kt.getState().tabs,j=new Set(O.map(U=>U.id)),F={};for(const U of $)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),F[U]="sent"):F[U]="skipped";g(F),c(!1)},S=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),i();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),y())},x=t.length>0&&t.every(O=>l[O.id]),T=()=>{const O=!x;p(Object.fromEntries(t.map(j=>[j.id,O])))},R=Object.values(f).some(O=>O==="skipped"),N=E?R?"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:S,"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:m,value:n,onChange:O=>r(O.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:x,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(O=>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[O.id],onChange:j=>p(F=>({...F,[O.id]:j.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),f[O.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[O.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.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 UD({tabId:i,cwd:e,onClose:t}){const n=Mf(k=>k.watchersForTab(i)),r=Mf(k=>k.add),l=Mf(k=>k.remove),p=z.useRef(null),[a,c]=z.useState(""),[f,g]=z.useState(""),[m,w]=z.useState(!1);z.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),z.useEffect(()=>{const k=E=>{p.current&&!p.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const $=async()=>{const k=f.trim();if(!k||m)return;w(!0);const E=await r({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),E&&(c(""),g(""))};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=>g(k.target.value),onKeyDown:k=>{k.key==="Enter"&&$()},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:$,disabled:!f.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),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 E=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:(E==null?void 0:E.line)??"",children:E?E.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
|
|
@@ -3030,7 +3030,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3030
3030
|
|
|
3031
3031
|
${t}`}const jf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},BN=["popover","review","diff"],Rk=["popover","review"];function GN(i,e){switch(e.type){case"SELECT":return{...jf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...jf,editCount:i.editCount};case"LISTEN":return Rk.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 BN.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:{...jf,editCount:i.editCount+1};case"RESET_FILE":return{...jf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function FN(i,e){let t=null;for(const n of e){const r=n.cwd;!r||!(i===r||i.startsWith(r.endsWith("/")?r:`${r}/`))||(t===null||r.length>t.length)&&(t=r)}return t}function HN(i,e,t){var l;let n=null,r=-1/0;for(const p of e){if(p.cwd!==i||p.status!=="dormant")continue;const a=((l=t[p.id])==null?void 0:l.lastEventAt)??0;(n===null||a>r)&&(n=p,r=a)}return n}const WN="sonnet";function UN(i,e){const[t,n]=z.useReducer(GN,jf),r=z.useRef(0),l=z.useRef(null),p=z.useRef(i),a=z.useRef(new Map);z.useEffect(()=>window.api.docEdit.onSessionResult(x=>{const T=a.current.get(x.requestId);T&&(a.current.delete(x.requestId),T(x))}),[]),z.useEffect(()=>{p.current!==i&&(p.current=i,r.current+=1,c(),n({type:"RESET_FILE"}))},[i]);function c(){const x=l.current;x&&(l.current=null,x.stop().catch(()=>{}),x.destroy(),Et.setState({externalRecording:!1}))}const f=z.useCallback(x=>{r.current+=1,c(),n({type:"SELECT",selection:x})},[]),g=z.useCallback(()=>{r.current+=1,c(),n({type:"CANCEL"})},[]),m=z.useCallback(()=>{if(!Rk.includes(t.phase))return;if(Et.getState().isRecording){et.error("Microphone is already in use");return}if(!Bv()){et.error("Microphone or Web Worker not available");return}const x=++r.current;n({type:"LISTEN"}),Et.setState({externalRecording:!0});const T=()=>{l.current===R&&(l.current=null),Et.setState({externalRecording:!1})},R=W1({onFinal:N=>{if(r.current!==x)return;R.stop().catch(()=>{}),R.destroy(),T();const O=N.trim();if(!O){n({type:"CANCEL"});return}n({type:"HEARD",transcript:O})},onError:N=>{r.current===x&&(R.destroy(),T(),et.error(`Microphone error: ${N}`),n({type:"CANCEL"}))},onModelStatus:(N,O)=>{r.current===x&&n({type:"MODEL_STATUS",status:N,message:O})},onProgress:N=>{r.current===x&&n({type:"MODEL_STATUS",status:"loading",message:`${N}%`})}});l.current=R,R.start().catch(N=>{r.current===x&&(R.destroy(),T(),et.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),w=z.useCallback(()=>{const x=FN(i,kt.getState().tabs);if(!x)return null;const T=HN(x,kt.getState().tabs,lv.getState().tabs);return!T||_i.getState().get(T.id).running?null:T},[i]),$=z.useCallback((x,T,R,N,O,j)=>{const F=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{a.current.set(F,U),window.api.docEdit.runInSession({tabId:x,sessionId:T,cwd:R,before:N,instruction:O,documentText:j,requestId:F})})},[]),k=z.useCallback(async(x,T)=>{const R=t.selection;if(!R)return;const N=++r.current;n({type:"RUN",instruction:x,recordInstruction:T});const O=zN(e);try{const j=w(),F=j?await $(j.id,j.sessionId,j.cwd,R.text,x,O):await window.api.docEdit.run({path:i,before:R.text,instruction:x,documentText:O});if(r.current!==N)return;if(!F.ok){et.error(F.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:R.text,after:F.after??""}})}catch(j){if(r.current!==N)return;et.error(j instanceof Error?j.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,w,$]),E=z.useCallback(x=>{k(x,!0)},[k]),b=z.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),y=z.useCallback(()=>{const x=t.instruction;x&&k(`${x}
|
|
3032
3032
|
|
|
3033
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),S=z.useCallback(x=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const R=ON(x,T.before,T.after);return R.ok?(r.current+=1,n({type:"ACCEPT"})):et.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:b,run:E,retry:y,accept:S}}const VN=[{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."}],Y0=320,Cf=8;function qN(){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 KN(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Cf),Math.max(Cf,e-Y0-Cf)),n=Math.max(i.top-Cf,Cf);return{position:"fixed",left:t,top:n,width:Y0,transform:"translateY(-100%)",zIndex:a2.dialog}}function XN({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:c,onCancel:f,onAccept:g,onReject:m,onRetry:w}){const[$,k]=z.useState(""),E=()=>{const b=$.trim();b&&(p(b),k(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:KN(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:a,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),VN.map(b=>d.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),d.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{autoFocus:!0,value:$,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?E():b.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&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(qN,{}),"Listening…"]}),r&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),d.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),d.jsxs("div",{className:"flex justify-end 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:"Cancel"}),d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:c,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:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&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:t.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),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:"Reject"}),d.jsx("button",{onClick:w,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 YN(){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 J0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:g}){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:Yf(WN)})]}),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(YN,{}),"Listening…"]}),r&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),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:g,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 JN(){const i=kt(t=>t.tabs),e=kt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function Z0(i){return i.split("/").filter(Boolean).pop()||i}function ZN({path:i,onRenamed:e,onDeleted:t}){const[n,r]=z.useState(!1),[l,p]=z.useState(!1),[a,c]=z.useState(""),[f,g]=z.useState(!1),m=xi(U=>U.buffers[i]),w=xi(U=>U.openFile),$=xi(U=>U.renameOpenFile),k=xi(U=>U.closeFile),E=JN(),b=Z0(i),y=()=>r(!1),S=()=>{c(b),p(!0),y()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const re=await window.api.files.rename(i,U);if(re.ok){const de=i.slice(0,i.lastIndexOf("/")),J=re.newPath??`${de}/${U}`;$(i,J),e==null||e(i,J),et.info(`Renamed to ${U}`)}else et.error(re.error??`Couldn't rename ${b}`)}catch(re){et.error(re instanceof Error?re.message:`Couldn't rename ${b}`)}p(!1)},T=async()=>{y();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(w(U.path),et.info(`Duplicated as ${Z0(U.path)}`)):et.error(U.error??`Couldn't duplicate ${b}`)}catch(U){et.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const U=await window.api.files.delete(i);U.ok?(k(i),t==null||t(i),et.info(`Deleted ${b}`)):et.error(U.error??`Couldn't delete ${b}`)}catch(U){et.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}g(!1)},N=async()=>{y();const U=m??"";try{await navigator.clipboard.writeText(U),et.info(`Copied ${U.length} chars`)}catch(re){et.error(re instanceof Error?re.message:`Couldn't copy ${b}`)}},O=()=>{if(y(),!E){et.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${i} `}),et.info(`Added ${b} to Claude context`)},j=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||et.error(U.error??`Couldn't open ${b}`)}).catch(U=>et.error(U instanceof Error?U.message:`Couldn't open ${b}`))},F=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||et.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>et.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>r(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${mn.contextMenuScrim}`,onMouseDown:y}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${mn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(F_,{children:"Edit"}),d.jsx(cd,{label:"Rename",onClick:S}),d.jsx(cd,{label:"Duplicate",onClick:T}),d.jsx(cd,{label:"Delete document",danger:!0,onClick:()=>{y(),g(!0)}}),d.jsx(Q0,{}),d.jsx(F_,{children:"Open"}),d.jsx(cd,{label:"Open in default app",onClick:j}),d.jsx(cd,{label:"Reveal in OS",onClick:F}),d.jsx(Q0,{}),d.jsx(F_,{children:"Export"}),d.jsx(cd,{label:"Copy as Markdown",onClick:N}),d.jsx(cd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(QN,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&d.jsx(eM,{name:b,onCancel:()=>g(!1),onConfirm:()=>void R()})]})}function F_({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 cd({label:i,onClick:e,danger:t,disabled:n,title:r}){return d.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function Q0(){return d.jsx("div",{className:"my-1 border-t border-line"})}function QN({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${mn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.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:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),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 eM({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${mn.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 tM(){const[i,e]=z.useState(!1),t=gd();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 ${mn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${mn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(uh,{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(uh,{label:"Word wrap",children:d.jsx(qg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(uh,{label:"Minimap",children:d.jsx(qg,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(uh,{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(uh,{label:"Autosave",children:d.jsx(qg,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(uh,{label:"Wide measure",children:d.jsx(qg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function uh({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 qg({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 iM=z.lazy(()=>mi(()=>import("./TiptapBody-CP_F_mwb.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Kg(i){return i.split("/").filter(Boolean).pop()||i}function Xg(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Yg(i){return nk(i)||sk(i)}function nM(){const i=kw(),e=xi(Oe=>Oe.openFiles),t=xi(Oe=>Oe.activeFilePath),n=xi(Oe=>Oe.dirty),r=xi(Oe=>Oe.viewMode),l=xi(Oe=>Oe.buffers),p=xi(Oe=>Oe.setActive),a=xi(Oe=>Oe.closeFile),c=xi(Oe=>Oe.closeOthers),f=xi(Oe=>Oe.closeToTheRight),g=xi(Oe=>Oe.closeAll),m=xi(Oe=>Oe.loadBuffer),w=xi(Oe=>Oe.setBuffer),$=xi(Oe=>Oe.markSaved),k=xi(Oe=>Oe.setViewMode),E=gd(),[b,y]=z.useState({}),[S,x]=z.useState({}),[T,R]=z.useState(null),[N,O]=z.useState(null),[j,F]=z.useState(!1),[U,re]=z.useState(!1),[de,J]=z.useState(!0),pe=z.useRef(null),ce=z.useRef(null),ye=z.useRef(void 0),$e=z.useRef(null),me=z.useRef(null),V=UN(t??"",l[t??""]??""),Y=z.useCallback(Oe=>{pe.current=Oe},[]),W=z.useCallback(()=>pe.current,[]);z.useEffect(()=>{NP()},[]),z.useEffect(()=>{const Oe=t;if(!Oe||Yg(Oe))return;if(xi.getState().hasBuffer(Oe)){y(ft=>ft[Oe]==="ready"?ft:{...ft,[Oe]:"ready"});return}let wt=!1;return y(ft=>({...ft,[Oe]:"loading"})),window.api.files.read(Oe).then(ft=>{wt||(ft.binary?y(Xe=>({...Xe,[Oe]:{binary:!0,size:ft.size??0,mime:ft.mime??"application/octet-stream",reason:ft.error??"Binary file"}})):ft.ok?(m(Oe,ft.text),y(Xe=>({...Xe,[Oe]:"ready"}))):y(Xe=>({...Xe,[Oe]:{error:ft.error??"failed to read"}})))}),()=>{wt=!0}},[t,m]),z.useEffect(()=>{O(null)},[t]);const ee=z.useCallback(async(Oe,wt=!1)=>{const ft=xi.getState().buffers[Oe];if(ft==null)return;wt&&F(!0);const Xe=await window.api.files.write(Oe,ft);Xe.ok?($(Oe),x(ct=>({...ct,[Oe]:(ct[Oe]??0)+1})),wt||et.info(`Saved ${Kg(Oe)}`)):et.error(Xe.error??`Couldn't save ${Kg(Oe)}`),wt&&F(!1)},[$]);z.useEffect(()=>{if(!E.autosave)return;const Oe=t;if(!(!Oe||Yg(Oe)||!n[Oe]))return window.clearTimeout(ye.current),ye.current=window.setTimeout(()=>{ee(Oe,!0)},1200),()=>window.clearTimeout(ye.current)},[E.autosave,t,n,l,ee]);const ue=z.useCallback(Oe=>{Oe.length&&(y(wt=>Xg(wt,Oe)),x(wt=>Xg(wt,Oe)))},[]),Ee=z.useCallback((Oe,wt)=>{y(ft=>Oe in ft?{...Xg(ft,[Oe]),[wt]:ft[Oe]}:ft),x(ft=>Oe in ft?{...Xg(ft,[Oe]),[wt]:ft[Oe]}:ft)},[]),Ge=z.useCallback(Oe=>{n[Oe]?R({kind:"one",path:Oe}):(a(Oe),ue([Oe]))},[n,a,ue]),Je=z.useCallback(Oe=>{e.some(ft=>ft.path!==Oe&&n[ft.path])?R({kind:"others",path:Oe}):(c(Oe),ue(e.filter(ft=>ft.path!==Oe).map(ft=>ft.path)))},[e,n,c,ue]),ve=z.useCallback(Oe=>{const wt=e.findIndex(Xe=>Xe.path===Oe);wt!==-1&&e.slice(wt+1).some(Xe=>n[Xe.path])?R({kind:"right",path:Oe}):(f(Oe),ue(wt!==-1?e.slice(wt+1).map(Xe=>Xe.path):[]))},[e,n,f,ue]);z.useEffect(()=>{const Oe=wt=>{if(i.current)if((wt.metaKey||wt.ctrlKey)&&(wt.key==="s"||wt.key==="S")){const ft=xi.getState().activeFilePath;ft&&!Yg(ft)&&(wt.preventDefault(),ee(ft))}else if((wt.metaKey||wt.ctrlKey)&&wt.shiftKey&&(wt.key==="f"||wt.key==="F"))wt.preventDefault(),re(ft=>!ft);else if((wt.metaKey||wt.ctrlKey)&&wt.shiftKey&&(wt.key==="w"||wt.key==="W")){const ft=xi.getState().activeFilePath;ft&&xi.getState().openFiles.length>1&&(wt.preventDefault(),Je(ft))}else wt.key==="Escape"&&V.state.phase!=="idle"?V.cancel():wt.key==="Escape"&&U&&re(!1)};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[ee,U,Je,V.state.phase,V.cancel]),z.useEffect(()=>{if(V.state.phase==="idle")return;const Oe=wt=>{var Xe,ct;const ft=wt.target;(Xe=me.current)!=null&&Xe.contains(ft)||(ct=$e.current)!=null&&ct.contains(ft)||V.cancel()};return window.addEventListener("mousedown",Oe),()=>window.removeEventListener("mousedown",Oe)},[V.state.phase,V.cancel]),z.useEffect(()=>{V.cancel()},[t,V.cancel]);const Z=z.useCallback(()=>{e.some(wt=>n[wt.path])?R({kind:"all",path:""}):(g(),y({}),x({}))},[e,n,g]),we=()=>{if(T){if(T.kind==="one")a(T.path),ue([T.path]);else if(T.kind==="others"){const Oe=e.filter(wt=>wt.path!==T.path).map(wt=>wt.path);c(T.path),ue(Oe)}else if(T.kind==="right"){const Oe=e.findIndex(ft=>ft.path===T.path),wt=Oe!==-1?e.slice(Oe+1).map(ft=>ft.path):[];f(T.path),ue(wt)}else g(),y({}),x({});R(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 fe=t,Ae=fe?Kg(fe):"",ke=fe?b[fe]:void 0,st=fe?ak(fe):!1,yt=fe?IP(fe):!1,ot=fe&&st?r[fe]??PP(fe):"edit",Nt=!!fe&&!Yg(fe)&&ke==="ready",gt=Nt,pi=yt?["edit","wysiwyg","preview","split"]:st?["edit","preview"]:[],it=fe&&d.jsx(rj,{path:fe,name:Ae,value:l[fe]??"",onChange:Oe=>w(fe,Oe),onSave:()=>void ee(fe),onReady:Y,onCursor:O}),Tt=j?"Saving…":fe&&n[fe]?E.autosave?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&d.jsx(qP,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Ge,onCloseOthers:Je,onCloseToTheRight:ve,onCloseAll:Z}),fe&&!U&&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:Ae}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:fe}),Nt&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",Tt]}),el(fe)&&(ot==="preview"||ot==="split")&&d.jsx("button",{onClick:()=>J(Oe=>!Oe),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),el(fe)&&(ot==="preview"||ot==="split")&&d.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),pi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:pi.map(Oe=>d.jsx("button",{onClick:()=>k(fe,Oe),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ot===Oe?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Oe},Oe))}),d.jsx("div",{className:"flex-1"}),d.jsx(ZN,{path:fe,onRenamed:Ee,onDeleted:Oe=>ue([Oe])}),Nt&&d.jsx(tM,{}),d.jsx("button",{onClick:()=>re(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&d.jsx("button",{onClick:()=>re(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),d.jsx("div",{className:"flex-1 min-h-0",children:fe?nk(fe)?d.jsx(DN,{path:fe,name:Ae}):sk(fe)?d.jsx($N,{path:fe}):ke&&typeof ke=="object"&&"binary"in ke?d.jsx(MN,{path:fe,name:Ae,size:ke.size,mime:ke.mime,reason:ke.reason}):ke&&typeof ke=="object"&&"error"in ke?d.jsx("div",{className:"p-6 text-xs text-red-400",children:ke.error}):ke!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ot==="wysiwyg"&&el(fe)?d.jsx(z.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(iM,{value:l[fe]??"",onChange:Oe=>w(fe,Oe)},fe)}):ot==="split"&&el(fe)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(q0,{text:l[fe]??"",scrollRef:ce}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(V0,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:it})]}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(Ub,{ref:ce,text:l[fe]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!U&&E.assistantRail&&d.jsx(J0,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)},onReject:V.cancel,onRetry:V.retry})]}):ot==="preview"&&el(fe)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(q0,{text:l[fe]??"",scrollRef:ce}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(Ub,{ref:ce,text:l[fe]??"",wideMeasure:E.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!U&&E.assistantRail&&d.jsx(J0,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)},onReject:V.cancel,onRetry:V.retry})]}):ot==="preview"&&ik(fe)?d.jsx(EN,{path:fe,dirty:!!n[fe],reloadToken:S[fe]??0}):ot==="preview"&&rk(fe)?d.jsx(IN,{path:fe,text:l[fe]??""}):ot==="preview"&&ok(fe)?d.jsx(jN,{path:fe,text:l[fe]??""}):el(fe)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(V0,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:it})]}):it:null}),gt&&d.jsx(kN,{text:l[fe]??"",cursor:N,language:Fr(fe)||void 0}),fe&&el(fe)&&(ot==="preview"||ot==="split")&&V.state.phase!=="idle"&&V.state.selection&&d.jsx("div",{ref:me,children:d.jsx(XN,{phase:V.state.phase,rect:V.state.selection.rect,diff:V.state.diff,transcript:V.state.transcript,modelStatus:V.state.modelStatus,onQuickAction:V.run,onRunCustom:V.run,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onReject:V.cancel,onRetry:V.retry,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)}})}),T&&d.jsx(sM,{message:T.kind==="one"?`Discard unsaved changes to ${Kg(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:()=>R(null),onConfirm:we})]})}const Kb=z.memo(nM);function sM({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${mn.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 rM={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},eS='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Xv({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?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),g=z.useRef(e);if(g.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(eS);y?y.focus():b.focus()},0),E=b=>{if(b.key==="Escape"){b.stopPropagation(),g.current();return}if(b.key==="Tab"){const y=c.current;if(!y)return;const S=Array.from(y.querySelectorAll(eS)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(S.length===0){b.preventDefault(),y.focus();return}const x=S[0],T=S[S.length-1],R=document.activeElement;b.shiftKey?(R===x||!y.contains(R))&&(b.preventDefault(),T.focus()):(R===T||!y.contains(R))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",E),()=>{clearTimeout(k),document.removeEventListener("keydown",E);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=$=>{$.target===$.currentTarget&&e()},w=d.jsx("div",{className:`fixed inset-0 ${mn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"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 ${rM[r]} ${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?Sh.createPortal(w,document.body):w}class jk extends z.Component{constructor(){super(...arguments);Li(this,"state",{error:null});Li(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 oM({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return d.jsxs(Xv,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="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(jk,{children:n})})]})}function Nk(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 tS=i=>Symbol.iterator in i,iS=i=>"entries"in i,nS=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},aM=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function lM(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:tS(i)&&tS(e)?iS(i)&&iS(e)?nS(i,e):aM(i,e):nS({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Jw(i){const e=jt.useRef(void 0);return t=>{const n=i(t);return lM(e.current,n)?e.current:e.current=n}}let sS=0;const cM=1e3;function dM(i){const e=performance.now();e-sS<cM||(sS=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function uM(){const i=Et(f=>f.isRecording),e=Et(f=>f.error),t=Et(f=>f.loadingProgress),n=Et(Jw(yv)),r=()=>{const f=Et.getState(),{canRecord:g,reason:m}=yv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return dM(m);const w=kt.getState().activeTabId;w&&f.startRecording(w)},l=Nk(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:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${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 hM(){const i=Et(t=>t.ttsEnabled),e=Et(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 pM(i){return/^monitor of /i.test(i.trim())}function rS(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function oS(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=rS(e),l=t.filter(p=>p.label&&rS(p.label)===r);return l.length===1?l[0]:null}async function aS(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&pM(n.label))):[]}const lS=!1;function Mk(){const i=Et(f=>f.isRecording);Et(f=>f.startRecording),Et(f=>f.stopRecording);const[e,t]=z.useState([]),[n,r]=z.useState(null),[l,p]=z.useState(null);z.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await aS(lS);if(f)return;t(m),p(g.selectedLabel);const w=oS(g.selectedDeviceId,g.selectedLabel,m);w?(r(w.deviceId),g.selectedDeviceId&&w.deviceId!==g.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){pt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=z.useCallback(async()=>{try{const f=await aS(lS);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=oS(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){pt.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 $;const g=f.target.value,m=g===""?null:g,w=m?(($=e.find(k=>k.deviceId===m))==null?void 0:$.label)??null:null;r(m),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:w}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){pt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await Et.getState().restartWithDevice()}catch(k){pt.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 fM(){const i=Et($=>$.isRecording),e=Et($=>$.levelMeterEnabled),[t,n]=z.useState(0),[r,l]=z.useState(0),p=z.useRef(0);p.current=r;const[a,c]=z.useState(0),[f,g]=z.useState(!1),m=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){n(0),l(0);return}let $=0,k=!1,E=null,b=null;const y=()=>{if(k)return;const x=b??q1();if(!x){$=requestAnimationFrame(y);return}b!==x&&(b=x,E=new Uint8Array(new ArrayBuffer(x.fftSize)));const T=E;x.getByteTimeDomainData(T);let R=0;for(let F=0;F<T.length;F++){const U=T[F]-128;R+=U*U}const N=Math.sqrt(R/T.length)/128,O=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(O+60)/60));l(N),n(j),N>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),$=requestAnimationFrame(y)};$=requestAnimationFrame(y);const S=setInterval(()=>{k||c(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame($),clearInterval(S),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return 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 Ok(){const i=Et(f=>f.submitCountdownStartAt),e=Et(f=>f.submitDelayMs),[t,n]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,c=Et.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 mM({open:i,onClose:e,variant:t="overlay"}){return d.jsx(oM,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:d.jsxs("div",{className:"p-4 space-y-4",children:[d.jsx(bM,{}),d.jsx(Ok,{}),d.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[d.jsx(uM,{}),d.jsx(Mk,{}),d.jsx(hM,{})]}),d.jsx(gM,{}),d.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[d.jsx("button",{type:"button",onClick:()=>Et.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),d.jsx(_M,{})]}),d.jsx(fM,{})]})})}function gM(){const i=Et(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",r=vM(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:r}),d.jsx("span",{children:" to record"})]})}function vM(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 _M(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return 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 bM(){const i=Et(l=>l.isRecording),e=Et(l=>l.lastTranscript),t=Et(l=>l.error),n=Et(l=>l.modelStatus),r=Et(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:[r,"%"]})]}),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:`${r}%`}})})]}):null}const Lk="~/.claude/session-manager/projects-prefs.json",wM={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Vl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(Lk,t).catch(()=>{})}const cS=Pn((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(Lk);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Vl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":wM[t];i({sort:{col:t,dir:r}}),Vl(e)},setRecentFilter:t=>{i({recentFilter:t}),Vl(e)},setHasRemote:t=>{i({hasRemote:t}),Vl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Vl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Vl(e)},setSearch:t=>{i({search:t}),Vl(e)},setEditor:t=>{i({editor:t}),Vl(e)}}));async function yM(i){const e=await um(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function xM(i,e){return wd(i,{fileTreeExpanded:[...e].slice(0,500)})}async function SM(){const i=await am();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function CM(i){Mv({fileTreeShowHidden:i}).catch(()=>{})}function H_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const W_={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:"!"}},kM=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 EM(i){const e=Fr(i);return kM.has(e)||tk.has(e)||e==="pdf"}function TM(i,e){if(e)return"#d97757";switch(Fr(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 kf(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}function DM({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=kw(),l=Gv(),[p,a]=z.useState([]),[c,f]=z.useState(new Set),g=z.useRef(c);g.current=c;const m=z.useRef(!1),[w,$]=z.useState(""),[k,E]=z.useState(!0),b=z.useRef(!1);z.useEffect(()=>{let it=!1;return SM().then(Tt=>{!it&&!b.current&&E(Tt)}),()=>{it=!0}},[]);const y=z.useCallback(it=>{b.current=!0,E(Tt=>{const Oe=typeof it=="function"?it(Tt):it;return CM(Oe),Oe})},[]),[S,x]=z.useState(!1),[T,R]=z.useState(null),[N,O]=z.useState({}),[j,F]=z.useState(null),[U,re]=z.useState(null),[de,J]=z.useState(""),[pe,ce]=z.useState(null),[ye,$e]=z.useState(""),[me,V]=z.useState(null),Y=z.useRef(null),W=z.useRef(null),ee=z.useRef(0),ue=z.useCallback(async()=>{if(!i)return;const it=++ee.current;x(!0),R(null);const Tt=await window.api.files.list(i,k);ee.current===it&&(Tt.ok?a(Tt.entries.map(Oe=>({...Oe}))):(R(Tt.error??"failed to list"),a([])),x(!1))},[i,k]),Ee=z.useCallback(async it=>{const Tt=ee.current,Oe=new Map;for(const ft of it){const Xe=ft.split("/").length,ct=Oe.get(Xe);ct?ct.push(ft):Oe.set(Xe,[ft])}const wt=[];for(const ft of[...Oe.keys()].sort((Xe,ct)=>Xe-ct)){const Xe=Oe.get(ft),ct=await Promise.all(Xe.map(async Zt=>({p:Zt,result:await window.api.files.list(Zt,k)})));if(ee.current!==Tt)return wt;for(const{p:Zt,result:ci}of ct)ci.ok?a(ii=>cv(ii,Zt,ci.entries.map(fi=>({...fi})))):wt.push(Zt)}return wt},[k]),Ge=z.useCallback(async it=>(await ue(),it.length?Ee(it):[]),[ue,Ee]);z.useEffect(()=>{$(""),re(null),F(null),ce(null),V(null),O({});let it=!1;return m.current=!1,(async()=>{const[Tt]=await Promise.all([yM(i),ue()]);if(it)return;if(!m.current){const wt=new Set(Tt);g.current=wt,f(wt)}if(!Tt.length)return;const Oe=await Ee(Tt);it||!Oe.length||ve(wt=>{const ft=new Set;let Xe=!1;for(const ct of wt){if(Oe.some(Zt=>ct===Zt||ct.startsWith(Zt+"/"))){Xe=!0;continue}ft.add(ct)}return Xe?ft:wt})})(),kf(i).then(Tt=>{it||O(Tt)}),()=>{it=!0}},[i]);const Je=z.useRef(!0);z.useEffect(()=>{if(Je.current){Je.current=!1;return}Ge([...g.current])},[k]),z.useEffect(()=>{if(!i||!l)return;kf(i).then(O);const it=window.setInterval(()=>{kf(i).then(O)},5e3);return()=>window.clearInterval(it)},[i,l]),z.useEffect(()=>{if(!j)return;const it=()=>F(null),Tt=Oe=>{r.current&&Oe.key==="Escape"&&F(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",Tt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",Tt)}},[j]),z.useEffect(()=>{U&&setTimeout(()=>{var it;return(it=Y.current)==null?void 0:it.select()},30)},[U]),z.useEffect(()=>{pe&&setTimeout(()=>{var it;return(it=W.current)==null?void 0:it.focus()},30)},[pe]);const ve=z.useCallback(it=>{const Tt=g.current,Oe=it(Tt);Oe!==Tt&&(m.current=!0,g.current=Oe,f(Oe),xM(i,Oe).catch(()=>{g.current===Oe&&(g.current=Tt,f(Tt),et.error("Couldn't save folder expansion — reverted."))}))},[i]),Z=z.useCallback(async it=>{if(c.has(it.path)){ve(Oe=>H_(Oe,it.path));return}if(ve(Oe=>new Set(Oe).add(it.path)),it.children)return;const Tt=await window.api.files.list(it.path,k);Tt.ok&&a(Oe=>cv(Oe,it.path,Tt.entries.map(wt=>({...wt}))))},[c,k,ve]),we=z.useCallback(async it=>{if(it===i){await ue();return}const Tt=await window.api.files.list(it,k);Tt.ok&&a(Oe=>cv(Oe,it,Tt.entries.map(wt=>({...wt}))))},[i,ue,k]),fe=z.useCallback(it=>{if(it.isDirectory){Z(it);return}EM(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[Z,e]),Ae=z.useCallback(it=>{if(t){t(it);return}if(n){const Tt=it.startsWith(i+"/")?it.slice(i.length+1):it;window.api.pty.write({tabId:n,data:`@${Tt} `})}},[t,n,i]),ke=z.useCallback((it,Tt)=>{it.preventDefault(),it.stopPropagation(),F({x:it.clientX,y:it.clientY,node:Tt})},[]),st=it=>{re(it.path),J(it.name)},yt=async()=>{if(!U)return;const it=de.trim();if(!it){re(null);return}const Tt=await window.api.files.rename(U,it);if(re(null),Tt.ok){const Oe=U.slice(0,U.lastIndexOf("/"));ve(wt=>H_(wt,U)),await we(Oe||i),kf(i).then(O)}else{const Oe=Tt.error??"rename failed";R(Oe),et.error(Oe)}},ot=async()=>{if(!pe)return;const it=ye.trim();if(!it){ce(null),$e("");return}const Tt=await window.api.files.create(pe.parent,it,pe.kind);if(ce(null),$e(""),Tt.ok)await we(pe.parent),pe.kind==="folder"&&ve(Oe=>new Set(Oe).add(pe.parent));else{const Oe=Tt.error??"create failed";R(Oe),et.error(Oe)}},Nt=async()=>{if(!me)return;const it=await window.api.files.delete(me.path),Tt=me.path.slice(0,me.path.lastIndexOf("/"));if(V(null),it.ok)ve(Oe=>H_(Oe,me.path)),await we(Tt||i),kf(i).then(O);else{const Oe=it.error??"delete failed";R(Oe),et.error(Oe)}},gt=z.useMemo(()=>{if(!w.trim())return p;const it=w.toLowerCase();return p.filter(Tt=>Tt.name.toLowerCase().includes(it))},[p,w]),pi=(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(Bk,{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:pi}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:ue,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:S,children:d.jsx(jM,{size:12,className:S?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:it=>$(it.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(NM,{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(MM,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>y(it=>!it),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(OM,{size:12}):d.jsx(LM,{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&>.length===0&&!S&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!T&&d.jsx(zk,{nodes:gt,depth:0,expanded:c,gitStatus:N,renaming:U,renameValue:de,renameInputRef:Y,onRenameChange:J,onRenameCommit:yt,onRenameCancel:()=>re(null),onToggleDir:Z,onFileClick:fe,onSendToChat:Ae,onContextMenu:ke})]}),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"}),j&&d.jsx($M,{x:j.x,y:j.y,node:j.node,onClose:()=>F(null),onRename:()=>{st(j.node),F(null)},onDelete:()=>{V(j.node),F(null)},onNewFile:()=>{ce({parent:j.node.path,kind:"file"}),F(null)},onNewFolder:()=>{ce({parent:j.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:j.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:j.node.path}),F(null)},onCopyPath:()=>{var it;(it=navigator.clipboard)==null||it.writeText(j.node.path),F(null)},onSendToChat:()=>{Ae(j.node.path),F(null)}}),pe&&d.jsx(dS,{title:`New ${pe.kind}`,subtitle:`in ${AM(pe.parent)}`,onCancel:()=>{ce(null),$e("")},onConfirm:ot,confirmLabel:"Create",confirmDisabled:!ye.trim(),children:d.jsx("input",{ref:W,value:ye,onChange:it=>$e(it.target.value),onKeyDown:it=>{it.key==="Enter"&&ot(),it.key==="Escape"&&(ce(null),$e(""))},placeholder:pe.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"})}),me&&d.jsx(dS,{title:`Delete ${me.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>V(null),onConfirm:Nt,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:['"',me.name,'"']})," to the trash?",me.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function zk(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,g=r[a.path],m=TM(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(RM,{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(IM,{size:12,color:m}):d.jsx(Bk,{size:12,color:m}):d.jsx(PM,{size:12,color:m}),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}),g&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:W_[g].color,backgroundColor:`${W_[g].color}20`},title:g,children:W_[g].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(zM,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(zk,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function $M(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${mn.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(ql,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(ql,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(ql,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(U_,{}),d.jsx(ql,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(ql,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(U_,{}),d.jsx(ql,{label:"New file",onClick:i.onNewFile}),d.jsx(ql,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(U_,{}),d.jsx(ql,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function ql({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 U_(){return d.jsx("div",{className:"my-1 border-t border-line"})}function dS(i){return d.jsx("div",{className:`fixed inset-0 ${mn.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 AM(i){return i.split("/").filter(Boolean).pop()||i}function cv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:cv(n.children,e,t)}:n)}function Sa({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 Bk({size:i,className:e,color:t}){return d.jsx(Sa,{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 IM({size:i,className:e,color:t}){return d.jsx(Sa,{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 PM({size:i,className:e,color:t}){return d.jsxs(Sa,{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 RM({size:i,className:e}){return d.jsx(Sa,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function jM({size:i,className:e}){return d.jsxs(Sa,{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 NM({size:i,className:e}){return d.jsxs(Sa,{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 MM({size:i,className:e}){return d.jsxs(Sa,{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 OM({size:i,className:e}){return d.jsxs(Sa,{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 LM({size:i,className:e}){return d.jsxs(Sa,{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 zM({size:i,className:e}){return d.jsxs(Sa,{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 Gk({content:i,children:e,align:t="bottom-right"}){const[n,r]=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:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${mn.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 Uf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Xb="sm.projects.splitPct",Yb=33,Fk=20,Hk=60,Wk="sm.projects.fileTreeCollapsed",BM=32;function GM(){try{const i=parseFloat(localStorage.getItem(Xb)??"");if(Number.isFinite(i))return Math.min(Hk,Math.max(Fk,i))}catch{}return Yb}function FM(){try{return localStorage.getItem(Wk)==="1"}catch{return!1}}function HM(){const i=kt(U=>U.tabs),e=kt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ri(U=>U.navFace),[r,l]=z.useState(null);z.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(re=>{U||l(re)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,c]=z.useState(()=>GM()),[f,g]=z.useState(()=>FM()),[m,w]=z.useState(!1),$=z.useRef(a);$.current=a;const k=z.useRef(null),E=z.useRef(null),{projects:b,openProject:y,archiveProjectByCwd:S}=Ch(),x=cS(U=>U.pinned),T=cS(U=>U.togglePin),R=[...b].sort((U,re)=>(x[re.cwd]?1:0)-(x[U.cwd]?1:0));z.useEffect(()=>{if(!m)return;const U=re=>{E.current&&!E.current.contains(re.target)&&w(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=z.useCallback(U=>{xi.getState().openFile(U)},[]),O=z.useCallback(U=>{U.preventDefault();const re=U.clientX,de=$.current;let J=de;const pe=ye=>{const $e=k.current;if(!$e)return;const me=$e.getBoundingClientRect(),V=ye.clientX-re;J=Math.min(Hk,Math.max(Fk,de+V/me.width*100)),c(J)},ce=()=>{window.removeEventListener("pointermove",pe),window.removeEventListener("pointerup",ce),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Xb,String(J))}catch{}};window.addEventListener("pointermove",pe),window.addEventListener("pointerup",ce),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=z.useCallback(()=>{c(Yb);try{localStorage.setItem(Xb,String(Yb))}catch{}},[]),F=z.useCallback(()=>{g(U=>{const re=!U;try{localStorage.setItem(Wk,re?"1":"0")}catch{}return re})},[]);return f?d.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:F,"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:BM},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(Kb,{})})]}):d.jsxs("div",{ref:k,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:`${a}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:E,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(U=>!U),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[d.jsx("span",{className:"flex-1 truncate text-left",children:p?Uf(p):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),d.jsx("button",{onClick:F,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${mn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:R.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):R.map(U=>{const re=Uf(U.cwd);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(Gk,{content:x[U.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>T(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{y(U.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await S(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.cwd)})})]}),p?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:p,children:Uf(p)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(DM,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):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:O,onDoubleClick:j,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(Kb,{})})]})}const WM=z.memo(HM),UM={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a 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 VM({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 qM({active:i}){const e=In(m=>m.learningPanelCollapsed),t=In(m=>m.setLearningPanelCollapsed),n=In(m=>m.hydrated),r=In(m=>m.hydrate);z.useEffect(()=>{n||r()},[n,r]);const[l,p]=z.useState(()=>!e),a=z.useRef(null);z.useEffect(()=>{n&&p(!e)},[n]);const c=z.useCallback(()=>{p(m=>{const w=!m;return t(!w),w})},[t]);z.useEffect(()=>{if(!l)return;const m=w=>{var $;($=a.current)!=null&&$.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[l,t]);const f=z.useRef(!1);z.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const g=UM[i];return g?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(VM,{content:g})})]}):null}function KM({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,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})]}),r&&d.jsx(qM,{active:r})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const XM=z.lazy(()=>mi(()=>import("./Skills-C3T_2_2o.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,14,15,1,2]),import.meta.url).then(i=>({default:i.Skills}))),YM=z.lazy(()=>mi(()=>import("./History-DfPR3_6N.js"),__vite__mapDeps([16,4,1,2]),import.meta.url).then(i=>({default:i.History}))),JM=z.lazy(()=>mi(()=>import("./Scheduler-eixbMGEk.js"),__vite__mapDeps([17,13,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),ZM=z.lazy(()=>mi(()=>import("./Settings-qD-0W-Ut.js"),__vite__mapDeps([18,4,8,7,19,20,21,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),QM=z.lazy(()=>mi(()=>import("./Permissions-ChSNRUJJ.js"),__vite__mapDeps([22,4,8,7,11,12,19,20,21,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),eO=z.lazy(()=>mi(()=>import("./SystemPrompt-B-xTy9Qn.js"),__vite__mapDeps([23,4,7,11,12,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),tO=z.lazy(()=>mi(()=>import("./Memory-DobxIoZ-.js"),__vite__mapDeps([24,4,5,6,21,1,2]),import.meta.url).then(i=>({default:i.Memory}))),iO=z.lazy(()=>mi(()=>import("./Plugins-CII221R2.js"),__vite__mapDeps([25,4,10,11,12,14,15,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),nO=z.lazy(()=>mi(()=>import("./McpServers-Bz9O79rz.js"),__vite__mapDeps([26,4,5,7,8,10,11,12,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),sO=z.lazy(()=>mi(()=>import("./Hooks-Bw7H_DmC.js"),__vite__mapDeps([27,4,5,7,8,10,11,12,19,20,21,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),rO=z.lazy(()=>mi(()=>import("./AgentLibrary-Bjeq2-kp.js"),__vite__mapDeps([28,4,5,12,29,14,20,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),oO=z.lazy(()=>mi(()=>import("./TagLibrary-BH67tR5z.js"),__vite__mapDeps([30,4,5,29,14,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),aO=z.lazy(()=>mi(()=>import("./DataModel-iPJw5jcG.js"),__vite__mapDeps([31,4,21,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),lO=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Lr({children:i}){return d.jsx(z.Suspense,{fallback:lO,children:i})}const cO={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"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:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},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."}},dO=()=>{},uS=new Map;function uO(i,e){const t=uS.get(i);if(t&&t.ctx===e)return t.node;const n=hO(i,e);return uS.set(i,{ctx:e,node:n}),n}function hO(i,e){switch(i){case"overview":return d.jsx(iP,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return d.jsx(WP,{});case"editor":return d.jsx(Kb,{});case"projects":return d.jsx(WM,{})}const t=cO[i],n=(()=>{switch(i){case"skills":return d.jsx(Lr,{children:d.jsx(XM,{})});case"history":return d.jsx(Lr,{children:d.jsx(YM,{})});case"scheduler":return d.jsx(Lr,{children:d.jsx(JM,{navigate:e.onNavigate})});case"plugins":return d.jsx(Lr,{children:d.jsx(iO,{})});case"mcp":return d.jsx(Lr,{children:d.jsx(nO,{})});case"hooks":return d.jsx(Lr,{children:d.jsx(sO,{})});case"memory":return d.jsx(Lr,{children:d.jsx(tO,{})});case"system-prompt":return d.jsx(Lr,{children:d.jsx(eO,{})});case"permissions":return d.jsx(Lr,{children:d.jsx(QM,{})});case"settings":return d.jsx(Lr,{children:d.jsx(ZM,{})});case"agent-library":return d.jsx(Lr,{children:d.jsx(rO,{})});case"tag-library":return d.jsx(Lr,{children:d.jsx(oO,{})});case"data-model":return d.jsx(Lr,{children:d.jsx(aO,{})});case"voice":return d.jsx(mM,{open:!0,onClose:dO,variant:"page"});default:return null}})();if(!n)return null;const r=XT[i];return t&&r?d.jsx(KM,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var V_={exports:{}},hS;function pO(){return hS||(hS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(S,x,T,R){var N,O=arguments.length,j=O<3?x:R===null?R=Object.getOwnPropertyDescriptor(x,T):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(S,x,T,R);else for(var F=S.length-1;F>=0;F--)(N=S[F])&&(j=(O<3?N(j):O>3?N(x,T,j):N(x,T))||j);return O>3&&j&&Object.defineProperty(x,T,j),j},g=this&&this.__param||function(S,x){return function(T,R){x(T,R,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=c(9042),w=c(9924),$=c(844),k=c(4725),E=c(2585),b=c(3656);let y=a.AccessibilityManager=class extends $.Disposable{constructor(S,x,T,R){super(),this._terminal=S,this._coreBrowserService=T,this._renderService=R,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(`
|
|
3033
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),S=z.useCallback(x=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const R=ON(x,T.before,T.after);return R.ok?(r.current+=1,n({type:"ACCEPT"})):et.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:b,run:E,retry:y,accept:S}}const VN=[{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."}],Y0=320,Cf=8;function qN(){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 KN(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Cf),Math.max(Cf,e-Y0-Cf)),n=Math.max(i.top-Cf,Cf);return{position:"fixed",left:t,top:n,width:Y0,transform:"translateY(-100%)",zIndex:a2.dialog}}function XN({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:c,onCancel:f,onAccept:g,onReject:m,onRetry:w}){const[$,k]=z.useState(""),E=()=>{const b=$.trim();b&&(p(b),k(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:KN(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:a,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),VN.map(b=>d.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),d.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{autoFocus:!0,value:$,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?E():b.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&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(qN,{}),"Listening…"]}),r&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),d.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),d.jsxs("div",{className:"flex justify-end 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:"Cancel"}),d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:c,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:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&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:t.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),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:"Reject"}),d.jsx("button",{onClick:w,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 YN(){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 J0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:g}){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:Yf(WN)})]}),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(YN,{}),"Listening…"]}),r&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),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:g,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 JN(){const i=kt(t=>t.tabs),e=kt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function Z0(i){return i.split("/").filter(Boolean).pop()||i}function ZN({path:i,onRenamed:e,onDeleted:t}){const[n,r]=z.useState(!1),[l,p]=z.useState(!1),[a,c]=z.useState(""),[f,g]=z.useState(!1),m=xi(U=>U.buffers[i]),w=xi(U=>U.openFile),$=xi(U=>U.renameOpenFile),k=xi(U=>U.closeFile),E=JN(),b=Z0(i),y=()=>r(!1),S=()=>{c(b),p(!0),y()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const re=await window.api.files.rename(i,U);if(re.ok){const de=i.slice(0,i.lastIndexOf("/")),J=re.newPath??`${de}/${U}`;$(i,J),e==null||e(i,J),et.info(`Renamed to ${U}`)}else et.error(re.error??`Couldn't rename ${b}`)}catch(re){et.error(re instanceof Error?re.message:`Couldn't rename ${b}`)}p(!1)},T=async()=>{y();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(w(U.path),et.info(`Duplicated as ${Z0(U.path)}`)):et.error(U.error??`Couldn't duplicate ${b}`)}catch(U){et.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const U=await window.api.files.delete(i);U.ok?(k(i),t==null||t(i),et.info(`Deleted ${b}`)):et.error(U.error??`Couldn't delete ${b}`)}catch(U){et.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}g(!1)},N=async()=>{y();const U=m??"";try{await navigator.clipboard.writeText(U),et.info(`Copied ${U.length} chars`)}catch(re){et.error(re instanceof Error?re.message:`Couldn't copy ${b}`)}},O=()=>{if(y(),!E){et.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${i} `}),et.info(`Added ${b} to Claude context`)},j=()=>{y(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||et.error(U.error??`Couldn't open ${b}`)}).catch(U=>et.error(U instanceof Error?U.message:`Couldn't open ${b}`))},F=()=>{y(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||et.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>et.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>r(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${mn.contextMenuScrim}`,onMouseDown:y}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${mn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(F_,{children:"Edit"}),d.jsx(cd,{label:"Rename",onClick:S}),d.jsx(cd,{label:"Duplicate",onClick:T}),d.jsx(cd,{label:"Delete document",danger:!0,onClick:()=>{y(),g(!0)}}),d.jsx(Q0,{}),d.jsx(F_,{children:"Open"}),d.jsx(cd,{label:"Open in default app",onClick:j}),d.jsx(cd,{label:"Reveal in OS",onClick:F}),d.jsx(Q0,{}),d.jsx(F_,{children:"Export"}),d.jsx(cd,{label:"Copy as Markdown",onClick:N}),d.jsx(cd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(QN,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&d.jsx(eM,{name:b,onCancel:()=>g(!1),onConfirm:()=>void R()})]})}function F_({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 cd({label:i,onClick:e,danger:t,disabled:n,title:r}){return d.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function Q0(){return d.jsx("div",{className:"my-1 border-t border-line"})}function QN({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${mn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.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:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),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 eM({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${mn.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 tM(){const[i,e]=z.useState(!1),t=gd();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 ${mn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${mn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(uh,{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(uh,{label:"Word wrap",children:d.jsx(qg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(uh,{label:"Minimap",children:d.jsx(qg,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(uh,{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(uh,{label:"Autosave",children:d.jsx(qg,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(uh,{label:"Wide measure",children:d.jsx(qg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function uh({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 qg({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 iM=z.lazy(()=>mi(()=>import("./TiptapBody-1r4ODLJ7.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Kg(i){return i.split("/").filter(Boolean).pop()||i}function Xg(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Yg(i){return nk(i)||sk(i)}function nM(){const i=kw(),e=xi(Oe=>Oe.openFiles),t=xi(Oe=>Oe.activeFilePath),n=xi(Oe=>Oe.dirty),r=xi(Oe=>Oe.viewMode),l=xi(Oe=>Oe.buffers),p=xi(Oe=>Oe.setActive),a=xi(Oe=>Oe.closeFile),c=xi(Oe=>Oe.closeOthers),f=xi(Oe=>Oe.closeToTheRight),g=xi(Oe=>Oe.closeAll),m=xi(Oe=>Oe.loadBuffer),w=xi(Oe=>Oe.setBuffer),$=xi(Oe=>Oe.markSaved),k=xi(Oe=>Oe.setViewMode),E=gd(),[b,y]=z.useState({}),[S,x]=z.useState({}),[T,R]=z.useState(null),[N,O]=z.useState(null),[j,F]=z.useState(!1),[U,re]=z.useState(!1),[de,J]=z.useState(!0),pe=z.useRef(null),ce=z.useRef(null),ye=z.useRef(void 0),$e=z.useRef(null),me=z.useRef(null),V=UN(t??"",l[t??""]??""),Y=z.useCallback(Oe=>{pe.current=Oe},[]),W=z.useCallback(()=>pe.current,[]);z.useEffect(()=>{NP()},[]),z.useEffect(()=>{const Oe=t;if(!Oe||Yg(Oe))return;if(xi.getState().hasBuffer(Oe)){y(ft=>ft[Oe]==="ready"?ft:{...ft,[Oe]:"ready"});return}let wt=!1;return y(ft=>({...ft,[Oe]:"loading"})),window.api.files.read(Oe).then(ft=>{wt||(ft.binary?y(Xe=>({...Xe,[Oe]:{binary:!0,size:ft.size??0,mime:ft.mime??"application/octet-stream",reason:ft.error??"Binary file"}})):ft.ok?(m(Oe,ft.text),y(Xe=>({...Xe,[Oe]:"ready"}))):y(Xe=>({...Xe,[Oe]:{error:ft.error??"failed to read"}})))}),()=>{wt=!0}},[t,m]),z.useEffect(()=>{O(null)},[t]);const ee=z.useCallback(async(Oe,wt=!1)=>{const ft=xi.getState().buffers[Oe];if(ft==null)return;wt&&F(!0);const Xe=await window.api.files.write(Oe,ft);Xe.ok?($(Oe),x(ct=>({...ct,[Oe]:(ct[Oe]??0)+1})),wt||et.info(`Saved ${Kg(Oe)}`)):et.error(Xe.error??`Couldn't save ${Kg(Oe)}`),wt&&F(!1)},[$]);z.useEffect(()=>{if(!E.autosave)return;const Oe=t;if(!(!Oe||Yg(Oe)||!n[Oe]))return window.clearTimeout(ye.current),ye.current=window.setTimeout(()=>{ee(Oe,!0)},1200),()=>window.clearTimeout(ye.current)},[E.autosave,t,n,l,ee]);const ue=z.useCallback(Oe=>{Oe.length&&(y(wt=>Xg(wt,Oe)),x(wt=>Xg(wt,Oe)))},[]),Ee=z.useCallback((Oe,wt)=>{y(ft=>Oe in ft?{...Xg(ft,[Oe]),[wt]:ft[Oe]}:ft),x(ft=>Oe in ft?{...Xg(ft,[Oe]),[wt]:ft[Oe]}:ft)},[]),Ge=z.useCallback(Oe=>{n[Oe]?R({kind:"one",path:Oe}):(a(Oe),ue([Oe]))},[n,a,ue]),Je=z.useCallback(Oe=>{e.some(ft=>ft.path!==Oe&&n[ft.path])?R({kind:"others",path:Oe}):(c(Oe),ue(e.filter(ft=>ft.path!==Oe).map(ft=>ft.path)))},[e,n,c,ue]),ve=z.useCallback(Oe=>{const wt=e.findIndex(Xe=>Xe.path===Oe);wt!==-1&&e.slice(wt+1).some(Xe=>n[Xe.path])?R({kind:"right",path:Oe}):(f(Oe),ue(wt!==-1?e.slice(wt+1).map(Xe=>Xe.path):[]))},[e,n,f,ue]);z.useEffect(()=>{const Oe=wt=>{if(i.current)if((wt.metaKey||wt.ctrlKey)&&(wt.key==="s"||wt.key==="S")){const ft=xi.getState().activeFilePath;ft&&!Yg(ft)&&(wt.preventDefault(),ee(ft))}else if((wt.metaKey||wt.ctrlKey)&&wt.shiftKey&&(wt.key==="f"||wt.key==="F"))wt.preventDefault(),re(ft=>!ft);else if((wt.metaKey||wt.ctrlKey)&&wt.shiftKey&&(wt.key==="w"||wt.key==="W")){const ft=xi.getState().activeFilePath;ft&&xi.getState().openFiles.length>1&&(wt.preventDefault(),Je(ft))}else wt.key==="Escape"&&V.state.phase!=="idle"?V.cancel():wt.key==="Escape"&&U&&re(!1)};return window.addEventListener("keydown",Oe),()=>window.removeEventListener("keydown",Oe)},[ee,U,Je,V.state.phase,V.cancel]),z.useEffect(()=>{if(V.state.phase==="idle")return;const Oe=wt=>{var Xe,ct;const ft=wt.target;(Xe=me.current)!=null&&Xe.contains(ft)||(ct=$e.current)!=null&&ct.contains(ft)||V.cancel()};return window.addEventListener("mousedown",Oe),()=>window.removeEventListener("mousedown",Oe)},[V.state.phase,V.cancel]),z.useEffect(()=>{V.cancel()},[t,V.cancel]);const Z=z.useCallback(()=>{e.some(wt=>n[wt.path])?R({kind:"all",path:""}):(g(),y({}),x({}))},[e,n,g]),we=()=>{if(T){if(T.kind==="one")a(T.path),ue([T.path]);else if(T.kind==="others"){const Oe=e.filter(wt=>wt.path!==T.path).map(wt=>wt.path);c(T.path),ue(Oe)}else if(T.kind==="right"){const Oe=e.findIndex(ft=>ft.path===T.path),wt=Oe!==-1?e.slice(Oe+1).map(ft=>ft.path):[];f(T.path),ue(wt)}else g(),y({}),x({});R(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 fe=t,Ae=fe?Kg(fe):"",ke=fe?b[fe]:void 0,st=fe?ak(fe):!1,yt=fe?IP(fe):!1,ot=fe&&st?r[fe]??PP(fe):"edit",Nt=!!fe&&!Yg(fe)&&ke==="ready",gt=Nt,pi=yt?["edit","wysiwyg","preview","split"]:st?["edit","preview"]:[],it=fe&&d.jsx(rj,{path:fe,name:Ae,value:l[fe]??"",onChange:Oe=>w(fe,Oe),onSave:()=>void ee(fe),onReady:Y,onCursor:O}),Tt=j?"Saving…":fe&&n[fe]?E.autosave?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&d.jsx(qP,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Ge,onCloseOthers:Je,onCloseToTheRight:ve,onCloseAll:Z}),fe&&!U&&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:Ae}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:fe}),Nt&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",Tt]}),el(fe)&&(ot==="preview"||ot==="split")&&d.jsx("button",{onClick:()=>J(Oe=>!Oe),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),el(fe)&&(ot==="preview"||ot==="split")&&d.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),pi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:pi.map(Oe=>d.jsx("button",{onClick:()=>k(fe,Oe),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ot===Oe?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Oe},Oe))}),d.jsx("div",{className:"flex-1"}),d.jsx(ZN,{path:fe,onRenamed:Ee,onDeleted:Oe=>ue([Oe])}),Nt&&d.jsx(tM,{}),d.jsx("button",{onClick:()=>re(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&d.jsx("button",{onClick:()=>re(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),d.jsx("div",{className:"flex-1 min-h-0",children:fe?nk(fe)?d.jsx(DN,{path:fe,name:Ae}):sk(fe)?d.jsx($N,{path:fe}):ke&&typeof ke=="object"&&"binary"in ke?d.jsx(MN,{path:fe,name:Ae,size:ke.size,mime:ke.mime,reason:ke.reason}):ke&&typeof ke=="object"&&"error"in ke?d.jsx("div",{className:"p-6 text-xs text-red-400",children:ke.error}):ke!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ot==="wysiwyg"&&el(fe)?d.jsx(z.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(iM,{value:l[fe]??"",onChange:Oe=>w(fe,Oe)},fe)}):ot==="split"&&el(fe)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(q0,{text:l[fe]??"",scrollRef:ce}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(V0,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:it})]}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(Ub,{ref:ce,text:l[fe]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!U&&E.assistantRail&&d.jsx(J0,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)},onReject:V.cancel,onRetry:V.retry})]}):ot==="preview"&&el(fe)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(q0,{text:l[fe]??"",scrollRef:ce}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(Ub,{ref:ce,text:l[fe]??"",wideMeasure:E.wideMeasure,onSelect:V.select,onDismissSelection:V.cancel})}),!U&&E.assistantRail&&d.jsx(J0,{phase:V.state.phase,transcript:V.state.transcript,diff:V.state.diff,editCount:V.state.editCount,modelStatus:V.state.modelStatus,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)},onReject:V.cancel,onRetry:V.retry})]}):ot==="preview"&&ik(fe)?d.jsx(EN,{path:fe,dirty:!!n[fe],reloadToken:S[fe]??0}):ot==="preview"&&rk(fe)?d.jsx(IN,{path:fe,text:l[fe]??""}):ot==="preview"&&ok(fe)?d.jsx(jN,{path:fe,text:l[fe]??""}):el(fe)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(V0,{getEditor:W}),d.jsx("div",{className:"flex-1 min-h-0",children:it})]}):it:null}),gt&&d.jsx(kN,{text:l[fe]??"",cursor:N,language:Fr(fe)||void 0}),fe&&el(fe)&&(ot==="preview"||ot==="split")&&V.state.phase!=="idle"&&V.state.selection&&d.jsx("div",{ref:me,children:d.jsx(XN,{phase:V.state.phase,rect:V.state.selection.rect,diff:V.state.diff,transcript:V.state.transcript,modelStatus:V.state.modelStatus,onQuickAction:V.run,onRunCustom:V.run,onListen:V.listen,onSendHeard:V.sendHeard,onCancel:V.cancel,onReject:V.cancel,onRetry:V.retry,onAccept:()=>{const Oe=V.accept(l[fe]??"");Oe.ok&&w(fe,Oe.next)}})}),T&&d.jsx(sM,{message:T.kind==="one"?`Discard unsaved changes to ${Kg(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:()=>R(null),onConfirm:we})]})}const Kb=z.memo(nM);function sM({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${mn.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 rM={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},eS='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Xv({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?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),g=z.useRef(e);if(g.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(eS);y?y.focus():b.focus()},0),E=b=>{if(b.key==="Escape"){b.stopPropagation(),g.current();return}if(b.key==="Tab"){const y=c.current;if(!y)return;const S=Array.from(y.querySelectorAll(eS)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(S.length===0){b.preventDefault(),y.focus();return}const x=S[0],T=S[S.length-1],R=document.activeElement;b.shiftKey?(R===x||!y.contains(R))&&(b.preventDefault(),T.focus()):(R===T||!y.contains(R))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",E),()=>{clearTimeout(k),document.removeEventListener("keydown",E);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=$=>{$.target===$.currentTarget&&e()},w=d.jsx("div",{className:`fixed inset-0 ${mn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"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 ${rM[r]} ${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?Sh.createPortal(w,document.body):w}class jk extends z.Component{constructor(){super(...arguments);Li(this,"state",{error:null});Li(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 oM({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return d.jsxs(Xv,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="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(jk,{children:n})})]})}function Nk(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 tS=i=>Symbol.iterator in i,iS=i=>"entries"in i,nS=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},aM=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function lM(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:tS(i)&&tS(e)?iS(i)&&iS(e)?nS(i,e):aM(i,e):nS({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Jw(i){const e=jt.useRef(void 0);return t=>{const n=i(t);return lM(e.current,n)?e.current:e.current=n}}let sS=0;const cM=1e3;function dM(i){const e=performance.now();e-sS<cM||(sS=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function uM(){const i=Et(f=>f.isRecording),e=Et(f=>f.error),t=Et(f=>f.loadingProgress),n=Et(Jw(yv)),r=()=>{const f=Et.getState(),{canRecord:g,reason:m}=yv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return dM(m);const w=kt.getState().activeTabId;w&&f.startRecording(w)},l=Nk(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:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${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 hM(){const i=Et(t=>t.ttsEnabled),e=Et(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 pM(i){return/^monitor of /i.test(i.trim())}function rS(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function oS(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=rS(e),l=t.filter(p=>p.label&&rS(p.label)===r);return l.length===1?l[0]:null}async function aS(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&pM(n.label))):[]}const lS=!1;function Mk(){const i=Et(f=>f.isRecording);Et(f=>f.startRecording),Et(f=>f.stopRecording);const[e,t]=z.useState([]),[n,r]=z.useState(null),[l,p]=z.useState(null);z.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await aS(lS);if(f)return;t(m),p(g.selectedLabel);const w=oS(g.selectedDeviceId,g.selectedLabel,m);w?(r(w.deviceId),g.selectedDeviceId&&w.deviceId!==g.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:w.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:w.deviceId,selectedLabel:w.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){pt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=z.useCallback(async()=>{try{const f=await aS(lS);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=oS(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){pt.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 $;const g=f.target.value,m=g===""?null:g,w=m?(($=e.find(k=>k.deviceId===m))==null?void 0:$.label)??null:null;r(m),p(w);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:w}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){pt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await Et.getState().restartWithDevice()}catch(k){pt.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 fM(){const i=Et($=>$.isRecording),e=Et($=>$.levelMeterEnabled),[t,n]=z.useState(0),[r,l]=z.useState(0),p=z.useRef(0);p.current=r;const[a,c]=z.useState(0),[f,g]=z.useState(!1),m=z.useRef(null);if(z.useEffect(()=>{if(!i||!e){n(0),l(0);return}let $=0,k=!1,E=null,b=null;const y=()=>{if(k)return;const x=b??q1();if(!x){$=requestAnimationFrame(y);return}b!==x&&(b=x,E=new Uint8Array(new ArrayBuffer(x.fftSize)));const T=E;x.getByteTimeDomainData(T);let R=0;for(let F=0;F<T.length;F++){const U=T[F]-128;R+=U*U}const N=Math.sqrt(R/T.length)/128,O=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(O+60)/60));l(N),n(j),N>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),$=requestAnimationFrame(y)};$=requestAnimationFrame(y);const S=setInterval(()=>{k||c(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame($),clearInterval(S),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const w=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return 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 Ok(){const i=Et(f=>f.submitCountdownStartAt),e=Et(f=>f.submitDelayMs),[t,n]=z.useState(()=>performance.now());if(z.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,c=Et.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 mM({open:i,onClose:e,variant:t="overlay"}){return d.jsx(oM,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:d.jsxs("div",{className:"p-4 space-y-4",children:[d.jsx(bM,{}),d.jsx(Ok,{}),d.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[d.jsx(uM,{}),d.jsx(Mk,{}),d.jsx(hM,{})]}),d.jsx(gM,{}),d.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[d.jsx("button",{type:"button",onClick:()=>Et.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),d.jsx(_M,{})]}),d.jsx(fM,{})]})})}function gM(){const i=Et(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",r=vM(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:r}),d.jsx("span",{children:" to record"})]})}function vM(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 _M(){const[i,e]=z.useState(null);if(z.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return 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 bM(){const i=Et(l=>l.isRecording),e=Et(l=>l.lastTranscript),t=Et(l=>l.error),n=Et(l=>l.modelStatus),r=Et(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:[r,"%"]})]}),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:`${r}%`}})})]}):null}const Lk="~/.claude/session-manager/projects-prefs.json",wM={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Vl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(Lk,t).catch(()=>{})}const cS=Pn((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(Lk);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Vl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":wM[t];i({sort:{col:t,dir:r}}),Vl(e)},setRecentFilter:t=>{i({recentFilter:t}),Vl(e)},setHasRemote:t=>{i({hasRemote:t}),Vl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Vl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Vl(e)},setSearch:t=>{i({search:t}),Vl(e)},setEditor:t=>{i({editor:t}),Vl(e)}}));async function yM(i){const e=await um(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function xM(i,e){return wd(i,{fileTreeExpanded:[...e].slice(0,500)})}async function SM(){const i=await am();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function CM(i){Mv({fileTreeShowHidden:i}).catch(()=>{})}function H_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const W_={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:"!"}},kM=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 EM(i){const e=Fr(i);return kM.has(e)||tk.has(e)||e==="pdf"}function TM(i,e){if(e)return"#d97757";switch(Fr(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 kf(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}function DM({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=kw(),l=Gv(),[p,a]=z.useState([]),[c,f]=z.useState(new Set),g=z.useRef(c);g.current=c;const m=z.useRef(!1),[w,$]=z.useState(""),[k,E]=z.useState(!0),b=z.useRef(!1);z.useEffect(()=>{let it=!1;return SM().then(Tt=>{!it&&!b.current&&E(Tt)}),()=>{it=!0}},[]);const y=z.useCallback(it=>{b.current=!0,E(Tt=>{const Oe=typeof it=="function"?it(Tt):it;return CM(Oe),Oe})},[]),[S,x]=z.useState(!1),[T,R]=z.useState(null),[N,O]=z.useState({}),[j,F]=z.useState(null),[U,re]=z.useState(null),[de,J]=z.useState(""),[pe,ce]=z.useState(null),[ye,$e]=z.useState(""),[me,V]=z.useState(null),Y=z.useRef(null),W=z.useRef(null),ee=z.useRef(0),ue=z.useCallback(async()=>{if(!i)return;const it=++ee.current;x(!0),R(null);const Tt=await window.api.files.list(i,k);ee.current===it&&(Tt.ok?a(Tt.entries.map(Oe=>({...Oe}))):(R(Tt.error??"failed to list"),a([])),x(!1))},[i,k]),Ee=z.useCallback(async it=>{const Tt=ee.current,Oe=new Map;for(const ft of it){const Xe=ft.split("/").length,ct=Oe.get(Xe);ct?ct.push(ft):Oe.set(Xe,[ft])}const wt=[];for(const ft of[...Oe.keys()].sort((Xe,ct)=>Xe-ct)){const Xe=Oe.get(ft),ct=await Promise.all(Xe.map(async Zt=>({p:Zt,result:await window.api.files.list(Zt,k)})));if(ee.current!==Tt)return wt;for(const{p:Zt,result:ci}of ct)ci.ok?a(ii=>cv(ii,Zt,ci.entries.map(fi=>({...fi})))):wt.push(Zt)}return wt},[k]),Ge=z.useCallback(async it=>(await ue(),it.length?Ee(it):[]),[ue,Ee]);z.useEffect(()=>{$(""),re(null),F(null),ce(null),V(null),O({});let it=!1;return m.current=!1,(async()=>{const[Tt]=await Promise.all([yM(i),ue()]);if(it)return;if(!m.current){const wt=new Set(Tt);g.current=wt,f(wt)}if(!Tt.length)return;const Oe=await Ee(Tt);it||!Oe.length||ve(wt=>{const ft=new Set;let Xe=!1;for(const ct of wt){if(Oe.some(Zt=>ct===Zt||ct.startsWith(Zt+"/"))){Xe=!0;continue}ft.add(ct)}return Xe?ft:wt})})(),kf(i).then(Tt=>{it||O(Tt)}),()=>{it=!0}},[i]);const Je=z.useRef(!0);z.useEffect(()=>{if(Je.current){Je.current=!1;return}Ge([...g.current])},[k]),z.useEffect(()=>{if(!i||!l)return;kf(i).then(O);const it=window.setInterval(()=>{kf(i).then(O)},5e3);return()=>window.clearInterval(it)},[i,l]),z.useEffect(()=>{if(!j)return;const it=()=>F(null),Tt=Oe=>{r.current&&Oe.key==="Escape"&&F(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",Tt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",Tt)}},[j]),z.useEffect(()=>{U&&setTimeout(()=>{var it;return(it=Y.current)==null?void 0:it.select()},30)},[U]),z.useEffect(()=>{pe&&setTimeout(()=>{var it;return(it=W.current)==null?void 0:it.focus()},30)},[pe]);const ve=z.useCallback(it=>{const Tt=g.current,Oe=it(Tt);Oe!==Tt&&(m.current=!0,g.current=Oe,f(Oe),xM(i,Oe).catch(()=>{g.current===Oe&&(g.current=Tt,f(Tt),et.error("Couldn't save folder expansion — reverted."))}))},[i]),Z=z.useCallback(async it=>{if(c.has(it.path)){ve(Oe=>H_(Oe,it.path));return}if(ve(Oe=>new Set(Oe).add(it.path)),it.children)return;const Tt=await window.api.files.list(it.path,k);Tt.ok&&a(Oe=>cv(Oe,it.path,Tt.entries.map(wt=>({...wt}))))},[c,k,ve]),we=z.useCallback(async it=>{if(it===i){await ue();return}const Tt=await window.api.files.list(it,k);Tt.ok&&a(Oe=>cv(Oe,it,Tt.entries.map(wt=>({...wt}))))},[i,ue,k]),fe=z.useCallback(it=>{if(it.isDirectory){Z(it);return}EM(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[Z,e]),Ae=z.useCallback(it=>{if(t){t(it);return}if(n){const Tt=it.startsWith(i+"/")?it.slice(i.length+1):it;window.api.pty.write({tabId:n,data:`@${Tt} `})}},[t,n,i]),ke=z.useCallback((it,Tt)=>{it.preventDefault(),it.stopPropagation(),F({x:it.clientX,y:it.clientY,node:Tt})},[]),st=it=>{re(it.path),J(it.name)},yt=async()=>{if(!U)return;const it=de.trim();if(!it){re(null);return}const Tt=await window.api.files.rename(U,it);if(re(null),Tt.ok){const Oe=U.slice(0,U.lastIndexOf("/"));ve(wt=>H_(wt,U)),await we(Oe||i),kf(i).then(O)}else{const Oe=Tt.error??"rename failed";R(Oe),et.error(Oe)}},ot=async()=>{if(!pe)return;const it=ye.trim();if(!it){ce(null),$e("");return}const Tt=await window.api.files.create(pe.parent,it,pe.kind);if(ce(null),$e(""),Tt.ok)await we(pe.parent),pe.kind==="folder"&&ve(Oe=>new Set(Oe).add(pe.parent));else{const Oe=Tt.error??"create failed";R(Oe),et.error(Oe)}},Nt=async()=>{if(!me)return;const it=await window.api.files.delete(me.path),Tt=me.path.slice(0,me.path.lastIndexOf("/"));if(V(null),it.ok)ve(Oe=>H_(Oe,me.path)),await we(Tt||i),kf(i).then(O);else{const Oe=it.error??"delete failed";R(Oe),et.error(Oe)}},gt=z.useMemo(()=>{if(!w.trim())return p;const it=w.toLowerCase();return p.filter(Tt=>Tt.name.toLowerCase().includes(it))},[p,w]),pi=(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(Bk,{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:pi}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:ue,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:S,children:d.jsx(jM,{size:12,className:S?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:it=>$(it.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(NM,{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(MM,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>y(it=>!it),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(OM,{size:12}):d.jsx(LM,{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&>.length===0&&!S&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!T&&d.jsx(zk,{nodes:gt,depth:0,expanded:c,gitStatus:N,renaming:U,renameValue:de,renameInputRef:Y,onRenameChange:J,onRenameCommit:yt,onRenameCancel:()=>re(null),onToggleDir:Z,onFileClick:fe,onSendToChat:Ae,onContextMenu:ke})]}),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"}),j&&d.jsx($M,{x:j.x,y:j.y,node:j.node,onClose:()=>F(null),onRename:()=>{st(j.node),F(null)},onDelete:()=>{V(j.node),F(null)},onNewFile:()=>{ce({parent:j.node.path,kind:"file"}),F(null)},onNewFolder:()=>{ce({parent:j.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:j.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:j.node.path}),F(null)},onCopyPath:()=>{var it;(it=navigator.clipboard)==null||it.writeText(j.node.path),F(null)},onSendToChat:()=>{Ae(j.node.path),F(null)}}),pe&&d.jsx(dS,{title:`New ${pe.kind}`,subtitle:`in ${AM(pe.parent)}`,onCancel:()=>{ce(null),$e("")},onConfirm:ot,confirmLabel:"Create",confirmDisabled:!ye.trim(),children:d.jsx("input",{ref:W,value:ye,onChange:it=>$e(it.target.value),onKeyDown:it=>{it.key==="Enter"&&ot(),it.key==="Escape"&&(ce(null),$e(""))},placeholder:pe.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"})}),me&&d.jsx(dS,{title:`Delete ${me.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>V(null),onConfirm:Nt,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:['"',me.name,'"']})," to the trash?",me.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function zk(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,g=r[a.path],m=TM(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(RM,{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(IM,{size:12,color:m}):d.jsx(Bk,{size:12,color:m}):d.jsx(PM,{size:12,color:m}),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}),g&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:W_[g].color,backgroundColor:`${W_[g].color}20`},title:g,children:W_[g].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(zM,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(zk,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function $M(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${mn.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(ql,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(ql,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(ql,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(U_,{}),d.jsx(ql,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(ql,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(U_,{}),d.jsx(ql,{label:"New file",onClick:i.onNewFile}),d.jsx(ql,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(U_,{}),d.jsx(ql,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function ql({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 U_(){return d.jsx("div",{className:"my-1 border-t border-line"})}function dS(i){return d.jsx("div",{className:`fixed inset-0 ${mn.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 AM(i){return i.split("/").filter(Boolean).pop()||i}function cv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:cv(n.children,e,t)}:n)}function Sa({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 Bk({size:i,className:e,color:t}){return d.jsx(Sa,{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 IM({size:i,className:e,color:t}){return d.jsx(Sa,{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 PM({size:i,className:e,color:t}){return d.jsxs(Sa,{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 RM({size:i,className:e}){return d.jsx(Sa,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function jM({size:i,className:e}){return d.jsxs(Sa,{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 NM({size:i,className:e}){return d.jsxs(Sa,{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 MM({size:i,className:e}){return d.jsxs(Sa,{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 OM({size:i,className:e}){return d.jsxs(Sa,{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 LM({size:i,className:e}){return d.jsxs(Sa,{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 zM({size:i,className:e}){return d.jsxs(Sa,{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 Gk({content:i,children:e,align:t="bottom-right"}){const[n,r]=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:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${mn.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 Uf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Xb="sm.projects.splitPct",Yb=33,Fk=20,Hk=60,Wk="sm.projects.fileTreeCollapsed",BM=32;function GM(){try{const i=parseFloat(localStorage.getItem(Xb)??"");if(Number.isFinite(i))return Math.min(Hk,Math.max(Fk,i))}catch{}return Yb}function FM(){try{return localStorage.getItem(Wk)==="1"}catch{return!1}}function HM(){const i=kt(U=>U.tabs),e=kt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ri(U=>U.navFace),[r,l]=z.useState(null);z.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(re=>{U||l(re)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,c]=z.useState(()=>GM()),[f,g]=z.useState(()=>FM()),[m,w]=z.useState(!1),$=z.useRef(a);$.current=a;const k=z.useRef(null),E=z.useRef(null),{projects:b,openProject:y,archiveProjectByCwd:S}=Ch(),x=cS(U=>U.pinned),T=cS(U=>U.togglePin),R=[...b].sort((U,re)=>(x[re.cwd]?1:0)-(x[U.cwd]?1:0));z.useEffect(()=>{if(!m)return;const U=re=>{E.current&&!E.current.contains(re.target)&&w(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=z.useCallback(U=>{xi.getState().openFile(U)},[]),O=z.useCallback(U=>{U.preventDefault();const re=U.clientX,de=$.current;let J=de;const pe=ye=>{const $e=k.current;if(!$e)return;const me=$e.getBoundingClientRect(),V=ye.clientX-re;J=Math.min(Hk,Math.max(Fk,de+V/me.width*100)),c(J)},ce=()=>{window.removeEventListener("pointermove",pe),window.removeEventListener("pointerup",ce),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Xb,String(J))}catch{}};window.addEventListener("pointermove",pe),window.addEventListener("pointerup",ce),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=z.useCallback(()=>{c(Yb);try{localStorage.setItem(Xb,String(Yb))}catch{}},[]),F=z.useCallback(()=>{g(U=>{const re=!U;try{localStorage.setItem(Wk,re?"1":"0")}catch{}return re})},[]);return f?d.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:F,"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:BM},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(Kb,{})})]}):d.jsxs("div",{ref:k,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:`${a}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:E,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(U=>!U),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[d.jsx("span",{className:"flex-1 truncate text-left",children:p?Uf(p):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),d.jsx("button",{onClick:F,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${mn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:R.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):R.map(U=>{const re=Uf(U.cwd);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(Gk,{content:x[U.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>T(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{y(U.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await S(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.cwd)})})]}),p?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:p,children:Uf(p)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(DM,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):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:O,onDoubleClick:j,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(Kb,{})})]})}const WM=z.memo(HM),UM={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a 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 VM({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 qM({active:i}){const e=In(m=>m.learningPanelCollapsed),t=In(m=>m.setLearningPanelCollapsed),n=In(m=>m.hydrated),r=In(m=>m.hydrate);z.useEffect(()=>{n||r()},[n,r]);const[l,p]=z.useState(()=>!e),a=z.useRef(null);z.useEffect(()=>{n&&p(!e)},[n]);const c=z.useCallback(()=>{p(m=>{const w=!m;return t(!w),w})},[t]);z.useEffect(()=>{if(!l)return;const m=w=>{var $;($=a.current)!=null&&$.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[l,t]);const f=z.useRef(!1);z.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const g=UM[i];return g?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(VM,{content:g})})]}):null}function KM({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,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})]}),r&&d.jsx(qM,{active:r})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const XM=z.lazy(()=>mi(()=>import("./Skills-CMmCZfIv.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,14,15,1,2]),import.meta.url).then(i=>({default:i.Skills}))),YM=z.lazy(()=>mi(()=>import("./History-Df3YwpPe.js"),__vite__mapDeps([16,4,1,2]),import.meta.url).then(i=>({default:i.History}))),JM=z.lazy(()=>mi(()=>import("./Scheduler-BehadU-0.js"),__vite__mapDeps([17,13,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),ZM=z.lazy(()=>mi(()=>import("./Settings-Cg9LIni0.js"),__vite__mapDeps([18,4,8,7,19,20,21,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),QM=z.lazy(()=>mi(()=>import("./Permissions-XvBiMj1-.js"),__vite__mapDeps([22,4,8,7,11,12,19,20,21,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),eO=z.lazy(()=>mi(()=>import("./SystemPrompt-D_-MV025.js"),__vite__mapDeps([23,4,7,11,12,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),tO=z.lazy(()=>mi(()=>import("./Memory-C3rUQ_cg.js"),__vite__mapDeps([24,4,5,6,21,1,2]),import.meta.url).then(i=>({default:i.Memory}))),iO=z.lazy(()=>mi(()=>import("./Plugins-CzHY1mgS.js"),__vite__mapDeps([25,4,10,11,12,14,15,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),nO=z.lazy(()=>mi(()=>import("./McpServers-Da-Ty5nc.js"),__vite__mapDeps([26,4,5,7,8,10,11,12,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),sO=z.lazy(()=>mi(()=>import("./Hooks-DplG6roH.js"),__vite__mapDeps([27,4,5,7,8,10,11,12,19,20,21,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),rO=z.lazy(()=>mi(()=>import("./AgentLibrary-Co54GThg.js"),__vite__mapDeps([28,4,5,12,29,14,20,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),oO=z.lazy(()=>mi(()=>import("./TagLibrary-D9Tv3yOJ.js"),__vite__mapDeps([30,4,5,29,14,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),aO=z.lazy(()=>mi(()=>import("./DataModel-DZ0vyJau.js"),__vite__mapDeps([31,4,21,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),lO=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Lr({children:i}){return d.jsx(z.Suspense,{fallback:lO,children:i})}const cO={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"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:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},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."}},dO=()=>{},uS=new Map;function uO(i,e){const t=uS.get(i);if(t&&t.ctx===e)return t.node;const n=hO(i,e);return uS.set(i,{ctx:e,node:n}),n}function hO(i,e){switch(i){case"overview":return d.jsx(iP,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return d.jsx(WP,{});case"editor":return d.jsx(Kb,{});case"projects":return d.jsx(WM,{})}const t=cO[i],n=(()=>{switch(i){case"skills":return d.jsx(Lr,{children:d.jsx(XM,{})});case"history":return d.jsx(Lr,{children:d.jsx(YM,{})});case"scheduler":return d.jsx(Lr,{children:d.jsx(JM,{navigate:e.onNavigate})});case"plugins":return d.jsx(Lr,{children:d.jsx(iO,{})});case"mcp":return d.jsx(Lr,{children:d.jsx(nO,{})});case"hooks":return d.jsx(Lr,{children:d.jsx(sO,{})});case"memory":return d.jsx(Lr,{children:d.jsx(tO,{})});case"system-prompt":return d.jsx(Lr,{children:d.jsx(eO,{})});case"permissions":return d.jsx(Lr,{children:d.jsx(QM,{})});case"settings":return d.jsx(Lr,{children:d.jsx(ZM,{})});case"agent-library":return d.jsx(Lr,{children:d.jsx(rO,{})});case"tag-library":return d.jsx(Lr,{children:d.jsx(oO,{})});case"data-model":return d.jsx(Lr,{children:d.jsx(aO,{})});case"voice":return d.jsx(mM,{open:!0,onClose:dO,variant:"page"});default:return null}})();if(!n)return null;const r=XT[i];return t&&r?d.jsx(KM,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var V_={exports:{}},hS;function pO(){return hS||(hS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(S,x,T,R){var N,O=arguments.length,j=O<3?x:R===null?R=Object.getOwnPropertyDescriptor(x,T):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(S,x,T,R);else for(var F=S.length-1;F>=0;F--)(N=S[F])&&(j=(O<3?N(j):O>3?N(x,T,j):N(x,T))||j);return O>3&&j&&Object.defineProperty(x,T,j),j},g=this&&this.__param||function(S,x){return function(T,R){x(T,R,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=c(9042),w=c(9924),$=c(844),k=c(4725),E=c(2585),b=c(3656);let y=a.AccessibilityManager=class extends $.Disposable{constructor(S,x,T,R){super(),this._terminal=S,this._coreBrowserService=T,this._renderService=R,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(`
|
|
3034
3034
|
`)))),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,$.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(S){for(let x=0;x<S;x++)this._handleChar(" ")}_handleChar(S){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==S&&(this._charsToAnnounce+=S):this._charsToAnnounce+=S,S===`
|
|
3035
3035
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(S){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(S)||this._charsToConsume.push(S)}_refreshRows(S,x){this._liveRegionDebouncer.refresh(S,x,this._terminal.rows)}_renderRows(S,x){const T=this._terminal.buffer,R=T.lines.length.toString();for(let N=S;N<=x;N++){const O=T.lines.get(T.ydisp+N),j=[],F=(O==null?void 0:O.translateToString(!0,void 0,void 0,j))||"",U=(T.ydisp+N+1).toString(),re=this._rowElements[N];re&&(F.length===0?(re.innerText=" ",this._rowColumns.set(re,[0,1])):(re.textContent=F,this._rowColumns.set(re,j)),re.setAttribute("aria-posinset",U),re.setAttribute("aria-setsize",R))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(S,x){const T=S.target,R=this._rowElements[x===0?1:this._rowElements.length-2];if(T.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||S.relatedTarget!==R)return;let N,O;if(x===0?(N=T,O=this._rowElements.pop(),this._rowContainer.removeChild(O)):(N=this._rowElements.shift(),O=T,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),O.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const j=this._createAccessibilityTreeNode();this._rowElements.unshift(j),this._rowContainer.insertAdjacentElement("afterbegin",j)}else{const j=this._createAccessibilityTreeNode();this._rowElements.push(j),this._rowContainer.appendChild(j)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),S.preventDefault(),S.stopImmediatePropagation()}_handleSelectionChange(){var F;if(this._rowElements.length===0)return;const S=document.getSelection();if(!S)return;if(S.isCollapsed)return void(this._rowContainer.contains(S.anchorNode)&&this._terminal.clearSelection());if(!S.anchorNode||!S.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:S.anchorNode,offset:S.anchorOffset},T={node:S.focusNode,offset:S.focusOffset};if((x.node.compareDocumentPosition(T.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===T.node&&x.offset>T.offset)&&([x,T]=[T,x]),x.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(x={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(x.node))return;const R=this._rowElements.slice(-1)[0];if(T.node.compareDocumentPosition(R)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(T={node:R,offset:((F=R.textContent)==null?void 0:F.length)??0}),!this._rowContainer.contains(T.node))return;const N=({node:U,offset:re})=>{const de=U instanceof Text?U.parentNode:U;let J=parseInt(de==null?void 0:de.getAttribute("aria-posinset"),10)-1;if(isNaN(J))return console.warn("row is invalid. Race condition?"),null;const pe=this._rowColumns.get(de);if(!pe)return console.warn("columns is null. Race condition?"),null;let ce=re<pe.length?pe[re]:pe.slice(-1)[0]+1;return ce>=this._terminal.cols&&(++J,ce=0),{row:J,column:ce}},O=N(x),j=N(T);if(O&&j){if(O.row>j.row||O.row===j.row&&O.column>=j.column)throw new Error("invalid range");this._terminal.select(O.column,O.row,(j.row-O.row)*this._terminal.cols-O.column+j.column)}}_handleResize(S){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let x=this._rowContainer.children.length;x<this._terminal.rows;x++)this._rowElements[x]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[x]);for(;this._rowElements.length>S;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const S=this._coreBrowserService.mainDocument.createElement("div");return S.setAttribute("role","listitem"),S.tabIndex=-1,this._refreshRowDimensions(S),S}_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 S=0;S<this._terminal.rows;S++)this._refreshRowDimensions(this._rowElements[S])}}_refreshRowDimensions(S){S.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=y=f([g(1,E.IInstantiationService),g(2,k.ICoreBrowserService),g(3,k.IRenderService)],y)},3614:(p,a)=>{function c(w){return w.replace(/\r?\n/g,"\r")}function f(w,$){return $?"\x1B[200~"+w+"\x1B[201~":w}function g(w,$,k,E){w=f(w=c(w),k.decPrivateModes.bracketedPasteMode&&E.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(w,!0),$.value=""}function m(w,$,k){const E=k.getBoundingClientRect(),b=w.clientX-E.left-10,y=w.clientY-E.top-10;$.style.width="20px",$.style.height="20px",$.style.left=`${b}px`,$.style.top=`${y}px`,$.style.zIndex="1000",$.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,$){w.clipboardData&&w.clipboardData.setData("text/plain",$.selectionText),w.preventDefault()},a.handlePasteEvent=function(w,$,k,E){w.stopPropagation(),w.clipboardData&&g(w.clipboardData.getData("text/plain"),$,k,E)},a.paste=g,a.moveTextAreaUnderMouseCursor=m,a.rightClickHandler=function(w,$,k,E,b){m(w,$,k),b&&E.rightClickSelect(w),$.value=E.selectionText,$.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(g,m,w){this._css.set(g,m,w)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,w){this._color.set(g,m,w)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(c,f,g,m){c.addEventListener(f,g,m);let w=!1;return{dispose:()=>{w||(w=!0,c.removeEventListener(f,g,m))}}}},3551:function(p,a,c){var f=this&&this.__decorate||function(y,S,x,T){var R,N=arguments.length,O=N<3?S:T===null?T=Object.getOwnPropertyDescriptor(S,x):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(y,S,x,T);else for(var j=y.length-1;j>=0;j--)(R=y[j])&&(O=(N<3?R(O):N>3?R(S,x,O):R(S,x))||O);return N>3&&O&&Object.defineProperty(S,x,O),O},g=this&&this.__param||function(y,S){return function(x,T){S(x,T,y)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const m=c(3656),w=c(8460),$=c(844),k=c(2585),E=c(4725);let b=a.Linkifier=class extends $.Disposable{get currentLink(){return this._currentLink}constructor(y,S,x,T,R){super(),this._element=y,this._mouseService=S,this._renderService=x,this._bufferService=T,this._linkProviderService=R,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,$.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,$.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(y){this._lastMouseEvent=y;const S=this._positionFromMouseEvent(y,this._element,this._mouseService);if(!S)return;this._isMouseOut=!1;const x=y.composedPath();for(let T=0;T<x.length;T++){const R=x[T];if(R.classList.contains("xterm"))break;if(R.classList.contains("xterm-hover"))return}this._lastBufferCell&&S.x===this._lastBufferCell.x&&S.y===this._lastBufferCell.y||(this._handleHover(S),this._lastBufferCell=S)}_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,S){var T,R;this._activeProviderReplies&&S||((T=this._activeProviderReplies)==null||T.forEach((N=>{N==null||N.forEach((O=>{O.link.dispose&&O.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=y.y);let x=!1;for(const[N,O]of this._linkProviderService.linkProviders.entries())S?(R=this._activeProviderReplies)!=null&&R.get(N)&&(x=this._checkLinkProviderResult(N,y,x)):O.provideLinks(y.y,(j=>{var U,re;if(this._isMouseOut)return;const F=j==null?void 0:j.map((de=>({link:de})));(U=this._activeProviderReplies)==null||U.set(N,F),x=this._checkLinkProviderResult(N,y,x),((re=this._activeProviderReplies)==null?void 0:re.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(y.y,this._activeProviderReplies)}))}_removeIntersectingLinks(y,S){const x=new Set;for(let T=0;T<S.size;T++){const R=S.get(T);if(R)for(let N=0;N<R.length;N++){const O=R[N],j=O.link.range.start.y<y?0:O.link.range.start.x,F=O.link.range.end.y>y?this._bufferService.cols:O.link.range.end.x;for(let U=j;U<=F;U++){if(x.has(U)){R.splice(N--,1);break}x.add(U)}}}}_checkLinkProviderResult(y,S,x){var N;if(!this._activeProviderReplies)return x;const T=this._activeProviderReplies.get(y);let R=!1;for(let O=0;O<y;O++)this._activeProviderReplies.has(O)&&!this._activeProviderReplies.get(O)||(R=!0);if(!R&&T){const O=T.find((j=>this._linkAtPosition(j.link,S)));O&&(x=!0,this._handleNewLink(O))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let O=0;O<this._activeProviderReplies.size;O++){const j=(N=this._activeProviderReplies.get(O))==null?void 0:N.find((F=>this._linkAtPosition(F.link,S)));if(j){x=!0,this._handleNewLink(j);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(y){if(!this._currentLink)return;const S=this._positionFromMouseEvent(y,this._element,this._mouseService);S&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,S)&&this._currentLink.link.activate(y,this._currentLink.link.text)}_clearCurrentLink(y,S){this._currentLink&&this._lastMouseEvent&&(!y||!S||this._currentLink.link.range.start.y>=y&&this._currentLink.link.range.end.y<=S)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,$.disposeArray)(this._linkCacheDisposables))}_handleNewLink(y){if(!this._lastMouseEvent)return;const S=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);S&&this._linkAtPosition(y.link,S)&&(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 x,T;return(T=(x=this._currentLink)==null?void 0:x.state)==null?void 0:T.decorations.pointerCursor},set:x=>{var T;(T=this._currentLink)!=null&&T.state&&this._currentLink.state.decorations.pointerCursor!==x&&(this._currentLink.state.decorations.pointerCursor=x,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",x))}},underline:{get:()=>{var x,T;return(T=(x=this._currentLink)==null?void 0:x.state)==null?void 0:T.decorations.underline},set:x=>{var T,R,N;(T=this._currentLink)!=null&&T.state&&((N=(R=this._currentLink)==null?void 0:R.state)==null?void 0:N.decorations.underline)!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(y.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const T=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,R=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=T&&this._currentLink.link.range.end.y<=R&&(this._clearCurrentLink(T,R),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(y,S,x){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!0),this._currentLink.state.decorations.pointerCursor&&y.classList.add("xterm-cursor-pointer")),S.hover&&S.hover(x,S.text)}_fireUnderlineEvent(y,S){const x=y.range,T=this._bufferService.buffer.ydisp,R=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-T-1,x.end.x,x.end.y-T-1,void 0);(S?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(R)}_linkLeave(y,S,x){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!1),this._currentLink.state.decorations.pointerCursor&&y.classList.remove("xterm-cursor-pointer")),S.leave&&S.leave(x,S.text)}_linkAtPosition(y,S){const x=y.range.start.y*this._bufferService.cols+y.range.start.x,T=y.range.end.y*this._bufferService.cols+y.range.end.x,R=S.y*this._bufferService.cols+S.x;return x<=R&&R<=T}_positionFromMouseEvent(y,S,x){const T=x.getCoords(y,S,this._bufferService.cols,this._bufferService.rows);if(T)return{x:T[0],y:T[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(y,S,x,T,R){return{x1:y,y1:S,x2:x,y2:T,cols:this._bufferService.cols,fg:R}}};a.Linkifier=b=f([g(1,E.IMouseService),g(2,E.IRenderService),g(3,k.IBufferService),g(4,E.ILinkProviderService)],b)},9042:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(p,a,c){var f=this&&this.__decorate||function(E,b,y,S){var x,T=arguments.length,R=T<3?b:S===null?S=Object.getOwnPropertyDescriptor(b,y):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(E,b,y,S);else for(var N=E.length-1;N>=0;N--)(x=E[N])&&(R=(T<3?x(R):T>3?x(b,y,R):x(b,y))||R);return T>3&&R&&Object.defineProperty(b,y,R),R},g=this&&this.__param||function(E,b){return function(y,S){b(y,S,E)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const m=c(511),w=c(2585);let $=a.OscLinkProvider=class{constructor(E,b,y){this._bufferService=E,this._optionsService=b,this._oscLinkService=y}provideLinks(E,b){var F;const y=this._bufferService.buffer.lines.get(E-1);if(!y)return void b(void 0);const S=[],x=this._optionsService.rawOptions.linkHandler,T=new m.CellData,R=y.getTrimmedLength();let N=-1,O=-1,j=!1;for(let U=0;U<R;U++)if(O!==-1||y.hasContent(U)){if(y.loadCell(U,T),T.hasExtendedAttrs()&&T.extended.urlId){if(O===-1){O=U,N=T.extended.urlId;continue}j=T.extended.urlId!==N}else O!==-1&&(j=!0);if(j||O!==-1&&U===R-1){const re=(F=this._oscLinkService.getLinkData(N))==null?void 0:F.uri;if(re){const de={start:{x:O+1,y:E},end:{x:U+(j||U!==R-1?0:1),y:E}};let J=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const pe=new URL(re);["http:","https:"].includes(pe.protocol)||(J=!0)}catch{J=!0}J||S.push({text:re,range:de,activate:(pe,ce)=>x?x.activate(pe,ce,de):k(0,ce),hover:(pe,ce)=>{var ye;return(ye=x==null?void 0:x.hover)==null?void 0:ye.call(x,pe,ce,de)},leave:(pe,ce)=>{var ye;return(ye=x==null?void 0:x.leave)==null?void 0:ye.call(x,pe,ce,de)}})}j=!1,T.hasExtendedAttrs()&&T.extended.urlId?(O=U,N=T.extended.urlId):(O=-1,N=-1)}}b(S)}};function k(E,b){if(confirm(`Do you want to navigate to ${b}?
|
|
3036
3036
|
|