claude-code-session-manager 0.135.0 → 0.135.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/dist/assets/{AgentLibrary-DRlcF1YD.js → AgentLibrary-BBY7E1ag.js} +1 -1
- package/dist/assets/{AppSettings-CBhYHKGI.js → AppSettings-vMiIi0xn.js} +1 -1
- package/dist/assets/{Button-DtBUGvGI.js → Button-C0Z090Ui.js} +1 -1
- package/dist/assets/{DocumentEditorPane-C82c7Qtl.js → DocumentEditorPane-Ds10W8SZ.js} +1 -1
- package/dist/assets/{Extensions-Kn-oUD2_.js → Extensions-CjPiz2I5.js} +2 -2
- package/dist/assets/{History-B4c3Uz9u.js → History-Bm3KXXs1.js} +1 -1
- package/dist/assets/{Library-1RpLT-aH.js → Library-D-khizDg.js} +1 -1
- package/dist/assets/{ListDetail-xr0oxNkv.js → ListDetail-CJYpp8fW.js} +1 -1
- package/dist/assets/{Panel-O8XPrpJu.js → Panel-BHFGylfy.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-DBGhhzg2.js → ProjectClaudeConfig-DIzNAala.js} +1 -1
- package/dist/assets/{ProvenanceBadge-DSaizfZL.js → ProvenanceBadge-CYryeTYF.js} +1 -1
- package/dist/assets/{Scheduler-D2_5NyiR.js → Scheduler-BS82wfRP.js} +1 -1
- package/dist/assets/{Settings-Clgqb3Lq.js → Settings-DWPHJ94d.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-D80RA7kR.js → SkillReferenceGraph-Cf2M7YNq.js} +1 -1
- package/dist/assets/{Skills-DNG7tHSf.js → Skills-DLq55Odf.js} +1 -1
- package/dist/assets/{SourceChip-D-Imzszd.js → SourceChip-CHxAzRlD.js} +1 -1
- package/dist/assets/{SystemPrompt-CGlOpUQA.js → SystemPrompt-BYtKMAr3.js} +1 -1
- package/dist/assets/{TiptapBody-CJFGfBdz.js → TiptapBody-O_Gfq0Ha.js} +1 -1
- package/dist/assets/{Toggle-0Ff0bPa_.js → Toggle-BJOUI5NY.js} +1 -1
- package/dist/assets/{ViewTabs-BCMYQwo_.js → ViewTabs-kkvNGu-S.js} +1 -1
- package/dist/assets/{VoiceButton-JzyC6DAB.js → VoiceButton-3i-6ju2L.js} +1 -1
- package/dist/assets/{historyTotals-B01WPBwh.js → historyTotals-CHrIptK1.js} +1 -1
- package/dist/assets/{index-rt7pTODX.js → index-D9qgN9_V.js} +3 -3
- package/dist/index.html +1 -1
- package/dist-web/app.js +1 -1
- package/package.json +1 -1
- package/plugins/CLAUDE.md +7 -8
- package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +113 -91
- package/plugins/session-manager-dev/skills/builder/manual.md +80 -0
- package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -56
- package/plugins/session-manager-dev/skills/develop/standards.md +11 -19
- package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +13 -18
- package/src/main/build-info.json +4 -4
- package/src/main/lib/CLAUDE.md +2 -0
- package/src/main/lib/epic/epicTranscriptPath.cjs +5 -4
- package/src/main/lib/epic/restorableSessions.cjs +16 -8
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +23 -0
- package/src/seed/agents/demo-video-builder.md +25 -32
- package/src/seed/agents/dev-lead.md +3 -3
- package/plugins/session-manager-dev/skills/builder/0-diff/SKILL.md +0 -44
- package/plugins/session-manager-dev/skills/builder/1-classify-and-bump/SKILL.md +0 -37
- package/plugins/session-manager-dev/skills/builder/2-gate/SKILL.md +0 -37
- package/plugins/session-manager-dev/skills/builder/3-publish/SKILL.md +0 -137
- package/plugins/session-manager-dev/skills/builder/4-manual/SKILL.md +0 -124
- package/plugins/session-manager-dev/skills/builder/5-report/SKILL.md +0 -35
|
@@ -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-O_Gfq0Ha.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./History-Bm3KXXs1.js","./Panel-BHFGylfy.js","./historyTotals-CHrIptK1.js","./Scheduler-BS82wfRP.js","./Settings-DWPHJ94d.js","./Library-D-khizDg.js","./Button-C0Z090Ui.js","./SourceChip-CHxAzRlD.js","./ViewTabs-kkvNGu-S.js","./claude-settings-schema-COigsajx.js","./ListDetail-CJYpp8fW.js","./ProvenanceBadge-CYryeTYF.js","./SystemPrompt-BYtKMAr3.js","./DocumentEditorPane-Ds10W8SZ.js","./ProjectClaudeConfig-DIzNAala.js","./VoiceButton-3i-6ju2L.js","./Skills-DLq55Odf.js","./Toggle-BJOUI5NY.js","./Extensions-CjPiz2I5.js","./AppSettings-vMiIi0xn.js","./AgentLibrary-BBY7E1ag.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var g$=Object.defineProperty;var v$=(n,e,t)=>e in n?g$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var oi=(n,e,t)=>v$(n,typeof e!="symbol"?e+"":e,t);import{_ as Kn}from"./monaco-editor-BsIlgG7c.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const u of a.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&i(u)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();function fy(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var xb={exports:{}},jf={},bb={exports:{}},Nn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -2931,7 +2931,7 @@ ${P}`,z=v.createShaderModule({code:R,label:o.name});vn("verbose",()=>`[WebGPU] $
|
|
|
2931
2931
|
* Licensed under the MIT License.
|
|
2932
2932
|
*/var B1;function xA(){return B1||(B1=1,(function(n,e){var t=(()=>{var i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,l=(Z=>typeof mo<"u"?mo:typeof Proxy<"u"?new Proxy(Z,{get:(ae,ge)=>(typeof mo<"u"?mo:ae)[ge]}):Z)(function(Z){if(typeof mo<"u")return mo.apply(this,arguments);throw Error('Dynamic require of "'+Z+'" is not supported')}),d=(Z,ae)=>()=>(Z&&(ae=Z(Z=0)),ae),h=(Z,ae)=>{for(var ge in ae)i(Z,ge,{get:ae[ge],enumerable:!0})},m=(Z,ae,ge,De)=>{if(ae&&typeof ae=="object"||typeof ae=="function")for(let ye of a(ae))!u.call(Z,ye)&&ye!==ge&&i(Z,ye,{get:()=>ae[ye],enumerable:!(De=s(ae,ye))||De.enumerable});return Z},g=Z=>m(i({},"__esModule",{value:!0}),Z),b,C,k,E,_,S=d(()=>{b=new Map,C=[],k=(Z,ae,ge)=>{if(ae&&typeof ae.init=="function"&&typeof ae.createInferenceSessionHandler=="function"){let De=b.get(Z);if(De===void 0)b.set(Z,{backend:ae,priority:ge});else{if(De.priority>ge)return;if(De.priority===ge&&De.backend!==ae)throw new Error(`cannot register backend "${Z}" using priority ${ge}`)}if(ge>=0){let ye=C.indexOf(Z);ye!==-1&&C.splice(ye,1);for(let Be=0;Be<C.length;Be++)if(b.get(C[Be]).priority<=ge){C.splice(Be,0,Z);return}C.push(Z)}return}throw new TypeError("not a valid backend")},E=async Z=>{let ae=b.get(Z);if(!ae)return"backend not found.";if(ae.initialized)return ae.backend;if(ae.aborted)return ae.error;{let ge=!!ae.initPromise;try{return ge||(ae.initPromise=ae.backend.init(Z)),await ae.initPromise,ae.initialized=!0,ae.backend}catch(De){return ge||(ae.error=`${De}`,ae.aborted=!0),ae.error}finally{delete ae.initPromise}}},_=async Z=>{let ae=Z.executionProviders||[],ge=ae.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=ge.length===0?C:ge,ye,Be=[],Ne=new Set;for(let Fe of De){let nt=await E(Fe);typeof nt=="string"?Be.push({name:Fe,err:nt}):(ye||(ye=nt),ye===nt&&Ne.add(Fe))}if(!ye)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:nt}of Be)ge.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${nt}`);let Ae=ae.filter(Fe=>Ne.has(typeof Fe=="string"?Fe:Fe.name));return[ye,new Proxy(Z,{get:(Fe,nt)=>nt==="executionProviders"?Ae:Reflect.get(Fe,nt)})]}}),x=d(()=>{S()}),y,T=d(()=>{y="1.26.0"}),$,I,O=d(()=>{T(),$="warning",I={wasm:{},webgl:{},webgpu:{},versions:{common:y},set logLevel(Z){if(Z!==void 0){if(typeof Z!="string"||["verbose","info","warning","error","fatal"].indexOf(Z)===-1)throw new Error(`Unsupported logging level: ${Z}`);$=Z}},get logLevel(){return $}},Object.defineProperty(I,"logLevel",{enumerable:!0})}),A,L=d(()=>{O(),A=I}),V,te,re=d(()=>{V=(Z,ae)=>{let ge=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ge.width=Z.dims[3],ge.height=Z.dims[2];let De=ge.getContext("2d");if(De!=null){let ye,Be;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(ye=Z.dims[2],Be=Z.dims[3]):(ye=Z.dims[3],Be=Z.dims[2]);let Ne=(ae==null?void 0:ae.format)!==void 0?ae.format:"RGB",Ae=ae==null?void 0:ae.norm,Fe,nt;Ae===void 0||Ae.mean===void 0?Fe=[255,255,255,255]:typeof Ae.mean=="number"?Fe=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Fe=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Fe[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?nt=[0,0,0,0]:typeof Ae.bias=="number"?nt=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(nt=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(nt[3]=Ae.bias[3]));let dt=Be*ye,st=0,Ze=dt,Lt=dt*2,Le=-1;Ne==="RGBA"?(st=0,Ze=dt,Lt=dt*2,Le=dt*3):Ne==="RGB"?(st=0,Ze=dt,Lt=dt*2):Ne==="RBG"&&(st=0,Lt=dt,Ze=dt*2);for(let ft=0;ft<Be;ft++)for(let Qn=0;Qn<ye;Qn++){let ln=(Z.data[st++]-nt[0])*Fe[0],cn=(Z.data[Ze++]-nt[1])*Fe[1],ei=(Z.data[Lt++]-nt[2])*Fe[2],Wt=Le===-1?255:(Z.data[Le++]-nt[3])*Fe[3];De.fillStyle="rgba("+ln+","+cn+","+ei+","+Wt+")",De.fillRect(Qn,ft,1,1)}if("toDataURL"in ge)return ge.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},te=(Z,ae)=>{let ge=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(ge!=null){let ye,Be,Ne;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(ye=Z.dims[2],Be=Z.dims[1],Ne=Z.dims[3]):(ye=Z.dims[3],Be=Z.dims[2],Ne=Z.dims[1]);let Ae=ae!==void 0&&ae.format!==void 0?ae.format:"RGB",Fe=ae==null?void 0:ae.norm,nt,dt;Fe===void 0||Fe.mean===void 0?nt=[255,255,255,255]:typeof Fe.mean=="number"?nt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(nt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(nt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?dt=[0,0,0,0]:typeof Fe.bias=="number"?dt=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(dt=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(dt[3]=Fe.bias[3]));let st=Be*ye;if(ae!==void 0&&(ae.format!==void 0&&Ne===4&&ae.format!=="RGBA"||Ne===3&&ae.format!=="RGB"&&ae.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ze=4,Lt=0,Le=1,ft=2,Qn=3,ln=0,cn=st,ei=st*2,Wt=-1;Ae==="RGBA"?(ln=0,cn=st,ei=st*2,Wt=st*3):Ae==="RGB"?(ln=0,cn=st,ei=st*2):Ae==="RBG"&&(ln=0,ei=st,cn=st*2),De=ge.createImageData(ye,Be);for(let ai=0;ai<Be*ye;Lt+=Ze,Le+=Ze,ft+=Ze,Qn+=Ze,ai++)De.data[Lt]=(Z.data[ln++]-dt[0])*nt[0],De.data[Le]=(Z.data[cn++]-dt[1])*nt[1],De.data[ft]=(Z.data[ei++]-dt[2])*nt[2],De.data[Qn]=Wt===-1?255:(Z.data[Wt++]-dt[3])*nt[3]}else throw new Error("Can not access image data");return De}}),K,de,J,he,Ce,ve,F=d(()=>{$e(),K=(Z,ae)=>{if(Z===void 0)throw new Error("Image buffer must be defined");if(ae.height===void 0||ae.width===void 0)throw new Error("Image height and width must be defined");if(ae.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ge,width:De}=ae,ye=ae.norm??{mean:255,bias:0},Be,Ne;typeof ye.mean=="number"?Be=[ye.mean,ye.mean,ye.mean,ye.mean]:Be=[ye.mean[0],ye.mean[1],ye.mean[2],ye.mean[3]??255],typeof ye.bias=="number"?Ne=[ye.bias,ye.bias,ye.bias,ye.bias]:Ne=[ye.bias[0],ye.bias[1],ye.bias[2],ye.bias[3]??0];let Ae=ae.format!==void 0?ae.format:"RGBA",Fe=ae.tensorFormat!==void 0&&ae.tensorFormat!==void 0?ae.tensorFormat:"RGB",nt=ge*De,dt=Fe==="RGBA"?new Float32Array(nt*4):new Float32Array(nt*3),st=4,Ze=0,Lt=1,Le=2,ft=3,Qn=0,ln=nt,cn=nt*2,ei=-1;Ae==="RGB"&&(st=3,Ze=0,Lt=1,Le=2,ft=-1),Fe==="RGBA"?ei=nt*3:Fe==="RBG"?(Qn=0,cn=nt,ln=nt*2):Fe==="BGR"&&(cn=0,ln=nt,Qn=nt*2);for(let Wt=0;Wt<nt;Wt++,Ze+=st,Le+=st,Lt+=st,ft+=st)dt[Qn++]=(Z[Ze]+Ne[0])/Be[0],dt[ln++]=(Z[Lt]+Ne[1])/Be[1],dt[cn++]=(Z[Le]+Ne[2])/Be[2],ei!==-1&&ft!==-1&&(dt[ei++]=(Z[ft]+Ne[3])/Be[3]);return Fe==="RGBA"?new ee("float32",dt,[1,4,ge,De]):new ee("float32",dt,[1,3,ge,De])},de=async(Z,ae)=>{let ge=typeof HTMLImageElement<"u"&&Z instanceof HTMLImageElement,De=typeof ImageData<"u"&&Z instanceof ImageData,ye=typeof ImageBitmap<"u"&&Z instanceof ImageBitmap,Be=typeof Z=="string",Ne,Ae=ae??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},nt=dt=>typeof HTMLCanvasElement<"u"&&dt instanceof HTMLCanvasElement||dt instanceof OffscreenCanvas?dt.getContext("2d"):null;if(ge){let dt=Fe();dt.width=Z.width,dt.height=Z.height;let st=nt(dt);if(st!=null){let Ze=Z.height,Lt=Z.width;if(ae!==void 0&&ae.resizedHeight!==void 0&&ae.resizedWidth!==void 0&&(Ze=ae.resizedHeight,Lt=ae.resizedWidth),ae!==void 0){if(Ae=ae,ae.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=Ze,Ae.width=Lt}else Ae.tensorFormat="RGBA",Ae.height=Ze,Ae.width=Lt;st.drawImage(Z,0,0),Ne=st.getImageData(0,0,Lt,Ze).data}else throw new Error("Can not access image data")}else if(De){let dt,st;if(ae!==void 0&&ae.resizedWidth!==void 0&&ae.resizedHeight!==void 0?(dt=ae.resizedHeight,st=ae.resizedWidth):(dt=Z.height,st=Z.width),ae!==void 0&&(Ae=ae),Ae.format="RGBA",Ae.height=dt,Ae.width=st,ae!==void 0){let Ze=Fe();Ze.width=st,Ze.height=dt;let Lt=nt(Ze);if(Lt!=null)Lt.putImageData(Z,0,0),Ne=Lt.getImageData(0,0,st,dt).data;else throw new Error("Can not access image data")}else Ne=Z.data}else if(ye){if(ae===void 0)throw new Error("Please provide image config with format for Imagebitmap");let dt=Fe();dt.width=Z.width,dt.height=Z.height;let st=nt(dt);if(st!=null){let Ze=Z.height,Lt=Z.width;return st.drawImage(Z,0,0,Lt,Ze),Ne=st.getImageData(0,0,Lt,Ze).data,Ae.height=Ze,Ae.width=Lt,K(Ne,Ae)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((dt,st)=>{let Ze=Fe(),Lt=nt(Ze);if(!Z||!Lt)return st();let Le=new Image;Le.crossOrigin="Anonymous",Le.src=Z,Le.onload=()=>{Ze.width=Le.width,Ze.height=Le.height,Lt.drawImage(Le,0,0,Ze.width,Ze.height);let ft=Lt.getImageData(0,0,Ze.width,Ze.height);Ae.height=Ze.height,Ae.width=Ze.width,dt(K(ft.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ne!==void 0)return K(Ne,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},J=(Z,ae)=>{let{width:ge,height:De,download:ye,dispose:Be}=ae,Ne=[1,De,ge,4];return new ee({location:"texture",type:"float32",texture:Z,dims:Ne,download:ye,dispose:Be})},he=(Z,ae)=>{let{dataType:ge,dims:De,download:ye,dispose:Be}=ae;return new ee({location:"gpu-buffer",type:ge??"float32",gpuBuffer:Z,dims:De,download:ye,dispose:Be})},Ce=(Z,ae)=>{let{dataType:ge,dims:De,download:ye,dispose:Be}=ae;return new ee({location:"ml-tensor",type:ge??"float32",mlTensor:Z,dims:De,download:ye,dispose:Be})},ve=(Z,ae,ge)=>new ee({location:"cpu-pinned",type:Z,data:ae,dims:ge??[ae.length]})}),q,W,Q,le,fe=d(()=>{q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),W=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Q=!1,le=()=>{if(!Q){Q=!0;let Z=typeof BigInt64Array<"u"&&BigInt64Array.from,ae=typeof BigUint64Array<"u"&&BigUint64Array.from,ge=globalThis.Float16Array,De=typeof ge<"u"&&ge.from;Z&&(q.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),ae&&(q.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),De?(q.set("float16",ge),W.set(ge,"float16")):q.set("float16",Uint16Array)}}}),Ie,He,me=d(()=>{$e(),Ie=Z=>{let ae=1;for(let ge=0;ge<Z.length;ge++){let De=Z[ge];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${ge}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${ge}] must be a non-negative integer, got: ${De}`);ae*=De}return ae},He=(Z,ae)=>{switch(Z.location){case"cpu":return new ee(Z.type,Z.data,ae);case"cpu-pinned":return new ee({location:"cpu-pinned",data:Z.data,type:Z.type,dims:ae});case"texture":return new ee({location:"texture",texture:Z.texture,type:Z.type,dims:ae});case"gpu-buffer":return new ee({location:"gpu-buffer",gpuBuffer:Z.gpuBuffer,type:Z.type,dims:ae});case"ml-tensor":return new ee({location:"ml-tensor",mlTensor:Z.mlTensor,type:Z.type,dims:ae});default:throw new Error(`tensorReshape: tensor location ${Z.location} is not supported`)}}}),ee,$e=d(()=>{re(),F(),fe(),me(),ee=class{constructor(Z,ae,ge){le();let De,ye;if(typeof Z=="object"&&"location"in Z)switch(this.dataLocation=Z.location,De=Z.type,ye=Z.dims,Z.location){case"cpu-pinned":{let Ne=q.get(De);if(!Ne)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(Z.data instanceof Ne))throw new TypeError(`buffer should be of type ${Ne.name}`);this.cpuData=Z.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=Z.texture,this.downloader=Z.download,this.disposer=Z.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=Z.gpuBuffer,this.downloader=Z.download,this.disposer=Z.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=Z.mlTensor,this.downloader=Z.download,this.disposer=Z.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ne,Ae;if(typeof Z=="string")if(De=Z,Ae=ge,Z==="string"){if(!Array.isArray(ae))throw new TypeError("A string tensor's data must be a string array.");Ne=ae}else{let Fe=q.get(Z);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${Z}.`);if(Array.isArray(ae)){if(Z==="float16"&&Fe===Uint16Array||Z==="uint4"||Z==="int4")throw new TypeError(`Creating a ${Z} tensor from number array is not supported. Please use ${Fe.name} as data.`);Z==="uint64"||Z==="int64"?Ne=Fe.from(ae,BigInt):Ne=Fe.from(ae)}else if(ae instanceof Fe)Ne=ae;else if(ae instanceof Uint8ClampedArray)if(Z==="uint8")Ne=Uint8Array.from(ae);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Z==="float16"&&ae instanceof Uint16Array&&Fe!==Uint16Array)Ne=new globalThis.Float16Array(ae.buffer,ae.byteOffset,ae.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if(Ae=ae,Array.isArray(Z)){if(Z.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof Z[0];if(Fe==="string")De="string",Ne=Z;else if(Fe==="boolean")De="bool",Ne=Uint8Array.from(Z);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(Z instanceof Uint8ClampedArray)De="uint8",Ne=Uint8Array.from(Z);else{let Fe=W.get(Z.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${Z.constructor}.`);De=Fe,Ne=Z}if(Ae===void 0)Ae=[Ne.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");ye=Ae,this.cpuData=Ne,this.dataLocation="cpu"}let Be=Ie(ye);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=ye,this.size=Be}static async fromImage(Z,ae){return de(Z,ae)}static fromTexture(Z,ae){return J(Z,ae)}static fromGpuBuffer(Z,ae){return he(Z,ae)}static fromMLTensor(Z,ae){return Ce(Z,ae)}static fromPinnedBuffer(Z,ae,ge){return ve(Z,ae,ge)}toDataURL(Z){return V(this,Z)}toImageData(Z){return te(this,Z)}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(Z){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 ae=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=ae,Z&&this.disposer&&(this.disposer(),this.disposer=void 0),ae}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(Z){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return He(this,Z)}}}),Ee,Te=d(()=>{$e(),Ee=ee}),be,Qe,vt,lt,$t,We,Ht=d(()=>{O(),be=(Z,ae)=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeStamp(`${Z}::ORT::${ae}`)},Qe=(Z,ae)=>{var ye;let ge=((ye=new Error().stack)==null?void 0:ye.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<ge.length;Be++){if(De&&!ge[Be].includes("TRACE_FUNC")){let Ne=`FUNC_${Z}::${ge[Be].trim().split(" ")[1]}`;ae&&(Ne+=`::${ae}`),be("CPU",Ne);return}ge[Be].includes("TRACE_FUNC")&&(De=!0)}},vt=Z=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("BEGIN",Z)},lt=Z=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||Qe("END",Z)},$t=Z=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.time(`ORT::${Z}`)},We=Z=>{(typeof I.trace>"u"?!I.wasm.trace:!I.trace)||console.timeEnd(`ORT::${Z}`)}}),Ct,sn=d(()=>{S(),Te(),Ht(),Ct=class D2{constructor(ae){this.handler=ae}async run(ae,ge,De){vt(),$t("InferenceSession.run");let ye={},Be={};if(typeof ae!="object"||ae===null||ae instanceof Ee||Array.isArray(ae))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ne=!0;if(typeof ge=="object"){if(ge===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ge instanceof Ee)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ge)){if(ge.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ne=!1;for(let nt of ge){if(typeof nt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(nt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${nt}.`);ye[nt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let nt=!1,dt=Object.getOwnPropertyNames(ge);for(let st of this.outputNames)if(dt.indexOf(st)!==-1){let Ze=ge[st];(Ze===null||Ze instanceof Ee)&&(nt=!0,Ne=!1,ye[st]=Ze)}if(nt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=ge}}else if(typeof ge<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let nt of this.inputNames)if(typeof ae[nt]>"u")throw new Error(`input '${nt}' is missing in 'feeds'.`);if(Ne)for(let nt of this.outputNames)ye[nt]=null;let Ae=await this.handler.run(ae,ye,Be),Fe={};for(let nt in Ae)if(Object.hasOwnProperty.call(Ae,nt)){let dt=Ae[nt];dt instanceof Ee?Fe[nt]=dt:Fe[nt]=new Ee(dt.type,dt.data,dt.dims)}return We("InferenceSession.run"),lt(),Fe}async release(){return this.handler.dispose()}static async create(ae,ge,De,ye){vt(),$t("InferenceSession.create");let Be,Ne={};if(typeof ae=="string"){if(Be=ae,typeof ge=="object"&&ge!==null)Ne=ge;else if(typeof ge<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof Uint8Array){if(Be=ae,typeof ge=="object"&&ge!==null)Ne=ge;else if(typeof ge<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&ae instanceof SharedArrayBuffer){let dt=ae,st=0,Ze=ae.byteLength;if(typeof ge=="object"&&ge!==null)Ne=ge;else if(typeof ge=="number"){if(st=ge,!Number.isSafeInteger(st))throw new RangeError("'byteOffset' must be an integer.");if(st<0||st>=dt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${dt.byteLength}).`);if(Ze=ae.byteLength-st,typeof De=="number"){if(Ze=De,!Number.isSafeInteger(Ze))throw new RangeError("'byteLength' must be an integer.");if(Ze<=0||st+Ze>dt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${dt.byteLength-st}].`);if(typeof ye=="object"&&ye!==null)Ne=ye;else if(typeof ye<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ge<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(dt,st,Ze)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Fe]=await _(Ne),nt=await Ae.createInferenceSessionHandler(Be,Fe);return We("InferenceSession.create"),lt(),new D2(nt)}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}}}),un,Ue=d(()=>{sn(),un=Ct}),xt=d(()=>{}),yt=d(()=>{}),Qt=d(()=>{}),Cn=d(()=>{}),Xn={};h(Xn,{InferenceSession:()=>un,TRACE:()=>be,TRACE_EVENT_BEGIN:()=>$t,TRACE_EVENT_END:()=>We,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>lt,Tensor:()=>Ee,env:()=>A,registerBackend:()=>k});var mn=d(()=>{x(),L(),Ue(),Te(),xt(),yt(),Ht(),Qt(),Cn()}),Rn=d(()=>{}),xn={};h(xn,{default:()=>ti});var Fn,ot,ti,hs=d(()=>{var Z;xe(),ui(),Gn(),Fn="ort-wasm-proxy-worker",ot=((Z=globalThis.self)==null?void 0:Z.name)===Fn,ot&&(self.onmessage=ae=>{let{type:ge,in:De}=ae.data;try{switch(ge){case"init-wasm":vi(De.wasm).then(()=>{Xo(De).then(()=>{postMessage({type:ge})},ye=>{postMessage({type:ge,err:ye})})},ye=>{postMessage({type:ge,err:ye})});break;case"init-ep":{let{epName:ye,env:Be}=De;Mr(Be,ye).then(()=>{postMessage({type:ge})},Ne=>{postMessage({type:ge,err:Ne})});break}case"copy-from":{let{buffer:ye}=De,Be=vn(ye);postMessage({type:ge,out:Be});break}case"create":{let{model:ye,options:Be}=De;Rs(ye,Be).then(Ne=>{postMessage({type:ge,out:Ne})},Ne=>{postMessage({type:ge,err:Ne})});break}case"release":eo(De),postMessage({type:ge});break;case"run":{let{sessionId:ye,inputIndices:Be,inputs:Ne,outputIndices:Ae,options:Fe}=De;Je(ye,Be,Ne,Ae,new Array(Ae.length).fill(null),Fe).then(nt=>{nt.some(dt=>dt[3]!=="cpu")?postMessage({type:ge,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ge,out:nt},_t([...Ne,...nt]))},nt=>{postMessage({type:ge,err:nt})});break}case"end-profiling":bs(De),postMessage({type:ge});break;default:}}catch(ye){postMessage({type:ge,err:ye})}}),ti=ot?null:ae=>new Worker(ae??Sn,{type:"classic",name:Fn})}),Mi,Oi,Sn,gi,In,rs,Dn,yi,it,mt,Pt,At,Mn,Gn=d(()=>{Rn(),Mi=typeof location>"u"?void 0:location.origin,Oi=()=>{var Z,ae;return typeof document<"u"?(Z=document.currentScript)==null?void 0:Z.src:typeof self<"u"?(ae=self.location)==null?void 0:ae.href:void 0},Sn=Oi(),gi=()=>{if(Sn&&!Sn.startsWith("blob:"))return Sn.substring(0,Sn.lastIndexOf("/")+1)},In=(Z,ae)=>{try{let ge=ae??Sn;return(ge?new URL(Z,ge):new URL(Z)).origin===Mi}catch{return!1}},rs=(Z,ae)=>{let ge=ae??Sn;try{return(ge?new URL(Z,ge):new URL(Z)).href}catch{return}},Dn=(Z,ae)=>`${ae??"./"}${Z}`,yi=async Z=>{let ae=await(await fetch(Z,{credentials:"same-origin"})).blob();return URL.createObjectURL(ae)},it=async Z=>(await import(Z)).default,mt=(hs(),g(xn)).default,Pt=async()=>{if(!Sn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(In(Sn))return[void 0,mt()];let Z=await yi(Sn);return[Z,mt(Z)]},At=void 0,Mn=async(Z,ae,ge,De)=>{let ye=At&&!(Z||ae);if(ye)if(Sn)ye=In(Sn)||De&&!ge;else if(De&&!ge)ye=!0;else throw new Error("cannot determine the script source URL.");if(ye)return[void 0,At];{let Be="ort-wasm-simd-threaded.mjs",Ne=Z??rs(Be,ae),Ae=ge&&Ne&&!In(Ne,ae),Fe=Ae?await yi(Ne):Ne??Dn(Be,ae);return[Ae?Fe:void 0,await it(Fe)]}}}),Hn,rt,fn,Jn,Zn,hn,On,vi,Et,ui=d(()=>{Gn(),rt=!1,fn=!1,Jn=!1,Zn=()=>{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}},hn=()=>{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}},On=()=>{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}},vi=async Z=>{if(rt)return Promise.resolve();if(fn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Jn)throw new Error("previous call to 'initializeWebAssembly()' failed.");fn=!0;let ae=Z.initTimeout,ge=Z.numThreads;if(Z.simd!==!1){if(Z.simd==="relaxed"){if(!On())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!hn())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=Zn();ge>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ge+", 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."),Z.numThreads=ge=1);let ye=Z.wasmPaths,Be=typeof ye=="string"?ye:void 0,Ne=ye==null?void 0:ye.mjs,Ae=(Ne==null?void 0:Ne.href)??Ne,Fe=ye==null?void 0:ye.wasm,nt=(Fe==null?void 0:Fe.href)??Fe,dt=Z.wasmBinary,[st,Ze]=await Mn(Ae,Be,ge>1,!!dt||!!nt),Lt=!1,Le=[];if(ae>0&&Le.push(new Promise(ft=>{setTimeout(()=>{Lt=!0,ft()},ae)})),Le.push(new Promise((ft,Qn)=>{let ln={numThreads:ge};if(dt)ln.wasmBinary=dt,ln.locateFile=cn=>cn;else if(nt||Be)ln.locateFile=cn=>nt??Be+cn;else if(Ae&&Ae.indexOf("blob:")!==0)ln.locateFile=cn=>new URL(cn,Ae).href;else if(st){let cn=gi();cn&&(ln.locateFile=ei=>cn+ei)}Ze(ln).then(cn=>{fn=!1,rt=!0,Hn=cn,ft(),st&&URL.revokeObjectURL(st)},cn=>{fn=!1,Jn=!0,Qn(cn)})})),await Promise.race(Le),Lt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${ae}ms`)},Et=()=>{if(rt&&Hn)return Hn;throw new Error("WebAssembly is not initialized yet.")}}),Yn,jn,Nt,sr=d(()=>{ui(),Yn=(Z,ae)=>{let ge=Et(),De=ge.lengthBytesUTF8(Z)+1,ye=ge._malloc(De);return ge.stringToUTF8(Z,ye,De),ae.push(ye),ye},jn=(Z,ae,ge,De)=>{if(typeof Z=="object"&&Z!==null){if(ge.has(Z))throw new Error("Circular reference in options");ge.add(Z)}Object.entries(Z).forEach(([ye,Be])=>{let Ne=ae?ae+ye:ye;if(typeof Be=="object")jn(Be,Ne+".",ge,De);else if(typeof Be=="string"||typeof Be=="number")De(Ne,Be.toString());else if(typeof Be=="boolean")De(Ne,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Nt=Z=>{let ae=Et(),ge=ae.stackSave();try{let De=ae.PTR_SIZE,ye=ae.stackAlloc(2*De);ae._OrtGetLastError(ye,ye+De);let Be=Number(ae.getValue(ye,De===4?"i32":"i64")),Ne=ae.getValue(ye+De,"*"),Ae=Ne?ae.UTF8ToString(Ne):"";throw new Error(`${Z} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Ae}`)}finally{ae.stackRestore(ge)}}}),br,Jr=d(()=>{ui(),sr(),br=Z=>{let ae=Et(),ge=0,De=[],ye=Z||{};try{if((Z==null?void 0:Z.logSeverityLevel)===void 0)ye.logSeverityLevel=2;else if(typeof Z.logSeverityLevel!="number"||!Number.isInteger(Z.logSeverityLevel)||Z.logSeverityLevel<0||Z.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Z.logSeverityLevel}`);if((Z==null?void 0:Z.logVerbosityLevel)===void 0)ye.logVerbosityLevel=0;else if(typeof Z.logVerbosityLevel!="number"||!Number.isInteger(Z.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Z.logVerbosityLevel}`);(Z==null?void 0:Z.terminate)===void 0&&(ye.terminate=!1);let Be=0;return(Z==null?void 0:Z.tag)!==void 0&&(Be=Yn(Z.tag,De)),ge=ae._OrtCreateRunOptions(ye.logSeverityLevel,ye.logVerbosityLevel,!!ye.terminate,Be),ge===0&&Nt("Can't create run options."),(Z==null?void 0:Z.extra)!==void 0&&jn(Z.extra,"",new WeakSet,(Ne,Ae)=>{let Fe=Yn(Ne,De),nt=Yn(Ae,De);ae._OrtAddRunConfigEntry(ge,Fe,nt)!==0&&Nt(`Can't set a run config entry: ${Ne} - ${Ae}.`)}),[ge,De]}catch(Be){throw ge!==0&&ae._OrtReleaseRunOptions(ge),De.forEach(Ne=>ae._free(Ne)),Be}}}),Is,_r,rr,Li,Zr,Qr,Pn=d(()=>{ui(),sr(),Is=Z=>{switch(Z){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: ${Z}`)}},_r=Z=>{switch(Z){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Z}`)}},rr=Z=>{Z.extra||(Z.extra={}),Z.extra.session||(Z.extra.session={});let ae=Z.extra.session;ae.use_ort_model_bytes_directly||(ae.use_ort_model_bytes_directly="1"),Z.executionProviders&&Z.executionProviders.some(ge=>(typeof ge=="string"?ge:ge.name)==="webgpu")&&(Z.enableMemPattern=!1)},Li=(Z,ae,ge,De)=>{let ye=Yn(ae,De),Be=Yn(ge,De);Et()._OrtAddSessionConfigEntry(Z,ye,Be)!==0&&Nt(`Can't set a session config entry: ${ae} - ${ge}.`)},Zr=async(Z,ae,ge)=>{let De=ae.executionProviders;for(let ye of De){let Be=typeof ye=="string"?ye:ye.name,Ne=[];switch(Be){case"webnn":if(Be="WEBNN",Li(Z,"session.disable_quant_qdq","1",ge),Li(Z,"session.disable_qdq_constant_folding","1",ge),typeof ye!="string"){let st=ye==null?void 0:ye.deviceType;st&&Li(Z,"deviceType",st,ge)}break;case"webgpu":if(Be="JS",typeof ye!="string"){let st=ye;if(st!=null&&st.preferredLayout){if(st.preferredLayout!=="NCHW"&&st.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${st.preferredLayout}`);Li(Z,"preferredLayout",st.preferredLayout,ge)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Ae=Yn(Be,ge),Fe=Ne.length,nt=0,dt=0;if(Fe>0){nt=Et()._malloc(Fe*Et().PTR_SIZE),ge.push(nt),dt=Et()._malloc(Fe*Et().PTR_SIZE),ge.push(dt);for(let st=0;st<Fe;st++)Et().setValue(nt+st*Et().PTR_SIZE,Ne[st][0],"*"),Et().setValue(dt+st*Et().PTR_SIZE,Ne[st][1],"*")}await Et()._OrtAppendExecutionProvider(Z,Ae,nt,dt,Fe)!==0&&Nt(`Can't append execution provider: ${Be}.`)}},Qr=async Z=>{let ae=Et(),ge=0,De=[],ye=Z||{};rr(ye);try{let Be=Is(ye.graphOptimizationLevel??"all"),Ne=_r(ye.executionMode??"sequential"),Ae=typeof ye.logId=="string"?Yn(ye.logId,De):0,Fe=ye.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let nt=ye.logVerbosityLevel??0;if(!Number.isInteger(nt)||nt<0||nt>4)throw new Error(`log verbosity level is not valid: ${nt}`);let dt=typeof ye.optimizedModelFilePath=="string"?Yn(ye.optimizedModelFilePath,De):0;if(ge=ae._OrtCreateSessionOptions(Be,!!ye.enableCpuMemArena,!!ye.enableMemPattern,Ne,!!ye.enableProfiling,0,Ae,Fe,nt,dt),ge===0&&Nt("Can't create session options."),ye.executionProviders&&await Zr(ge,ye,De),ye.enableGraphCapture!==void 0){if(typeof ye.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ye.enableGraphCapture}`);Li(ge,"enableGraphCapture",ye.enableGraphCapture.toString(),De)}if(ye.freeDimensionOverrides)for(let[st,Ze]of Object.entries(ye.freeDimensionOverrides)){if(typeof st!="string")throw new Error(`free dimension override name must be a string: ${st}`);if(typeof Ze!="number"||!Number.isInteger(Ze)||Ze<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ze}`);let Lt=Yn(st,De);ae._OrtAddFreeDimensionOverride(ge,Lt,Ze)!==0&&Nt(`Can't set a free dimension override: ${st} - ${Ze}.`)}return ye.extra!==void 0&&jn(ye.extra,"",new WeakSet,(st,Ze)=>{Li(ge,st,Ze,De)}),[ge,De]}catch(Be){throw ge!==0&&ae._OrtReleaseSessionOptions(ge)!==0&&Nt("Can't release session options."),De.forEach(Ne=>ae._free(Ne)),Be}}}),Me,ct,en,yn,xi,Tn,bi,Ti,qt=d(()=>{Me=Z=>{switch(Z){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: ${Z}`)}},ct=Z=>{switch(Z){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: ${Z}`)}},en=(Z,ae)=>{let ge=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Z],De=typeof ae=="number"?ae:ae.reduce((ye,Be)=>ye*Be,1);return ge>0?Math.ceil(De*ge):void 0},yn=Z=>{switch(Z){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: ${Z}`)}},xi=Z=>{switch(Z){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: ${Z}`)}},Tn=Z=>Z==="float32"||Z==="float16"||Z==="int32"||Z==="int64"||Z==="uint32"||Z==="uint8"||Z==="bool"||Z==="uint4"||Z==="int4",bi=Z=>Z==="float32"||Z==="float16"||Z==="int32"||Z==="int64"||Z==="uint32"||Z==="uint64"||Z==="int8"||Z==="uint8"||Z==="bool"||Z==="uint4"||Z==="int4",Ti=Z=>{switch(Z){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: ${Z}`)}}}),Si,Rr=d(()=>{Rn(),Si=async Z=>{if(typeof Z=="string"){let ae=await fetch(Z);if(!ae.ok)throw new Error(`failed to load external data file: ${Z}`);let ge=ae.headers.get("Content-Length"),De=ge?parseInt(ge,10):0;if(De<1073741824)return new Uint8Array(await ae.arrayBuffer());{if(!ae.body)throw new Error(`failed to load external data file: ${Z}, no response body.`);let ye=ae.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch(Ae){if(Ae instanceof RangeError){let Fe=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Ae}let Ne=0;for(;;){let{done:Ae,value:Fe}=await ye.read();if(Ae)break;let nt=Fe.byteLength;new Uint8Array(Be,Ne,nt).set(Fe),Ne+=nt}return new Uint8Array(Be,0,De)}}else return Z instanceof Blob?new Uint8Array(await Z.arrayBuffer()):Z instanceof Uint8Array?Z:new Uint8Array(Z)}}),Ps,Xo,Mr,xs,or,Or,vn,Rs,eo,Js,Je,bs,_t,xe=d(()=>{mn(),Jr(),Pn(),qt(),ui(),sr(),Rr(),Ps=(Z,ae)=>{Et()._OrtInit(Z,ae)!==0&&Nt("Can't initialize onnxruntime.")},Xo=async Z=>{Ps(Z.wasm.numThreads,xi(Z.logLevel))},Mr=async(Z,ae)=>{var De,ye;(ye=(De=Et()).asyncInit)==null||ye.call(De);let ge=Z.webgpu.adapter;if(ae==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ge){if(typeof ge.limits!="object"||typeof ge.features!="object"||typeof ge.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=Z.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Ne=Z.webgpu.forceFallbackAdapter;if(Ne!==void 0&&typeof Ne!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ne}"`);if(ge=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Ne}),!ge)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(ae==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},xs=new Map,or=Z=>{let ae=Et(),ge=ae.stackSave();try{let De=ae.PTR_SIZE,ye=ae.stackAlloc(2*De);ae._OrtGetInputOutputCount(Z,ye,ye+De)!==0&&Nt("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(ae.getValue(ye,Be)),Number(ae.getValue(ye+De,Be))]}finally{ae.stackRestore(ge)}},Or=(Z,ae)=>{let ge=Et(),De=ge.stackSave(),ye=0;try{let Be=ge.PTR_SIZE,Ne=ge.stackAlloc(2*Be);ge._OrtGetInputOutputMetadata(Z,ae,Ne,Ne+Be)!==0&&Nt("Can't get session input/output metadata.");let Ae=Number(ge.getValue(Ne,"*"));ye=Number(ge.getValue(Ne+Be,"*"));let Fe=ge.HEAP32[ye/4];if(Fe===0)return[Ae,0];let nt=ge.HEAPU32[ye/4+1],dt=[];for(let st=0;st<nt;st++){let Ze=Number(ge.getValue(ye+8+st*Be,"*"));dt.push(Ze!==0?ge.UTF8ToString(Ze):Number(ge.getValue(ye+8+(st+nt)*Be,"*")))}return[Ae,Fe,dt]}finally{ge.stackRestore(De),ye!==0&&ge._OrtFree(ye)}},vn=Z=>{let ae=Et(),ge=ae._malloc(Z.byteLength);if(ge===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Z.byteLength}.`);return ae.HEAPU8.set(Z,ge),[ge,Z.byteLength]},Rs=async(Z,ae)=>{var dt,st,Ze;let ge,De,ye=Et();Array.isArray(Z)?[ge,De]=Z:Z.buffer===ye.HEAPU8.buffer?[ge,De]=[Z.byteOffset,Z.byteLength]:[ge,De]=vn(Z);let Be=0,Ne=0,Ae=[],Fe=[],nt=[];try{if([Ne,Ae]=await Qr(ae),(ae==null?void 0:ae.externalData)&&ye.mountExternalData){let ai=[];for(let kn of ae.externalData){let Ji=typeof kn=="string"?kn:kn.path;ai.push(Si(typeof kn=="string"?kn:kn.data).then(ps=>{ye.mountExternalData(Ji,ps)}))}await Promise.all(ai)}for(let ai of(ae==null?void 0:ae.executionProviders)??[])if((typeof ai=="string"?ai:ai.name)==="webnn"){if(ye.shouldTransferToMLTensor=!1,typeof ai!="string"){let kn=ai,Ji=kn==null?void 0:kn.context,ps=kn==null?void 0:kn.gpuDevice,_s=kn==null?void 0:kn.deviceType,Ia=kn==null?void 0:kn.powerPreference;Ji?ye.currentContext=Ji:ps?ye.currentContext=await ye.webnnCreateMLContext(ps):ye.currentContext=await ye.webnnCreateMLContext({deviceType:_s,powerPreference:Ia})}else ye.currentContext=await ye.webnnCreateMLContext();break}Be=await ye._OrtCreateSession(ge,De,Ne),(dt=ye.webgpuOnCreateSession)==null||dt.call(ye,Be),Be===0&&Nt("Can't create a session."),(st=ye.jsepOnCreateSession)==null||st.call(ye),ye.currentContext&&(ye.webnnRegisterMLContext(Be,ye.currentContext),ye.currentContext=void 0,ye.shouldTransferToMLTensor=!0);let[Lt,Le]=or(Be),ft=!!(ae!=null&&ae.enableGraphCapture),Qn=[],ln=[],cn=[],ei=[],Wt=[];for(let ai=0;ai<Lt;ai++){let[kn,Ji,ps]=Or(Be,ai);kn===0&&Nt("Can't get an input name."),Fe.push(kn);let _s=ye.UTF8ToString(kn);Qn.push(_s),cn.push(Ji===0?{name:_s,isTensor:!1}:{name:_s,isTensor:!0,type:ct(Ji),shape:ps})}for(let ai=0;ai<Le;ai++){let[kn,Ji,ps]=Or(Be,ai+Lt);kn===0&&Nt("Can't get an output name."),nt.push(kn);let _s=ye.UTF8ToString(kn);ln.push(_s),ei.push(Ji===0?{name:_s,isTensor:!1}:{name:_s,isTensor:!0,type:ct(Ji),shape:ps})}return xs.set(Be,[Be,Fe,nt,null,ft,!1]),[Be,Qn,ln,cn,ei]}catch(Lt){throw Fe.forEach(Le=>ye._OrtFree(Le)),nt.forEach(Le=>ye._OrtFree(Le)),Be!==0&&ye._OrtReleaseSession(Be)!==0&&Nt("Can't release session."),Lt}finally{ye._free(ge),Ne!==0&&ye._OrtReleaseSessionOptions(Ne)!==0&&Nt("Can't release session options."),Ae.forEach(Lt=>ye._free(Lt)),(Ze=ye.unmountExternalData)==null||Ze.call(ye)}},eo=Z=>{var Fe,nt,dt;let ae=Et(),ge=xs.get(Z);if(!ge)throw new Error(`cannot release session. invalid session id: ${Z}`);let[De,ye,Be,Ne,Ae]=ge;Ne&&(Ae&&ae._OrtClearBoundOutputs(Ne.handle)!==0&&Nt("Can't clear bound outputs."),ae._OrtReleaseBinding(Ne.handle)!==0&&Nt("Can't release IO binding.")),(Fe=ae.jsepOnReleaseSession)==null||Fe.call(ae,Z),(nt=ae.webnnOnReleaseSession)==null||nt.call(ae,Z),(dt=ae.webgpuOnReleaseSession)==null||dt.call(ae,Z),ye.forEach(st=>ae._OrtFree(st)),Be.forEach(st=>ae._OrtFree(st)),ae._OrtReleaseSession(De)!==0&&Nt("Can't release session."),xs.delete(Z)},Js=async(Z,ae,ge,De,ye,Be,Ne=!1)=>{if(!Z){ae.push(0);return}let Ae=Et(),Fe=Ae.PTR_SIZE,nt=Z[0],dt=Z[1],st=Z[3],Ze=st,Lt,Le;if(nt==="string"&&(st==="gpu-buffer"||st==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ne&&st!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(st==="gpu-buffer"){let ln=Z[2].gpuBuffer;Le=en(Me(nt),dt);{let cn=Ae.jsepRegisterBuffer;if(!cn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Lt=cn(De,Be,ln,Le)}}else if(st==="ml-tensor"){let ln=Z[2].mlTensor;Le=en(Me(nt),dt);let cn=Ae.webnnRegisterMLTensor;if(!cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Lt=cn(De,ln,Me(nt),dt)}else{let ln=Z[2];if(Array.isArray(ln)){Le=Fe*ln.length,Lt=Ae._malloc(Le),ge.push(Lt);for(let cn=0;cn<ln.length;cn++){if(typeof ln[cn]!="string")throw new TypeError(`tensor data at index ${cn} is not a string`);Ae.setValue(Lt+cn*Fe,Yn(ln[cn],ge),"*")}}else{let cn=Ae.webnnIsGraphInput,ei=Ae.webnnIsGraphOutput;if(nt!=="string"&&cn&&ei){let Wt=Ae.UTF8ToString(ye);if(cn(De,Wt)||ei(De,Wt)){let ai=Me(nt);Le=en(ai,dt),Ze="ml-tensor";let kn=Ae.webnnCreateTemporaryTensor,Ji=Ae.webnnUploadTensor;if(!kn||!Ji)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let ps=await kn(De,ai,dt);Ji(ps,new Uint8Array(ln.buffer,ln.byteOffset,ln.byteLength)),Lt=ps}else Le=ln.byteLength,Lt=Ae._malloc(Le),ge.push(Lt),Ae.HEAPU8.set(new Uint8Array(ln.buffer,ln.byteOffset,Le),Lt)}else Le=ln.byteLength,Lt=Ae._malloc(Le),ge.push(Lt),Ae.HEAPU8.set(new Uint8Array(ln.buffer,ln.byteOffset,Le),Lt)}}let ft=Ae.stackSave(),Qn=Ae.stackAlloc(4*dt.length);try{dt.forEach((cn,ei)=>Ae.setValue(Qn+ei*Fe,cn,Fe===4?"i32":"i64"));let ln=Ae._OrtCreateTensor(Me(nt),Lt,Le,Qn,dt.length,Ti(Ze));ln===0&&Nt(`Can't create tensor for input/output. session=${De}, index=${Be}.`),ae.push(ln)}finally{Ae.stackRestore(ft)}},Je=async(Z,ae,ge,De,ye,Be)=>{var ws,xl,wc;let Ne=Et(),Ae=Ne.PTR_SIZE,Fe=xs.get(Z);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${Z}`);let nt=Fe[0],dt=Fe[1],st=Fe[2],Ze=Fe[3],Lt=Fe[4];Fe[5];let Le=ae.length,ft=De.length,Qn=0,ln=[],cn=[],ei=[],Wt=[],ai=[],kn=Ne.stackSave(),Ji=Ne.stackAlloc(Le*Ae),ps=Ne.stackAlloc(Le*Ae),_s=Ne.stackAlloc(ft*Ae),Ia=Ne.stackAlloc(ft*Ae);try{[Qn,ln]=br(Be),$t("wasm prepareInputOutputTensor");for(let _n=0;_n<Le;_n++)await Js(ge[_n],cn,Wt,Z,dt[ae[_n]],ae[_n],Lt);for(let _n=0;_n<ft;_n++)await Js(ye[_n],ei,Wt,Z,st[De[_n]],Le+De[_n],Lt);We("wasm prepareInputOutputTensor");for(let _n=0;_n<Le;_n++)Ne.setValue(Ji+_n*Ae,cn[_n],"*"),Ne.setValue(ps+_n*Ae,dt[ae[_n]],"*");for(let _n=0;_n<ft;_n++)Ne.setValue(_s+_n*Ae,ei[_n],"*"),Ne.setValue(Ia+_n*Ae,st[De[_n]],"*");(ws=Ne.jsepOnRunStart)==null||ws.call(Ne,nt),(xl=Ne.webnnOnRunStart)==null||xl.call(Ne,nt);let Zi;Zi=await Ne._OrtRun(nt,ps,Ji,Le,Ia,ft,_s,Qn),Zi!==0&&Nt("failed to call OrtRun().");let yr=[],yc=[];$t("wasm ProcessOutputTensor");for(let _n=0;_n<ft;_n++){let lr=Number(Ne.getValue(_s+_n*Ae,"*"));if(lr===ei[_n]||ai.includes(ei[_n])){yr.push(ye[_n]),lr!==ei[_n]&&Ne._OrtReleaseTensor(lr)!==0&&Nt("Can't release tensor.");continue}let Ld=Ne.stackSave(),Br=Ne.stackAlloc(4*Ae),Jo=!1,Bi,ys=0;try{Ne._OrtGetTensorData(lr,Br,Br+Ae,Br+2*Ae,Br+3*Ae)!==0&&Nt(`Can't access output tensor data on index ${_n}.`);let bl=Ae===4?"i32":"i64",Ss=Number(Ne.getValue(Br,bl));ys=Ne.getValue(Br+Ae,"*");let Sc=Ne.getValue(Br+Ae*2,"*"),zd=Number(Ne.getValue(Br+Ae*3,bl)),Fr=[];for(let Fi=0;Fi<zd;Fi++)Fr.push(Number(Ne.getValue(Sc+Fi*Ae,bl)));Ne._OrtFree(Sc)!==0&&Nt("Can't free memory for tensor dims.");let cr=Fr.reduce((Fi,_i)=>Fi*_i,1);Bi=ct(Ss);let Sr=Ze==null?void 0:Ze.outputPreferredLocations[De[_n]];if(Bi==="string"){if(Sr==="gpu-buffer"||Sr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Fi=[];for(let _i=0;_i<cr;_i++){let dr=Ne.getValue(ys+_i*Ae,"*"),Cc=Ne.getValue(ys+(_i+1)*Ae,"*"),kc=_i===cr-1?void 0:Cc-dr;Fi.push(Ne.UTF8ToString(dr,kc))}yr.push([Bi,Fr,Fi,"cpu"])}else if(Sr==="gpu-buffer"&&cr>0){let Fi=Ne.jsepGetBuffer;if(!Fi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let _i=Fi(ys),dr=en(Ss,cr);if(dr===void 0||!Tn(Bi))throw new Error(`Unsupported data type: ${Bi}`);Jo=!0,yr.push([Bi,Fr,{gpuBuffer:_i,download:Ne.jsepCreateDownloader(_i,dr,Bi),dispose:()=>{Ne._OrtReleaseTensor(lr)!==0&&Nt("Can't release tensor.")}},"gpu-buffer"])}else if(Sr==="ml-tensor"&&cr>0){let Fi=Ne.webnnEnsureTensor,_i=Ne.webnnIsGraphInputOutputTypeSupported;if(!Fi||!_i)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(en(Ss,cr)===void 0||!bi(Bi))throw new Error(`Unsupported data type: ${Bi}`);if(!_i(Z,Bi,!1))throw new Error(`preferredLocation "ml-tensor" for ${Bi} output is not supported by current WebNN Context.`);let dr=await Fi(Z,ys,Ss,Fr,!1);Jo=!0,yr.push([Bi,Fr,{mlTensor:dr,download:Ne.webnnCreateMLTensorDownloader(ys,Bi),dispose:()=>{Ne.webnnReleaseTensorId(ys),Ne._OrtReleaseTensor(lr)}},"ml-tensor"])}else if(Sr==="ml-tensor-cpu-output"&&cr>0){let Fi=Ne.webnnCreateMLTensorDownloader(ys,Bi)(),_i=yr.length;Jo=!0,yc.push((async()=>{let dr=[_i,await Fi];return Ne.webnnReleaseTensorId(ys),Ne._OrtReleaseTensor(lr),dr})()),yr.push([Bi,Fr,[],"cpu"])}else{let Fi=yn(Bi),_i=new Fi(cr);new Uint8Array(_i.buffer,_i.byteOffset,_i.byteLength).set(Ne.HEAPU8.subarray(ys,ys+_i.byteLength)),yr.push([Bi,Fr,_i,"cpu"])}}finally{Ne.stackRestore(Ld),Bi==="string"&&ys&&Ne._free(ys),Jo||Ne._OrtReleaseTensor(lr)}}Ze&&!Lt&&(Ne._OrtClearBoundOutputs(Ze.handle)!==0&&Nt("Can't clear bound outputs."),xs.set(Z,[nt,dt,st,Ze,Lt,!1]));for(let[_n,lr]of await Promise.all(yc))yr[_n][2]=lr;return We("wasm ProcessOutputTensor"),yr}finally{(wc=Ne.webnnOnRunEnd)==null||wc.call(Ne,nt),Ne.stackRestore(kn),cn.forEach(Zi=>Ne._OrtReleaseTensor(Zi)),ei.forEach(Zi=>Ne._OrtReleaseTensor(Zi)),Wt.forEach(Zi=>Ne._free(Zi)),Qn!==0&&Ne._OrtReleaseRunOptions(Qn),ln.forEach(Zi=>Ne._free(Zi))}},bs=Z=>{let ae=Et(),ge=xs.get(Z);if(!ge)throw new Error("invalid session id");let De=ge[0],ye=ae._OrtEndProfiling(De);ye===0&&Nt("Can't get an profile file name."),ae._OrtFree(ye)},_t=Z=>{let ae=[];for(let ge of Z){let De=ge[2];!Array.isArray(De)&&"buffer"in De&&ae.push(De.buffer)}return ae}}),Re,et,Rt,pn,bn,ri,ni,Pi,hi,zi,ii,ar,to,bo,wr,Od,_o,wo,xc=d(()=>{mn(),xe(),ui(),Gn(),Re=()=>!!A.wasm.proxy&&typeof document<"u",Rt=!1,pn=!1,bn=!1,Pi=new Map,hi=(Z,ae)=>{let ge=Pi.get(Z);ge?ge.push(ae):Pi.set(Z,[ae])},zi=()=>{if(Rt||!pn||bn||!et)throw new Error("worker not ready")},ii=Z=>{switch(Z.data.type){case"init-wasm":Rt=!1,Z.data.err?(bn=!0,ni[1](Z.data.err)):(pn=!0,ni[0]()),ri&&(URL.revokeObjectURL(ri),ri=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let ae=Pi.get(Z.data.type);Z.data.err?ae.shift()[1](Z.data.err):ae.shift()[0](Z.data.out);break}}},ar=async()=>{if(!pn){if(Rt)throw new Error("multiple calls to 'initWasm()' detected.");if(bn)throw new Error("previous call to 'initWasm()' failed.");if(Rt=!0,Re())return new Promise((Z,ae)=>{et==null||et.terminate(),Pt().then(([ge,De])=>{try{et=De,et.onerror=Be=>ae(Be),et.onmessage=ii,ni=[Z,ae];let ye={type:"init-wasm",in:A};if(!ye.in.wasm.wasmPaths&&ge){let Be=gi();Be&&(ye.in.wasm.wasmPaths=Be)}et.postMessage(ye),ri=ge}catch(ye){ae(ye)}},ae)});try{await vi(A.wasm),await Xo(A),pn=!0}catch(Z){throw bn=!0,Z}finally{Rt=!1}}},to=async Z=>{if(Re())return zi(),new Promise((ae,ge)=>{hi("init-ep",[ae,ge]);let De={type:"init-ep",in:{epName:Z,env:A}};et.postMessage(De)});await Mr(A,Z)},bo=async Z=>Re()?(zi(),new Promise((ae,ge)=>{hi("copy-from",[ae,ge]);let De={type:"copy-from",in:{buffer:Z}};et.postMessage(De,[Z.buffer])})):vn(Z),wr=async(Z,ae)=>{if(Re()){if(ae!=null&&ae.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return zi(),new Promise((ge,De)=>{hi("create",[ge,De]);let ye={type:"create",in:{model:Z,options:{...ae}}},Be=[];Z instanceof Uint8Array&&Be.push(Z.buffer),et.postMessage(ye,Be)})}else return Rs(Z,ae)},Od=async Z=>{if(Re())return zi(),new Promise((ae,ge)=>{hi("release",[ae,ge]);let De={type:"release",in:Z};et.postMessage(De)});eo(Z)},_o=async(Z,ae,ge,De,ye,Be)=>{if(Re()){if(ge.some(Ne=>Ne[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ye.some(Ne=>Ne))throw new Error("pre-allocated output tensor is not supported for proxy.");return zi(),new Promise((Ne,Ae)=>{hi("run",[Ne,Ae]);let Fe=ge,nt={type:"run",in:{sessionId:Z,inputIndices:ae,inputs:Fe,outputIndices:De,options:Be}};et.postMessage(nt,_t(Fe))})}else return Je(Z,ae,ge,De,ye,Be)},wo=async Z=>{if(Re())return zi(),new Promise((ae,ge)=>{hi("end-profiling",[ae,ge]);let De={type:"end-profiling",in:Z};et.postMessage(De)});bs(Z)}}),fl,yo,Aa,ml=d(()=>{mn(),xc(),qt(),Rn(),Rr(),fl=(Z,ae)=>{switch(Z.location){case"cpu":return[Z.type,Z.dims,Z.data,"cpu"];case"gpu-buffer":return[Z.type,Z.dims,{gpuBuffer:Z.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Z.type,Z.dims,{mlTensor:Z.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Z.location} for ${ae()}`)}},yo=Z=>{switch(Z[3]){case"cpu":return new Ee(Z[0],Z[2],Z[1]);case"gpu-buffer":{let ae=Z[0];if(!Tn(ae))throw new Error(`not supported data type: ${ae} for deserializing GPU tensor`);let{gpuBuffer:ge,download:De,dispose:ye}=Z[2];return Ee.fromGpuBuffer(ge,{dataType:ae,dims:Z[1],download:De,dispose:ye})}case"ml-tensor":{let ae=Z[0];if(!bi(ae))throw new Error(`not supported data type: ${ae} for deserializing MLTensor tensor`);let{mlTensor:ge,download:De,dispose:ye}=Z[2];return Ee.fromMLTensor(ge,{dataType:ae,dims:Z[1],download:De,dispose:ye})}default:throw new Error(`invalid data location: ${Z[3]}`)}},Aa=class{async fetchModelAndCopyToWasmMemory(Z){return bo(await Si(Z))}async loadModel(Z,ae){vt();let ge;typeof Z=="string"?ge=await this.fetchModelAndCopyToWasmMemory(Z):ge=Z,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await wr(ge,ae),lt()}async dispose(){return Od(this.sessionId)}async run(Z,ae,ge){vt();let De=[],ye=[];Object.entries(Z).forEach(st=>{let Ze=st[0],Lt=st[1],Le=this.inputNames.indexOf(Ze);if(Le===-1)throw new Error(`invalid input '${Ze}'`);De.push(Lt),ye.push(Le)});let Be=[],Ne=[];Object.entries(ae).forEach(st=>{let Ze=st[0],Lt=st[1],Le=this.outputNames.indexOf(Ze);if(Le===-1)throw new Error(`invalid output '${Ze}'`);Be.push(Lt),Ne.push(Le)});let Ae=De.map((st,Ze)=>fl(st,()=>`input "${this.inputNames[ye[Ze]]}"`)),Fe=Be.map((st,Ze)=>st?fl(st,()=>`output "${this.outputNames[Ne[Ze]]}"`):null),nt=await _o(this.sessionId,ye,Ae,Ne,Fe,ge),dt={};for(let st=0;st<nt.length;st++)dt[this.outputNames[Ne[st]]]=Be[st]??yo(nt[st]);return lt(),dt}startProfiling(){}endProfiling(){wo(this.sessionId)}}}),Lr={};h(Lr,{OnnxruntimeWebAssemblyBackend:()=>zr,initializeFlags:()=>no,wasmBackend:()=>So});var no,zr,So,bc=d(()=>{mn(),xc(),ml(),no=()=>{(typeof A.wasm.initTimeout!="number"||A.wasm.initTimeout<0)&&(A.wasm.initTimeout=0);let Z=A.wasm.simd;if(typeof Z!="boolean"&&Z!==void 0&&Z!=="fixed"&&Z!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Z}". Reset it to \`false\` and ignore SIMD feature checking.`),A.wasm.simd=!1),typeof A.wasm.proxy!="boolean"&&(A.wasm.proxy=!1),typeof A.wasm.trace!="boolean"&&(A.wasm.trace=!1),typeof A.wasm.numThreads!="number"||!Number.isInteger(A.wasm.numThreads)||A.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)A.wasm.numThreads=1;else{let ae=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;A.wasm.numThreads=Math.min(4,Math.ceil((ae||1)/2))}},zr=class{async init(Z){no(),await ar(),await to(Z)}async createInferenceSessionHandler(Z,ae){let ge=new Aa;return await ge.loadModel(Z,ae),ge}},So=new zr}),_c={};h(_c,{InferenceSession:()=>un,TRACE:()=>be,TRACE_EVENT_BEGIN:()=>$t,TRACE_EVENT_END:()=>We,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>lt,Tensor:()=>Ee,default:()=>vl,env:()=>A,registerBackend:()=>k}),mn(),mn(),mn();var gl="1.26.0",vl=Xn;{let Z=(bc(),g(Lr)).wasmBackend;k("cpu",Z,10),k("wasm",Z,10)}return Object.defineProperty(A.versions,"web",{value:gl,enumerable:!0}),g(_c)})();n.exports=t})($b)),$b.exports}var F1;function bA(){return F1||(F1=1,(function(n){var e=nl&&nl.__createBinding||(Object.create?(function(y,T,$,I){I===void 0&&(I=$);var O=Object.getOwnPropertyDescriptor(T,$);(!O||("get"in O?!T.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return T[$]}}),Object.defineProperty(y,I,O)}):(function(y,T,$,I){I===void 0&&(I=$),y[I]=T[$]})),t=nl&&nl.__setModuleDefault||(Object.create?(function(y,T){Object.defineProperty(y,"default",{enumerable:!0,value:T})}):function(y,T){y.default=T}),i=nl&&nl.__importStar||function(y){if(y&&y.__esModule)return y;var T={};if(y!=null)for(var $ in y)$!=="default"&&Object.prototype.hasOwnProperty.call(y,$)&&e(T,y,$);return t(T,y),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=i(xA()),a=ky(),u=Ey(),l=Gm(),d=Vx(),h=E2(),m=T2();n.DEFAULT_MODEL="legacy",n.ort=s;const g="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",C="silero_vad_legacy.onnx",k=y=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:y,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async T=>{T.getTracks().forEach($=>{$.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"});n.getDefaultRealTimeVADOptions=k;const E=y=>"audioWorklet"in y&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function _(y,T,$,I,O){await $.audioWorklet.addModule(y),T.processorOptions={...T.processorOptions??{},frameSamples:I};const A=new AudioWorkletNode($,"vad-helper-worklet",T);return A.port.onmessage=async L=>{const V=L.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case d.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const te=new Float32Array(V.data);await O(te);break}}},A}async function S(y,T,$){const I=new m.Resampler({nativeSampleRate:y.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const A=y.createScriptProcessor(4096,1,1);let L=!1;return A.onaudioprocess=async V=>{if(!L){L=!0;try{const te=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const K=I.process(te);for(const de of K)await $(de)}catch(te){console.error("Error processing audio:",te)}finally{L=!1}}},A.connect(y.destination),A}class x{constructor(T,$,I,O,A=!1,L=null,V=null,te=null,re=null,K=null,de=null,J="uninitialized",he=!1){this.options=T,this.frameProcessor=$,this.model=I,this.frameSamples=O,this.listening=A,this.errored=L,this._stream=V,this._audioContext=te,this._vadNode=re,this._mediaStreamAudioSourceNode=K,this._audioProcessorAdapterType=de,this.initializationState=J,this.ownsAudioContext=he,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ce=>{this.initializationState="errored",this.errored=Ce},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?E(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await _(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await S(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:Ce,audioContext:ve,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const q=new MediaStreamAudioSourceNode(ve,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=q,q.connect(F);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ce,mediaStreamAudioSourceNode:ve}=this.getAudioInstances();await this.options.pauseStream(Ce),ve.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ve;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ve=this._audioContext)==null?void 0:ve.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(Ce.audio);break}}}static async new(T={}){const $={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,u.validateOptions)($),n.ort.env.wasm.wasmPaths=$.onnxWASMBasePath,$.ortConfig!==void 0&&$.ortConfig(n.ort);const I=$.model==="v5"?b:C,O=$.baseAssetPath+I,A=$.model==="v5"?h.SileroV5.new:h.SileroLegacy.new;let L;try{L=await A(n.ort,()=>(0,a.defaultModelFetcher)(O))}catch(de){throw console.error(`Encountered an error while loading model file ${O}`),de}const V=$.model==="v5"?512:1536,te=V/16,re=new u.FrameProcessor(L.process,L.reset_state,{positiveSpeechThreshold:$.positiveSpeechThreshold,negativeSpeechThreshold:$.negativeSpeechThreshold,redemptionMs:$.redemptionMs,preSpeechPadMs:$.preSpeechPadMs,minSpeechMs:$.minSpeechMs,submitUserSpeechOnPause:$.submitUserSpeechOnPause},te),K=new x($,re,L,V);if($.startOnLoad)try{await K.start()}catch(de){throw console.error("Error starting micVad",de),de}return K}}n.MicVAD=x})(nl)),nl}var G1;function _A(){return G1||(G1=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=S2();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=ky();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var i=Ey();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var s=Vx();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=gA();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const u=vA();n.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var l=bA();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(Tb)),Tb}var wA=_A();function tv(n,e,t,i,s){var u,l;try{(l=(u=window.api)==null?void 0:u.logs)==null||l.write(n,e,t,i,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;i!==void 0?a(`[${n}]`,t,i):a(`[${n}]`,t)}const gt={debug:(n,e,t)=>tv(n,"debug",e,t),info:(n,e,t)=>tv(n,"info",e,t),warn:(n,e,t)=>tv(n,"warn",e,t),error:(n,e,t,i)=>tv(n,"error",e,t,i)},j2=16e3,yA=6,_h=j2*yA,SA=400,CA=j2*SA/1e3,H1=300,W1=2e3,U1=1500,V1=3e3,kA=600,$2=.5,N2=.35,q1=.85,K1=.7;let qs=null,Uo=!1,ir=!1;const J_=new Set;function nv(n){for(const e of Array.from(J_))try{e(n)}catch(t){gt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Nb=0;const Y1=2;let Mh=!1,A2=!1;function I2(n){n.addEventListener("message",e=>{var i;if(((i=e.data)==null?void 0:i.type)!=="log")return;const t=e.data.level||"info";gt[t]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{gt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),EA(`error:${e.message||"unknown"}`)})}function vx(){return qs||(qs=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),I2(qs),gt.info("speech","worker spawned"),qs)}let iv=!1;function EA(n){if(!Mh){if(iv){gt.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(iv=!0,Nb+=1,A2=!0,gt.warn("speech","respawnWorker: starting",{reason:n,attempt:Nb}),nv({reason:n,respawned:!1,finalOnly:!0}),Nb>Y1){if(Mh=!0,gt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Y1}),qs)try{qs.terminate()}catch{}qs=null,Uo=!1,ir=!1,nv({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),iv=!1;return}if(qs)try{qs.terminate()}catch{}qs=null,Uo=!1,ir=!1;try{qs=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),I2(qs),ir=!0,qs.postMessage({type:"load"}),gt.info("speech","respawnWorker: new worker spawned, load posted"),nv({reason:n,respawned:!0,finalOnly:!0})}catch(e){Mh=!0,gt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),nv({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{iv=!1}}}function TA(n,e){if(Uo||ir)return;ir=!0;const t=vx();gt.info("speech","preloadModel: posting load");const i=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(Uo=!0,ir=!1,gt.info("speech","preloadModel: ready"),t.removeEventListener("message",i))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(ir=!1,gt.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),t.removeEventListener("message",i))};t.addEventListener("message",i),t.postMessage({type:"load"})}function DA(){gt.info("speech","resetModel: clearing load flags"),Uo=!1,ir=!1}function jA(){if(gt.info("speech","releaseModel: terminating worker"),qs)try{qs.terminate()}catch{}qs=null,Uo=!1,ir=!1}function qx(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function $A(n){const e=vx();return!Uo&&!ir&&(ir=!0,e.postMessage({type:"load"})),new Promise((t,i)=>{const s=a=>{var u,l,d;((u=a.data)==null?void 0:u.type)==="result"?(e.removeEventListener("message",s),t((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),i(new Error(String(a.data.error??"Transcription failed")))):((d=a.data)==null?void 0:d.type)==="status"&&a.data.status==="ready"&&(Uo=!0,ir=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function P2(n){let e=vx(),t=!1,i=null,s=null,a=null,u=null,l=null;const d=[],h=new Set;let m=null,g=0,b=!1,C=0,k=!1,E=!1,_=0,S=0,x=0,y=-1,T=H1,$=0,I=null,O="",A="",L=!1,V=0;function te(le,fe){const Ie=Math.min(le.length,fe.length);let He=0;for(;He<Ie&&le.charCodeAt(He)===fe.charCodeAt(He);)He++;return He}function re(le){const fe=te(O,le);return O=le,fe>A.length&&(A=le.slice(0,fe)),A.length>le.length&&(A=le),A}const K=()=>(m||(m=new Float32Array(_h)),m),de=()=>{g=0},J=le=>{const fe=K(),Ie=le.length;if(Ie>=_h){fe.set(le.subarray(Ie-_h)),g=_h;return}if(g+Ie<=_h){fe.set(le,g),g+=Ie;return}const He=g+Ie-_h;fe.copyWithin(0,He,g),g-=He,fe.set(le,g),g+=Ie},he=()=>{I&&(clearTimeout(I),I=null)},Ce=()=>{he(),b=!1,k=!1,E=!1,T=H1,O="",A="",L=!1,V=0,de()},ve=()=>{if(t||!b||E||k||I)return;if(g<CA){I=setTimeout(()=>{I=null,ve()},T);return}const le=performance.now()-_;if(le<T&&_!==0){I=setTimeout(()=>{I=null,ve()},T-le);return}if(A2||Mh||n.partialsEnabled&&!n.partialsEnabled())return;const fe=K(),Ie=new Float32Array(g);Ie.set(fe.subarray(0,g)),S+=1,x=S,k=!0,$=performance.now(),_=$,e.postMessage({type:"transcribe-partial",audio:Ie,seq:S},[Ie.buffer])},F=le=>le.length===0?Promise.resolve():Mh?(gt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(fe=>{d.push(fe),S+=1;const Ie=S;y=Ie,e.postMessage({type:"transcribe",audio:le,seq:Ie},[le.buffer])}),q=le=>{const fe=F(le);return h.add(fe),fe.finally(()=>{h.delete(fe)}),fe},W=le=>{var fe,Ie,He,me,ee;if(le.data.type==="result"){const $e=le.data.text,Ee=le.data.seq??0;Ee&&Ee<y&>.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ee,latestFinalSeq:y}),!t&&$e&&n.onFinal($e),(fe=d.shift())==null||fe()}else if(le.data.type==="partial"){const $e=le.data.seq??0,Ee=le.data.text??"",Te=performance.now()-$;k=!1,Te>=V1?(E=!0,gt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Te),seq:$e})):Te>=U1&&(T=Math.min(T*2,W1),gt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Te),newIntervalMs:T,seq:$e})),L||(L=!0,Te>kA&&T<500&&(T=500,gt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Te),newIntervalMs:500})));const be=$e!==x||$e<=y;if(!t&&!be&&Ee){const Qe=re(Ee);Qe&&((Ie=n.onPartial)==null||Ie.call(n,Qe),V===0&&(V=performance.now(),gt.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-C)})))}ve()}else if(le.data.type==="partial-error"){const $e=performance.now()-$;k=!1,$e>=V1?(E=!0,gt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round($e),seq:le.data.seq})):$e>=U1&&(T=Math.min(T*2,W1),gt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round($e),newIntervalMs:T,seq:le.data.seq})),gt.warn("speech","partial encode failed",{error:le.data.error,seq:le.data.seq}),ve()}else le.data.type==="error"?(t||n.onError(le.data.error),(He=d.shift())==null||He()):le.data.type==="status"?(t||(me=n.onModelStatus)==null||me.call(n,le.data.status,le.data.message),le.data.status==="ready"&&(Uo=!0,ir=!1)):le.data.type==="progress"&&(t||(ee=n.onProgress)==null||ee.call(n,le.data.pct))};e.addEventListener("message",W);const Q=le=>{var fe,Ie;if(!t){for(gt.warn("speech","createRecognition: worker death event",le),(fe=n.onStatusChange)==null||fe.call(n,"restarting");d.length;)(Ie=d.shift())==null||Ie();if(h.clear(),he(),k=!1,le.respawned){try{e.removeEventListener("message",W)}catch{}e=vx(),e.addEventListener("message",W)}}};return J_.add(Q),{start:async()=>{if(!t){if(Mh){n.onError("Speech recognition disabled — please reload the app.");return}!Uo&&!ir&&(ir=!0,gt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),gt.info("speech","createRecognition.start: initializing VAD",{modelReady:Uo,modelLoading:ir});try{const le=new URL("vad/",document.baseURI).href;gt.info("speech","vad: asset base resolved",{vadBase:le}),uA();const fe=n.inputDeviceId||null,Ie={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};fe&&(Ie.deviceId={exact:fe}),gt.info("speech","getUserMedia",{hasDeviceId:!!fe,deviceIdPrefix:fe?fe.slice(0,8):null});const He=await navigator.mediaDevices.getUserMedia({audio:Ie});s=He,a=new AudioContext;for(const me of He.getAudioTracks())me.addEventListener("ended",()=>{t||(gt.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),u=a.createAnalyser(),u.fftSize=2048,u.smoothingTimeConstant=.3,l.connect(u)}catch(me){gt.warn("speech","analyser init failed",{error:me instanceof Error?me.message:String(me)}),l=null,u=null}i=await wA.MicVAD.new({audioContext:a,getStream:async()=>He,resumeStream:async()=>He,pauseStream:async()=>{},baseAssetPath:le,onnxWASMBasePath:le,model:"v5",positiveSpeechThreshold:$2,negativeSpeechThreshold:N2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(me,ee)=>{var $e;t||(($e=n.onFrame)==null||$e.call(n,me),b&&(J(ee),ve()))},onSpeechStart:()=>{var me;t||(Ce(),b=!0,C=performance.now(),(me=n.onSpeechStart)==null||me.call(n))},onSpeechEnd:me=>{var ee;t||((ee=n.onStatusChange)==null||ee.call(n,"transcribing"),Ce(),q(me))},onVADMisfire:()=>{var me,ee;t||((me=n.onStatusChange)==null||me.call(n,"idle"),Ce(),(ee=n.onMisfire)==null||ee.call(n))}}),gt.info("speech","vad: ort wasm files loaded",{files:dA()}),i.start()}catch(le){const fe=le instanceof Error?le.message:"Microphone access denied",Ie=le instanceof Error?le.stack:"";if(gt.error("speech","createRecognition.start: VAD init failed",{error:fe,stack:Ie}),u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(He=>He.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(fe)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(Ce();h.size>0;)await Promise.all(Array.from(h));if(i){try{await i.destroy()}catch{}i=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(le=>le.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(le,fe)=>{if(i)try{i.setOptions({positiveSpeechThreshold:le,negativeSpeechThreshold:fe})}catch(Ie){gt.warn("speech","setVadThresholds failed",{error:Ie instanceof Error?Ie.message:String(Ie)})}},getAnalyser:()=>u,destroy:()=>{if(t=!0,Ce(),i){try{i.destroy()}catch{}i=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(le=>le.stop())}catch{}s=null}J_.delete(Q),e.removeEventListener("message",W)}}}let pm=null;const Z_=new Set,Q_=new Set;function NA(){for(const n of Z_)try{n()}catch{}}function ew(){for(const n of Q_)try{n()}catch{}}function AA(n){return n.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function IA(n){if(!window.speechSynthesis)return;const e=AA(n);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{pm=performance.now(),NA()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(pm=null,ew())},t.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(pm=null,ew())},window.speechSynthesis.speak(t)}function R2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),pm=null,ew())}function M2(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function PA(){return pm}function RA(n){return Z_.add(n),()=>{Z_.delete(n)}}function MA(n){return Q_.add(n),()=>{Q_.delete(n)}}function OA(n){M2()&&(n.setVadThresholds(q1,K1),gt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=RA(()=>{n.setVadThresholds(q1,K1),gt.info("voice","tts.duck.on")}),t=MA(()=>{n.setVadThresholds($2,N2),gt.info("voice","tts.duck.off")});return()=>{e(),t()}}const LA=[{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 zA(n){const e=n.trim();return LA.find(t=>t.match.test(e))??null}const BA=4e4;let Dd=null;function Oh(){Dd&&clearTimeout(Dd),Dd=setTimeout(()=>{Dd=null,Vt.getState().stopRecording()},BA)}function sv(){Dd&&(clearTimeout(Dd),Dd=null)}let uc=null,rc=null;const FA=.04,GA=.3;let xx=0,tw=0;function HA(n){rc!==null&&cancelAnimationFrame(rc);const e=()=>{if(uc===null||Vt.getState().submitCountdownStartAt===null){rc=null;return}const t=performance.now();if(t-tw<200&&xx>GA){const s=t-n;gt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:xx.toFixed(2),msIntoCountdown:Math.round(s)}),nc(),Oh();return}const i=WA();if(i){const s=new Uint8Array(i.fftSize);i.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const d=(s[l]-128)/128;a+=d*d}const u=Math.sqrt(a/s.length);if(u>FA){const l=t-n;gt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:u.toFixed(3),msIntoCountdown:Math.round(l)}),nc(),Oh();return}}rc=requestAnimationFrame(e)};rc=requestAnimationFrame(e)}function X1(n){uc&&clearTimeout(uc);const e=Vt.getState().submitDelayMs,t=performance.now();Vt.setState({submitCountdownStartAt:t}),uc=setTimeout(()=>{var s;uc=null,Vt.setState({submitCountdownStartAt:null});const i=jt.getState().tabs.find(a=>a.id===n);if((i==null?void 0:i.status)==="dormant"){const a=(s=wn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(wn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:a}),wn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){gt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Oh()},e),HA(t)}function nc(){rc!==null&&(cancelAnimationFrame(rc),rc=null),uc&&(clearTimeout(uc),uc=null),Vt.getState().submitCountdownStartAt!==null&&Vt.setState({submitCountdownStartAt:null})}let cs=null,tr=null,Lf=null;function WA(){var n;return((n=cs==null?void 0:cs.getAnalyser)==null?void 0:n.call(cs))??null}const rv=1e4;let fm=null;function ov(){fm&&(clearTimeout(fm),fm=null)}let Vv=null,qv=null;function av(){Vv=null,qv&&(qv(),qv=null)}const UA=1500,VA=9e4;let zf=0,Kv=null,nw=-1;function Bf(){Kv&&(clearTimeout(Kv),Kv=null,nw=-1)}const qA=1800*1e3;let mm=null,lv=!1;function J1(){mm&&(clearTimeout(mm),mm=null)}const KA=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Vt=Ei((n,e)=>{function t(){J1(),mm=setTimeout(()=>{if(mm=null,e().isRecording||cs){t();return}gt.info("voice","model idle timeout: releasing worker"),Bf(),zf++,jA(),n({modelStatus:"idle",loadingProgress:0,error:null,errorKind:null})},qA)}function i(){return e().modelStatus==="error"?e().resetAndRetryModel():e().initModel(),new Promise((s,a)=>{let u=()=>{};const l=d=>d.modelStatus==="ready"?(u(),s(),!0):d.modelStatus==="error"?(u(),a(new Error(d.error??"Model load failed")),!0):!1;l(e())||(u=Vt.subscribe(d=>{l(d)}))})}return{isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;gt.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const s=++zf,a=()=>{s===zf&&(Bf(),nw=s,Kv=setTimeout(()=>{nw===s&&e().modelStatus==="loading"&&(gt.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},VA))};a(),TA((u,l)=>{s===zf&&(u==="ready"?(Bf(),gt.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null}),!e().isRecording&&!cs&&t()):u==="error"?(Bf(),gt.error("voice","modelStatus -> error",{msg:l}),n({modelStatus:"error",error:l,errorKind:"load"})):(a(),n({modelStatus:"loading"})))},u=>{s===zf&&(a(),n({loadingProgress:Math.round(u)}))})},resetAndRetryModel:()=>{gt.info("voice","mic.gate.retry"),Bf(),DA(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(s,a)=>{if(e().isRecording)return;if(cs){gt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!qx()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}if(e().modelStatus!=="ready"){if(lv)return;lv=!0,i().then(()=>{lv=!1,e().startRecording(s,a)}).catch(l=>{lv=!1;const d=l instanceof Error?l.message:String(l);gt.error("voice","startRecording: model load failed",{error:d}),ze.error(`Could not load speech model: ${d}`)});return}J1();const u=l=>{try{const d=P2({inputDeviceId:l,onStatusChange:h=>{n(h==="transcribing"?{statusPill:"transcribing"}:h==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:h=>{e().partialsEnabled&&n({lastPartial:h})},partialsEnabled:()=>e().partialsEnabled,onFrame:h=>{xx=h.isSpeech,tw=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),sv(),nc(),M2()){const m=PA(),g=m!==null?performance.now()-m:null;R2(),n({lastBargeInAt:performance.now()}),gt.info("voice","barge-in",{tabId:s,utteranceOffsetMs:g})}else gt.debug("voice","barge-in.no-op",{tabId:s})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Oh();const h=e().lastBargeInAt;h!==null&&performance.now()-h<600&>.warn("voice","barge-in.misfire",{tabId:s,sinceBargeInMs:Math.round(performance.now()-h)})},onFinal:h=>{var k;Oh();const m=h.trim();if(!m||KA.has(m)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Lf){Lf(m),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((k=jt.getState().tabs.find(E=>E.id===s))==null?void 0:k.status)==="dormant"){wn.getState().setPendingVoiceText(s,m),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&X1(s);const E=window;E.__transcripts&&(E.__transcripts.push({tabId:s,text:m}),E.__transcripts.length>500&&E.__transcripts.shift());return}const b=zA(m);if(b){gt.info("voice","voice-command",{tabId:s,label:b.label,transcript:m}),window.api.pty.write({tabId:s,data:b.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),nc();const E=window;E.__transcripts&&(E.__transcripts.push({tabId:s,text:m}),E.__transcripts.length>500&&E.__transcripts.shift());return}window.api.pty.write({tabId:s,data:m}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&X1(s);const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift())},onError:h=>{gt.error("voice","recognition error",{err:h}),nc(),n({error:h,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),tr==null||tr(),tr=null,sv(),cs==null||cs.destroy(),cs=null,Lf=null,ze.error(`Microphone error: ${h}`)},onModelStatus:h=>{h==="ready"?n({modelStatus:"ready",loadingProgress:100}):h==="loading"&&n({modelStatus:"loading"})},onProgress:h=>n({loadingProgress:Math.round(h)})});cs=d,Lf=(a==null?void 0:a.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Oh(),d.start().then(()=>{cs===d&&(tr==null||tr(),tr=OA(d))}).catch(h=>{const m=h instanceof Error?h.message:String(h);gt.error("voice","handle.start() failed",{error:m}),ze.error(`Could not start mic: ${m}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,d,h;return((h=(d=(l=window.api)==null?void 0:l.voice)==null?void 0:d.getDevicePref)==null?void 0:h.call(d))??Promise.resolve(null)}).then(l=>u((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{gt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),u(null)})},stopRecording:()=>{const s=cs;s&&(sv(),nc(),xx=0,tw=0,tr==null||tr(),tr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t(),s.stop().finally(()=>{s.destroy(),cs===s&&(cs=null,Lf=null),e().hotkeyState==="stopping"&&(ov(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const s=cs;if(!s)return;sv(),tr==null||tr(),tr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await s.stop()}catch(l){gt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}s.destroy(),cs===s&&(cs=null);const{useSessions:a}=await Kn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>DN);return{useSessions:l}},[],import.meta.url),u=a.getState().activeTabId;u&&e().startRecording(u)},setExternalRecording:s=>n({externalRecording:s}),toggleTTS:()=>{const s=!e().ttsEnabled;n({ttsEnabled:s}),Promise.resolve().then(()=>{var a,u,l;return(l=(u=(a=window.api)==null?void 0:a.voice)==null?void 0:u.setTtsEnabled)==null?void 0:l.call(u,s)}).catch(a=>{gt.warn("voice","setTtsEnabled failed",{error:a instanceof Error?a.message:String(a)})})},setAutoSubmit:s=>n({autoSubmit:s}),setSubmitDelayMs:s=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(s)))}),cancelSubmit:()=>nc(),setPartialsEnabled:s=>{e().partialsEnabled!==s&&(n({partialsEnabled:s}),s||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:s=>{e().permissionState!==s&&(gt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:s}),n({permissionState:s}))},setLevelMeterEnabled:s=>{e().levelMeterEnabled!==s&&n({levelMeterEnabled:s})},setTurnDetectorRuntimeState:s=>{e().turnDetectorState!==s&&(n({turnDetectorState:s}),s==="load_failed"?gt.warn("voice-turn","voice-turn.load_failed"):s==="runtime_error"?gt.warn("voice-turn","voice-turn.runtime_error"):s==="disabled"&>.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:s=>{e().wizardArmed!==s&&n({wizardArmed:s})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:s,source:a,mode:u,tabId:l})=>{const d=e(),{canRecord:h,reason:m}=O2(d);if(s==="down"){if(m==="error"||m==="load-timeout"){d.resetAndRetryModel(),gt.info("voice-hotkey","down.retry",{source:a,reason:m});return}if(!h&&m!=="loading"){gt.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:m});return}if(d.hotkeyState==="recording"||d.isRecording){(u==="toggle"||a==="global")&&(n({hotkeyState:"stopping"}),ov(),fm=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:rv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},rv),d.stopRecording());return}if(m==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),gt.info("voice-hotkey","armed",{source:a,modelStatus:d.modelStatus})),av(),Vv={tabId:l,source:a,mode:u},qv=Vt.subscribe((g,b)=>{if(Vv&&g.modelStatus==="ready"&&b.modelStatus!=="ready"&&g.hotkeyState==="armed"){const C=Vv;if(av(),!C.tabId){gt.warn("voice-hotkey","armed-promote-no-tab",{source:C.source}),n({hotkeyState:"idle"});return}gt.info("voice-hotkey","armed-promote",C),n({hotkeyState:"recording"}),Vt.getState().startRecording(C.tabId)}});return}if(!l){gt.warn("voice-hotkey","no-active-tab",{source:a});return}gt.info("voice-hotkey","start",{source:a,mode:u,tabId:l}),d.startRecording(l),e().isRecording?n({hotkeyState:"recording"}):(gt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(u!=="hold"||a==="global")){if(d.hotkeyState==="armed"){av(),gt.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),ov(),fm=setTimeout(()=>{e().hotkeyState==="stopping"&&(gt.warn("voice-hotkey","drain-timeout",{durationMs:rv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},rv),d.stopRecording())}},destroyHotkey:()=>{const s=e();if(av(),nc(),s.hotkeyState==="recording"){gt.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{s.stopRecording()}catch{}}else(s.hotkeyState==="armed"||s.hotkeyState==="stopping")&&(ov(),n({hotkeyState:"destroyed"}))}}}),YA=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),O2=n=>qx()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};typeof window<"u"&&Promise.resolve().then(()=>{var n,e,t;return(t=(e=(n=window.api)==null?void 0:n.voice)==null?void 0:e.getTtsEnabled)==null?void 0:t.call(e)}).then(n=>{typeof n=="boolean"&&Vt.setState({ttsEnabled:n})}).catch(n=>{gt.warn("voice","getTtsEnabled failed",{error:n instanceof Error?n.message:String(n)})});if(typeof window<"u"){const n=window;n.__voice=Vt,n.__transcripts=[]}const Em=6e4,XA=3e5,JA=.25,ZA=5e3,Tm=Ei(()=>({data:null,refreshing:!1}));let Z1=!1,Yv=null,Ab=Em,cv=!1,ol=null;function QA(n,e){if(n.kind==="ok")return{delayMs:Em,nextBackoffMs:Em};const t=Math.min(e*2,XA),i=t*JA;let s=t+(Math.random()*2-1)*i;const a=n.kind==="meter_rate_limited"?n.retryAfterMs:void 0;return typeof a=="number"&&Number.isFinite(a)&&a>s&&(s=a),{delayMs:s,nextBackoffMs:t}}function Q1(){return QE(window.api.billing.fetch(),ZA,"billing.fetch")}function eS(n){Tm.setState({data:n,refreshing:!1})}async function Ty(){Tm.setState({refreshing:!0});let n=Em;try{const e=await Q1();ol&&(ol.cancel(),ol=null),eS(e);const{delayMs:t,nextBackoffMs:i}=QA(e,Ab);Ab=i,n=t}catch(e){Ab=Em,Tm.setState({refreshing:!1});const t=e2({error:e,retry:Q1,onRetrySuccess:i=>{ol=null,eS(i)},onStillFailing:i=>{ol=null,cv||(cv=!0,ze.warn(`Billing usage fetch: ${i}`))}});if(t)ol=t;else if(!cv){cv=!0;const i=e instanceof Error?e.message:String(e);ze.warn(`Billing usage fetch failed: ${i}`)}}Yv=setTimeout(Ty,n)}function eI(){Z1||(Z1=!0,Ty())}function L2(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function tI(){Yv!==null&&(clearTimeout(Yv),Yv=null),ol&&(ol.cancel(),ol=null),Ty()}function Dm(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!t)return n;const i=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),s=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${i} ${s} ${e[1]}`:`${i} ${s}`}function jm(n){const e=/(opus|sonnet|haiku|fable)/i.exec(n);return e?e[1].toLowerCase():null}const dv=new Map,nI=3e4;function Dy(n){const[e,t]=M.useState(()=>{var i;return n?((i=dv.get(n))==null?void 0:i.value)??null:null});return M.useEffect(()=>{if(!n){t(null);return}let i=!1;return(async()=>{const a=dv.get(n);if(a&&Date.now()-a.ts<nI){i||t(a.value);return}try{const u=await window.api.app.gitBranch(n);if(i)return;dv.set(n,{value:u,ts:Date.now()}),t(u)}catch{if(i)return;dv.set(n,{value:null,ts:Date.now()}),t(null)}})(),()=>{i=!0}},[n]),e}const iI="~/.claude/session-manager/ui-chrome-prefs.json",z2=ja(iI),sI=180,rI=480,iw=252,gd={sidebarWidth:iw,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function sw(n){return Math.min(rI,Math.max(sI,n))}let oc=null,Xv={};function oI(n){const e=()=>{const t=n(),i={sidebarWidth:t.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed,collapsedGroups:t.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed,tourCompletedAt:t.tourCompletedAt,density:t.density};z2.patch(i).catch(()=>{})};n().hydrated||!oc?e():oc.then(e)}function wh(n,e,t){n(t),!e().hydrated&&oc&&Object.assign(Xv,t),oI(e)}const ss=Ei((n,e)=>({...gd,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():oc||(oc=(async()=>{try{const t=await z2.read();if(Object.keys(t).length>0){n({sidebarWidth:typeof t.sidebarWidth=="number"?sw(t.sidebarWidth):gd.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed??gd.sidebarCollapsed,collapsedGroups:Array.isArray(t.collapsedGroups)?t.collapsedGroups:gd.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed??gd.learningPanelCollapsed,tourCompletedAt:typeof t.tourCompletedAt=="number"?t.tourCompletedAt:gd.tourCompletedAt,density:t.density==="compact"?"compact":gd.density,...Xv,hydrated:!0});return}}catch{}n({...Xv,hydrated:!0})})().finally(()=>{oc=null,Xv={}}),oc),setSidebarWidth:t=>wh(n,e,{sidebarWidth:sw(t)}),setSidebarCollapsed:t=>wh(n,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>wh(n,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>wh(n,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>wh(n,e,{tourCompletedAt:t}),setDensity:t=>wh(n,e,{density:t})})),aI=52;function lI(n){return new Set(n.filter(e=>e==="Workspace"||e==="Claude Code"||e==="Session Manager"))}function cI(){const n=jt(t=>{var i;return((i=t.tabs.find(s=>s.id===t.activeTabId))==null?void 0:i.cwd)??null});return{scheduler:Yr(t=>{var i;return(((i=t.snapshot)==null?void 0:i.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function dI({active:n,onNavigate:e,onNewSession:t}){const i=ss(K=>K.hydrated),s=ss(K=>K.hydrate);M.useEffect(()=>{i||s()},[i,s]);const a=ss(K=>K.collapsedGroups),u=ss(K=>K.setCollapsedGroups),l=M.useMemo(()=>lI(a),[a]),d=M.useCallback(K=>{const de=new Set(l);de.has(K)?de.delete(K):de.add(K),u(Array.from(de))},[l,u]),h=ss(K=>K.sidebarCollapsed),m=ss(K=>K.setSidebarCollapsed),g=M.useCallback(()=>{m(!h)},[h,m]),b=jt(K=>K.tabs),C=jt(K=>K.activeTabId),k=b.find(K=>K.id===C)??null,E=cI(),_=En(K=>K.navFace),S=AN(_),x=S.filter(K=>K.group==="Workspace"),y=S.filter(K=>K.group==="Claude Code"),T=S.filter(K=>K.group==="Session Manager"),$=_==="home"&&!h,I=ss(K=>K.sidebarWidth),O=ss(K=>K.setSidebarWidth),[A,L]=M.useState(I),V=M.useRef(A);V.current=A,M.useEffect(()=>{L(I)},[I]);const te=M.useCallback(K=>{K.preventDefault();const de=K.clientX,J=V.current;let he=J;const Ce=F=>{he=sw(J+(F.clientX-de)),L(he)},ve=()=>{window.removeEventListener("pointermove",Ce),window.removeEventListener("pointerup",ve),document.body.style.cursor="",document.body.style.userSelect="",O(he)};window.addEventListener("pointermove",Ce),window.addEventListener("pointerup",ve),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[O]),re=M.useCallback(()=>{L(iw),O(iw)},[O]);return r.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:h?aI:A},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[r.jsx(uI,{tab:k,navFace:_,onNewSession:t,rail:h,onToggleRail:g}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:h?"4px":"8px"},children:$?r.jsxs(r.Fragment,{children:[r.jsx(Ib,{label:"Workspace",desc:kb.Workspace,collapsed:l.has("Workspace"),count:x.length,onToggle:()=>d("Workspace")}),!l.has("Workspace")&&x.map(K=>r.jsx(uv,{item:K,active:n===K.key,live:K.liveKind?E[K.liveKind]:!1,onClick:()=>e(K.key),rail:!1},K.key)),r.jsx(Ib,{label:"Claude Code",desc:kb["Claude Code"],collapsed:l.has("Claude Code"),count:y.length,onToggle:()=>d("Claude Code")}),!l.has("Claude Code")&&y.map(K=>r.jsx(uv,{item:K,active:n===K.key,live:!1,onClick:()=>e(K.key),rail:!1},K.key)),r.jsx(Ib,{label:"Session Manager",desc:kb["Session Manager"],collapsed:l.has("Session Manager"),count:T.length,onToggle:()=>d("Session Manager")}),!l.has("Session Manager")&&T.map(K=>r.jsx(uv,{item:K,active:n===K.key,live:!1,onClick:()=>e(K.key),rail:!1},K.key))]}):r.jsx("div",{className:"pt-2",children:S.map(K=>r.jsx(uv,{item:K,active:n===K.key,live:K.liveKind?E[K.liveKind]:!1,onClick:()=>e(K.key),rail:h},K.key))})}),r.jsx(hI,{rail:h,navFace:_}),!h&&r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:te,onDoubleClick:re,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 uI({tab:n,navFace:e,onNewSession:t,rail:i,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",u=Dy((n==null?void 0:n.cwd)??null);return i?r.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[r.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:r.jsx(wi,{name:"plus",size:15,stroke:1.8})}),r.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:r.jsx(wi,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?r.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),r.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:r.jsx(wi,{name:"chevron",size:13,stroke:1.8})})})]}),r.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:r.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:[r.jsx(wi,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):r.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),r.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:r.jsx(wi,{name:"chevron",size:13,stroke:1.8})})})]}),r.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[r.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),r.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),r.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:u?`⌥${u}`:n?n.cwd:"—"}),r.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:r.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:[r.jsx(wi,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Ib({label:n,desc:e,collapsed:t,count:i,onToggle:s}){return r.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[r.jsxs("button",{onClick:s,"aria-expanded":!t,title:t?`Expand ${n}`:`Collapse ${n}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[r.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),r.jsx("span",{className:"flex-1",children:n}),t&&r.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!t&&r.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 uv({item:n,active:e,live:t,onClick:i,rail:s}){return r.jsxs("button",{onClick:i,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":n.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&r.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),r.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:r.jsx(wi,{name:n.icon,size:17,stroke:1.6})}),!s&&r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"block truncate",children:n.label}),n.hint&&r.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&t&&r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&t&&r.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 hI({rail:n,navFace:e}){const t=Vt(d=>d.isRecording),i=jt(d=>d.tabs),s=jt(d=>d.activeTabId),a=i.find(d=>d.id===s)??null,[u,l]=M.useState(null);return M.useEffect(()=>{let d=!1;if(!(a!=null&&a.presetId)){l(null);return}return YE(a.presetId).then(h=>{d||l((h==null?void 0:h.model)??null)}).catch(()=>{d||l(null)}),()=>{d=!0}},[a==null?void 0:a.presetId]),n?r.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):r.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:[r.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")&&r.jsx("span",{className:"truncate",title:u??"",children:t?"recording…":u?`Claude · ${Dm(u)}`:"Claude Code"})]})}function pI(n,e,t){return e?n.map(i=>i.id===e?{...i,lastActivityAt:t}:i):n}function fI(n,e,t){return{tabId:n,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function mI(n,e,t){const i=Date.now(),s={...n,lastEventAt:t!=null&&t.replay?n.lastEventAt:i},a=[],u=(l,d)=>l.length>d?l.slice(0,d-1)+"…":l;switch(e.kind){case"todo_write":{const l=Array.isArray(e.data)?e.data:[];s.todos=l,t!=null&&t.replay||a.push({id:0,kind:"todo-update",at:i,label:`Todos · ${l.length} item${l.length!==1?"s":""}`});break}case"tool_use":{const l=e.data,d=l.input,h={};for(const m of["command","file_path","pattern","url","query","subagent_type","description"])d&&m in d&&(h[m]=d[m]);if(s.lastToolUses=[{id:l.id,name:l.name,input:h,at:i},...n.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const m=l.input,g=["Edit","Write","NotebookEdit"].includes(l.name),b=typeof(m==null?void 0:m.file_path)=="string"?m.file_path:void 0,C=typeof(m==null?void 0:m.command)=="string"?m.command:void 0,k=b?b.split("/").pop()??b:C?u(C,28):"";a.push({id:0,kind:"tool-use",at:i,label:k?`${l.name} · ${k}`:l.name,target:b??C,toolName:l.name}),g&&b&&a.push({id:0,kind:"file-edit",at:i,label:`${l.name} · ${u(b.split("/").pop()??b,34)}`,target:b,toolName:l.name})}break}case"plan":{const l=e.data,d=typeof l=="string"?l:(l==null?void 0:l.plan)??JSON.stringify(l);s.plans=[{at:i,content:d??""},...n.plans].slice(0,50),t!=null&&t.replay||a.push({id:0,kind:"plan-revision",at:i,label:"Plan revised"});break}case"agent_spawn":{const l=e.data;s.agents=[{id:l==null?void 0:l.toolUseId,at:i,subagentType:l==null?void 0:l.subagent_type,description:l==null?void 0:l.description,lastActivityAt:i},...n.agents].slice(0,50),t!=null&&t.replay||a.push({id:0,kind:"agent-spawn",at:i,label:l!=null&&l.subagent_type?`Agent: ${u(l.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const l=e.data,d=(n.usage.inputTokens||0)+(n.usage.outputTokens||0),h=l.input_tokens??l.inputTokens??0,m=l.output_tokens??l.outputTokens??0,g=d+h+m;s.usage={inputTokens:(n.usage.inputTokens||0)+h,outputTokens:(n.usage.outputTokens||0)+m,cacheCreationInputTokens:(n.usage.cacheCreationInputTokens||0)+(l.cache_creation_input_tokens??l.cacheCreationInputTokens??0),cacheReadInputTokens:(n.usage.cacheReadInputTokens||0)+(l.cache_read_input_tokens??l.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(g/1e3)>Math.floor(d/1e3)&&a.push({id:0,kind:"usage-tick",at:i,label:`${Math.floor(g/1e3)}k tokens`});break}case"tool_result":{const l=e.data;s.agents=pI(n.agents,l==null?void 0:l.toolUseId,i);break}}return{next:s,newActivity:a}}const Jv=Ei((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,i,s)=>{const a={...e().refs};if(a[t]=(a[t]??0)+1,n({refs:a}),a[t]>1)return;n({tabs:{...e().tabs,[t]:fI(t,i,s)}});const u=window.api.transcripts.onEvent(t,l=>e().ingestBatch(t,l));n({unsubs:{...e().unsubs,[t]:u}}),window.api.transcripts.subscribe({tabId:t,cwd:i,sessionUuid:s}).then(async l=>{const d=e().tabs[t];if(!d)return;if(!l.ok){const{toast:m}=await Kn(async()=>{const{toast:g}=await Promise.resolve().then(()=>JE);return{toast:g}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[t]:{...d,path:null}}});return}n({tabs:{...e().tabs,[t]:{...d,path:l.path}}});const h=await window.api.transcripts.buffer(t);e().ingestBatch(t,h,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",t,l))},unsubscribe:t=>{const i={...e().refs};if(!i[t])return;if(i[t]--,i[t]>0){n({refs:i});return}delete i[t];const s=e().unsubs[t];s==null||s();const a={...e().unsubs};delete a[t];const u={...e().tabs};delete u[t],window.api.transcripts.unsubscribe(t),n({refs:i,unsubs:a,tabs:u})},ingest:(t,i,s)=>{e().ingestBatch(t,[i],s)},ingestBatch:(t,i,s)=>{const a=e().tabs[t];if(!a||i.length===0)return;let u=a,l=[];for(const d of i){const{next:h,newActivity:m}=mI(u,d,s);u=h,l=l.concat(m)}if(l.length>0){let d=a.activitySeq;const h=l.map(m=>({...m,id:++d}));u={...u,activitySeq:d,activityRing:[...a.activityRing,...h].slice(-32)}}n({tabs:{...e().tabs,[t]:u}})}}));function gI(n){const e=Jv(s=>s.subscribe),t=Jv(s=>s.unsubscribe),i=Jv(s=>n?s.tabs[n.id]:void 0);return M.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>t(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,t]),i}function B2(n){if(!n)return null;const e=new Date(n);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const i=Math.floor(t/864e5),s=Math.floor(t%864e5/36e5),a=Math.floor(t%36e5/6e4),u=i>0?`${i}d ${s}h`:s>0?`${s}h ${a}m`:`${a}m`,l=i>=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:u,abs:`${l} PT`}}function rw(n){return!n||typeof n.utilization!="number"||Number.isNaN(n.utilization)?null:Math.round(n.utilization)}function tS(n,e){const t=rw(e);if(t==null)return`${n} — usage unavailable`;const i=B2((e==null?void 0:e.resets_at)??null),s=i?` · resets in ${i.rel}${i.abs?` (${i.abs})`:""}`:"";return`${n} · ${t}% used${s} — click to open Home`}function _V(n,e){return n?n==="session"||n==="five_hour"?"Session · 5h":n==="weekly_all"?"Weekly · all models":n==="weekly_scoped"?"Weekly · scoped":n:null}const F2=M.createContext(null);function vI({panelId:n,children:e}){return r.jsx(F2.Provider,{value:n,children:e})}function Kx(n){const e=M.useContext(F2),t=n??e;return En(i=>t==null||i.focusedPanelId===t)}function jy(n){const e=Kx(n),t=M.useRef(e);return t.current=e,t}const xI=5e3;let Ed=null;const ow=new Set;let Pb=0,gm=null;function bI(){ow.forEach(n=>n())}async function bx(){try{Ed=await window.api.schedule.sessionSlots(),bI()}catch{}}const _I=0,wI=10;async function wV(n){Ed||await bx();const e=Ed?Ed.min:_I,t=Ed?Ed.max:wI,i=Math.min(t,Math.max(e,Math.round(n)));await window.api.schedule.setSessionSlots(i),await bx()}function yI(){gm==null&&(bx(),gm=setInterval(()=>{bx()},xI))}function SI(){gm!=null&&(clearInterval(gm),gm=null)}function $y(n){const e=Kx(n),[,t]=M.useState(0);return M.useEffect(()=>{const i=()=>t(s=>s+1);return ow.add(i),()=>{ow.delete(i)}},[]),M.useEffect(()=>{if(e)return Pb+=1,yI(),()=>{Pb-=1,Pb<=0&&SI()}},[e]),Ed}let $h=null;const aw=new Set;let Rb=0,Zv=null,lw=!1;const CI=360*60*1e3;let Qv=null;function nS(n){$h=n.check||!($h!=null&&$h.check)?n:{...n,check:$h.check},aw.forEach(e=>e())}function kI(){if(lw)return;lw=!0,Zv=window.api.updater.onStatus(nS);const n=()=>{window.api.updater.status().then(nS).catch(()=>{})};n(),Qv=setInterval(n,CI)}function EI(){lw=!1,Qv!=null&&(clearInterval(Qv),Qv=null),Zv&&(Zv(),Zv=null)}function TI(){const[,n]=M.useState(0);return M.useEffect(()=>{const e=()=>n(t=>t+1);return aw.add(e),Rb+=1,kI(),()=>{aw.delete(e),Rb-=1,Rb<=0&&EI()}},[]),$h}function DI({total:n,inUse:e,size:t}){const i=Math.min(Math.max(e,0),n),s=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return r.jsx(r.Fragment,{children:Array.from({length:n},(a,u)=>r.jsx("span",{"data-testid":"slot-dot","data-filled":u<i?"true":"false",className:`${s} ${u<i?"bg-accent border-accent":"bg-bg border-line"}`},u))})}function jI({onNavigate:n}){const e=jt(J=>J.tabs),t=jt(J=>J.activeTabId),i=e.find(J=>J.id===t)??null,s=gI(i),a=(s==null?void 0:s.lastEventAt)??0,u=Tm(J=>J.data),l=Yr(J=>{var he;return((he=J.snapshot)==null?void 0:he.paused)??null}),d=Dy((i==null?void 0:i.cwd)??null),h=$y(),m=TI(),g=(m==null?void 0:m.check)??null,b=Wi(J=>J.show),[,C]=M.useState(0);M.useEffect(()=>{const J=setInterval(()=>C(he=>he+1),6e4);return()=>clearInterval(J)},[]);const k=async()=>{const J=(m==null?void 0:m.latest)??"";try{const he=await window.api.updater.install(!1),Ce=(he==null?void 0:he.status)??await window.api.updater.status();(Ce==null?void 0:Ce.state)==="deferred"&&b("info",`Update v${J} will install when ${Ce.busyReason??"running jobs"} finish`)}catch(he){b("error",he instanceof Error?he.message:String(he))}},E=(s==null?void 0:s.todos)??[],[_,S]=M.useState(!1),x=M.useRef(null);M.useEffect(()=>{if(!_)return;const J=he=>{x.current&&!x.current.contains(he.target)&&S(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[_]),M.useEffect(()=>{E.length===0&&S(!1)},[E.length]);const y=L2(u),T=(y==null?void 0:y.usage.five_hour)??null,$=(y==null?void 0:y.usage.seven_day)??null,I=rw(T),O=rw($),A=(u==null?void 0:u.kind)==="ok"||(u==null?void 0:u.kind)==="ok-stale",L=a>0?AI(Date.now()-a):"—",V=(h==null?void 0:h.total)??5,te=h?Math.min(Math.max(h.inUse,0),h.total):0,re=h?`${te} / ${V}`:`— / ${V}`,K=h&&h.holders.length>0?`
|
|
2933
2933
|
`+h.holders.slice(0,5).map(J=>J.owner).join(`
|
|
2934
|
-
`):"",de=`${re} Claude sessions running${K}`;return r.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:[r.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:A?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:A?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:tS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:I!=null?`${I}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:tS("Weekly window (all models)",$),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:O!=null?`${O}%`:"—"})]}),l&&r.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),i&&r.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,d&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),E.length>0&&r.jsx($I,{ref:x,todos:E,open:_,onToggle:()=>S(J=>!J)}),r.jsx("span",{className:"flex-1"}),r.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:de,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(DI,{total:V,inUse:(h==null?void 0:h.inUse)??0,size:"sm"})}),(m==null?void 0:m.state)==="ready"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",m.latest]}):(m==null?void 0:m.state)==="deferred"?r.jsxs("span",{className:"text-amber-300",title:`Waiting for ${m.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",m.latest," installs when idle"]}):(m==null?void 0:m.state)==="downloading"?r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",m.latest,"…"]}):g!=null&&g.behind&&g.latest&&g.channel==="installer"?r.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(()=>{b("error",`Couldn't open URL: ${J}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.latest?r.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]}):r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.135.0"]})]})}const $I=M.forwardRef(function({todos:e,open:t,onToggle:i},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return r.jsxs("div",{ref:s,className:"relative",children:[r.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[r.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),r.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),r.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),r.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&r.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 ${Ii.dialog}`,"data-testid":"footer-todos-popover",children:r.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>r.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[r.jsx(NI,{status:u.status}),r.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function NI({status:n}){return n==="completed"?r.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?r.jsx("span",{className:"w-3 shrink-0",children:r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):r.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function AI(n){const e=Math.max(0,Math.floor(n/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 II({onClose:n,onSent:e}){const t=jt(O=>O.tabs),[i,s]=M.useState(""),[a,u]=M.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[l,d]=M.useState(!1),[h,m]=M.useState({}),g=M.useRef(null),b=M.useRef(e);M.useEffect(()=>{b.current=e},[e]),M.useEffect(()=>{u(O=>{const A={};for(const L of t)A[L.id]=O[L.id]??!0;return A})},[t]),M.useEffect(()=>{var O;(O=g.current)==null||O.focus()},[]),M.useEffect(()=>window.api.pty.onWriteError(A=>{m(L=>A.tabId in L?{...L,[A.tabId]:"skipped"}:L)}),[]),M.useEffect(()=>{if(Object.keys(h).length===0)return;const O=Object.values(h).filter(L=>L==="sent").length,A=window.setTimeout(()=>b.current(O),1500);return()=>window.clearTimeout(A)},[h]);const C=t.filter(O=>a[O.id]).map(O=>O.id),k=C.length,E=Object.keys(h).length>0,_=i.length>0&&k>0&&!l&&!E,S=()=>{if(!_)return;d(!0);const O=jt.getState().tabs,A=new Set(O.map(V=>V.id)),L={};for(const V of C)A.has(V)?(window.api.pty.write({tabId:V,data:i+"\r"}),L[V]="sent"):L[V]="skipped";m(L),d(!1)},x=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),n();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),S())},y=t.length>0&&t.every(O=>a[O.id]),T=()=>{const O=!y;u(Object.fromEntries(t.map(A=>[A.id,O])))},$=Object.values(h).some(O=>O==="skipped"),I=E?$?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return r.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),r.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),r.jsx("textarea",{ref:g,value:i,onChange:O=>s(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"}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:y,onChange:T,className:"accent-accent"}),r.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),r.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(O=>r.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:!!a[O.id],onChange:A=>u(L=>({...L,[O.id]:A.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),h[O.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[O.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.id))})]}),r.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[r.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:S,disabled:!_,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:I})]})]})}function PI({tabId:n,cwd:e,onClose:t}){const i=hm(k=>k.watchersForTab(n)),s=hm(k=>k.add),a=hm(k=>k.remove),u=M.useRef(null),[l,d]=M.useState(""),[h,m]=M.useState(""),[g,b]=M.useState(!1);M.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),M.useEffect(()=>{const k=E=>{u.current&&!u.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const C=async()=>{const k=h.trim();if(!k||g)return;b(!0);const E=await s({tabId:n,label:l.trim(),command:k,cwd:e});b(!1),E&&(d(""),m(""))};return r.jsxs("div",{ref:u,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:[r.jsxs("div",{className:"flex items-center mb-2",children:[r.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),r.jsxs("span",{className:"text-fg-faint ml-2",children:[i.length," active"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[r.jsx("input",{value:l,onChange:k=>d(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("input",{value:h,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&C()},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"}),r.jsx("button",{onClick:C,disabled:!h.trim()||g,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),r.jsxs("span",{className:"text-fg-faint",children:["cwd: ",r.jsx("span",{className:"font-mono",children:e})]})]}),i.length===0?r.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):r.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:i.map(k=>{const E=k.lines[k.lines.length-1];return r.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),r.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>a(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),r.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),r.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2934
|
+
`):"",de=`${re} Claude sessions running${K}`;return r.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:[r.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:A?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:A?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:tS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:I!=null?`${I}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:tS("Weekly window (all models)",$),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:O!=null?`${O}%`:"—"})]}),l&&r.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),i&&r.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,d&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),E.length>0&&r.jsx($I,{ref:x,todos:E,open:_,onToggle:()=>S(J=>!J)}),r.jsx("span",{className:"flex-1"}),r.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:de,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(DI,{total:V,inUse:(h==null?void 0:h.inUse)??0,size:"sm"})}),(m==null?void 0:m.state)==="ready"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",m.latest]}):(m==null?void 0:m.state)==="deferred"?r.jsxs("span",{className:"text-amber-300",title:`Waiting for ${m.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",m.latest," installs when idle"]}):(m==null?void 0:m.state)==="downloading"?r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",m.latest,"…"]}):g!=null&&g.behind&&g.latest&&g.channel==="installer"?r.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(()=>{b("error",`Couldn't open URL: ${J}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.latest?r.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]}):r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.135.1"]})]})}const $I=M.forwardRef(function({todos:e,open:t,onToggle:i},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return r.jsxs("div",{ref:s,className:"relative",children:[r.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[r.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),r.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),r.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),r.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&r.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 ${Ii.dialog}`,"data-testid":"footer-todos-popover",children:r.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>r.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[r.jsx(NI,{status:u.status}),r.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function NI({status:n}){return n==="completed"?r.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?r.jsx("span",{className:"w-3 shrink-0",children:r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):r.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function AI(n){const e=Math.max(0,Math.floor(n/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 II({onClose:n,onSent:e}){const t=jt(O=>O.tabs),[i,s]=M.useState(""),[a,u]=M.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[l,d]=M.useState(!1),[h,m]=M.useState({}),g=M.useRef(null),b=M.useRef(e);M.useEffect(()=>{b.current=e},[e]),M.useEffect(()=>{u(O=>{const A={};for(const L of t)A[L.id]=O[L.id]??!0;return A})},[t]),M.useEffect(()=>{var O;(O=g.current)==null||O.focus()},[]),M.useEffect(()=>window.api.pty.onWriteError(A=>{m(L=>A.tabId in L?{...L,[A.tabId]:"skipped"}:L)}),[]),M.useEffect(()=>{if(Object.keys(h).length===0)return;const O=Object.values(h).filter(L=>L==="sent").length,A=window.setTimeout(()=>b.current(O),1500);return()=>window.clearTimeout(A)},[h]);const C=t.filter(O=>a[O.id]).map(O=>O.id),k=C.length,E=Object.keys(h).length>0,_=i.length>0&&k>0&&!l&&!E,S=()=>{if(!_)return;d(!0);const O=jt.getState().tabs,A=new Set(O.map(V=>V.id)),L={};for(const V of C)A.has(V)?(window.api.pty.write({tabId:V,data:i+"\r"}),L[V]="sent"):L[V]="skipped";m(L),d(!1)},x=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),n();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),S())},y=t.length>0&&t.every(O=>a[O.id]),T=()=>{const O=!y;u(Object.fromEntries(t.map(A=>[A.id,O])))},$=Object.values(h).some(O=>O==="skipped"),I=E?$?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return r.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),r.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),r.jsx("textarea",{ref:g,value:i,onChange:O=>s(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"}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:y,onChange:T,className:"accent-accent"}),r.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),r.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(O=>r.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:!!a[O.id],onChange:A=>u(L=>({...L,[O.id]:A.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),h[O.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[O.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.id))})]}),r.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[r.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:S,disabled:!_,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:I})]})]})}function PI({tabId:n,cwd:e,onClose:t}){const i=hm(k=>k.watchersForTab(n)),s=hm(k=>k.add),a=hm(k=>k.remove),u=M.useRef(null),[l,d]=M.useState(""),[h,m]=M.useState(""),[g,b]=M.useState(!1);M.useEffect(()=>{const k=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),M.useEffect(()=>{const k=E=>{u.current&&!u.current.contains(E.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const C=async()=>{const k=h.trim();if(!k||g)return;b(!0);const E=await s({tabId:n,label:l.trim(),command:k,cwd:e});b(!1),E&&(d(""),m(""))};return r.jsxs("div",{ref:u,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:[r.jsxs("div",{className:"flex items-center mb-2",children:[r.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),r.jsxs("span",{className:"text-fg-faint ml-2",children:[i.length," active"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[r.jsx("input",{value:l,onChange:k=>d(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("input",{value:h,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&C()},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"}),r.jsx("button",{onClick:C,disabled:!h.trim()||g,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),r.jsxs("span",{className:"text-fg-faint",children:["cwd: ",r.jsx("span",{className:"font-mono",children:e})]})]}),i.length===0?r.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):r.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:i.map(k=>{const E=k.lines[k.lines.length-1];return r.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),r.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>a(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),r.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),r.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2935
2935
|
* dockview-core
|
|
2936
2936
|
* @version 6.6.1
|
|
2937
2937
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3051,7 +3051,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3051
3051
|
|
|
3052
3052
|
${t}`}const cm={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},q4=["popover","review","diff"],lj=["popover","review"];function K4(n,e){switch(e.type){case"SELECT":return{...cm,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...cm,editCount:n.editCount};case"LISTEN":return lj.includes(n.phase)?{...n,phase:"listening",transcript:"",modelStatus:null}:n;case"HEARD":return n.phase!=="listening"?n:{...n,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return q4.includes(n.phase)?{...n,phase:"thinking",instruction:e.recordInstruction?e.instruction:n.instruction}:n;case"RUN_OK":return n.phase!=="thinking"?n:{...n,phase:"diff",diff:e.diff};case"RUN_ERR":return n.phase!=="thinking"?n:{...n,phase:"popover",transcript:"",diff:null};case"ACCEPT":return n.phase!=="diff"?n:{...cm,editCount:n.editCount+1};case"RESET_FILE":return{...cm,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function Y4(n,e){let t=null;for(const i of e){const s=i.cwd;!s||!(n===s||n.startsWith(s.endsWith("/")?s:`${s}/`))||(t===null||s.length>t.length)&&(t=s)}return t}function X4(n,e,t){var a;let i=null,s=-1/0;for(const u of e){if(u.cwd!==n||u.status!=="dormant")continue;const l=((a=t[u.id])==null?void 0:a.lastEventAt)??0;(i===null||l>s)&&(i=u,s=l)}return i}const J4="sonnet";function Z4(n,e){const[t,i]=M.useReducer(K4,cm),s=M.useRef(0),a=M.useRef(null),u=M.useRef(n),l=M.useRef(new Map);M.useEffect(()=>window.api.docEdit.onSessionResult(y=>{const T=l.current.get(y.requestId);T&&(l.current.delete(y.requestId),T(y))}),[]),M.useEffect(()=>{u.current!==n&&(u.current=n,s.current+=1,d(),i({type:"RESET_FILE"}))},[n]);function d(){const y=a.current;y&&(a.current=null,y.stop().catch(()=>{}),y.destroy(),Vt.setState({externalRecording:!1}))}const h=M.useCallback(y=>{s.current+=1,d(),i({type:"SELECT",selection:y})},[]),m=M.useCallback(()=>{s.current+=1,d(),i({type:"CANCEL"})},[]),g=M.useCallback(()=>{if(!lj.includes(t.phase))return;if(Vt.getState().isRecording){ze.error("Microphone is already in use");return}if(!qx()){ze.error("Microphone or Web Worker not available");return}const y=++s.current;i({type:"LISTEN"}),Vt.setState({externalRecording:!0});const T=()=>{a.current===$&&(a.current=null),Vt.setState({externalRecording:!1})},$=P2({onFinal:I=>{if(s.current!==y)return;$.stop().catch(()=>{}),$.destroy(),T();const O=I.trim();if(!O){i({type:"CANCEL"});return}i({type:"HEARD",transcript:O})},onError:I=>{s.current===y&&($.destroy(),T(),ze.error(`Microphone error: ${I}`),i({type:"CANCEL"}))},onModelStatus:(I,O)=>{s.current===y&&i({type:"MODEL_STATUS",status:I,message:O})},onProgress:I=>{s.current===y&&i({type:"MODEL_STATUS",status:"loading",message:`${I}%`})}});a.current=$,$.start().catch(I=>{s.current===y&&($.destroy(),T(),ze.error(`Could not start mic: ${I instanceof Error?I.message:String(I)}`),i({type:"CANCEL"}))})},[t.phase]),b=M.useCallback(()=>{const y=Y4(n,jt.getState().tabs);if(!y)return null;const T=X4(y,jt.getState().tabs,Jv.getState().tabs);return!T||wn.getState().get(T.id).running?null:T},[n]),C=M.useCallback((y,T,$,I,O,A)=>{const L=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(V=>{l.current.set(L,V),window.api.docEdit.runInSession({tabId:y,sessionId:T,cwd:$,before:I,instruction:O,documentText:A,requestId:L})})},[]),k=M.useCallback(async(y,T)=>{const $=t.selection;if(!$)return;const I=++s.current;i({type:"RUN",instruction:y,recordInstruction:T});const O=V4(e);try{const A=b(),L=A?await C(A.id,A.sessionId,A.cwd,$.text,y,O):await window.api.docEdit.run({path:n,before:$.text,instruction:y,documentText:O});if(s.current!==I)return;if(!L.ok){ze.error(L.error||"Edit failed"),i({type:"RUN_ERR"});return}i({type:"RUN_OK",diff:{before:$.text,after:L.after??""}})}catch(A){if(s.current!==I)return;ze.error(A instanceof Error?A.message:"Edit failed"),i({type:"RUN_ERR"})}},[n,t.selection,e,b,C]),E=M.useCallback(y=>{k(y,!0)},[k]),_=M.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),S=M.useCallback(()=>{const y=t.instruction;y&&k(`${y}
|
|
3053
3053
|
|
|
3054
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),x=M.useCallback(y=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const $=W4(y,T.before,T.after);return $.ok?(s.current+=1,i({type:"ACCEPT"})):ze.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[t.diff]);return{state:t,select:h,cancel:m,listen:g,sendHeard:_,run:E,retry:S,accept:x}}const Q4=[{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."}],mk=320,Jf=8;function eB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function tB(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,Jf),Math.max(Jf,e-mk-Jf)),i=Math.max(n.top-Jf,Jf);return{position:"fixed",left:t,top:i,width:mk,transform:"translateY(-100%)",zIndex:YN.dialog}}function nB({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:d,onSendHeard:h,onCancel:m,onAccept:g,onReject:b,onRetry:C}){const[k,E]=M.useState(""),[_,S]=M.useState(!1),x=Wi(I=>I.show),y=M.useRef(null);M.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const T=async()=>{if(!await Vo(t)){x("error","Copy failed");return}S(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>S(!1),1500)},$=()=>{const I=k.trim();I&&(l(I),E(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:tB(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&r.jsxs("div",{className:"p-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:_?"Copied":"Copy"}),r.jsx("button",{onClick:d,"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"}),Q4.map(I=>r.jsx("button",{onClick:()=>u(I.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:I.label},I.label))]}),r.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),r.jsx("input",{value:k,onChange:I=>E(I.target.value),onKeyDown:I=>{I.key==="Enter"?$():I.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&r.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[r.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(eB,{}),"Listening…"]}),a&&r.jsx("span",{className:"text-[10px] text-fg-faint",children:a})]}),r.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[r.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsxs("div",{className:"p-3 flex items-center justify-between",children:[r.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),r.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&r.jsxs("div",{className:"p-3",children:[r.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:C,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function iB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function gk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:d,onReject:h,onRetry:m}){return r.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[r.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),r.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Dm(J4)})]}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&r.jsxs("div",{className:"text-fg-faint",children:[r.jsx("p",{children:"Select text in the doc…"}),r.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),n==="popover"&&r.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&r.jsxs("div",{children:[r.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[r.jsx(iB,{}),"Listening…"]}),s&&r.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),r.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{children:[r.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&t&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-3 space-y-2",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function sB(){const n=jt(t=>t.tabs),e=jt(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function rB({path:n,onRenamed:e,onDeleted:t}){const[i,s]=M.useState(!1),[a,u]=M.useState(!1),[l,d]=M.useState(""),[h,m]=M.useState(!1),g=An(V=>V.buffers[n]),b=An(V=>V.openFile),C=An(V=>V.renameOpenFile),k=An(V=>V.closeFile),E=sB(),_=xo(n),S=()=>s(!1),x=()=>{d(_),u(!0),S()},y=async()=>{const V=l.trim();if(!V||V===_){u(!1);return}try{const te=await window.api.files.rename(n,V);if(te.ok){const re=n.slice(0,n.lastIndexOf("/")),K=te.newPath??`${re}/${V}`;C(n,K),e==null||e(n,K),ze.info(`Renamed to ${V}`)}else ze.error(te.error??`Couldn't rename ${_}`)}catch(te){ze.error(te instanceof Error?te.message:`Couldn't rename ${_}`)}u(!1)},T=async()=>{S();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(b(V.path),ze.info(`Duplicated as ${xo(V.path)}`)):ze.error(V.error??`Couldn't duplicate ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't duplicate ${_}`)}},$=async()=>{try{const V=await window.api.files.delete(n);V.ok?(k(n),t==null||t(n),ze.info(`Deleted ${_}`)):ze.error(V.error??`Couldn't delete ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't delete ${_}`)}m(!1)},I=async()=>{S();const V=g??"";await Vo(V)?ze.info(`Copied ${V.length} chars`):ze.error(`Couldn't copy ${_}`)},O=()=>{if(S(),!E){ze.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${n} `}),ze.info(`Added ${_} to Claude context`)},A=()=>{S(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't open ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't open ${_}`))},L=()=>{S(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't reveal ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't reveal ${_}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(V=>!V),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:"Document actions",children:"Document ▾"}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:S}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[r.jsx(v_,{children:"Edit"}),r.jsx(wd,{label:"Rename",onClick:x}),r.jsx(wd,{label:"Duplicate",onClick:T}),r.jsx(wd,{label:"Delete document",danger:!0,onClick:()=>{S(),m(!0)}}),r.jsx(vk,{}),r.jsx(v_,{children:"Open"}),r.jsx(wd,{label:"Open in default app",onClick:A}),r.jsx(wd,{label:"Reveal in OS",onClick:L}),r.jsx(vk,{}),r.jsx(v_,{children:"Export"}),r.jsx(wd,{label:"Copy as Markdown",onClick:I}),r.jsx(wd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(oB,{value:l,onChange:d,onCancel:()=>u(!1),onConfirm:()=>void y()}),h&&r.jsx(aB,{name:_,onCancel:()=>m(!1),onConfirm:()=>void $()})]})}function v_({children:n}){return r.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function wd({label:n,onClick:e,danger:t,disabled:i,title:s}){return r.jsx("button",{onClick:e,disabled:i,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function vk(){return r.jsx("div",{className:"my-1 border-t border-line"})}function oB({value:n,onChange:e,onCancel:t,onConfirm:i}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),r.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?i():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function aB({name:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function lB(){const[n,e]=M.useState(!1),t=$d();return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>e(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:()=>e(!1)}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[r.jsx(Eh,{label:"Text size",children:r.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[r.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−"}),r.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),r.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+"})]})}),r.jsx(Eh,{label:"Word wrap",children:r.jsx(Iv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx(Eh,{label:"Minimap",children:r.jsx(Iv,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx(Eh,{label:"Theme",children:r.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"})}),r.jsx(Eh,{label:"Autosave",children:r.jsx(Iv,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx(Eh,{label:"Wide measure",children:r.jsx(Iv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Eh({label:n,children:e}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Iv({on:n,onClick:e}){return r.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const cB=M.lazy(()=>Kn(()=>import("./TiptapBody-CJFGfBdz.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Pv(n,e){if(!e.length)return n;const t=new Set(e),i={};for(const[s,a]of Object.entries(n))t.has(s)||(i[s]=a);return i}function Zf(n){const e=n.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",i=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||i===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||i==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function Rv(n){return uD(n)||hD(n)}function dB(){const n=jy(),e=An(Ue=>Ue.openFiles),t=An(Ue=>Ue.activeFilePath),i=An(Ue=>Ue.dirty),s=An(Ue=>Ue.viewMode),a=An(Ue=>Ue.buffers),u=An(Ue=>Ue.setActive),l=An(Ue=>Ue.closeFile),d=An(Ue=>Ue.closeOthers),h=An(Ue=>Ue.closeToTheRight),m=An(Ue=>Ue.closeAll),g=An(Ue=>Ue.loadBuffer),b=An(Ue=>Ue.setBuffer),C=An(Ue=>Ue.markSaved),k=An(Ue=>Ue.setViewMode),E=$d(),[_,S]=M.useState({}),[x,y]=M.useState({}),[T,$]=M.useState(null),[I,O]=M.useState(null),[A,L]=M.useState(!1),[V,te]=M.useState(!1),[re,K]=M.useState(!0),de=M.useRef(null),J=M.useRef(null),he=M.useRef(void 0),Ce=M.useRef(null),ve=M.useRef(null),F=Z4(t??"",a[t??""]??""),q=M.useCallback((Ue,xt)=>{b(Ue,xt),Zf(Ue)&&Ca.getState().setDraft(Ue,xt)},[b]),W=M.useCallback(Ue=>{de.current=Ue},[]),Q=M.useCallback(()=>de.current,[]);M.useEffect(()=>{ZO()},[]),M.useEffect(()=>{const Ue=t;if(!Ue||Rv(Ue))return;if(An.getState().hasBuffer(Ue)){S(yt=>yt[Ue]==="ready"?yt:{...yt,[Ue]:"ready"});return}let xt=!1;return S(yt=>({...yt,[Ue]:"loading"})),Zf(Ue)?((async()=>{if(await Ca.getState().loadText(Ue,!0),xt)return;const yt=Ca.getState().files[Ue];if(!yt||yt.loadError&&!yt.exists){S(Qt=>({...Qt,[Ue]:{error:(yt==null?void 0:yt.loadError)??"failed to read"}}));return}g(Ue,yt.diskRaw),yt.dirty&&An.getState().setBuffer(Ue,yt.draftRaw),S(Qt=>({...Qt,[Ue]:"ready"}))})(),()=>{xt=!0}):(window.api.files.read(Ue).then(yt=>{xt||(yt.binary?S(Qt=>({...Qt,[Ue]:{binary:!0,size:yt.size??0,mime:yt.mime??"application/octet-stream",reason:yt.error??"Binary file"}})):yt.ok?(g(Ue,yt.text),S(Qt=>({...Qt,[Ue]:"ready"}))):S(Qt=>({...Qt,[Ue]:{error:yt.error??"failed to read"}})))}),()=>{xt=!0})},[t,g]),M.useEffect(()=>{O(null)},[t]);const le=M.useCallback(async(Ue,xt=!1)=>{const yt=An.getState().buffers[Ue];if(yt==null)return;xt&&L(!0);const Qt=Zf(Ue);let Cn;if(Qt){const Xn=Ca.getState();if(Xn.setDraft(Ue,yt),Cn=await Xn.saveText(Ue),!Cn.ok&&Cn.error==="conflict"){xt&&L(!1);return}}else Cn=await window.api.files.write(Ue,yt);Cn.ok?(C(Ue),y(Xn=>({...Xn,[Ue]:(Xn[Ue]??0)+1})),xt||ze.info(`Saved ${xo(Ue)}`)):ze.error(Cn.error??`Couldn't save ${xo(Ue)}`),xt&&L(!1)},[C]);M.useEffect(()=>{if(!E.autosave)return;const Ue=t;if(!(!Ue||Rv(Ue)||Zf(Ue)||!i[Ue]))return window.clearTimeout(he.current),he.current=window.setTimeout(()=>{le(Ue,!0)},1200),()=>window.clearTimeout(he.current)},[E.autosave,t,i,a,le]);const fe=M.useCallback(Ue=>{Ue.length&&(S(xt=>Pv(xt,Ue)),y(xt=>Pv(xt,Ue)))},[]),Ie=M.useCallback((Ue,xt)=>{S(yt=>Ue in yt?{...Pv(yt,[Ue]),[xt]:yt[Ue]}:yt),y(yt=>Ue in yt?{...Pv(yt,[Ue]),[xt]:yt[Ue]}:yt)},[]),He=M.useCallback(Ue=>{i[Ue]?$({kind:"one",path:Ue}):(l(Ue),fe([Ue]))},[i,l,fe]),me=M.useCallback(Ue=>{e.some(yt=>yt.path!==Ue&&i[yt.path])?$({kind:"others",path:Ue}):(d(Ue),fe(e.filter(yt=>yt.path!==Ue).map(yt=>yt.path)))},[e,i,d,fe]),ee=M.useCallback(Ue=>{const xt=e.findIndex(Qt=>Qt.path===Ue);xt!==-1&&e.slice(xt+1).some(Qt=>i[Qt.path])?$({kind:"right",path:Ue}):(h(Ue),fe(xt!==-1?e.slice(xt+1).map(Qt=>Qt.path):[]))},[e,i,h,fe]);M.useEffect(()=>{const Ue=xt=>{if(n.current)if((xt.metaKey||xt.ctrlKey)&&(xt.key==="s"||xt.key==="S")){const yt=An.getState().activeFilePath;yt&&!Rv(yt)&&(xt.preventDefault(),le(yt))}else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="f"||xt.key==="F"))xt.preventDefault(),te(yt=>!yt);else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="w"||xt.key==="W")){const yt=An.getState().activeFilePath;yt&&An.getState().openFiles.length>1&&(xt.preventDefault(),me(yt))}else xt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():xt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[le,V,me,F.state.phase,F.cancel]),M.useEffect(()=>{if(F.state.phase==="idle")return;const Ue=xt=>{var Qt,Cn;const yt=xt.target;(Qt=ve.current)!=null&&Qt.contains(yt)||(Cn=Ce.current)!=null&&Cn.contains(yt)||F.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[F.state.phase,F.cancel]),M.useEffect(()=>{F.cancel()},[t,F.cancel]);const $e=M.useCallback(()=>{e.some(xt=>i[xt.path])?$({kind:"all",path:""}):(m(),S({}),y({}))},[e,i,m]),Ee=()=>{if(T){if(T.kind==="one")l(T.path),fe([T.path]);else if(T.kind==="others"){const Ue=e.filter(xt=>xt.path!==T.path).map(xt=>xt.path);d(T.path),fe(Ue)}else if(T.kind==="right"){const Ue=e.findIndex(yt=>yt.path===T.path),xt=Ue!==-1?e.slice(Ue+1).map(yt=>yt.path):[];h(T.path),fe(xt)}else m(),S({}),y({});$(null)}};if(e.length===0)return r.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"mb-2",children:"no file open"}),r.jsxs("div",{children:["open the ",r.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Te=t,be=Te?xo(Te):"",Qe=Te?_[Te]:void 0,vt=Te?mD(Te):!1,lt=Te?KO(Te):!1,$t=Te&&vt?s[Te]??YO(Te):"edit",We=!!Te&&!Rv(Te)&&Qe==="ready",Ht=We,Ct=lt?["edit","wysiwyg","preview","split"]:vt?["edit","preview"]:[],sn=Te&&r.jsx(j4,{path:Te,name:be,value:a[Te]??"",onChange:Ue=>q(Te,Ue),onSave:()=>void le(Te),onReady:W,onCursor:O}),un=A?"Saving…":Te&&i[Te]?E.autosave&&!Zf(Te)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&r.jsx(mz,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:He,onCloseOthers:me,onCloseToTheRight:ee,onCloseAll:$e}),Te&&!V&&r.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[r.jsx("span",{className:"text-xs font-medium text-fg truncate",children:be}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Te}),We&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",un]}),rl(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:()=>K(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${re?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),rl(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Ct.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:Ct.map(Ue=>r.jsx("button",{onClick:()=>k(Te,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${$t===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),r.jsx("div",{className:"flex-1"}),r.jsx(rB,{path:Te,onRenamed:Ie,onDeleted:Ue=>fe([Ue])}),We&&r.jsx(lB,{}),r.jsx("button",{onClick:()=>te(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&r.jsx("button",{onClick:()=>te(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),r.jsx("div",{className:"flex-1 min-h-0",children:Te?uD(Te)?r.jsx(M4,{path:Te,name:be}):hD(Te)?r.jsx(O4,{path:Te}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(H4,{path:Te,name:be,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?r.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):$t==="wysiwyg"&&rl(Te)?r.jsx(M.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(cB,{value:a[Te]??"",onChange:Ue=>q(Te,Ue)},Te)}):$t==="split"&&rl(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[re&&r.jsx(hk,{text:a[Te]??"",scrollRef:J}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(uk,{getEditor:Q}),r.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx($x,{ref:J,text:a[Te]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(gk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&rl(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[re&&r.jsx(hk,{text:a[Te]??"",scrollRef:J}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx($x,{ref:J,text:a[Te]??"",wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(gk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&dD(Te)?r.jsx(P4,{path:Te,dirty:!!i[Te],reloadToken:x[Te]??0}):$t==="preview"&&pD(Te)?r.jsx(z4,{path:Te,text:a[Te]??""}):$t==="preview"&&fD(Te)?r.jsx(G4,{path:Te,text:a[Te]??""}):rl(Te)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(uk,{getEditor:Q}),r.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),Ht&&r.jsx(I4,{text:a[Te]??"",cursor:I,language:Xr(Te)||void 0}),Te&&rl(Te)&&($t==="preview"||$t==="split")&&F.state.phase!=="idle"&&F.state.selection&&r.jsx("div",{ref:ve,children:r.jsx(nB,{phase:F.state.phase,rect:F.state.selection.rect,selectedText:F.state.selection.text,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)}})}),T&&r.jsx(uB,{message:T.kind==="one"?`Discard unsaved changes to ${xo(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:()=>$(null),onConfirm:Ee})]})}const Gw=M.memo(dB);function uB({message:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const hB="~/.claude/session-manager/projects-prefs.json";let xk=Promise.resolve(),Mv=null;function bk(n){const e=xk.then(n);return xk=e.catch(()=>{}),e}const cj=()=>ja(hB);async function _k(){const n=(await cj().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const x_=Ei(n=>({pinned:{},hydrated:!1,hydrate:()=>Mv||(Mv=bk(async()=>{try{n({pinned:await _k(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Mv),togglePin:e=>{bk(async()=>{let t;try{t=await _k()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const i={...t};i[e]?delete i[e]:i[e]=!0;try{await cj().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function pB(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function fB(n,e,t){const i=M.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(pB))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;M.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const u=window.api.config.onChanged(l=>{s.includes(l.path)&&i.current(l.path)});return()=>{u(),window.api.config.unwatch(s,t)}},[a])}function c0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function dj(n){return n.split(/[\\/]+/).filter(Boolean)}function uj(n){const e=dj(n);return e.length?e[e.length-1]:n}function wk(n){const e=n.length>1?n.replace(/[\\/]+$/,""):n,t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t<0?"":t===0?e.slice(0,1):/^[A-Za-z]:$/.test(e.slice(0,t))?e.slice(0,t+1):e.slice(0,t)}function hj(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=c0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const yk=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Rm(n,e){return yk(n).startsWith(yk(e)+"/")}const Hw="reveal:";function EV(n){En.getState().openPanel("projects",Hw+n)}function mB(n){return n.startsWith(Hw)&&n.slice(Hw.length)||null}const gB=/^[A-Za-z]:$/;function Sk(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(gB.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function pj(n,e){const t=Sk(n),i=Sk(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function vB(n){const e=await Kh(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function xB(n,e){return vc(n,{fileTreeExpanded:[...e].slice(0,500)})}async function bB(){const n=await sb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function _B(n){rb({fileTreeShowHidden:n}).catch(()=>{})}function b_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Rm(s,e)){t=!0;continue}i.add(s)}return t?i:n}const Ck=(n,e)=>`${e?1:0}:${n}`,__={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:"!"}},wB=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 yB(n){const e=Xr(n);return wB.has(e)||cD.has(e)||e==="pdf"}function SB(n,e){if(e)return"#d97757";switch(Xr(n)){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 Qf(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const kk=64,CB=250,kB={depth:0};function w_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function EB({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=jy(),l=Kx(),[d,h]=M.useState([]),m=M.useRef(d);m.current=d;const[g,b]=M.useState(null),C=M.useRef(null),k=M.useRef(null),[E,_]=M.useState(0),[S,x]=M.useState(null),[y,T]=M.useState(null),$=M.useRef(null),[I,O]=M.useState(0),A=M.useRef(a);A.current=a;const[L,V]=M.useState(new Set),te=M.useRef(L);te.current=L;const re=M.useRef(!1),[K,de]=M.useState(""),[J,he]=M.useState(!0),Ce=M.useRef(!1);M.useEffect(()=>{let it=!1;return bB().then(mt=>{!it&&!Ce.current&&he(mt)}),()=>{it=!0}},[]);const ve=M.useCallback(it=>{Ce.current=!0,he(mt=>{const Pt=typeof it=="function"?it(mt):it;return _B(Pt),Pt})},[]),[F,q]=M.useState(!1),[W,Q]=M.useState(null),[le,fe]=M.useState({}),[Ie,He]=M.useState(null),[me,ee]=M.useState(null),[$e,Ee]=M.useState(""),[Te,be]=M.useState(null),[Qe,vt]=M.useState(""),[lt,$t]=M.useState(null),We=M.useRef(null),Ht=M.useRef(null),Ct=M.useRef(0),sn=M.useCallback(async()=>{if(!n)return;const it=++Ct.current;q(!0),Q(null);const mt=await window.api.files.list(n,J);Ct.current===it&&(mt.ok?h(mt.entries.map(Pt=>({...Pt}))):(Q(mt.error??"failed to list"),h([])),T(Ck(n,J)),q(!1))},[n,J]),un=M.useCallback(async it=>{const mt=Ct.current,Pt=new Map;for(const Mn of it){const Gn=dj(Mn).length,Hn=Pt.get(Gn);Hn?Hn.push(Mn):Pt.set(Gn,[Mn])}const At=[];for(const Mn of[...Pt.keys()].sort((Gn,Hn)=>Gn-Hn)){const Gn=Pt.get(Mn),Hn=await Promise.all(Gn.map(async rt=>({p:rt,result:await window.api.files.list(rt,J)})));if(Ct.current!==mt)return At;for(const{p:rt,result:fn}of Hn)fn.ok?h(Jn=>dm(Jn,rt,fn.entries.map(Zn=>({...Zn})),te.current)):At.push(rt)}return At},[J]),Ue=M.useCallback(async it=>(await sn(),it.length?un(it):[]),[sn,un]);M.useEffect(()=>{de(""),ee(null),He(null),be(null),$t(null),fe({}),b(null);let it=!1;return re.current=!1,(async()=>{const[mt]=await Promise.all([vB(n),sn()]);if(it)return;if(!re.current){const At=new Set(mt);te.current=At,V(At)}if(x(n),!mt.length)return;const Pt=await un(mt);it||!Pt.length||xn(At=>{const Mn=new Set;let Gn=!1;for(const Hn of At){if(Pt.some(rt=>Hn===rt||Rm(Hn,rt))){Gn=!0;continue}Mn.add(Hn)}return Gn?Mn:At})})(),Qf(n).then(mt=>{it||fe(mt)}),()=>{it=!0}},[n]);const xt=M.useRef(!0);M.useEffect(()=>{if(xt.current){xt.current=!1;return}Ue([...te.current])},[J]),M.useEffect(()=>{if(!n||!l)return;Qf(n).then(fe);const it=window.setInterval(()=>{Qf(n).then(fe)},5e3);return()=>window.clearInterval(it)},[n,l]);const yt=M.useMemo(()=>{if(!n)return[];const it=[...L].filter(mt=>mt!==n);return[n,...it.slice(-63)]},[n,L]),Qt=M.useRef(!1);M.useEffect(()=>{!n||L.size+1<=kk||Qt.current||(Qt.current=!0,console.warn(`FileTree: watching only ${kk} of ${L.size+1} folders (cap reached)`))},[n,L]);const Cn=M.useRef(new Map),Xn=M.useRef(new Set),mn=M.useRef(!1);mn.current=me!==null||Te!==null;const Rn=M.useRef(()=>{});Rn.current=it=>{if(!(it!==w_(n)&&!te.current.has(it))){if(mn.current){Xn.current.add(it);return}it===w_(n)?Ue([...te.current]):ot(it)}},fB(yt,it=>{if(it!==w_(n)&&!te.current.has(it))return;const mt=Cn.current,Pt=mt.get(it);Pt&&clearTimeout(Pt),mt.set(it,setTimeout(()=>{mt.delete(it),Rn.current(it)},CB))},kB),M.useEffect(()=>{if(me!==null||Te!==null)return;const it=[...Xn.current];Xn.current.clear();for(const mt of it)Rn.current(mt)},[me,Te]),M.useEffect(()=>{const it=Cn.current,mt=Xn.current;return()=>{for(const Pt of it.values())clearTimeout(Pt);it.clear(),mt.clear()}},[n]),M.useEffect(()=>{if(!Ie)return;const it=()=>He(null),mt=Pt=>{u.current&&Pt.key==="Escape"&&He(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",mt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",mt)}},[Ie]),M.useEffect(()=>{me&&setTimeout(()=>{var it;return(it=We.current)==null?void 0:it.select()},30)},[me]),M.useEffect(()=>{Te&&setTimeout(()=>{var it;return(it=Ht.current)==null?void 0:it.focus()},30)},[Te]);const xn=M.useCallback(it=>{const mt=te.current,Pt=it(mt);Pt!==mt&&(re.current=!0,te.current=Pt,V(Pt),xB(n,Pt).catch(()=>{te.current===Pt&&(te.current=mt,V(mt),ze.error("Couldn't save folder expansion — reverted."))}))},[n]),Fn=M.useCallback(async it=>{if(L.has(it.path)){xn(Pt=>b_(Pt,it.path));return}if(xn(Pt=>new Set(Pt).add(it.path)),it.children)return;const mt=await window.api.files.list(it.path,J);mt.ok&&h(Pt=>dm(Pt,it.path,mt.entries.map(At=>({...At})),te.current))},[L,J,xn]),ot=M.useCallback(async it=>{if(it===n){await sn();return}const mt=await window.api.files.list(it,J);mt.ok&&h(Pt=>dm(Pt,it,mt.entries.map(At=>({...At})),te.current))},[n,sn,J]),ti=M.useCallback(async(it,mt)=>{const Pt=()=>{var hn;return(hn=A.current)==null?void 0:hn.call(A,it.token)};if(!mt.length){b(null),Pt();return}const At=Ct.current,Mn=mt.slice(0,-1).map((hn,On)=>hj(n,...mt.slice(0,On+1))),Gn=await Promise.all(Mn.map(hn=>window.api.files.list(hn,J)));if(Ct.current!==At){$.current=null,O(hn=>hn+1);return}let Hn=m.current;const rt=[];let fn=null,Jn="not found";for(let hn=0;hn<mt.length;hn++){const On=Hn.find(ui=>ui.name===mt[hn]);if(!On)break;if(hn===mt.length-1){fn=On;break}const vi=Gn[hn];if(!On.isDirectory)break;if(!vi.ok){Jn=vi.error??"could not list its folder";break}const Et=vi.entries.map(ui=>({...ui}));rt.push({path:On.path,children:Et}),Hn=Et}if(!fn){ze.error(`Couldn't reveal ${it.path}: ${Jn}`),Pt();return}const Zn=rt.map(hn=>hn.path);xn(hn=>Zn.every(On=>hn.has(On))?hn:new Set([...hn,...Zn])),h(hn=>rt.reduce((On,vi)=>dm(On,vi.path,vi.children,te.current),hn)),de(""),Q(null),b(fn.path),_(hn=>hn+1),Pt()},[n,J,xn]);M.useEffect(()=>{var mt;if(!s||$.current===s.token||S!==n||y!==Ck(n,J)||F)return;const it=pj(s.path,n);if(!it){$.current=s.token,ze.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(mt=A.current)==null||mt.call(A,s.token);return}if(it.some(Pt=>Pt.startsWith("."))&&(Ce.current=!0,!J)){he(!0);return}$.current=s.token,ti(s,it)},[s,S,y,F,n,J,I,ti]),M.useEffect(()=>{if(!E)return;const it=k.current,mt=C.current;it&&mt&&Vm(it,mt,{block:"nearest"})},[E]);const hs=M.useCallback(it=>{if(it.isDirectory){Fn(it);return}yB(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[Fn,e]),Mi=M.useCallback(it=>{if(t){t(it);return}if(i){const mt=Rm(it,n)?it.slice(n.replace(/[\\/]+$/,"").length+1):it;window.api.pty.write({tabId:i,data:`@${mt} `})}},[t,i,n]),Oi=M.useCallback((it,mt)=>{it.preventDefault(),it.stopPropagation(),He({x:it.clientX,y:it.clientY,node:mt})},[]),Sn=it=>{ee(it.path),Ee(it.name)},gi=async()=>{if(!me)return;const it=$e.trim();if(!it){ee(null);return}const mt=await window.api.files.rename(me,it);if(ee(null),mt.ok){const Pt=wk(me);xn(At=>b_(At,me)),await ot(Pt||n),Qf(n).then(fe)}else{const Pt=mt.error??"rename failed";Q(Pt),ze.error(Pt)}},In=async()=>{if(!Te)return;const it=Qe.trim();if(!it){be(null),vt("");return}const mt=await window.api.files.create(Te.parent,it,Te.kind);if(be(null),vt(""),mt.ok)await ot(Te.parent),Te.kind==="folder"&&xn(Pt=>new Set(Pt).add(Te.parent));else{const Pt=mt.error??"create failed";Q(Pt),ze.error(Pt)}},rs=async()=>{if(!lt)return;const it=await window.api.files.delete(lt.path),mt=wk(lt.path);if($t(null),it.ok)xn(Pt=>b_(Pt,lt.path)),await ot(mt||n),Qf(n).then(fe);else{const Pt=it.error??"delete failed";Q(Pt),ze.error(Pt)}},Dn=M.useMemo(()=>{if(!K.trim())return d;const it=K.toLowerCase();return d.filter(mt=>mt.name.toLowerCase().includes(it))},[d,K]),yi=(n?uj(n):"")||"project";return r.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[r.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[r.jsx(mj,{size:14,className:"shrink-0 text-accent"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs font-medium text-fg truncate",children:yi}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:sn,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:F,children:r.jsx(IB,{size:12,className:F?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:K,onChange:it=>de(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"})})]}),r.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[r.jsx("button",{onClick:()=>be({parent:n,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:r.jsx(PB,{size:12})}),r.jsx("button",{onClick:()=>be({parent:n,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:r.jsx(RB,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>ve(it=>!it),className:`p-1.5 rounded transition-colors ${J?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:J?"Hide hidden files":"Show hidden files",children:J?r.jsx(MB,{size:12}):r.jsx(OB,{size:12})})]}),r.jsxs("div",{ref:k,className:"flex-1 overflow-y-auto py-1",children:[W&&r.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:W}),!W&&Dn.length===0&&!F&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:K?"no matches":"empty folder"}),!W&&r.jsx(fj,{nodes:Dn,depth:0,expanded:L,gitStatus:le,renaming:me,selected:g,selectedRowRef:C,onSelect:b,renameValue:$e,renameInputRef:We,onRenameChange:Ee,onRenameCommit:gi,onRenameCancel:()=>ee(null),onToggleDir:Fn,onFileClick:hs,onSendToChat:Mi,onContextMenu:Oi})]}),r.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"}),Ie&&r.jsx(TB,{x:Ie.x,y:Ie.y,node:Ie.node,onClose:()=>He(null),onRename:()=>{Sn(Ie.node),He(null)},onDelete:()=>{$t(Ie.node),He(null)},onNewFile:()=>{be({parent:Ie.node.path,kind:"file"}),He(null)},onNewFolder:()=>{be({parent:Ie.node.path,kind:"folder"}),He(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Ie.node.path}),He(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Ie.node.path}),He(null)},onCopyPath:()=>{const it=Ie.node.path;Vo(it).then(mt=>{mt||ze.error("Couldn't copy path")}),He(null)},onSendToChat:()=>{Mi(Ie.node.path),He(null)}}),Te&&r.jsx(Ek,{title:`New ${Te.kind}`,subtitle:`in ${DB(Te.parent)}`,onCancel:()=>{be(null),vt("")},onConfirm:In,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:Ht,value:Qe,onChange:it=>vt(it.target.value),onKeyDown:it=>{it.key==="Enter"&&In(),it.key==="Escape"&&(be(null),vt(""))},placeholder:Te.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"})}),lt&&r.jsx(Ek,{title:`Delete ${lt.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>$t(null),onConfirm:rs,confirmLabel:"Delete",danger:!0,children:r.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",r.jsxs("span",{className:"text-fg font-medium",children:['"',lt.name,'"']})," to the trash?",lt.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function fj(n){const{nodes:e,depth:t,expanded:i,gitStatus:s,renaming:a,selected:u,onContextMenu:l}=n;return r.jsx(r.Fragment,{children:e.map(d=>{const h=i.has(d.path),m=a===d.path,g=u===d.path,b=s[d.path],C=SB(d.name,d.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:g?n.selectedRowRef:void 0,"data-path":d.path,"data-selected":g?"true":void 0,className:`group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi ${g?"bg-accent/15":""}`,style:{paddingLeft:`${8+t*14}px`},onClick:()=>{m||(n.onSelect(d.path),d.isDirectory?n.onToggleDir(d):n.onFileClick(d))},onDoubleClick:()=>{d.isDirectory||window.api.shell.open({as:"openPath",path:d.path})},onContextMenu:k=>l(k,d),children:[d.isDirectory?r.jsx(AB,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),d.isDirectory?h?r.jsx($B,{size:12,color:C}):r.jsx(mj,{size:12,color:C}):r.jsx(NB,{size:12,color:C}),m?r.jsx("input",{ref:n.renameInputRef,value:n.renameValue,onChange:k=>n.onRenameChange(k.target.value),onClick:k=>k.stopPropagation(),onBlur:n.onRenameCommit,onKeyDown:k=>{k.key==="Enter"&&n.onRenameCommit(),k.key==="Escape"&&n.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"}):r.jsx("span",{className:`flex-1 truncate text-xs ${d.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:d.name}),b&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:__[b].color,backgroundColor:`${__[b].color}20`},title:b,children:__[b].label}),!d.isDirectory&&r.jsx("button",{onClick:k=>{k.stopPropagation(),n.onSendToChat(d.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:r.jsx(LB,{size:10})})]}),d.isDirectory&&h&&d.children&&r.jsx(fj,{...n,nodes:d.children,depth:t+1})]},d.path)})})}function TB(n){const{x:e,y:t,node:i}=n;return r.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!i.isDirectory&&r.jsx(Jl,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(Jl,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(Jl,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(y_,{}),r.jsx(Jl,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(Jl,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(y_,{}),r.jsx(Jl,{label:"New file",onClick:n.onNewFile}),r.jsx(Jl,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(y_,{}),r.jsx(Jl,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function Jl({label:n,onClick:e,danger:t}){return r.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:n})}function y_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function Ek(n){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&n.onCancel()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:n.title}),n.subtitle&&r.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:n.subtitle}),r.jsx("div",{className:"mb-4",children:n.children}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:n.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:n.onConfirm,disabled:!!n.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:n.confirmLabel??"OK"})]})]})})}function DB(n){return uj(n)}function dm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:jB(s.children,t,i)}:s.children?{...s,children:dm(s.children,e,t,i)}:s)}function jB(n,e,t){const i=new Map;for(const s of n??[])s.children&&t.has(s.path)&&i.set(s.path,s.children);return i.size?e.map(s=>{const a=s.isDirectory?i.get(s.path):void 0;return a?{...s,children:a}:s}):e}function Na({size:n,children:e,className:t,color:i}){return r.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:i||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function mj({size:n,className:e,color:t}){return r.jsx(Na,{size:n,className:e,color:t,children:r.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 $B({size:n,className:e,color:t}){return r.jsx(Na,{size:n,className:e,color:t,children:r.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 NB({size:n,className:e,color:t}){return r.jsxs(Na,{size:n,className:e,color:t,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function AB({size:n,className:e}){return r.jsx(Na,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function IB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("polyline",{points:"1 20 1 14 7 14"}),r.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 PB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),r.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function RB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.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"}),r.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),r.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function MB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function OB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.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"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function LB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function gj({content:n,children:e,align:t="bottom-right"}){const[i,s]=M.useState(!1),a=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return r.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,i&&r.jsx("span",{role:"tooltip",className:`absolute ${Ii.dialog} ${a} 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:n})]})}function ym(n,e){if(!e)return n;const t=c0(e),i=e.length>1?e.replace(/[\\/]+$/,""):e;if(n===i)return"~";const s=i.endsWith(t)?i:`${i}${t}`;return n.startsWith(s)?`~${t}${n.slice(s.length)}`:n}function S_(n){rb(n).catch(()=>ze.error("Couldn't save File Explorer layout."))}const C_=33,zB=20,BB=60,FB=32;function Tk(n){return Math.min(BB,Math.max(zB,n))}function GB(){const n=jt(F=>F.tabs),e=jt(F=>F.activeTabId),t=n.find(F=>F.id===e)??null,i=En(F=>F.navFace),s=Qx(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=M.useState(C_),[d,h]=M.useState(!1),m=M.useRef(!1),[g,b]=M.useState(!1),C=M.useRef(u);C.current=u;const k=M.useRef(d);k.current=d;const E=M.useRef(null),_=M.useRef(null),S=M.useRef(!1),{projects:x,openProject:y,archiveProjectByCwd:T}=Rd(),$=x_(F=>F.pinned),I=x_(F=>F.togglePin);M.useEffect(()=>{x_.getState().hydrate()},[]),M.useEffect(()=>{let F=!1;return sb().then(q=>{F||m.current||(typeof q.projectsSplitPct=="number"&&Number.isFinite(q.projectsSplitPct)&&l(Tk(q.projectsSplitPct)),typeof q.projectsFileTreeCollapsed=="boolean"&&!S.current&&h(q.projectsFileTreeCollapsed))}),()=>{F=!0}},[]);const O=M.useRef(0),[A,L]=M.useState(null),[V,te]=M.useState(null);WN("projects",F=>{const q=mB(F);q&&L({path:q,token:++O.current})});const re=(t==null?void 0:t.cwd)??null;M.useEffect(()=>{if(!A)return;const{path:F}=A,q=fe=>!!fe&&pj(F,fe)!==null,W=i==="home"?s:re,Q=i==="home"?{face:"project",root:re}:{face:"home",root:s};let le=null;if(q(W))le={face:i,root:W};else{if(s===null)return;q(Q.root)&&(le={face:Q.face,root:Q.root})}if(L(null),!le){window.api.shell.open({as:"revealPath",path:F}).then(fe=>{fe.ok||ze.error(`Couldn't reveal ${F}: ${fe.error??"unknown error"}`)},fe=>ze.error(`Couldn't reveal ${F}: ${fe instanceof Error?fe.message:String(fe)}`));return}le.face!==i&&En.getState().setNavFace(le.face),S.current=!0,h(!1),te({...A,root:le.root})},[A,i,s,re]),M.useEffect(()=>{te(F=>F&&a!==null&&F.root!==a?null:F)},[a]);const K=M.useCallback(F=>{te(q=>q&&q.token===F?null:q)},[]),de=[...x].sort((F,q)=>($[q.cwd]?1:0)-($[F.cwd]?1:0));M.useEffect(()=>{if(!g)return;const F=q=>{_.current&&!_.current.contains(q.target)&&b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[g]);const J=M.useCallback(F=>{An.getState().openFile(F)},[]),he=M.useCallback(F=>{F.preventDefault(),m.current=!0;const q=F.clientX,W=C.current;let Q=W;const le=Ie=>{const He=E.current;if(!He)return;const me=He.getBoundingClientRect(),ee=Ie.clientX-q;Q=Tk(W+ee/me.width*100),l(Q)},fe=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",fe),document.body.style.cursor="",document.body.style.userSelect="",S_({projectsSplitPct:Q})};window.addEventListener("pointermove",le),window.addEventListener("pointerup",fe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),Ce=M.useCallback(()=>{m.current=!0,l(C_),S_({projectsSplitPct:C_})},[]),ve=M.useCallback(()=>{m.current=!0;const F=!k.current;h(F),S_({projectsFileTreeCollapsed:F})},[]);return d?r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:ve,"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:FB},children:[r.jsx("span",{className:"text-[11px]",children:"▸"}),r.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Gw,{})})]}):r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${u}%`},"data-testid":"projects-file-tree-pane",children:[r.jsxs("div",{ref:_,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(F=>!F),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:[r.jsx("span",{className:"flex-1 truncate text-left",children:a?ym(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),r.jsx("button",{onClick:ve,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),g&&r.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Ii.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:de.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):de.map(F=>{const q=ym(F.cwd,s);return r.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[r.jsx(gj,{content:$[F.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>I(F.cwd),className:`shrink-0 text-sm leading-none transition-colors ${$[F.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:$[F.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{y(F.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:q}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${q}?`)&&await T(F)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},F.cwd)})})]}),a?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:a,children:ym(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(EB,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:J,reveal:V&&V.root===a?V:null,onRevealDone:K})})]}):r.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:i==="home"?"Loading home folder…":"No session selected."})]}),r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:he,onDoubleClick:Ce,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Gw,{})})]})}const HB=M.memo(GB),WB={"project-home":{headline:"Pages, Videos and Tools — this project's generated library and its tools",intro:"Project Home is this project's own library, written by builder agents from what they read in the repository. Three key buttons at the top switch the area below them: Pages holds Knowledge Pages (static HTML pages that explain a topic), Videos holds short self-contained HTML/JS videos that show the project, and Tools holds one-press tools for the project, led by Review MD network.",sections:[{title:"The key buttons",items:[{term:"Pages",body:"Opens the knowledge-page library. The badge counts ready pages plus any page being built; the line under the name reads “Nothing generated yet”, “<n> building · <m> ready” while a build runs, or the page count and how long ago the newest page was made."},{term:"Videos",body:"The same, for the video library."},{term:"Tools",body:"Opens the tool list. Once you have opened Tools for this project, an accent badge shows how many findings Review MD network's link map found. Its Expand button (or a click on any doc in the map) opens a full-screen explorer with a doc preview and a Docs table."}]},{title:"Pages and Videos",items:[{term:"The list",body:"One row per page or video; a video row adds a thumbnail, its length, its loudness (LUFS) and its reading grade. Select a row to open it — a page shows in a sandboxed frame where no script runs, a video plays in its player above its SOURCES and QUALITY REPORT cards. Rename and Delete sit under the selected row."},{term:"Generate page / Generate video",body:"Opens the Generate composer. Start from a template — Overview, How it works, FAQ, Getting started, What’s new or Custom topic (you name the topic) for a page; Project demo, Feature spotlight, Blog post, Whiteboard explainer or Custom for a video — then adjust it. A page takes Written for (Newcomers, Users or Contributors), Length (Brief, Standard or In-depth) and Read from (README & docs, Source tree, Git log); a video takes Kind, a Feature or Post target, Style, Length (30 or 60 seconds) and Character on or off. Both take an optional Focus note. Your choices reach the builder as plain lines such as “Audience: Users” or “Video length: 60”."},{term:"Regenerate…",body:"In the selected page's or video's title bar. Opens the composer pre-filled from that entry and rebuilds it in place: the builder also gets a “Replace entry: <id>” line, so you end up with one updated entry, not a second copy."},{term:"While it builds",body:"A build runs in the background as a scheduler job in the builder's Session, so Project Home stays put. A building row sits at the top of the list (or the regenerated entry's own row turns building); select it to see its progress and, for a build started in this window, what was sent to the builder. Open session jumps to that Session. When the build finishes, a toast says “<title>” is ready; a failed build shows its reason in that row's place."},{term:"Empty library",body:"With nothing generated yet, the tab shows a starter gallery with one card per template. A card's Generate builds that template's defaults straight away; Customize opens the composer on it (the Custom topic card asks you to name a topic first)."}]},{title:"Tools",items:[{term:"Review MD network",body:"Always listed first. Its LINK MAP draws CLAUDE.md and the docs its links lead to; FINDINGS lists broken links and docs no link path from CLAUDE.md reaches; records (machine-written docs in a record collection, such as validation records) are left out of orphan findings. The strip above the cards says what the tracked docs are: how many are in the network, how many are records and how many are unlinked. Expand on the LINK MAP, or a click on a doc in it, opens the full-screen explorer: zoom and pan the whole map, search paths, and click a doc to read it in the doc preview (its role, usage, recency and contents, with links you can follow). Its Docs view is a table of every tracked doc you can filter and sort by recency, size, links and code mentions. Pick a Scope and a Mode (Full review or Drift check), then Run review opens an architect Session that reports first and changes no files until you approve. The map is scanned when you first open it and again on Refresh — never on a timer."},{term:"Your tools",body:"Every macro saved with Shown on: Project Home for this project is listed after it. A tool with inputs shows its form; otherwise press Run. Each press starts a new Session and opens it, the same as pressing a hot key."},{term:"Add a tool",body:"Opens the macro editor with Shown on already set to Project Home."}]},{title:"Behaviors this affects",items:[{body:"Pages and videos are folders under session-manager-operations/project-pages/ (knowledge/<id>/ and videos/<id>/). Rename changes only the title in the entry's meta.json; Delete removes the entry's folder."},{body:"A build needs delegation to be ready; if it is not, the press shows why in a toast and nothing is queued. Each library builds one entry at a time — Generate and Regenerate stay disabled while a build is queued or running."}]}],tips:["To refresh an out-of-date page or video, use Regenerate… on it — it replaces that entry instead of adding another.","Videos play only for projects inside your home folder.","The Tools badge stays hidden until you open Tools for this project — Project Home never scans on its own."]},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 Permissions tab of this page 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 of this page."},{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 Extensions › MCP Servers 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:"Merging is per key: Local beats Project beats User. Objects merge key by key, so a Project-scoped { permissions: { allow: [...] } } adds to the user-scoped permissions object instead of replacing it. Lists merge too (allow + allow), and for a plain value the more specific scope wins."}]}],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."]},memory:{headline:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},"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."]},extensions:{headline:"Extensions — skills, MCP servers and plugins in one place",intro:"Three tabs, one page. Each tab edits the real file Claude Code reads (shown as a chip at the top): ~/.claude/skills for skills, ~/.claude.json mcpServers for MCP servers, installed_plugins.json plus settings.json enabledPlugins for plugins. The Add button opens that tab's catalog.",sections:[{title:"Tabs",items:[{term:"Skills",body:"Markdown files Claude loads on demand, at User or Project scope. Each skill has frontmatter saying when to trigger it."},{term:"MCP Servers",body:"External tools Claude can call. User scope lives in ~/.claude.json; project scope in <repo>/.mcp.json."},{term:"Plugins",body:"Bundles of skills, subagents, hooks and MCP servers installed together and enabled per scope."}]}],tips:["Home face only — User-scope config is machine-wide."]},"app-settings":{headline:"App Settings — Session Manager's own preferences",intro:"Everything here configures this app, not Claude Code: voice input, appearance, telemetry, phone remote, updates and retention, startup behavior, and a map of where the app stores its data. Claude Code's own settings.json lives on the Settings page.",sections:[{title:"Tabs",items:[{term:"Voice",body:"On-device transcription, push-to-talk hotkey, microphone and text-to-speech."},{term:"Storage map",body:"A hand-maintained ERD of what Session Manager persists, its paths and single-writer owners."}]}],tips:["Home face only — these preferences are machine-wide."]}};function UB({content:n}){return r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:n.intro}),n.sections.map(e=>r.jsxs("div",{className:"mb-3 last:mb-0",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),r.jsx("ul",{className:"space-y-1",children:e.items.map((t,i)=>r.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&r.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",r.jsx("span",{children:t.body})]},i))})]},e.title)),n.tips&&n.tips.length>0&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),r.jsx("ul",{className:"space-y-1",children:n.tips.map((e,t)=>r.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function VB({active:n}){const e=ss(g=>g.learningPanelCollapsed),t=ss(g=>g.setLearningPanelCollapsed),i=ss(g=>g.hydrated),s=ss(g=>g.hydrate);M.useEffect(()=>{i||s()},[i,s]);const[a,u]=M.useState(()=>!e),l=M.useRef(null);M.useEffect(()=>{i&&u(!e)},[i]);const d=M.useCallback(()=>{u(g=>{const b=!g;return t(!b),b})},[t]);M.useEffect(()=>{if(!a)return;const g=b=>{var C;(C=l.current)!=null&&C.contains(b.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a,t]);const h=M.useRef(!1);M.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const m=WB[n];return m?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:d,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":a,title:a?"Close learning panel":"What is this?",children:"Learn"}),a&&r.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:r.jsx(UB,{content:m})})]}):null}function qB({eyebrow:n,title:e,intro:t,frame:i=!0,learnKey:s,hideTitle:a=!1,children:u}){const l=i&&(n||e||t);return r.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[l&&r.jsxs("header",{className:`shrink-0 px-8 pt-7 flex items-start justify-between gap-4 ${a?"pb-0":"pb-5"}`,children:[r.jsxs("div",{className:"max-w-[820px]",children:[n&&r.jsx("div",{className:`text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint${a?"":" mb-2"}`,children:n}),a?r.jsx("div",{"aria-hidden":"true",className:"h-2","data-testid":"section-frame-title-spacer"}):e&&r.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&r.jsx("p",{className:`text-[14px] text-fg-dim leading-[1.55]${a?"":" mt-3"}`,children:t})]}),s&&r.jsx(VB,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const KB=M.lazy(()=>Kn(()=>import("./History-B4c3Uz9u.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(n=>({default:n.History}))),YB=M.lazy(()=>Kn(()=>import("./Scheduler-D2_5NyiR.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(n=>({default:n.Scheduler}))),XB=M.lazy(()=>Kn(()=>import("./Settings-Clgqb3Lq.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(n=>({default:n.Settings}))),JB=M.lazy(()=>Kn(()=>import("./SystemPrompt-CGlOpUQA.js"),__vite__mapDeps([15,4,8,9,16,10,1,2]),import.meta.url).then(n=>({default:n.SystemPrompt}))),ZB=M.lazy(()=>Kn(()=>import("./ProjectClaudeConfig-DBGhhzg2.js"),__vite__mapDeps([17,11,10,8,9,16,18,7,4,12,13,14,1,2,19,20]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),QB=M.lazy(()=>Kn(()=>import("./Extensions-Kn-oUD2_.js"),__vite__mapDeps([21,10,19,4,13,8,9,14,20,1,2]),import.meta.url).then(n=>({default:n.Extensions}))),eF=M.lazy(()=>Kn(()=>import("./AppSettings-CBhYHKGI.js"),__vite__mapDeps([22,11,10,20,18,4,1,2]),import.meta.url).then(n=>({default:n.AppSettings}))),tF=M.lazy(()=>Kn(()=>import("./AgentLibrary-DRlcF1YD.js"),__vite__mapDeps([23,4,13,11,10,9,12,1,2]),import.meta.url).then(n=>({default:n.AgentLibrary}))),nF=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Zl({children:n}){return r.jsx(M.Suspense,{fallback:nF,children:n})}const iF={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."},memory:{title:"Claude config",intro:"This project's own Claude Code files — its memory folder, CLAUDE.md and CLAUDE.local.md, .claude/settings.json and settings.local.json, .mcp.json and .claude/skills/. Each tab edits the real file the claude CLI reads when a session starts here; ~/.claude is edited from Home."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads.",hideTitle:!0},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Global personas live in ~/.claude/agents, and any open project, picked in a persona’s project override, can get its own model or effort. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},Dk=new Map;function sF(n,e){const t=Dk.get(n);if(t&&t.ctx===e)return t.node;const i=rF(n,e);return Dk.set(n,{ctx:e,node:i}),i}function rF(n,e){switch(n){case"overview":return r.jsx(MM,{onNavigate:e.onNavigate});case"project-home":return r.jsx(uz,{});case"editor":return r.jsx(Gw,{});case"projects":return r.jsx(HB,{})}const t=iF[n],i=(()=>{switch(n){case"history":return r.jsx(Zl,{children:r.jsx(KB,{})});case"scheduler":return r.jsx(Zl,{children:r.jsx(YB,{navigate:e.onNavigate})});case"memory":return r.jsx(Zl,{children:r.jsx(ZB,{})});case"system-prompt":return r.jsx(Zl,{children:r.jsx(JB,{})});case"settings":return r.jsx(Zl,{children:r.jsx(XB,{scope:"user"})});case"extensions":return r.jsx(Zl,{children:r.jsx(QB,{})});case"app-settings":return r.jsx(Zl,{children:r.jsx(eF,{})});case"agent-library":return r.jsx(Zl,{children:r.jsx(tF,{})});default:return null}})();if(!i)return null;const s=IN[n];return t&&s?r.jsx(qB,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class oF extends M.Component{constructor(){super(...arguments);oi(this,"state",{error:null});oi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,i){console.error("[ErrorBoundary]",t,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):r.jsxs("div",{className:"p-6 text-xs",children:[r.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),r.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),r.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}}var k_={exports:{}},jk;function aF(){return jk||(jk=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,d){var h=this&&this.__decorate||function(x,y,T,$){var I,O=arguments.length,A=O<3?y:$===null?$=Object.getOwnPropertyDescriptor(y,T):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,y,T,$);else for(var L=x.length-1;L>=0;L--)(I=x[L])&&(A=(O<3?I(A):O>3?I(y,T,A):I(y,T))||A);return O>3&&A&&Object.defineProperty(y,T,A),A},m=this&&this.__param||function(x,y){return function(T,$){y(T,$,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const g=d(9042),b=d(9924),C=d(844),k=d(4725),E=d(2585),_=d(3656);let S=l.AccessibilityManager=class extends C.Disposable{constructor(x,y,T,$){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=$,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 I=0;I<this._terminal.rows;I++)this._rowElements[I]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[I]);if(this._topBoundaryFocusListener=I=>this._handleBoundaryFocus(I,0),this._bottomBoundaryFocusListener=I=>this._handleBoundaryFocus(I,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 b.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((I=>this._handleResize(I.rows)))),this.register(this._terminal.onRender((I=>this._refreshRows(I.start,I.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((I=>this._handleChar(I)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3054
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),x=M.useCallback(y=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const $=W4(y,T.before,T.after);return $.ok?(s.current+=1,i({type:"ACCEPT"})):ze.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[t.diff]);return{state:t,select:h,cancel:m,listen:g,sendHeard:_,run:E,retry:S,accept:x}}const Q4=[{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."}],mk=320,Jf=8;function eB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function tB(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,Jf),Math.max(Jf,e-mk-Jf)),i=Math.max(n.top-Jf,Jf);return{position:"fixed",left:t,top:i,width:mk,transform:"translateY(-100%)",zIndex:YN.dialog}}function nB({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:d,onSendHeard:h,onCancel:m,onAccept:g,onReject:b,onRetry:C}){const[k,E]=M.useState(""),[_,S]=M.useState(!1),x=Wi(I=>I.show),y=M.useRef(null);M.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const T=async()=>{if(!await Vo(t)){x("error","Copy failed");return}S(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>S(!1),1500)},$=()=>{const I=k.trim();I&&(l(I),E(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:tB(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&r.jsxs("div",{className:"p-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:_?"Copied":"Copy"}),r.jsx("button",{onClick:d,"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"}),Q4.map(I=>r.jsx("button",{onClick:()=>u(I.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:I.label},I.label))]}),r.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),r.jsx("input",{value:k,onChange:I=>E(I.target.value),onKeyDown:I=>{I.key==="Enter"?$():I.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&r.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[r.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(eB,{}),"Listening…"]}),a&&r.jsx("span",{className:"text-[10px] text-fg-faint",children:a})]}),r.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[r.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsxs("div",{className:"p-3 flex items-center justify-between",children:[r.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),r.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&r.jsxs("div",{className:"p-3",children:[r.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:C,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function iB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function gk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:d,onReject:h,onRetry:m}){return r.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[r.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),r.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Dm(J4)})]}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&r.jsxs("div",{className:"text-fg-faint",children:[r.jsx("p",{children:"Select text in the doc…"}),r.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),n==="popover"&&r.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&r.jsxs("div",{children:[r.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[r.jsx(iB,{}),"Listening…"]}),s&&r.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),r.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{children:[r.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&t&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-3 space-y-2",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function sB(){const n=jt(t=>t.tabs),e=jt(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function rB({path:n,onRenamed:e,onDeleted:t}){const[i,s]=M.useState(!1),[a,u]=M.useState(!1),[l,d]=M.useState(""),[h,m]=M.useState(!1),g=An(V=>V.buffers[n]),b=An(V=>V.openFile),C=An(V=>V.renameOpenFile),k=An(V=>V.closeFile),E=sB(),_=xo(n),S=()=>s(!1),x=()=>{d(_),u(!0),S()},y=async()=>{const V=l.trim();if(!V||V===_){u(!1);return}try{const te=await window.api.files.rename(n,V);if(te.ok){const re=n.slice(0,n.lastIndexOf("/")),K=te.newPath??`${re}/${V}`;C(n,K),e==null||e(n,K),ze.info(`Renamed to ${V}`)}else ze.error(te.error??`Couldn't rename ${_}`)}catch(te){ze.error(te instanceof Error?te.message:`Couldn't rename ${_}`)}u(!1)},T=async()=>{S();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(b(V.path),ze.info(`Duplicated as ${xo(V.path)}`)):ze.error(V.error??`Couldn't duplicate ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't duplicate ${_}`)}},$=async()=>{try{const V=await window.api.files.delete(n);V.ok?(k(n),t==null||t(n),ze.info(`Deleted ${_}`)):ze.error(V.error??`Couldn't delete ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't delete ${_}`)}m(!1)},I=async()=>{S();const V=g??"";await Vo(V)?ze.info(`Copied ${V.length} chars`):ze.error(`Couldn't copy ${_}`)},O=()=>{if(S(),!E){ze.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${n} `}),ze.info(`Added ${_} to Claude context`)},A=()=>{S(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't open ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't open ${_}`))},L=()=>{S(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't reveal ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't reveal ${_}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(V=>!V),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:"Document actions",children:"Document ▾"}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:S}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[r.jsx(v_,{children:"Edit"}),r.jsx(wd,{label:"Rename",onClick:x}),r.jsx(wd,{label:"Duplicate",onClick:T}),r.jsx(wd,{label:"Delete document",danger:!0,onClick:()=>{S(),m(!0)}}),r.jsx(vk,{}),r.jsx(v_,{children:"Open"}),r.jsx(wd,{label:"Open in default app",onClick:A}),r.jsx(wd,{label:"Reveal in OS",onClick:L}),r.jsx(vk,{}),r.jsx(v_,{children:"Export"}),r.jsx(wd,{label:"Copy as Markdown",onClick:I}),r.jsx(wd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(oB,{value:l,onChange:d,onCancel:()=>u(!1),onConfirm:()=>void y()}),h&&r.jsx(aB,{name:_,onCancel:()=>m(!1),onConfirm:()=>void $()})]})}function v_({children:n}){return r.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function wd({label:n,onClick:e,danger:t,disabled:i,title:s}){return r.jsx("button",{onClick:e,disabled:i,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function vk(){return r.jsx("div",{className:"my-1 border-t border-line"})}function oB({value:n,onChange:e,onCancel:t,onConfirm:i}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),r.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?i():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function aB({name:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function lB(){const[n,e]=M.useState(!1),t=$d();return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>e(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:()=>e(!1)}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[r.jsx(Eh,{label:"Text size",children:r.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[r.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−"}),r.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),r.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+"})]})}),r.jsx(Eh,{label:"Word wrap",children:r.jsx(Iv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx(Eh,{label:"Minimap",children:r.jsx(Iv,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx(Eh,{label:"Theme",children:r.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"})}),r.jsx(Eh,{label:"Autosave",children:r.jsx(Iv,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx(Eh,{label:"Wide measure",children:r.jsx(Iv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Eh({label:n,children:e}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Iv({on:n,onClick:e}){return r.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const cB=M.lazy(()=>Kn(()=>import("./TiptapBody-O_Gfq0Ha.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Pv(n,e){if(!e.length)return n;const t=new Set(e),i={};for(const[s,a]of Object.entries(n))t.has(s)||(i[s]=a);return i}function Zf(n){const e=n.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",i=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||i===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||i==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function Rv(n){return uD(n)||hD(n)}function dB(){const n=jy(),e=An(Ue=>Ue.openFiles),t=An(Ue=>Ue.activeFilePath),i=An(Ue=>Ue.dirty),s=An(Ue=>Ue.viewMode),a=An(Ue=>Ue.buffers),u=An(Ue=>Ue.setActive),l=An(Ue=>Ue.closeFile),d=An(Ue=>Ue.closeOthers),h=An(Ue=>Ue.closeToTheRight),m=An(Ue=>Ue.closeAll),g=An(Ue=>Ue.loadBuffer),b=An(Ue=>Ue.setBuffer),C=An(Ue=>Ue.markSaved),k=An(Ue=>Ue.setViewMode),E=$d(),[_,S]=M.useState({}),[x,y]=M.useState({}),[T,$]=M.useState(null),[I,O]=M.useState(null),[A,L]=M.useState(!1),[V,te]=M.useState(!1),[re,K]=M.useState(!0),de=M.useRef(null),J=M.useRef(null),he=M.useRef(void 0),Ce=M.useRef(null),ve=M.useRef(null),F=Z4(t??"",a[t??""]??""),q=M.useCallback((Ue,xt)=>{b(Ue,xt),Zf(Ue)&&Ca.getState().setDraft(Ue,xt)},[b]),W=M.useCallback(Ue=>{de.current=Ue},[]),Q=M.useCallback(()=>de.current,[]);M.useEffect(()=>{ZO()},[]),M.useEffect(()=>{const Ue=t;if(!Ue||Rv(Ue))return;if(An.getState().hasBuffer(Ue)){S(yt=>yt[Ue]==="ready"?yt:{...yt,[Ue]:"ready"});return}let xt=!1;return S(yt=>({...yt,[Ue]:"loading"})),Zf(Ue)?((async()=>{if(await Ca.getState().loadText(Ue,!0),xt)return;const yt=Ca.getState().files[Ue];if(!yt||yt.loadError&&!yt.exists){S(Qt=>({...Qt,[Ue]:{error:(yt==null?void 0:yt.loadError)??"failed to read"}}));return}g(Ue,yt.diskRaw),yt.dirty&&An.getState().setBuffer(Ue,yt.draftRaw),S(Qt=>({...Qt,[Ue]:"ready"}))})(),()=>{xt=!0}):(window.api.files.read(Ue).then(yt=>{xt||(yt.binary?S(Qt=>({...Qt,[Ue]:{binary:!0,size:yt.size??0,mime:yt.mime??"application/octet-stream",reason:yt.error??"Binary file"}})):yt.ok?(g(Ue,yt.text),S(Qt=>({...Qt,[Ue]:"ready"}))):S(Qt=>({...Qt,[Ue]:{error:yt.error??"failed to read"}})))}),()=>{xt=!0})},[t,g]),M.useEffect(()=>{O(null)},[t]);const le=M.useCallback(async(Ue,xt=!1)=>{const yt=An.getState().buffers[Ue];if(yt==null)return;xt&&L(!0);const Qt=Zf(Ue);let Cn;if(Qt){const Xn=Ca.getState();if(Xn.setDraft(Ue,yt),Cn=await Xn.saveText(Ue),!Cn.ok&&Cn.error==="conflict"){xt&&L(!1);return}}else Cn=await window.api.files.write(Ue,yt);Cn.ok?(C(Ue),y(Xn=>({...Xn,[Ue]:(Xn[Ue]??0)+1})),xt||ze.info(`Saved ${xo(Ue)}`)):ze.error(Cn.error??`Couldn't save ${xo(Ue)}`),xt&&L(!1)},[C]);M.useEffect(()=>{if(!E.autosave)return;const Ue=t;if(!(!Ue||Rv(Ue)||Zf(Ue)||!i[Ue]))return window.clearTimeout(he.current),he.current=window.setTimeout(()=>{le(Ue,!0)},1200),()=>window.clearTimeout(he.current)},[E.autosave,t,i,a,le]);const fe=M.useCallback(Ue=>{Ue.length&&(S(xt=>Pv(xt,Ue)),y(xt=>Pv(xt,Ue)))},[]),Ie=M.useCallback((Ue,xt)=>{S(yt=>Ue in yt?{...Pv(yt,[Ue]),[xt]:yt[Ue]}:yt),y(yt=>Ue in yt?{...Pv(yt,[Ue]),[xt]:yt[Ue]}:yt)},[]),He=M.useCallback(Ue=>{i[Ue]?$({kind:"one",path:Ue}):(l(Ue),fe([Ue]))},[i,l,fe]),me=M.useCallback(Ue=>{e.some(yt=>yt.path!==Ue&&i[yt.path])?$({kind:"others",path:Ue}):(d(Ue),fe(e.filter(yt=>yt.path!==Ue).map(yt=>yt.path)))},[e,i,d,fe]),ee=M.useCallback(Ue=>{const xt=e.findIndex(Qt=>Qt.path===Ue);xt!==-1&&e.slice(xt+1).some(Qt=>i[Qt.path])?$({kind:"right",path:Ue}):(h(Ue),fe(xt!==-1?e.slice(xt+1).map(Qt=>Qt.path):[]))},[e,i,h,fe]);M.useEffect(()=>{const Ue=xt=>{if(n.current)if((xt.metaKey||xt.ctrlKey)&&(xt.key==="s"||xt.key==="S")){const yt=An.getState().activeFilePath;yt&&!Rv(yt)&&(xt.preventDefault(),le(yt))}else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="f"||xt.key==="F"))xt.preventDefault(),te(yt=>!yt);else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="w"||xt.key==="W")){const yt=An.getState().activeFilePath;yt&&An.getState().openFiles.length>1&&(xt.preventDefault(),me(yt))}else xt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():xt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[le,V,me,F.state.phase,F.cancel]),M.useEffect(()=>{if(F.state.phase==="idle")return;const Ue=xt=>{var Qt,Cn;const yt=xt.target;(Qt=ve.current)!=null&&Qt.contains(yt)||(Cn=Ce.current)!=null&&Cn.contains(yt)||F.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[F.state.phase,F.cancel]),M.useEffect(()=>{F.cancel()},[t,F.cancel]);const $e=M.useCallback(()=>{e.some(xt=>i[xt.path])?$({kind:"all",path:""}):(m(),S({}),y({}))},[e,i,m]),Ee=()=>{if(T){if(T.kind==="one")l(T.path),fe([T.path]);else if(T.kind==="others"){const Ue=e.filter(xt=>xt.path!==T.path).map(xt=>xt.path);d(T.path),fe(Ue)}else if(T.kind==="right"){const Ue=e.findIndex(yt=>yt.path===T.path),xt=Ue!==-1?e.slice(Ue+1).map(yt=>yt.path):[];h(T.path),fe(xt)}else m(),S({}),y({});$(null)}};if(e.length===0)return r.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"mb-2",children:"no file open"}),r.jsxs("div",{children:["open the ",r.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Te=t,be=Te?xo(Te):"",Qe=Te?_[Te]:void 0,vt=Te?mD(Te):!1,lt=Te?KO(Te):!1,$t=Te&&vt?s[Te]??YO(Te):"edit",We=!!Te&&!Rv(Te)&&Qe==="ready",Ht=We,Ct=lt?["edit","wysiwyg","preview","split"]:vt?["edit","preview"]:[],sn=Te&&r.jsx(j4,{path:Te,name:be,value:a[Te]??"",onChange:Ue=>q(Te,Ue),onSave:()=>void le(Te),onReady:W,onCursor:O}),un=A?"Saving…":Te&&i[Te]?E.autosave&&!Zf(Te)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&r.jsx(mz,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:He,onCloseOthers:me,onCloseToTheRight:ee,onCloseAll:$e}),Te&&!V&&r.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[r.jsx("span",{className:"text-xs font-medium text-fg truncate",children:be}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Te}),We&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",un]}),rl(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:()=>K(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${re?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),rl(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Ct.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:Ct.map(Ue=>r.jsx("button",{onClick:()=>k(Te,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${$t===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),r.jsx("div",{className:"flex-1"}),r.jsx(rB,{path:Te,onRenamed:Ie,onDeleted:Ue=>fe([Ue])}),We&&r.jsx(lB,{}),r.jsx("button",{onClick:()=>te(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&r.jsx("button",{onClick:()=>te(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),r.jsx("div",{className:"flex-1 min-h-0",children:Te?uD(Te)?r.jsx(M4,{path:Te,name:be}):hD(Te)?r.jsx(O4,{path:Te}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(H4,{path:Te,name:be,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?r.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):$t==="wysiwyg"&&rl(Te)?r.jsx(M.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(cB,{value:a[Te]??"",onChange:Ue=>q(Te,Ue)},Te)}):$t==="split"&&rl(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[re&&r.jsx(hk,{text:a[Te]??"",scrollRef:J}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(uk,{getEditor:Q}),r.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx($x,{ref:J,text:a[Te]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(gk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&rl(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[re&&r.jsx(hk,{text:a[Te]??"",scrollRef:J}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx($x,{ref:J,text:a[Te]??"",wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(gk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&dD(Te)?r.jsx(P4,{path:Te,dirty:!!i[Te],reloadToken:x[Te]??0}):$t==="preview"&&pD(Te)?r.jsx(z4,{path:Te,text:a[Te]??""}):$t==="preview"&&fD(Te)?r.jsx(G4,{path:Te,text:a[Te]??""}):rl(Te)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(uk,{getEditor:Q}),r.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),Ht&&r.jsx(I4,{text:a[Te]??"",cursor:I,language:Xr(Te)||void 0}),Te&&rl(Te)&&($t==="preview"||$t==="split")&&F.state.phase!=="idle"&&F.state.selection&&r.jsx("div",{ref:ve,children:r.jsx(nB,{phase:F.state.phase,rect:F.state.selection.rect,selectedText:F.state.selection.text,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)}})}),T&&r.jsx(uB,{message:T.kind==="one"?`Discard unsaved changes to ${xo(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:()=>$(null),onConfirm:Ee})]})}const Gw=M.memo(dB);function uB({message:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const hB="~/.claude/session-manager/projects-prefs.json";let xk=Promise.resolve(),Mv=null;function bk(n){const e=xk.then(n);return xk=e.catch(()=>{}),e}const cj=()=>ja(hB);async function _k(){const n=(await cj().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const x_=Ei(n=>({pinned:{},hydrated:!1,hydrate:()=>Mv||(Mv=bk(async()=>{try{n({pinned:await _k(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Mv),togglePin:e=>{bk(async()=>{let t;try{t=await _k()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const i={...t};i[e]?delete i[e]:i[e]=!0;try{await cj().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function pB(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function fB(n,e,t){const i=M.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(pB))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;M.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const u=window.api.config.onChanged(l=>{s.includes(l.path)&&i.current(l.path)});return()=>{u(),window.api.config.unwatch(s,t)}},[a])}function c0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function dj(n){return n.split(/[\\/]+/).filter(Boolean)}function uj(n){const e=dj(n);return e.length?e[e.length-1]:n}function wk(n){const e=n.length>1?n.replace(/[\\/]+$/,""):n,t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t<0?"":t===0?e.slice(0,1):/^[A-Za-z]:$/.test(e.slice(0,t))?e.slice(0,t+1):e.slice(0,t)}function hj(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=c0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const yk=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Rm(n,e){return yk(n).startsWith(yk(e)+"/")}const Hw="reveal:";function EV(n){En.getState().openPanel("projects",Hw+n)}function mB(n){return n.startsWith(Hw)&&n.slice(Hw.length)||null}const gB=/^[A-Za-z]:$/;function Sk(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(gB.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function pj(n,e){const t=Sk(n),i=Sk(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function vB(n){const e=await Kh(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function xB(n,e){return vc(n,{fileTreeExpanded:[...e].slice(0,500)})}async function bB(){const n=await sb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function _B(n){rb({fileTreeShowHidden:n}).catch(()=>{})}function b_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Rm(s,e)){t=!0;continue}i.add(s)}return t?i:n}const Ck=(n,e)=>`${e?1:0}:${n}`,__={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:"!"}},wB=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 yB(n){const e=Xr(n);return wB.has(e)||cD.has(e)||e==="pdf"}function SB(n,e){if(e)return"#d97757";switch(Xr(n)){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 Qf(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const kk=64,CB=250,kB={depth:0};function w_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function EB({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=jy(),l=Kx(),[d,h]=M.useState([]),m=M.useRef(d);m.current=d;const[g,b]=M.useState(null),C=M.useRef(null),k=M.useRef(null),[E,_]=M.useState(0),[S,x]=M.useState(null),[y,T]=M.useState(null),$=M.useRef(null),[I,O]=M.useState(0),A=M.useRef(a);A.current=a;const[L,V]=M.useState(new Set),te=M.useRef(L);te.current=L;const re=M.useRef(!1),[K,de]=M.useState(""),[J,he]=M.useState(!0),Ce=M.useRef(!1);M.useEffect(()=>{let it=!1;return bB().then(mt=>{!it&&!Ce.current&&he(mt)}),()=>{it=!0}},[]);const ve=M.useCallback(it=>{Ce.current=!0,he(mt=>{const Pt=typeof it=="function"?it(mt):it;return _B(Pt),Pt})},[]),[F,q]=M.useState(!1),[W,Q]=M.useState(null),[le,fe]=M.useState({}),[Ie,He]=M.useState(null),[me,ee]=M.useState(null),[$e,Ee]=M.useState(""),[Te,be]=M.useState(null),[Qe,vt]=M.useState(""),[lt,$t]=M.useState(null),We=M.useRef(null),Ht=M.useRef(null),Ct=M.useRef(0),sn=M.useCallback(async()=>{if(!n)return;const it=++Ct.current;q(!0),Q(null);const mt=await window.api.files.list(n,J);Ct.current===it&&(mt.ok?h(mt.entries.map(Pt=>({...Pt}))):(Q(mt.error??"failed to list"),h([])),T(Ck(n,J)),q(!1))},[n,J]),un=M.useCallback(async it=>{const mt=Ct.current,Pt=new Map;for(const Mn of it){const Gn=dj(Mn).length,Hn=Pt.get(Gn);Hn?Hn.push(Mn):Pt.set(Gn,[Mn])}const At=[];for(const Mn of[...Pt.keys()].sort((Gn,Hn)=>Gn-Hn)){const Gn=Pt.get(Mn),Hn=await Promise.all(Gn.map(async rt=>({p:rt,result:await window.api.files.list(rt,J)})));if(Ct.current!==mt)return At;for(const{p:rt,result:fn}of Hn)fn.ok?h(Jn=>dm(Jn,rt,fn.entries.map(Zn=>({...Zn})),te.current)):At.push(rt)}return At},[J]),Ue=M.useCallback(async it=>(await sn(),it.length?un(it):[]),[sn,un]);M.useEffect(()=>{de(""),ee(null),He(null),be(null),$t(null),fe({}),b(null);let it=!1;return re.current=!1,(async()=>{const[mt]=await Promise.all([vB(n),sn()]);if(it)return;if(!re.current){const At=new Set(mt);te.current=At,V(At)}if(x(n),!mt.length)return;const Pt=await un(mt);it||!Pt.length||xn(At=>{const Mn=new Set;let Gn=!1;for(const Hn of At){if(Pt.some(rt=>Hn===rt||Rm(Hn,rt))){Gn=!0;continue}Mn.add(Hn)}return Gn?Mn:At})})(),Qf(n).then(mt=>{it||fe(mt)}),()=>{it=!0}},[n]);const xt=M.useRef(!0);M.useEffect(()=>{if(xt.current){xt.current=!1;return}Ue([...te.current])},[J]),M.useEffect(()=>{if(!n||!l)return;Qf(n).then(fe);const it=window.setInterval(()=>{Qf(n).then(fe)},5e3);return()=>window.clearInterval(it)},[n,l]);const yt=M.useMemo(()=>{if(!n)return[];const it=[...L].filter(mt=>mt!==n);return[n,...it.slice(-63)]},[n,L]),Qt=M.useRef(!1);M.useEffect(()=>{!n||L.size+1<=kk||Qt.current||(Qt.current=!0,console.warn(`FileTree: watching only ${kk} of ${L.size+1} folders (cap reached)`))},[n,L]);const Cn=M.useRef(new Map),Xn=M.useRef(new Set),mn=M.useRef(!1);mn.current=me!==null||Te!==null;const Rn=M.useRef(()=>{});Rn.current=it=>{if(!(it!==w_(n)&&!te.current.has(it))){if(mn.current){Xn.current.add(it);return}it===w_(n)?Ue([...te.current]):ot(it)}},fB(yt,it=>{if(it!==w_(n)&&!te.current.has(it))return;const mt=Cn.current,Pt=mt.get(it);Pt&&clearTimeout(Pt),mt.set(it,setTimeout(()=>{mt.delete(it),Rn.current(it)},CB))},kB),M.useEffect(()=>{if(me!==null||Te!==null)return;const it=[...Xn.current];Xn.current.clear();for(const mt of it)Rn.current(mt)},[me,Te]),M.useEffect(()=>{const it=Cn.current,mt=Xn.current;return()=>{for(const Pt of it.values())clearTimeout(Pt);it.clear(),mt.clear()}},[n]),M.useEffect(()=>{if(!Ie)return;const it=()=>He(null),mt=Pt=>{u.current&&Pt.key==="Escape"&&He(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",mt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",mt)}},[Ie]),M.useEffect(()=>{me&&setTimeout(()=>{var it;return(it=We.current)==null?void 0:it.select()},30)},[me]),M.useEffect(()=>{Te&&setTimeout(()=>{var it;return(it=Ht.current)==null?void 0:it.focus()},30)},[Te]);const xn=M.useCallback(it=>{const mt=te.current,Pt=it(mt);Pt!==mt&&(re.current=!0,te.current=Pt,V(Pt),xB(n,Pt).catch(()=>{te.current===Pt&&(te.current=mt,V(mt),ze.error("Couldn't save folder expansion — reverted."))}))},[n]),Fn=M.useCallback(async it=>{if(L.has(it.path)){xn(Pt=>b_(Pt,it.path));return}if(xn(Pt=>new Set(Pt).add(it.path)),it.children)return;const mt=await window.api.files.list(it.path,J);mt.ok&&h(Pt=>dm(Pt,it.path,mt.entries.map(At=>({...At})),te.current))},[L,J,xn]),ot=M.useCallback(async it=>{if(it===n){await sn();return}const mt=await window.api.files.list(it,J);mt.ok&&h(Pt=>dm(Pt,it,mt.entries.map(At=>({...At})),te.current))},[n,sn,J]),ti=M.useCallback(async(it,mt)=>{const Pt=()=>{var hn;return(hn=A.current)==null?void 0:hn.call(A,it.token)};if(!mt.length){b(null),Pt();return}const At=Ct.current,Mn=mt.slice(0,-1).map((hn,On)=>hj(n,...mt.slice(0,On+1))),Gn=await Promise.all(Mn.map(hn=>window.api.files.list(hn,J)));if(Ct.current!==At){$.current=null,O(hn=>hn+1);return}let Hn=m.current;const rt=[];let fn=null,Jn="not found";for(let hn=0;hn<mt.length;hn++){const On=Hn.find(ui=>ui.name===mt[hn]);if(!On)break;if(hn===mt.length-1){fn=On;break}const vi=Gn[hn];if(!On.isDirectory)break;if(!vi.ok){Jn=vi.error??"could not list its folder";break}const Et=vi.entries.map(ui=>({...ui}));rt.push({path:On.path,children:Et}),Hn=Et}if(!fn){ze.error(`Couldn't reveal ${it.path}: ${Jn}`),Pt();return}const Zn=rt.map(hn=>hn.path);xn(hn=>Zn.every(On=>hn.has(On))?hn:new Set([...hn,...Zn])),h(hn=>rt.reduce((On,vi)=>dm(On,vi.path,vi.children,te.current),hn)),de(""),Q(null),b(fn.path),_(hn=>hn+1),Pt()},[n,J,xn]);M.useEffect(()=>{var mt;if(!s||$.current===s.token||S!==n||y!==Ck(n,J)||F)return;const it=pj(s.path,n);if(!it){$.current=s.token,ze.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(mt=A.current)==null||mt.call(A,s.token);return}if(it.some(Pt=>Pt.startsWith("."))&&(Ce.current=!0,!J)){he(!0);return}$.current=s.token,ti(s,it)},[s,S,y,F,n,J,I,ti]),M.useEffect(()=>{if(!E)return;const it=k.current,mt=C.current;it&&mt&&Vm(it,mt,{block:"nearest"})},[E]);const hs=M.useCallback(it=>{if(it.isDirectory){Fn(it);return}yB(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[Fn,e]),Mi=M.useCallback(it=>{if(t){t(it);return}if(i){const mt=Rm(it,n)?it.slice(n.replace(/[\\/]+$/,"").length+1):it;window.api.pty.write({tabId:i,data:`@${mt} `})}},[t,i,n]),Oi=M.useCallback((it,mt)=>{it.preventDefault(),it.stopPropagation(),He({x:it.clientX,y:it.clientY,node:mt})},[]),Sn=it=>{ee(it.path),Ee(it.name)},gi=async()=>{if(!me)return;const it=$e.trim();if(!it){ee(null);return}const mt=await window.api.files.rename(me,it);if(ee(null),mt.ok){const Pt=wk(me);xn(At=>b_(At,me)),await ot(Pt||n),Qf(n).then(fe)}else{const Pt=mt.error??"rename failed";Q(Pt),ze.error(Pt)}},In=async()=>{if(!Te)return;const it=Qe.trim();if(!it){be(null),vt("");return}const mt=await window.api.files.create(Te.parent,it,Te.kind);if(be(null),vt(""),mt.ok)await ot(Te.parent),Te.kind==="folder"&&xn(Pt=>new Set(Pt).add(Te.parent));else{const Pt=mt.error??"create failed";Q(Pt),ze.error(Pt)}},rs=async()=>{if(!lt)return;const it=await window.api.files.delete(lt.path),mt=wk(lt.path);if($t(null),it.ok)xn(Pt=>b_(Pt,lt.path)),await ot(mt||n),Qf(n).then(fe);else{const Pt=it.error??"delete failed";Q(Pt),ze.error(Pt)}},Dn=M.useMemo(()=>{if(!K.trim())return d;const it=K.toLowerCase();return d.filter(mt=>mt.name.toLowerCase().includes(it))},[d,K]),yi=(n?uj(n):"")||"project";return r.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[r.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[r.jsx(mj,{size:14,className:"shrink-0 text-accent"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs font-medium text-fg truncate",children:yi}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:sn,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:F,children:r.jsx(IB,{size:12,className:F?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:K,onChange:it=>de(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"})})]}),r.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[r.jsx("button",{onClick:()=>be({parent:n,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:r.jsx(PB,{size:12})}),r.jsx("button",{onClick:()=>be({parent:n,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:r.jsx(RB,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>ve(it=>!it),className:`p-1.5 rounded transition-colors ${J?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:J?"Hide hidden files":"Show hidden files",children:J?r.jsx(MB,{size:12}):r.jsx(OB,{size:12})})]}),r.jsxs("div",{ref:k,className:"flex-1 overflow-y-auto py-1",children:[W&&r.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:W}),!W&&Dn.length===0&&!F&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:K?"no matches":"empty folder"}),!W&&r.jsx(fj,{nodes:Dn,depth:0,expanded:L,gitStatus:le,renaming:me,selected:g,selectedRowRef:C,onSelect:b,renameValue:$e,renameInputRef:We,onRenameChange:Ee,onRenameCommit:gi,onRenameCancel:()=>ee(null),onToggleDir:Fn,onFileClick:hs,onSendToChat:Mi,onContextMenu:Oi})]}),r.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"}),Ie&&r.jsx(TB,{x:Ie.x,y:Ie.y,node:Ie.node,onClose:()=>He(null),onRename:()=>{Sn(Ie.node),He(null)},onDelete:()=>{$t(Ie.node),He(null)},onNewFile:()=>{be({parent:Ie.node.path,kind:"file"}),He(null)},onNewFolder:()=>{be({parent:Ie.node.path,kind:"folder"}),He(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Ie.node.path}),He(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Ie.node.path}),He(null)},onCopyPath:()=>{const it=Ie.node.path;Vo(it).then(mt=>{mt||ze.error("Couldn't copy path")}),He(null)},onSendToChat:()=>{Mi(Ie.node.path),He(null)}}),Te&&r.jsx(Ek,{title:`New ${Te.kind}`,subtitle:`in ${DB(Te.parent)}`,onCancel:()=>{be(null),vt("")},onConfirm:In,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:Ht,value:Qe,onChange:it=>vt(it.target.value),onKeyDown:it=>{it.key==="Enter"&&In(),it.key==="Escape"&&(be(null),vt(""))},placeholder:Te.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"})}),lt&&r.jsx(Ek,{title:`Delete ${lt.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>$t(null),onConfirm:rs,confirmLabel:"Delete",danger:!0,children:r.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",r.jsxs("span",{className:"text-fg font-medium",children:['"',lt.name,'"']})," to the trash?",lt.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function fj(n){const{nodes:e,depth:t,expanded:i,gitStatus:s,renaming:a,selected:u,onContextMenu:l}=n;return r.jsx(r.Fragment,{children:e.map(d=>{const h=i.has(d.path),m=a===d.path,g=u===d.path,b=s[d.path],C=SB(d.name,d.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:g?n.selectedRowRef:void 0,"data-path":d.path,"data-selected":g?"true":void 0,className:`group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi ${g?"bg-accent/15":""}`,style:{paddingLeft:`${8+t*14}px`},onClick:()=>{m||(n.onSelect(d.path),d.isDirectory?n.onToggleDir(d):n.onFileClick(d))},onDoubleClick:()=>{d.isDirectory||window.api.shell.open({as:"openPath",path:d.path})},onContextMenu:k=>l(k,d),children:[d.isDirectory?r.jsx(AB,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),d.isDirectory?h?r.jsx($B,{size:12,color:C}):r.jsx(mj,{size:12,color:C}):r.jsx(NB,{size:12,color:C}),m?r.jsx("input",{ref:n.renameInputRef,value:n.renameValue,onChange:k=>n.onRenameChange(k.target.value),onClick:k=>k.stopPropagation(),onBlur:n.onRenameCommit,onKeyDown:k=>{k.key==="Enter"&&n.onRenameCommit(),k.key==="Escape"&&n.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"}):r.jsx("span",{className:`flex-1 truncate text-xs ${d.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:d.name}),b&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:__[b].color,backgroundColor:`${__[b].color}20`},title:b,children:__[b].label}),!d.isDirectory&&r.jsx("button",{onClick:k=>{k.stopPropagation(),n.onSendToChat(d.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:r.jsx(LB,{size:10})})]}),d.isDirectory&&h&&d.children&&r.jsx(fj,{...n,nodes:d.children,depth:t+1})]},d.path)})})}function TB(n){const{x:e,y:t,node:i}=n;return r.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!i.isDirectory&&r.jsx(Jl,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(Jl,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(Jl,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(y_,{}),r.jsx(Jl,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(Jl,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(y_,{}),r.jsx(Jl,{label:"New file",onClick:n.onNewFile}),r.jsx(Jl,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(y_,{}),r.jsx(Jl,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function Jl({label:n,onClick:e,danger:t}){return r.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:n})}function y_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function Ek(n){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&n.onCancel()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:n.title}),n.subtitle&&r.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:n.subtitle}),r.jsx("div",{className:"mb-4",children:n.children}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:n.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:n.onConfirm,disabled:!!n.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:n.confirmLabel??"OK"})]})]})})}function DB(n){return uj(n)}function dm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:jB(s.children,t,i)}:s.children?{...s,children:dm(s.children,e,t,i)}:s)}function jB(n,e,t){const i=new Map;for(const s of n??[])s.children&&t.has(s.path)&&i.set(s.path,s.children);return i.size?e.map(s=>{const a=s.isDirectory?i.get(s.path):void 0;return a?{...s,children:a}:s}):e}function Na({size:n,children:e,className:t,color:i}){return r.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:i||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function mj({size:n,className:e,color:t}){return r.jsx(Na,{size:n,className:e,color:t,children:r.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 $B({size:n,className:e,color:t}){return r.jsx(Na,{size:n,className:e,color:t,children:r.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 NB({size:n,className:e,color:t}){return r.jsxs(Na,{size:n,className:e,color:t,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function AB({size:n,className:e}){return r.jsx(Na,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function IB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("polyline",{points:"1 20 1 14 7 14"}),r.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 PB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),r.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function RB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.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"}),r.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),r.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function MB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function OB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.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"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function LB({size:n,className:e}){return r.jsxs(Na,{size:n,className:e,children:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function gj({content:n,children:e,align:t="bottom-right"}){const[i,s]=M.useState(!1),a=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return r.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,i&&r.jsx("span",{role:"tooltip",className:`absolute ${Ii.dialog} ${a} 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:n})]})}function ym(n,e){if(!e)return n;const t=c0(e),i=e.length>1?e.replace(/[\\/]+$/,""):e;if(n===i)return"~";const s=i.endsWith(t)?i:`${i}${t}`;return n.startsWith(s)?`~${t}${n.slice(s.length)}`:n}function S_(n){rb(n).catch(()=>ze.error("Couldn't save File Explorer layout."))}const C_=33,zB=20,BB=60,FB=32;function Tk(n){return Math.min(BB,Math.max(zB,n))}function GB(){const n=jt(F=>F.tabs),e=jt(F=>F.activeTabId),t=n.find(F=>F.id===e)??null,i=En(F=>F.navFace),s=Qx(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=M.useState(C_),[d,h]=M.useState(!1),m=M.useRef(!1),[g,b]=M.useState(!1),C=M.useRef(u);C.current=u;const k=M.useRef(d);k.current=d;const E=M.useRef(null),_=M.useRef(null),S=M.useRef(!1),{projects:x,openProject:y,archiveProjectByCwd:T}=Rd(),$=x_(F=>F.pinned),I=x_(F=>F.togglePin);M.useEffect(()=>{x_.getState().hydrate()},[]),M.useEffect(()=>{let F=!1;return sb().then(q=>{F||m.current||(typeof q.projectsSplitPct=="number"&&Number.isFinite(q.projectsSplitPct)&&l(Tk(q.projectsSplitPct)),typeof q.projectsFileTreeCollapsed=="boolean"&&!S.current&&h(q.projectsFileTreeCollapsed))}),()=>{F=!0}},[]);const O=M.useRef(0),[A,L]=M.useState(null),[V,te]=M.useState(null);WN("projects",F=>{const q=mB(F);q&&L({path:q,token:++O.current})});const re=(t==null?void 0:t.cwd)??null;M.useEffect(()=>{if(!A)return;const{path:F}=A,q=fe=>!!fe&&pj(F,fe)!==null,W=i==="home"?s:re,Q=i==="home"?{face:"project",root:re}:{face:"home",root:s};let le=null;if(q(W))le={face:i,root:W};else{if(s===null)return;q(Q.root)&&(le={face:Q.face,root:Q.root})}if(L(null),!le){window.api.shell.open({as:"revealPath",path:F}).then(fe=>{fe.ok||ze.error(`Couldn't reveal ${F}: ${fe.error??"unknown error"}`)},fe=>ze.error(`Couldn't reveal ${F}: ${fe instanceof Error?fe.message:String(fe)}`));return}le.face!==i&&En.getState().setNavFace(le.face),S.current=!0,h(!1),te({...A,root:le.root})},[A,i,s,re]),M.useEffect(()=>{te(F=>F&&a!==null&&F.root!==a?null:F)},[a]);const K=M.useCallback(F=>{te(q=>q&&q.token===F?null:q)},[]),de=[...x].sort((F,q)=>($[q.cwd]?1:0)-($[F.cwd]?1:0));M.useEffect(()=>{if(!g)return;const F=q=>{_.current&&!_.current.contains(q.target)&&b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[g]);const J=M.useCallback(F=>{An.getState().openFile(F)},[]),he=M.useCallback(F=>{F.preventDefault(),m.current=!0;const q=F.clientX,W=C.current;let Q=W;const le=Ie=>{const He=E.current;if(!He)return;const me=He.getBoundingClientRect(),ee=Ie.clientX-q;Q=Tk(W+ee/me.width*100),l(Q)},fe=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",fe),document.body.style.cursor="",document.body.style.userSelect="",S_({projectsSplitPct:Q})};window.addEventListener("pointermove",le),window.addEventListener("pointerup",fe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),Ce=M.useCallback(()=>{m.current=!0,l(C_),S_({projectsSplitPct:C_})},[]),ve=M.useCallback(()=>{m.current=!0;const F=!k.current;h(F),S_({projectsFileTreeCollapsed:F})},[]);return d?r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:ve,"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:FB},children:[r.jsx("span",{className:"text-[11px]",children:"▸"}),r.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Gw,{})})]}):r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${u}%`},"data-testid":"projects-file-tree-pane",children:[r.jsxs("div",{ref:_,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(F=>!F),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:[r.jsx("span",{className:"flex-1 truncate text-left",children:a?ym(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),r.jsx("button",{onClick:ve,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),g&&r.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Ii.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:de.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):de.map(F=>{const q=ym(F.cwd,s);return r.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[r.jsx(gj,{content:$[F.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>I(F.cwd),className:`shrink-0 text-sm leading-none transition-colors ${$[F.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:$[F.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{y(F.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:q}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${q}?`)&&await T(F)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},F.cwd)})})]}),a?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:a,children:ym(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(EB,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:J,reveal:V&&V.root===a?V:null,onRevealDone:K})})]}):r.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:i==="home"?"Loading home folder…":"No session selected."})]}),r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:he,onDoubleClick:Ce,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Gw,{})})]})}const HB=M.memo(GB),WB={"project-home":{headline:"Pages, Videos and Tools — this project's generated library and its tools",intro:"Project Home is this project's own library, written by builder agents from what they read in the repository. Three key buttons at the top switch the area below them: Pages holds Knowledge Pages (static HTML pages that explain a topic), Videos holds short self-contained HTML/JS videos that show the project, and Tools holds one-press tools for the project, led by Review MD network.",sections:[{title:"The key buttons",items:[{term:"Pages",body:"Opens the knowledge-page library. The badge counts ready pages plus any page being built; the line under the name reads “Nothing generated yet”, “<n> building · <m> ready” while a build runs, or the page count and how long ago the newest page was made."},{term:"Videos",body:"The same, for the video library."},{term:"Tools",body:"Opens the tool list. Once you have opened Tools for this project, an accent badge shows how many findings Review MD network's link map found. Its Expand button (or a click on any doc in the map) opens a full-screen explorer with a doc preview and a Docs table."}]},{title:"Pages and Videos",items:[{term:"The list",body:"One row per page or video; a video row adds a thumbnail, its length, its loudness (LUFS) and its reading grade. Select a row to open it — a page shows in a sandboxed frame where no script runs, a video plays in its player above its SOURCES and QUALITY REPORT cards. Rename and Delete sit under the selected row."},{term:"Generate page / Generate video",body:"Opens the Generate composer. Start from a template — Overview, How it works, FAQ, Getting started, What’s new or Custom topic (you name the topic) for a page; Project demo, Feature spotlight, Blog post, Whiteboard explainer or Custom for a video — then adjust it. A page takes Written for (Newcomers, Users or Contributors), Length (Brief, Standard or In-depth) and Read from (README & docs, Source tree, Git log); a video takes Kind, a Feature or Post target, Style, Length (30 or 60 seconds) and Character on or off. Both take an optional Focus note. Your choices reach the builder as plain lines such as “Audience: Users” or “Video length: 60”."},{term:"Regenerate…",body:"In the selected page's or video's title bar. Opens the composer pre-filled from that entry and rebuilds it in place: the builder also gets a “Replace entry: <id>” line, so you end up with one updated entry, not a second copy."},{term:"While it builds",body:"A build runs in the background as a scheduler job in the builder's Session, so Project Home stays put. A building row sits at the top of the list (or the regenerated entry's own row turns building); select it to see its progress and, for a build started in this window, what was sent to the builder. Open session jumps to that Session. When the build finishes, a toast says “<title>” is ready; a failed build shows its reason in that row's place."},{term:"Empty library",body:"With nothing generated yet, the tab shows a starter gallery with one card per template. A card's Generate builds that template's defaults straight away; Customize opens the composer on it (the Custom topic card asks you to name a topic first)."}]},{title:"Tools",items:[{term:"Review MD network",body:"Always listed first. Its LINK MAP draws CLAUDE.md and the docs its links lead to; FINDINGS lists broken links and docs no link path from CLAUDE.md reaches; records (machine-written docs in a record collection, such as validation records) are left out of orphan findings. The strip above the cards says what the tracked docs are: how many are in the network, how many are records and how many are unlinked. Expand on the LINK MAP, or a click on a doc in it, opens the full-screen explorer: zoom and pan the whole map, search paths, and click a doc to read it in the doc preview (its role, usage, recency and contents, with links you can follow). Its Docs view is a table of every tracked doc you can filter and sort by recency, size, links and code mentions. Pick a Scope and a Mode (Full review or Drift check), then Run review opens an architect Session that reports first and changes no files until you approve. The map is scanned when you first open it and again on Refresh — never on a timer."},{term:"Your tools",body:"Every macro saved with Shown on: Project Home for this project is listed after it. A tool with inputs shows its form; otherwise press Run. Each press starts a new Session and opens it, the same as pressing a hot key."},{term:"Add a tool",body:"Opens the macro editor with Shown on already set to Project Home."}]},{title:"Behaviors this affects",items:[{body:"Pages and videos are folders under session-manager-operations/project-pages/ (knowledge/<id>/ and videos/<id>/). Rename changes only the title in the entry's meta.json; Delete removes the entry's folder."},{body:"A build needs delegation to be ready; if it is not, the press shows why in a toast and nothing is queued. Each library builds one entry at a time — Generate and Regenerate stay disabled while a build is queued or running."}]}],tips:["To refresh an out-of-date page or video, use Regenerate… on it — it replaces that entry instead of adding another.","Videos play only for projects inside your home folder.","The Tools badge stays hidden until you open Tools for this project — Project Home never scans on its own."]},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 Permissions tab of this page 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 of this page."},{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 Extensions › MCP Servers 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:"Merging is per key: Local beats Project beats User. Objects merge key by key, so a Project-scoped { permissions: { allow: [...] } } adds to the user-scoped permissions object instead of replacing it. Lists merge too (allow + allow), and for a plain value the more specific scope wins."}]}],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."]},memory:{headline:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},"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."]},extensions:{headline:"Extensions — skills, MCP servers and plugins in one place",intro:"Three tabs, one page. Each tab edits the real file Claude Code reads (shown as a chip at the top): ~/.claude/skills for skills, ~/.claude.json mcpServers for MCP servers, installed_plugins.json plus settings.json enabledPlugins for plugins. The Add button opens that tab's catalog.",sections:[{title:"Tabs",items:[{term:"Skills",body:"Markdown files Claude loads on demand, at User or Project scope. Each skill has frontmatter saying when to trigger it."},{term:"MCP Servers",body:"External tools Claude can call. User scope lives in ~/.claude.json; project scope in <repo>/.mcp.json."},{term:"Plugins",body:"Bundles of skills, subagents, hooks and MCP servers installed together and enabled per scope."}]}],tips:["Home face only — User-scope config is machine-wide."]},"app-settings":{headline:"App Settings — Session Manager's own preferences",intro:"Everything here configures this app, not Claude Code: voice input, appearance, telemetry, phone remote, updates and retention, startup behavior, and a map of where the app stores its data. Claude Code's own settings.json lives on the Settings page.",sections:[{title:"Tabs",items:[{term:"Voice",body:"On-device transcription, push-to-talk hotkey, microphone and text-to-speech."},{term:"Storage map",body:"A hand-maintained ERD of what Session Manager persists, its paths and single-writer owners."}]}],tips:["Home face only — these preferences are machine-wide."]}};function UB({content:n}){return r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:n.intro}),n.sections.map(e=>r.jsxs("div",{className:"mb-3 last:mb-0",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),r.jsx("ul",{className:"space-y-1",children:e.items.map((t,i)=>r.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&r.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",r.jsx("span",{children:t.body})]},i))})]},e.title)),n.tips&&n.tips.length>0&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),r.jsx("ul",{className:"space-y-1",children:n.tips.map((e,t)=>r.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function VB({active:n}){const e=ss(g=>g.learningPanelCollapsed),t=ss(g=>g.setLearningPanelCollapsed),i=ss(g=>g.hydrated),s=ss(g=>g.hydrate);M.useEffect(()=>{i||s()},[i,s]);const[a,u]=M.useState(()=>!e),l=M.useRef(null);M.useEffect(()=>{i&&u(!e)},[i]);const d=M.useCallback(()=>{u(g=>{const b=!g;return t(!b),b})},[t]);M.useEffect(()=>{if(!a)return;const g=b=>{var C;(C=l.current)!=null&&C.contains(b.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a,t]);const h=M.useRef(!1);M.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const m=WB[n];return m?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:d,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":a,title:a?"Close learning panel":"What is this?",children:"Learn"}),a&&r.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:r.jsx(UB,{content:m})})]}):null}function qB({eyebrow:n,title:e,intro:t,frame:i=!0,learnKey:s,hideTitle:a=!1,children:u}){const l=i&&(n||e||t);return r.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[l&&r.jsxs("header",{className:`shrink-0 px-8 pt-7 flex items-start justify-between gap-4 ${a?"pb-0":"pb-5"}`,children:[r.jsxs("div",{className:"max-w-[820px]",children:[n&&r.jsx("div",{className:`text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint${a?"":" mb-2"}`,children:n}),a?r.jsx("div",{"aria-hidden":"true",className:"h-2","data-testid":"section-frame-title-spacer"}):e&&r.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&r.jsx("p",{className:`text-[14px] text-fg-dim leading-[1.55]${a?"":" mt-3"}`,children:t})]}),s&&r.jsx(VB,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const KB=M.lazy(()=>Kn(()=>import("./History-Bm3KXXs1.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(n=>({default:n.History}))),YB=M.lazy(()=>Kn(()=>import("./Scheduler-BS82wfRP.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(n=>({default:n.Scheduler}))),XB=M.lazy(()=>Kn(()=>import("./Settings-DWPHJ94d.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(n=>({default:n.Settings}))),JB=M.lazy(()=>Kn(()=>import("./SystemPrompt-BYtKMAr3.js"),__vite__mapDeps([15,4,8,9,16,10,1,2]),import.meta.url).then(n=>({default:n.SystemPrompt}))),ZB=M.lazy(()=>Kn(()=>import("./ProjectClaudeConfig-DIzNAala.js"),__vite__mapDeps([17,11,10,8,9,16,18,7,4,12,13,14,1,2,19,20]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),QB=M.lazy(()=>Kn(()=>import("./Extensions-CjPiz2I5.js"),__vite__mapDeps([21,10,19,4,13,8,9,14,20,1,2]),import.meta.url).then(n=>({default:n.Extensions}))),eF=M.lazy(()=>Kn(()=>import("./AppSettings-vMiIi0xn.js"),__vite__mapDeps([22,11,10,20,18,4,1,2]),import.meta.url).then(n=>({default:n.AppSettings}))),tF=M.lazy(()=>Kn(()=>import("./AgentLibrary-BBY7E1ag.js"),__vite__mapDeps([23,4,13,11,10,9,12,1,2]),import.meta.url).then(n=>({default:n.AgentLibrary}))),nF=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Zl({children:n}){return r.jsx(M.Suspense,{fallback:nF,children:n})}const iF={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."},memory:{title:"Claude config",intro:"This project's own Claude Code files — its memory folder, CLAUDE.md and CLAUDE.local.md, .claude/settings.json and settings.local.json, .mcp.json and .claude/skills/. Each tab edits the real file the claude CLI reads when a session starts here; ~/.claude is edited from Home."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads.",hideTitle:!0},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Global personas live in ~/.claude/agents, and any open project, picked in a persona’s project override, can get its own model or effort. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},Dk=new Map;function sF(n,e){const t=Dk.get(n);if(t&&t.ctx===e)return t.node;const i=rF(n,e);return Dk.set(n,{ctx:e,node:i}),i}function rF(n,e){switch(n){case"overview":return r.jsx(MM,{onNavigate:e.onNavigate});case"project-home":return r.jsx(uz,{});case"editor":return r.jsx(Gw,{});case"projects":return r.jsx(HB,{})}const t=iF[n],i=(()=>{switch(n){case"history":return r.jsx(Zl,{children:r.jsx(KB,{})});case"scheduler":return r.jsx(Zl,{children:r.jsx(YB,{navigate:e.onNavigate})});case"memory":return r.jsx(Zl,{children:r.jsx(ZB,{})});case"system-prompt":return r.jsx(Zl,{children:r.jsx(JB,{})});case"settings":return r.jsx(Zl,{children:r.jsx(XB,{scope:"user"})});case"extensions":return r.jsx(Zl,{children:r.jsx(QB,{})});case"app-settings":return r.jsx(Zl,{children:r.jsx(eF,{})});case"agent-library":return r.jsx(Zl,{children:r.jsx(tF,{})});default:return null}})();if(!i)return null;const s=IN[n];return t&&s?r.jsx(qB,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class oF extends M.Component{constructor(){super(...arguments);oi(this,"state",{error:null});oi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,i){console.error("[ErrorBoundary]",t,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):r.jsxs("div",{className:"p-6 text-xs",children:[r.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),r.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),r.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}}var k_={exports:{}},jk;function aF(){return jk||(jk=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,d){var h=this&&this.__decorate||function(x,y,T,$){var I,O=arguments.length,A=O<3?y:$===null?$=Object.getOwnPropertyDescriptor(y,T):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,y,T,$);else for(var L=x.length-1;L>=0;L--)(I=x[L])&&(A=(O<3?I(A):O>3?I(y,T,A):I(y,T))||A);return O>3&&A&&Object.defineProperty(y,T,A),A},m=this&&this.__param||function(x,y){return function(T,$){y(T,$,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const g=d(9042),b=d(9924),C=d(844),k=d(4725),E=d(2585),_=d(3656);let S=l.AccessibilityManager=class extends C.Disposable{constructor(x,y,T,$){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=$,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 I=0;I<this._terminal.rows;I++)this._rowElements[I]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[I]);if(this._topBoundaryFocusListener=I=>this._handleBoundaryFocus(I,0),this._bottomBoundaryFocusListener=I=>this._handleBoundaryFocus(I,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 b.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((I=>this._handleResize(I.rows)))),this.register(this._terminal.onRender((I=>this._refreshRows(I.start,I.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((I=>this._handleChar(I)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3055
3055
|
`)))),this.register(this._terminal.onA11yTab((I=>this._handleTab(I)))),this.register(this._terminal.onKey((I=>this._handleKey(I.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,_.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,C.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(x){for(let y=0;y<x;y++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
|
|
3056
3056
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,y){this._liveRegionDebouncer.refresh(x,y,this._terminal.rows)}_renderRows(x,y){const T=this._terminal.buffer,$=T.lines.length.toString();for(let I=x;I<=y;I++){const O=T.lines.get(T.ydisp+I),A=[],L=(O==null?void 0:O.translateToString(!0,void 0,void 0,A))||"",V=(T.ydisp+I+1).toString(),te=this._rowElements[I];te&&(L.length===0?(te.innerText=" ",this._rowColumns.set(te,[0,1])):(te.textContent=L,this._rowColumns.set(te,A)),te.setAttribute("aria-posinset",V),te.setAttribute("aria-setsize",$))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,y){const T=x.target,$=this._rowElements[y===0?1:this._rowElements.length-2];if(T.getAttribute("aria-posinset")===(y===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==$)return;let I,O;if(y===0?(I=T,O=this._rowElements.pop(),this._rowContainer.removeChild(O)):(I=this._rowElements.shift(),O=T,this._rowContainer.removeChild(I)),I.removeEventListener("focus",this._topBoundaryFocusListener),O.removeEventListener("focus",this._bottomBoundaryFocusListener),y===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(y===0?-1:1),this._rowElements[y===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var L;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let y={node:x.anchorNode,offset:x.anchorOffset},T={node:x.focusNode,offset:x.focusOffset};if((y.node.compareDocumentPosition(T.node)&Node.DOCUMENT_POSITION_PRECEDING||y.node===T.node&&y.offset>T.offset)&&([y,T]=[T,y]),y.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(y={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(y.node))return;const $=this._rowElements.slice(-1)[0];if(T.node.compareDocumentPosition($)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(T={node:$,offset:((L=$.textContent)==null?void 0:L.length)??0}),!this._rowContainer.contains(T.node))return;const I=({node:V,offset:te})=>{const re=V instanceof Text?V.parentNode:V;let K=parseInt(re==null?void 0:re.getAttribute("aria-posinset"),10)-1;if(isNaN(K))return console.warn("row is invalid. Race condition?"),null;const de=this._rowColumns.get(re);if(!de)return console.warn("columns is null. Race condition?"),null;let J=te<de.length?de[te]:de.slice(-1)[0]+1;return J>=this._terminal.cols&&(++K,J=0),{row:K,column:J}},O=I(y),A=I(T);if(O&&A){if(O.row>A.row||O.row===A.row&&O.column>=A.column)throw new Error("invalid range");this._terminal.select(O.column,O.row,(A.row-O.row)*this._terminal.cols-O.column+A.column)}}_handleResize(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let y=this._rowContainer.children.length;y<this._terminal.rows;y++)this._rowElements[y]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[y]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=S=h([m(1,E.IInstantiationService),m(2,k.ICoreBrowserService),m(3,k.IRenderService)],S)},3614:(u,l)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function h(b,C){return C?"\x1B[200~"+b+"\x1B[201~":b}function m(b,C,k,E){b=h(b=d(b),k.decPrivateModes.bracketedPasteMode&&E.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(b,!0),C.value=""}function g(b,C,k){const E=k.getBoundingClientRect(),_=b.clientX-E.left-10,S=b.clientY-E.top-10;C.style.width="20px",C.style.height="20px",C.style.left=`${_}px`,C.style.top=`${S}px`,C.style.zIndex="1000",C.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=d,l.bracketTextForPaste=h,l.copyHandler=function(b,C){b.clipboardData&&b.clipboardData.setData("text/plain",C.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,C,k,E){b.stopPropagation(),b.clipboardData&&m(b.clipboardData.getData("text/plain"),C,k,E)},l.paste=m,l.moveTextAreaUnderMouseCursor=g,l.rightClickHandler=function(b,C,k,E,_){g(b,C,k),_&&E.rightClickSelect(b),C.value=E.selectionText,C.select()}},7239:(u,l,d)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const h=d(1505);l.ColorContrastCache=class{constructor(){this._color=new h.TwoKeyMap,this._css=new h.TwoKeyMap}setCss(m,g,b){this._css.set(m,g,b)}getCss(m,g){return this._css.get(m,g)}setColor(m,g,b){this._color.set(m,g,b)}getColor(m,g){return this._color.get(m,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(d,h,m,g){d.addEventListener(h,m,g);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(h,m,g))}}}},3551:function(u,l,d){var h=this&&this.__decorate||function(S,x,y,T){var $,I=arguments.length,O=I<3?x:T===null?T=Object.getOwnPropertyDescriptor(x,y):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(S,x,y,T);else for(var A=S.length-1;A>=0;A--)($=S[A])&&(O=(I<3?$(O):I>3?$(x,y,O):$(x,y))||O);return I>3&&O&&Object.defineProperty(x,y,O),O},m=this&&this.__param||function(S,x){return function(y,T){x(y,T,S)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const g=d(3656),b=d(8460),C=d(844),k=d(2585),E=d(4725);let _=l.Linkifier=class extends C.Disposable{get currentLink(){return this._currentLink}constructor(S,x,y,T,$){super(),this._element=S,this._mouseService=x,this._renderService=y,this._bufferService=T,this._linkProviderService=$,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,C.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,C.toDisposable)((()=>{var I;this._lastMouseEvent=void 0,(I=this._activeProviderReplies)==null||I.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(S){this._lastMouseEvent=S;const x=this._positionFromMouseEvent(S,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const y=S.composedPath();for(let T=0;T<y.length;T++){const $=y[T];if($.classList.contains("xterm"))break;if($.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(S){if(this._activeLine!==S.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(S,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,S)||(this._clearCurrentLink(),this._askForLink(S,!0))}_askForLink(S,x){var T,$;this._activeProviderReplies&&x||((T=this._activeProviderReplies)==null||T.forEach((I=>{I==null||I.forEach((O=>{O.link.dispose&&O.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=S.y);let y=!1;for(const[I,O]of this._linkProviderService.linkProviders.entries())x?($=this._activeProviderReplies)!=null&&$.get(I)&&(y=this._checkLinkProviderResult(I,S,y)):O.provideLinks(S.y,(A=>{var V,te;if(this._isMouseOut)return;const L=A==null?void 0:A.map((re=>({link:re})));(V=this._activeProviderReplies)==null||V.set(I,L),y=this._checkLinkProviderResult(I,S,y),((te=this._activeProviderReplies)==null?void 0:te.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(S.y,this._activeProviderReplies)}))}_removeIntersectingLinks(S,x){const y=new Set;for(let T=0;T<x.size;T++){const $=x.get(T);if($)for(let I=0;I<$.length;I++){const O=$[I],A=O.link.range.start.y<S?0:O.link.range.start.x,L=O.link.range.end.y>S?this._bufferService.cols:O.link.range.end.x;for(let V=A;V<=L;V++){if(y.has(V)){$.splice(I--,1);break}y.add(V)}}}}_checkLinkProviderResult(S,x,y){var I;if(!this._activeProviderReplies)return y;const T=this._activeProviderReplies.get(S);let $=!1;for(let O=0;O<S;O++)this._activeProviderReplies.has(O)&&!this._activeProviderReplies.get(O)||($=!0);if(!$&&T){const O=T.find((A=>this._linkAtPosition(A.link,x)));O&&(y=!0,this._handleNewLink(O))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!y)for(let O=0;O<this._activeProviderReplies.size;O++){const A=(I=this._activeProviderReplies.get(O))==null?void 0:I.find((L=>this._linkAtPosition(L.link,x)));if(A){y=!0,this._handleNewLink(A);break}}return y}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(S){if(!this._currentLink)return;const x=this._positionFromMouseEvent(S,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(S,this._currentLink.link.text)}_clearCurrentLink(S,x){this._currentLink&&this._lastMouseEvent&&(!S||!x||this._currentLink.link.range.start.y>=S&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,C.disposeArray)(this._linkCacheDisposables))}_handleNewLink(S){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(S.link,x)&&(this._currentLink=S,this._currentLink.state={decorations:{underline:S.link.decorations===void 0||S.link.decorations.underline,pointerCursor:S.link.decorations===void 0||S.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,S.link,this._lastMouseEvent),S.link.decorations={},Object.defineProperties(S.link.decorations,{pointerCursor:{get:()=>{var y,T;return(T=(y=this._currentLink)==null?void 0:y.state)==null?void 0:T.decorations.pointerCursor},set:y=>{var T;(T=this._currentLink)!=null&&T.state&&this._currentLink.state.decorations.pointerCursor!==y&&(this._currentLink.state.decorations.pointerCursor=y,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",y))}},underline:{get:()=>{var y,T;return(T=(y=this._currentLink)==null?void 0:y.state)==null?void 0:T.decorations.underline},set:y=>{var T,$,I;(T=this._currentLink)!=null&&T.state&&((I=($=this._currentLink)==null?void 0:$.state)==null?void 0:I.decorations.underline)!==y&&(this._currentLink.state.decorations.underline=y,this._currentLink.state.isHovered&&this._fireUnderlineEvent(S.link,y))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((y=>{if(!this._currentLink)return;const T=y.start===0?0:y.start+1+this._bufferService.buffer.ydisp,$=this._bufferService.buffer.ydisp+1+y.end;if(this._currentLink.link.range.start.y>=T&&this._currentLink.link.range.end.y<=$&&(this._clearCurrentLink(T,$),this._lastMouseEvent)){const I=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);I&&this._askForLink(I,!1)}}))))}_linkHover(S,x,y){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&S.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(y,x.text)}_fireUnderlineEvent(S,x){const y=S.range,T=this._bufferService.buffer.ydisp,$=this._createLinkUnderlineEvent(y.start.x-1,y.start.y-T-1,y.end.x,y.end.y-T-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire($)}_linkLeave(S,x,y){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&S.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(y,x.text)}_linkAtPosition(S,x){const y=S.range.start.y*this._bufferService.cols+S.range.start.x,T=S.range.end.y*this._bufferService.cols+S.range.end.x,$=x.y*this._bufferService.cols+x.x;return y<=$&&$<=T}_positionFromMouseEvent(S,x,y){const T=y.getCoords(S,x,this._bufferService.cols,this._bufferService.rows);if(T)return{x:T[0],y:T[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(S,x,y,T,$){return{x1:S,y1:x,x2:y,y2:T,cols:this._bufferService.cols,fg:$}}};l.Linkifier=_=h([m(1,E.IMouseService),m(2,E.IRenderService),m(3,k.IBufferService),m(4,E.ILinkProviderService)],_)},9042:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(u,l,d){var h=this&&this.__decorate||function(E,_,S,x){var y,T=arguments.length,$=T<3?_:x===null?x=Object.getOwnPropertyDescriptor(_,S):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(E,_,S,x);else for(var I=E.length-1;I>=0;I--)(y=E[I])&&($=(T<3?y($):T>3?y(_,S,$):y(_,S))||$);return T>3&&$&&Object.defineProperty(_,S,$),$},m=this&&this.__param||function(E,_){return function(S,x){_(S,x,E)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const g=d(511),b=d(2585);let C=l.OscLinkProvider=class{constructor(E,_,S){this._bufferService=E,this._optionsService=_,this._oscLinkService=S}provideLinks(E,_){var L;const S=this._bufferService.buffer.lines.get(E-1);if(!S)return void _(void 0);const x=[],y=this._optionsService.rawOptions.linkHandler,T=new g.CellData,$=S.getTrimmedLength();let I=-1,O=-1,A=!1;for(let V=0;V<$;V++)if(O!==-1||S.hasContent(V)){if(S.loadCell(V,T),T.hasExtendedAttrs()&&T.extended.urlId){if(O===-1){O=V,I=T.extended.urlId;continue}A=T.extended.urlId!==I}else O!==-1&&(A=!0);if(A||O!==-1&&V===$-1){const te=(L=this._oscLinkService.getLinkData(I))==null?void 0:L.uri;if(te){const re={start:{x:O+1,y:E},end:{x:V+(A||V!==$-1?0:1),y:E}};let K=!1;if(!(y!=null&&y.allowNonHttpProtocols))try{const de=new URL(te);["http:","https:"].includes(de.protocol)||(K=!0)}catch{K=!0}K||x.push({text:te,range:re,activate:(de,J)=>y?y.activate(de,J,re):k(0,J),hover:(de,J)=>{var he;return(he=y==null?void 0:y.hover)==null?void 0:he.call(y,de,J,re)},leave:(de,J)=>{var he;return(he=y==null?void 0:y.leave)==null?void 0:he.call(y,de,J,re)}})}A=!1,T.hasExtendedAttrs()&&T.extended.urlId?(O=V,I=T.extended.urlId):(O=-1,I=-1)}}_(x)}};function k(E,_){if(confirm(`Do you want to navigate to ${_}?
|
|
3057
3057
|
|