claude-code-session-manager 0.140.0 → 0.141.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AppSettings-CMFEM68R.js → AppSettings-DExeJhqQ.js} +1 -1
- package/dist/assets/{History--JwsFnbn.js → History-DJMiuXyK.js} +1 -1
- package/dist/assets/{HomeClaudeConfig-ijEXs--3.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
- package/dist/assets/{Panel-CALyU0pe.js → Panel-Bf1Cf8UL.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-sdlA-fUb.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
- package/dist/assets/{Scheduler-YT3j8SUa.js → Scheduler-cyr61UAC.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-CxAuwhNN.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
- package/dist/assets/{Skills-DtRzghn5.js → Skills-C1v91GEO.js} +1 -1
- package/dist/assets/{TiptapBody-DApeu7x8.js → TiptapBody-BrcWVpiW.js} +1 -1
- package/dist/assets/{ViewTabs-B7qLXRAH.js → ViewTabs-DXhOWFG0.js} +1 -1
- package/dist/assets/{VoiceButton-DtStfv1H.js → VoiceButton-qivnDV6K.js} +1 -1
- package/dist/assets/{historyTotals-ydfnwepc.js → historyTotals-CMCPTKqC.js} +1 -1
- package/dist/assets/{index-CtxruO1L.js → index-B2TQz3nd.js} +3 -3
- package/dist/index.html +1 -1
- package/dist-web/app.js +1 -1
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -0
- package/scripts/scheduler-mcp-server.cjs +5 -0
- package/src/main/build-info.json +4 -4
- package/src/main/ipcSchemas.cjs +10 -0
- package/src/main/lib/mcpToolCatalog.cjs +11 -2
- package/src/main/lib/prd/prdCreate.cjs +27 -1
- package/src/main/lib/prd/prdFrontmatter.cjs +28 -3
- package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
- package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
- package/src/main/scheduler/prdParser.cjs +16 -1
- package/src/main/scheduler/reviewLadder.cjs +36 -3
- package/src/main/scheduler/starvation.cjs +69 -0
- package/src/main/scheduler.cjs +335 -25
- package/src/main/templates/PRD_AUTHORING.md +9 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./History
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./History-DJMiuXyK.js","./Panel-Bf1Cf8UL.js","./historyTotals-CMCPTKqC.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./Scheduler-cyr61UAC.js","./ProjectClaudeConfig-BWPpypf9.js","./Skills-C1v91GEO.js","./ViewTabs-DXhOWFG0.js","./TiptapBody-BrcWVpiW.js","./VoiceButton-qivnDV6K.js","./HomeClaudeConfig-CTp2tkZ4.js","./AppSettings-DExeJhqQ.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var pN=Object.defineProperty;var fN=(n,e,t)=>e in n?pN(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ri=(n,e,t)=>fN(n,typeof e!="symbol"?e+"":e,t);import{_ as ti}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 zy(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Pb={exports:{}},Of={},Mb={exports:{}},Pn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -2932,7 +2932,7 @@ ${P}`,z=_.createShaderModule({code:O,label:o.name});xn("verbose",()=>`[WebGPU] $
|
|
|
2932
2932
|
* Licensed under the MIT License.
|
|
2933
2933
|
*/var vS;function EI(){return vS||(vS=1,(function(n,e){var t=(()=>{var i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,l=(Q=>typeof go<"u"?go:typeof Proxy<"u"?new Proxy(Q,{get:(ae,me)=>(typeof go<"u"?go:ae)[me]}):Q)(function(Q){if(typeof go<"u")return go.apply(this,arguments);throw Error('Dynamic require of "'+Q+'" is not supported')}),c=(Q,ae)=>()=>(Q&&(ae=Q(Q=0)),ae),h=(Q,ae)=>{for(var me in ae)i(Q,me,{get:ae[me],enumerable:!0})},m=(Q,ae,me,$e)=>{if(ae&&typeof ae=="object"||typeof ae=="function")for(let Se of a(ae))!u.call(Q,Se)&&Se!==me&&i(Q,Se,{get:()=>ae[Se],enumerable:!($e=s(ae,Se))||$e.enumerable});return Q},g=Q=>m(i({},"__esModule",{value:!0}),Q),v,E,k,C,x,b=c(()=>{v=new Map,E=[],k=(Q,ae,me)=>{if(ae&&typeof ae.init=="function"&&typeof ae.createInferenceSessionHandler=="function"){let $e=v.get(Q);if($e===void 0)v.set(Q,{backend:ae,priority:me});else{if($e.priority>me)return;if($e.priority===me&&$e.backend!==ae)throw new Error(`cannot register backend "${Q}" using priority ${me}`)}if(me>=0){let Se=E.indexOf(Q);Se!==-1&&E.splice(Se,1);for(let Fe=0;Fe<E.length;Fe++)if(v.get(E[Fe]).priority<=me){E.splice(Fe,0,Q);return}E.push(Q)}return}throw new TypeError("not a valid backend")},C=async Q=>{let ae=v.get(Q);if(!ae)return"backend not found.";if(ae.initialized)return ae.backend;if(ae.aborted)return ae.error;{let me=!!ae.initPromise;try{return me||(ae.initPromise=ae.backend.init(Q)),await ae.initPromise,ae.initialized=!0,ae.backend}catch($e){return me||(ae.error=`${$e}`,ae.aborted=!0),ae.error}finally{delete ae.initPromise}}},x=async Q=>{let ae=Q.executionProviders||[],me=ae.map(Ge=>typeof Ge=="string"?Ge:Ge.name),$e=me.length===0?E:me,Se,Fe=[],Ie=new Set;for(let Ge of $e){let nt=await C(Ge);typeof nt=="string"?Fe.push({name:Ge,err:nt}):(Se||(Se=nt),Se===nt&&Ie.add(Ge))}if(!Se)throw new Error(`no available backend found. ERR: ${Fe.map(Ge=>`[${Ge.name}] ${Ge.err}`).join(", ")}`);for(let{name:Ge,err:nt}of Fe)me.includes(Ge)&&console.warn(`removing requested execution provider "${Ge}" from session options because it is not available: ${nt}`);let Re=ae.filter(Ge=>Ie.has(typeof Ge=="string"?Ge:Ge.name));return[Se,new Proxy(Q,{get:(Ge,nt)=>nt==="executionProviders"?Re:Reflect.get(Ge,nt)})]}}),w=c(()=>{b()}),S,T=c(()=>{S="1.26.0"}),I,A,M=c(()=>{T(),I="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:S},set logLevel(Q){if(Q!==void 0){if(typeof Q!="string"||["verbose","info","warning","error","fatal"].indexOf(Q)===-1)throw new Error(`Unsupported logging level: ${Q}`);I=Q}},get logLevel(){return I}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),N,L=c(()=>{M(),N=A}),U,J,Z=c(()=>{U=(Q,ae)=>{let me=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);me.width=Q.dims[3],me.height=Q.dims[2];let $e=me.getContext("2d");if($e!=null){let Se,Fe;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(Se=Q.dims[2],Fe=Q.dims[3]):(Se=Q.dims[3],Fe=Q.dims[2]);let Ie=(ae==null?void 0:ae.format)!==void 0?ae.format:"RGB",Re=ae==null?void 0:ae.norm,Ge,nt;Re===void 0||Re.mean===void 0?Ge=[255,255,255,255]:typeof Re.mean=="number"?Ge=[Re.mean,Re.mean,Re.mean,Re.mean]:(Ge=[Re.mean[0],Re.mean[1],Re.mean[2],0],Re.mean[3]!==void 0&&(Ge[3]=Re.mean[3])),Re===void 0||Re.bias===void 0?nt=[0,0,0,0]:typeof Re.bias=="number"?nt=[Re.bias,Re.bias,Re.bias,Re.bias]:(nt=[Re.bias[0],Re.bias[1],Re.bias[2],0],Re.bias[3]!==void 0&&(nt[3]=Re.bias[3]));let ht=Fe*Se,rt=0,Je=ht,Bt=ht*2,Be=-1;Ie==="RGBA"?(rt=0,Je=ht,Bt=ht*2,Be=ht*3):Ie==="RGB"?(rt=0,Je=ht,Bt=ht*2):Ie==="RBG"&&(rt=0,Bt=ht,Je=ht*2);for(let xt=0;xt<Fe;xt++)for(let Xn=0;Xn<Se;Xn++){let dn=(Q.data[rt++]-nt[0])*Ge[0],un=(Q.data[Je++]-nt[1])*Ge[1],Jn=(Q.data[Bt++]-nt[2])*Ge[2],qt=Be===-1?255:(Q.data[Be++]-nt[3])*Ge[3];$e.fillStyle="rgba("+dn+","+un+","+Jn+","+qt+")",$e.fillRect(Xn,xt,1,1)}if("toDataURL"in me)return me.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},J=(Q,ae)=>{let me=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),$e;if(me!=null){let Se,Fe,Ie;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(Se=Q.dims[2],Fe=Q.dims[1],Ie=Q.dims[3]):(Se=Q.dims[3],Fe=Q.dims[2],Ie=Q.dims[1]);let Re=ae!==void 0&&ae.format!==void 0?ae.format:"RGB",Ge=ae==null?void 0:ae.norm,nt,ht;Ge===void 0||Ge.mean===void 0?nt=[255,255,255,255]:typeof Ge.mean=="number"?nt=[Ge.mean,Ge.mean,Ge.mean,Ge.mean]:(nt=[Ge.mean[0],Ge.mean[1],Ge.mean[2],255],Ge.mean[3]!==void 0&&(nt[3]=Ge.mean[3])),Ge===void 0||Ge.bias===void 0?ht=[0,0,0,0]:typeof Ge.bias=="number"?ht=[Ge.bias,Ge.bias,Ge.bias,Ge.bias]:(ht=[Ge.bias[0],Ge.bias[1],Ge.bias[2],0],Ge.bias[3]!==void 0&&(ht[3]=Ge.bias[3]));let rt=Fe*Se;if(ae!==void 0&&(ae.format!==void 0&&Ie===4&&ae.format!=="RGBA"||Ie===3&&ae.format!=="RGB"&&ae.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Je=4,Bt=0,Be=1,xt=2,Xn=3,dn=0,un=rt,Jn=rt*2,qt=-1;Re==="RGBA"?(dn=0,un=rt,Jn=rt*2,qt=rt*3):Re==="RGB"?(dn=0,un=rt,Jn=rt*2):Re==="RBG"&&(dn=0,Jn=rt,un=rt*2),$e=me.createImageData(Se,Fe);for(let li=0;li<Fe*Se;Bt+=Je,Be+=Je,xt+=Je,Xn+=Je,li++)$e.data[Bt]=(Q.data[dn++]-ht[0])*nt[0],$e.data[Be]=(Q.data[un++]-ht[1])*nt[1],$e.data[xt]=(Q.data[Jn++]-ht[2])*nt[2],$e.data[Xn]=qt===-1?255:(Q.data[qt++]-ht[3])*nt[3]}else throw new Error("Can not access image data");return $e}}),q,le,ie,he,ve,fe,B=c(()=>{Ae(),q=(Q,ae)=>{if(Q===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:me,width:$e}=ae,Se=ae.norm??{mean:255,bias:0},Fe,Ie;typeof Se.mean=="number"?Fe=[Se.mean,Se.mean,Se.mean,Se.mean]:Fe=[Se.mean[0],Se.mean[1],Se.mean[2],Se.mean[3]??255],typeof Se.bias=="number"?Ie=[Se.bias,Se.bias,Se.bias,Se.bias]:Ie=[Se.bias[0],Se.bias[1],Se.bias[2],Se.bias[3]??0];let Re=ae.format!==void 0?ae.format:"RGBA",Ge=ae.tensorFormat!==void 0&&ae.tensorFormat!==void 0?ae.tensorFormat:"RGB",nt=me*$e,ht=Ge==="RGBA"?new Float32Array(nt*4):new Float32Array(nt*3),rt=4,Je=0,Bt=1,Be=2,xt=3,Xn=0,dn=nt,un=nt*2,Jn=-1;Re==="RGB"&&(rt=3,Je=0,Bt=1,Be=2,xt=-1),Ge==="RGBA"?Jn=nt*3:Ge==="RBG"?(Xn=0,un=nt,dn=nt*2):Ge==="BGR"&&(un=0,dn=nt,Xn=nt*2);for(let qt=0;qt<nt;qt++,Je+=rt,Be+=rt,Bt+=rt,xt+=rt)ht[Xn++]=(Q[Je]+Ie[0])/Fe[0],ht[dn++]=(Q[Bt]+Ie[1])/Fe[1],ht[un++]=(Q[Be]+Ie[2])/Fe[2],Jn!==-1&&xt!==-1&&(ht[Jn++]=(Q[xt]+Ie[3])/Fe[3]);return Ge==="RGBA"?new te("float32",ht,[1,4,me,$e]):new te("float32",ht,[1,3,me,$e])},le=async(Q,ae)=>{let me=typeof HTMLImageElement<"u"&&Q instanceof HTMLImageElement,$e=typeof ImageData<"u"&&Q instanceof ImageData,Se=typeof ImageBitmap<"u"&&Q instanceof ImageBitmap,Fe=typeof Q=="string",Ie,Re=ae??{},Ge=()=>{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=ht=>typeof HTMLCanvasElement<"u"&&ht instanceof HTMLCanvasElement||ht instanceof OffscreenCanvas?ht.getContext("2d"):null;if(me){let ht=Ge();ht.width=Q.width,ht.height=Q.height;let rt=nt(ht);if(rt!=null){let Je=Q.height,Bt=Q.width;if(ae!==void 0&&ae.resizedHeight!==void 0&&ae.resizedWidth!==void 0&&(Je=ae.resizedHeight,Bt=ae.resizedWidth),ae!==void 0){if(Re=ae,ae.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Re.tensorFormat="RGBA",Re.height=Je,Re.width=Bt}else Re.tensorFormat="RGBA",Re.height=Je,Re.width=Bt;rt.drawImage(Q,0,0),Ie=rt.getImageData(0,0,Bt,Je).data}else throw new Error("Can not access image data")}else if($e){let ht,rt;if(ae!==void 0&&ae.resizedWidth!==void 0&&ae.resizedHeight!==void 0?(ht=ae.resizedHeight,rt=ae.resizedWidth):(ht=Q.height,rt=Q.width),ae!==void 0&&(Re=ae),Re.format="RGBA",Re.height=ht,Re.width=rt,ae!==void 0){let Je=Ge();Je.width=rt,Je.height=ht;let Bt=nt(Je);if(Bt!=null)Bt.putImageData(Q,0,0),Ie=Bt.getImageData(0,0,rt,ht).data;else throw new Error("Can not access image data")}else Ie=Q.data}else if(Se){if(ae===void 0)throw new Error("Please provide image config with format for Imagebitmap");let ht=Ge();ht.width=Q.width,ht.height=Q.height;let rt=nt(ht);if(rt!=null){let Je=Q.height,Bt=Q.width;return rt.drawImage(Q,0,0,Bt,Je),Ie=rt.getImageData(0,0,Bt,Je).data,Re.height=Je,Re.width=Bt,q(Ie,Re)}else throw new Error("Can not access image data")}else{if(Fe)return new Promise((ht,rt)=>{let Je=Ge(),Bt=nt(Je);if(!Q||!Bt)return rt();let Be=new Image;Be.crossOrigin="Anonymous",Be.src=Q,Be.onload=()=>{Je.width=Be.width,Je.height=Be.height,Bt.drawImage(Be,0,0,Je.width,Je.height);let xt=Bt.getImageData(0,0,Je.width,Je.height);Re.height=Je.height,Re.width=Je.width,ht(q(xt.data,Re))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ie!==void 0)return q(Ie,Re);throw new Error("Input data provided is not supported - aborted tensor creation")},ie=(Q,ae)=>{let{width:me,height:$e,download:Se,dispose:Fe}=ae,Ie=[1,$e,me,4];return new te({location:"texture",type:"float32",texture:Q,dims:Ie,download:Se,dispose:Fe})},he=(Q,ae)=>{let{dataType:me,dims:$e,download:Se,dispose:Fe}=ae;return new te({location:"gpu-buffer",type:me??"float32",gpuBuffer:Q,dims:$e,download:Se,dispose:Fe})},ve=(Q,ae)=>{let{dataType:me,dims:$e,download:Se,dispose:Fe}=ae;return new te({location:"ml-tensor",type:me??"float32",mlTensor:Q,dims:$e,download:Se,dispose:Fe})},fe=(Q,ae,me)=>new te({location:"cpu-pinned",type:Q,data:ae,dims:me??[ae.length]})}),K,W,ee,ce,ge=c(()=>{K=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),W=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ee=!1,ce=()=>{if(!ee){ee=!0;let Q=typeof BigInt64Array<"u"&&BigInt64Array.from,ae=typeof BigUint64Array<"u"&&BigUint64Array.from,me=globalThis.Float16Array,$e=typeof me<"u"&&me.from;Q&&(K.set("int64",BigInt64Array),W.set(BigInt64Array,"int64")),ae&&(K.set("uint64",BigUint64Array),W.set(BigUint64Array,"uint64")),$e?(K.set("float16",me),W.set(me,"float16")):K.set("float16",Uint16Array)}}}),Oe,We,xe=c(()=>{Ae(),Oe=Q=>{let ae=1;for(let me=0;me<Q.length;me++){let $e=Q[me];if(typeof $e!="number"||!Number.isSafeInteger($e))throw new TypeError(`dims[${me}] must be an integer, got: ${$e}`);if($e<0)throw new RangeError(`dims[${me}] must be a non-negative integer, got: ${$e}`);ae*=$e}return ae},We=(Q,ae)=>{switch(Q.location){case"cpu":return new te(Q.type,Q.data,ae);case"cpu-pinned":return new te({location:"cpu-pinned",data:Q.data,type:Q.type,dims:ae});case"texture":return new te({location:"texture",texture:Q.texture,type:Q.type,dims:ae});case"gpu-buffer":return new te({location:"gpu-buffer",gpuBuffer:Q.gpuBuffer,type:Q.type,dims:ae});case"ml-tensor":return new te({location:"ml-tensor",mlTensor:Q.mlTensor,type:Q.type,dims:ae});default:throw new Error(`tensorReshape: tensor location ${Q.location} is not supported`)}}}),te,Ae=c(()=>{Z(),B(),ge(),xe(),te=class{constructor(Q,ae,me){ce();let $e,Se;if(typeof Q=="object"&&"location"in Q)switch(this.dataLocation=Q.location,$e=Q.type,Se=Q.dims,Q.location){case"cpu-pinned":{let Ie=K.get($e);if(!Ie)throw new TypeError(`unsupported type "${$e}" to create tensor from pinned buffer`);if(!(Q.data instanceof Ie))throw new TypeError(`buffer should be of type ${Ie.name}`);this.cpuData=Q.data;break}case"texture":{if($e!=="float32")throw new TypeError(`unsupported type "${$e}" to create tensor from texture`);this.gpuTextureData=Q.texture,this.downloader=Q.download,this.disposer=Q.dispose;break}case"gpu-buffer":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" to create tensor from gpu buffer`);this.gpuBufferData=Q.gpuBuffer,this.downloader=Q.download,this.disposer=Q.dispose;break}case"ml-tensor":{if($e!=="float32"&&$e!=="float16"&&$e!=="int32"&&$e!=="int64"&&$e!=="uint32"&&$e!=="uint64"&&$e!=="int8"&&$e!=="uint8"&&$e!=="bool"&&$e!=="uint4"&&$e!=="int4")throw new TypeError(`unsupported type "${$e}" to create tensor from MLTensor`);this.mlTensorData=Q.mlTensor,this.downloader=Q.download,this.disposer=Q.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ie,Re;if(typeof Q=="string")if($e=Q,Re=me,Q==="string"){if(!Array.isArray(ae))throw new TypeError("A string tensor's data must be a string array.");Ie=ae}else{let Ge=K.get(Q);if(Ge===void 0)throw new TypeError(`Unsupported tensor type: ${Q}.`);if(Array.isArray(ae)){if(Q==="float16"&&Ge===Uint16Array||Q==="uint4"||Q==="int4")throw new TypeError(`Creating a ${Q} tensor from number array is not supported. Please use ${Ge.name} as data.`);Q==="uint64"||Q==="int64"?Ie=Ge.from(ae,BigInt):Ie=Ge.from(ae)}else if(ae instanceof Ge)Ie=ae;else if(ae instanceof Uint8ClampedArray)if(Q==="uint8")Ie=Uint8Array.from(ae);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Q==="float16"&&ae instanceof Uint16Array&&Ge!==Uint16Array)Ie=new globalThis.Float16Array(ae.buffer,ae.byteOffset,ae.length);else throw new TypeError(`A ${$e} tensor's data must be type of ${Ge}`)}else if(Re=ae,Array.isArray(Q)){if(Q.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Ge=typeof Q[0];if(Ge==="string")$e="string",Ie=Q;else if(Ge==="boolean")$e="bool",Ie=Uint8Array.from(Q);else throw new TypeError(`Invalid element type of data array: ${Ge}.`)}else if(Q instanceof Uint8ClampedArray)$e="uint8",Ie=Uint8Array.from(Q);else{let Ge=W.get(Q.constructor);if(Ge===void 0)throw new TypeError(`Unsupported type for tensor data: ${Q.constructor}.`);$e=Ge,Ie=Q}if(Re===void 0)Re=[Ie.length];else if(!Array.isArray(Re))throw new TypeError("A tensor's dims must be a number array");Se=Re,this.cpuData=Ie,this.dataLocation="cpu"}let Fe=Oe(Se);if(this.cpuData&&Fe!==this.cpuData.length&&!(($e==="uint4"||$e==="int4")&&Math.ceil(Fe/2)===this.cpuData.length))throw new Error(`Tensor's size(${Fe}) does not match data length(${this.cpuData.length}).`);this.type=$e,this.dims=Se,this.size=Fe}static async fromImage(Q,ae){return le(Q,ae)}static fromTexture(Q,ae){return ie(Q,ae)}static fromGpuBuffer(Q,ae){return he(Q,ae)}static fromMLTensor(Q,ae){return ve(Q,ae)}static fromPinnedBuffer(Q,ae,me){return fe(Q,ae,me)}toDataURL(Q){return U(this,Q)}toImageData(Q){return J(this,Q)}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(Q){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,Q&&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(Q){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return We(this,Q)}}}),Te,je=c(()=>{Ae(),Te=te}),Ee,Qe,bt,et,wt,gt,cn=c(()=>{M(),Ee=(Q,ae)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${Q}::ORT::${ae}`)},Qe=(Q,ae)=>{var Se;let me=((Se=new Error().stack)==null?void 0:Se.split(/\r\n|\r|\n/g))||[],$e=!1;for(let Fe=0;Fe<me.length;Fe++){if($e&&!me[Fe].includes("TRACE_FUNC")){let Ie=`FUNC_${Q}::${me[Fe].trim().split(" ")[1]}`;ae&&(Ie+=`::${ae}`),Ee("CPU",Ie);return}me[Fe].includes("TRACE_FUNC")&&($e=!0)}},bt=Q=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||Qe("BEGIN",Q)},et=Q=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||Qe("END",Q)},wt=Q=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.time(`ORT::${Q}`)},gt=Q=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeEnd(`ORT::${Q}`)}}),on,dt=c(()=>{b(),je(),cn(),on=class gT{constructor(ae){this.handler=ae}async run(ae,me,$e){bt(),wt("InferenceSession.run");let Se={},Fe={};if(typeof ae!="object"||ae===null||ae instanceof Te||Array.isArray(ae))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ie=!0;if(typeof me=="object"){if(me===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(me instanceof Te)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(me)){if(me.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ie=!1;for(let nt of me){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}.`);Se[nt]=null}if(typeof $e=="object"&&$e!==null)Fe=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else{let nt=!1,ht=Object.getOwnPropertyNames(me);for(let rt of this.outputNames)if(ht.indexOf(rt)!==-1){let Je=me[rt];(Je===null||Je instanceof Te)&&(nt=!0,Ie=!1,Se[rt]=Je)}if(nt){if(typeof $e=="object"&&$e!==null)Fe=$e;else if(typeof $e<"u")throw new TypeError("'options' must be an object.")}else Fe=me}}else if(typeof me<"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(Ie)for(let nt of this.outputNames)Se[nt]=null;let Re=await this.handler.run(ae,Se,Fe),Ge={};for(let nt in Re)if(Object.hasOwnProperty.call(Re,nt)){let ht=Re[nt];ht instanceof Te?Ge[nt]=ht:Ge[nt]=new Te(ht.type,ht.data,ht.dims)}return gt("InferenceSession.run"),et(),Ge}async release(){return this.handler.dispose()}static async create(ae,me,$e,Se){bt(),wt("InferenceSession.create");let Fe,Ie={};if(typeof ae=="string"){if(Fe=ae,typeof me=="object"&&me!==null)Ie=me;else if(typeof me<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof Uint8Array){if(Fe=ae,typeof me=="object"&&me!==null)Ie=me;else if(typeof me<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&ae instanceof SharedArrayBuffer){let ht=ae,rt=0,Je=ae.byteLength;if(typeof me=="object"&&me!==null)Ie=me;else if(typeof me=="number"){if(rt=me,!Number.isSafeInteger(rt))throw new RangeError("'byteOffset' must be an integer.");if(rt<0||rt>=ht.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${ht.byteLength}).`);if(Je=ae.byteLength-rt,typeof $e=="number"){if(Je=$e,!Number.isSafeInteger(Je))throw new RangeError("'byteLength' must be an integer.");if(Je<=0||rt+Je>ht.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${ht.byteLength-rt}].`);if(typeof Se=="object"&&Se!==null)Ie=Se;else if(typeof Se<"u")throw new TypeError("'options' must be an object.")}else if(typeof $e<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof me<"u")throw new TypeError("'options' must be an object.");Fe=new Uint8Array(ht,rt,Je)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Re,Ge]=await x(Ie),nt=await Re.createInferenceSessionHandler(Fe,Ge);return gt("InferenceSession.create"),et(),new gT(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}}}),vt,_e=c(()=>{dt(),vt=on}),ot=c(()=>{}),it=c(()=>{}),Lt=c(()=>{}),bn=c(()=>{}),Tn={};h(Tn,{InferenceSession:()=>vt,TRACE:()=>Ee,TRACE_EVENT_BEGIN:()=>wt,TRACE_EVENT_END:()=>gt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>et,Tensor:()=>Te,env:()=>N,registerBackend:()=>k});var vn=c(()=>{w(),L(),_e(),je(),ot(),it(),cn(),Lt(),bn()}),oi=c(()=>{}),jn={};h(jn,{default:()=>Li});var Dn,Vt,Li,xi=c(()=>{var Q;be(),Hn(),On(),Dn="ort-wasm-proxy-worker",Vt=((Q=globalThis.self)==null?void 0:Q.name)===Dn,Vt&&(self.onmessage=ae=>{let{type:me,in:$e}=ae.data;try{switch(me){case"init-wasm":at($e.wasm).then(()=>{wn($e).then(()=>{postMessage({type:me})},Se=>{postMessage({type:me,err:Se})})},Se=>{postMessage({type:me,err:Se})});break;case"init-ep":{let{epName:Se,env:Fe}=$e;ii(Fe,Se).then(()=>{postMessage({type:me})},Ie=>{postMessage({type:me,err:Ie})});break}case"copy-from":{let{buffer:Se}=$e,Fe=xn(Se);postMessage({type:me,out:Fe});break}case"create":{let{model:Se,options:Fe}=$e;Hs(Se,Fe).then(Ie=>{postMessage({type:me,out:Ie})},Ie=>{postMessage({type:me,err:Ie})});break}case"release":to($e),postMessage({type:me});break;case"run":{let{sessionId:Se,inputIndices:Fe,inputs:Ie,outputIndices:Re,options:Ge}=$e;Xe(Se,Fe,Ie,Re,new Array(Re.length).fill(null),Ge).then(nt=>{nt.some(ht=>ht[3]!=="cpu")?postMessage({type:me,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:me,out:nt},kt([...Ie,...nt]))},nt=>{postMessage({type:me,err:nt})});break}case"end-profiling":Es($e),postMessage({type:me});break;default:}}catch(Se){postMessage({type:me,err:Se})}}),Li=Vt?null:ae=>new Worker(ae??ct,{type:"classic",name:Dn})}),zi,qi,ct,Mn,qn,_i,hi,Ki,st,St,Mt,pn,Gn,On=c(()=>{oi(),zi=typeof location>"u"?void 0:location.origin,qi=()=>{var Q,ae;return typeof document<"u"?(Q=document.currentScript)==null?void 0:Q.src:typeof self<"u"?(ae=self.location)==null?void 0:ae.href:void 0},ct=qi(),Mn=()=>{if(ct&&!ct.startsWith("blob:"))return ct.substring(0,ct.lastIndexOf("/")+1)},qn=(Q,ae)=>{try{let me=ae??ct;return(me?new URL(Q,me):new URL(Q)).origin===zi}catch{return!1}},_i=(Q,ae)=>{let me=ae??ct;try{return(me?new URL(Q,me):new URL(Q)).href}catch{return}},hi=(Q,ae)=>`${ae??"./"}${Q}`,Ki=async Q=>{let ae=await(await fetch(Q,{credentials:"same-origin"})).blob();return URL.createObjectURL(ae)},st=async Q=>(await import(Q)).default,St=(xi(),g(jn)).default,Mt=async()=>{if(!ct)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(qn(ct))return[void 0,St()];let Q=await Ki(ct);return[Q,St(Q)]},pn=void 0,Gn=async(Q,ae,me,$e)=>{let Se=pn&&!(Q||ae);if(Se)if(ct)Se=qn(ct)||$e&&!me;else if($e&&!me)Se=!0;else throw new Error("cannot determine the script source URL.");if(Se)return[void 0,pn];{let Fe="ort-wasm-simd-threaded.mjs",Ie=Q??_i(Fe,ae),Re=me&&Ie&&!qn(Ie,ae),Ge=Re?await Ki(Ie):Ie??hi(Fe,ae);return[Re?Ge:void 0,await st(Ge)]}}}),kn,$n,Yn,pi,Yi,Dt,Zn,at,yt,Hn=c(()=>{On(),$n=!1,Yn=!1,pi=!1,Yi=()=>{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}},Dt=()=>{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}},Zn=()=>{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}},at=async Q=>{if($n)return Promise.resolve();if(Yn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(pi)throw new Error("previous call to 'initializeWebAssembly()' failed.");Yn=!0;let ae=Q.initTimeout,me=Q.numThreads;if(Q.simd!==!1){if(Q.simd==="relaxed"){if(!Zn())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Dt())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let $e=Yi();me>1&&!$e&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+me+", 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."),Q.numThreads=me=1);let Se=Q.wasmPaths,Fe=typeof Se=="string"?Se:void 0,Ie=Se==null?void 0:Se.mjs,Re=(Ie==null?void 0:Ie.href)??Ie,Ge=Se==null?void 0:Se.wasm,nt=(Ge==null?void 0:Ge.href)??Ge,ht=Q.wasmBinary,[rt,Je]=await Gn(Re,Fe,me>1,!!ht||!!nt),Bt=!1,Be=[];if(ae>0&&Be.push(new Promise(xt=>{setTimeout(()=>{Bt=!0,xt()},ae)})),Be.push(new Promise((xt,Xn)=>{let dn={numThreads:me};if(ht)dn.wasmBinary=ht,dn.locateFile=un=>un;else if(nt||Fe)dn.locateFile=un=>nt??Fe+un;else if(Re&&Re.indexOf("blob:")!==0)dn.locateFile=un=>new URL(un,Re).href;else if(rt){let un=Mn();un&&(dn.locateFile=Jn=>un+Jn)}Je(dn).then(un=>{Yn=!1,$n=!0,kn=un,xt(),rt&&URL.revokeObjectURL(rt)},un=>{Yn=!1,pi=!0,Xn(un)})})),await Promise.race(Be),Bt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${ae}ms`)},yt=()=>{if($n&&kn)return kn;throw new Error("WebAssembly is not initialized yet.")}}),En,mn,Tt,Bi=c(()=>{Hn(),En=(Q,ae)=>{let me=yt(),$e=me.lengthBytesUTF8(Q)+1,Se=me._malloc($e);return me.stringToUTF8(Q,Se,$e),ae.push(Se),Se},mn=(Q,ae,me,$e)=>{if(typeof Q=="object"&&Q!==null){if(me.has(Q))throw new Error("Circular reference in options");me.add(Q)}Object.entries(Q).forEach(([Se,Fe])=>{let Ie=ae?ae+Se:Se;if(typeof Fe=="object")mn(Fe,Ie+".",me,$e);else if(typeof Fe=="string"||typeof Fe=="number")$e(Ie,Fe.toString());else if(typeof Fe=="boolean")$e(Ie,Fe?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Fe}`)})},Tt=Q=>{let ae=yt(),me=ae.stackSave();try{let $e=ae.PTR_SIZE,Se=ae.stackAlloc(2*$e);ae._OrtGetLastError(Se,Se+$e);let Fe=Number(ae.getValue(Se,$e===4?"i32":"i64")),Ie=ae.getValue(Se+$e,"*"),Re=Ie?ae.UTF8ToString(Ie):"";throw new Error(`${Q} ERROR_CODE: ${Fe}, ERROR_MESSAGE: ${Re}`)}finally{ae.stackRestore(me)}}}),us,Tr=c(()=>{Hn(),Bi(),us=Q=>{let ae=yt(),me=0,$e=[],Se=Q||{};try{if((Q==null?void 0:Q.logSeverityLevel)===void 0)Se.logSeverityLevel=2;else if(typeof Q.logSeverityLevel!="number"||!Number.isInteger(Q.logSeverityLevel)||Q.logSeverityLevel<0||Q.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Q.logSeverityLevel}`);if((Q==null?void 0:Q.logVerbosityLevel)===void 0)Se.logVerbosityLevel=0;else if(typeof Q.logVerbosityLevel!="number"||!Number.isInteger(Q.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Q.logVerbosityLevel}`);(Q==null?void 0:Q.terminate)===void 0&&(Se.terminate=!1);let Fe=0;return(Q==null?void 0:Q.tag)!==void 0&&(Fe=En(Q.tag,$e)),me=ae._OrtCreateRunOptions(Se.logSeverityLevel,Se.logVerbosityLevel,!!Se.terminate,Fe),me===0&&Tt("Can't create run options."),(Q==null?void 0:Q.extra)!==void 0&&mn(Q.extra,"",new WeakSet,(Ie,Re)=>{let Ge=En(Ie,$e),nt=En(Re,$e);ae._OrtAddRunConfigEntry(me,Ge,nt)!==0&&Tt(`Can't set a run config entry: ${Ie} - ${Re}.`)}),[me,$e]}catch(Fe){throw me!==0&&ae._OrtReleaseRunOptions(me),$e.forEach(Ie=>ae._free(Ie)),Fe}}}),ks,Fi,fr,Ri,Fr,eo,Ln=c(()=>{Hn(),Bi(),ks=Q=>{switch(Q){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: ${Q}`)}},Fi=Q=>{switch(Q){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Q}`)}},fr=Q=>{Q.extra||(Q.extra={}),Q.extra.session||(Q.extra.session={});let ae=Q.extra.session;ae.use_ort_model_bytes_directly||(ae.use_ort_model_bytes_directly="1"),Q.executionProviders&&Q.executionProviders.some(me=>(typeof me=="string"?me:me.name)==="webgpu")&&(Q.enableMemPattern=!1)},Ri=(Q,ae,me,$e)=>{let Se=En(ae,$e),Fe=En(me,$e);yt()._OrtAddSessionConfigEntry(Q,Se,Fe)!==0&&Tt(`Can't set a session config entry: ${ae} - ${me}.`)},Fr=async(Q,ae,me)=>{let $e=ae.executionProviders;for(let Se of $e){let Fe=typeof Se=="string"?Se:Se.name,Ie=[];switch(Fe){case"webnn":if(Fe="WEBNN",Ri(Q,"session.disable_quant_qdq","1",me),Ri(Q,"session.disable_qdq_constant_folding","1",me),typeof Se!="string"){let rt=Se==null?void 0:Se.deviceType;rt&&Ri(Q,"deviceType",rt,me)}break;case"webgpu":if(Fe="JS",typeof Se!="string"){let rt=Se;if(rt!=null&&rt.preferredLayout){if(rt.preferredLayout!=="NCHW"&&rt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${rt.preferredLayout}`);Ri(Q,"preferredLayout",rt.preferredLayout,me)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Fe}`)}let Re=En(Fe,me),Ge=Ie.length,nt=0,ht=0;if(Ge>0){nt=yt()._malloc(Ge*yt().PTR_SIZE),me.push(nt),ht=yt()._malloc(Ge*yt().PTR_SIZE),me.push(ht);for(let rt=0;rt<Ge;rt++)yt().setValue(nt+rt*yt().PTR_SIZE,Ie[rt][0],"*"),yt().setValue(ht+rt*yt().PTR_SIZE,Ie[rt][1],"*")}await yt()._OrtAppendExecutionProvider(Q,Re,nt,ht,Ge)!==0&&Tt(`Can't append execution provider: ${Fe}.`)}},eo=async Q=>{let ae=yt(),me=0,$e=[],Se=Q||{};fr(Se);try{let Fe=ks(Se.graphOptimizationLevel??"all"),Ie=Fi(Se.executionMode??"sequential"),Re=typeof Se.logId=="string"?En(Se.logId,$e):0,Ge=Se.logSeverityLevel??2;if(!Number.isInteger(Ge)||Ge<0||Ge>4)throw new Error(`log severity level is not valid: ${Ge}`);let nt=Se.logVerbosityLevel??0;if(!Number.isInteger(nt)||nt<0||nt>4)throw new Error(`log verbosity level is not valid: ${nt}`);let ht=typeof Se.optimizedModelFilePath=="string"?En(Se.optimizedModelFilePath,$e):0;if(me=ae._OrtCreateSessionOptions(Fe,!!Se.enableCpuMemArena,!!Se.enableMemPattern,Ie,!!Se.enableProfiling,0,Re,Ge,nt,ht),me===0&&Tt("Can't create session options."),Se.executionProviders&&await Fr(me,Se,$e),Se.enableGraphCapture!==void 0){if(typeof Se.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Se.enableGraphCapture}`);Ri(me,"enableGraphCapture",Se.enableGraphCapture.toString(),$e)}if(Se.freeDimensionOverrides)for(let[rt,Je]of Object.entries(Se.freeDimensionOverrides)){if(typeof rt!="string")throw new Error(`free dimension override name must be a string: ${rt}`);if(typeof Je!="number"||!Number.isInteger(Je)||Je<0)throw new Error(`free dimension override value must be a non-negative integer: ${Je}`);let Bt=En(rt,$e);ae._OrtAddFreeDimensionOverride(me,Bt,Je)!==0&&Tt(`Can't set a free dimension override: ${rt} - ${Je}.`)}return Se.extra!==void 0&&mn(Se.extra,"",new WeakSet,(rt,Je)=>{Ri(me,rt,Je,$e)}),[me,$e]}catch(Fe){throw me!==0&&ae._OrtReleaseSessionOptions(me)!==0&&Tt("Can't release session options."),$e.forEach(Ie=>ae._free(Ie)),Fe}}}),Xi,ai,ki,Bs,Fs,rr,hs,Pi,Wt=c(()=>{Xi=Q=>{switch(Q){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: ${Q}`)}},ai=Q=>{switch(Q){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: ${Q}`)}},ki=(Q,ae)=>{let me=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Q],$e=typeof ae=="number"?ae:ae.reduce((Se,Fe)=>Se*Fe,1);return me>0?Math.ceil($e*me):void 0},Bs=Q=>{switch(Q){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: ${Q}`)}},Fs=Q=>{switch(Q){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: ${Q}`)}},rr=Q=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",hs=Q=>Q==="float32"||Q==="float16"||Q==="int32"||Q==="int64"||Q==="uint32"||Q==="uint64"||Q==="int8"||Q==="uint8"||Q==="bool"||Q==="uint4"||Q==="int4",Pi=Q=>{switch(Q){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: ${Q}`)}}}),De,ut=c(()=>{oi(),De=async Q=>{if(typeof Q=="string"){let ae=await fetch(Q);if(!ae.ok)throw new Error(`failed to load external data file: ${Q}`);let me=ae.headers.get("Content-Length"),$e=me?parseInt(me,10):0;if($e<1073741824)return new Uint8Array(await ae.arrayBuffer());{if(!ae.body)throw new Error(`failed to load external data file: ${Q}, no response body.`);let Se=ae.body.getReader(),Fe;try{Fe=new ArrayBuffer($e)}catch(Re){if(Re instanceof RangeError){let Ge=Math.ceil($e/65536);Fe=new WebAssembly.Memory({initial:Ge,maximum:Ge}).buffer}else throw Re}let Ie=0;for(;;){let{done:Re,value:Ge}=await Se.read();if(Re)break;let nt=Ge.byteLength;new Uint8Array(Fe,Ie,nt).set(Ge),Ie+=nt}return new Uint8Array(Fe,0,$e)}}else return Q instanceof Blob?new Uint8Array(await Q.arrayBuffer()):Q instanceof Uint8Array?Q:new Uint8Array(Q)}}),Jt,wn,ii,yn,Ei,Gs,xn,Hs,to,or,Xe,Es,kt,be=c(()=>{vn(),Tr(),Ln(),Wt(),Hn(),Bi(),ut(),Jt=(Q,ae)=>{yt()._OrtInit(Q,ae)!==0&&Tt("Can't initialize onnxruntime.")},wn=async Q=>{Jt(Q.wasm.numThreads,Fs(Q.logLevel))},ii=async(Q,ae)=>{var $e,Se;(Se=($e=yt()).asyncInit)==null||Se.call($e);let me=Q.webgpu.adapter;if(ae==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(me){if(typeof me.limits!="object"||typeof me.features!="object"||typeof me.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Fe=Q.webgpu.powerPreference;if(Fe!==void 0&&Fe!=="low-power"&&Fe!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Fe}"`);let Ie=Q.webgpu.forceFallbackAdapter;if(Ie!==void 0&&typeof Ie!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ie}"`);if(me=await navigator.gpu.requestAdapter({powerPreference:Fe,forceFallbackAdapter:Ie}),!me)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")},yn=new Map,Ei=Q=>{let ae=yt(),me=ae.stackSave();try{let $e=ae.PTR_SIZE,Se=ae.stackAlloc(2*$e);ae._OrtGetInputOutputCount(Q,Se,Se+$e)!==0&&Tt("Can't get session input/output count.");let Fe=$e===4?"i32":"i64";return[Number(ae.getValue(Se,Fe)),Number(ae.getValue(Se+$e,Fe))]}finally{ae.stackRestore(me)}},Gs=(Q,ae)=>{let me=yt(),$e=me.stackSave(),Se=0;try{let Fe=me.PTR_SIZE,Ie=me.stackAlloc(2*Fe);me._OrtGetInputOutputMetadata(Q,ae,Ie,Ie+Fe)!==0&&Tt("Can't get session input/output metadata.");let Re=Number(me.getValue(Ie,"*"));Se=Number(me.getValue(Ie+Fe,"*"));let Ge=me.HEAP32[Se/4];if(Ge===0)return[Re,0];let nt=me.HEAPU32[Se/4+1],ht=[];for(let rt=0;rt<nt;rt++){let Je=Number(me.getValue(Se+8+rt*Fe,"*"));ht.push(Je!==0?me.UTF8ToString(Je):Number(me.getValue(Se+8+(rt+nt)*Fe,"*")))}return[Re,Ge,ht]}finally{me.stackRestore($e),Se!==0&&me._OrtFree(Se)}},xn=Q=>{let ae=yt(),me=ae._malloc(Q.byteLength);if(me===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Q.byteLength}.`);return ae.HEAPU8.set(Q,me),[me,Q.byteLength]},Hs=async(Q,ae)=>{var ht,rt,Je;let me,$e,Se=yt();Array.isArray(Q)?[me,$e]=Q:Q.buffer===Se.HEAPU8.buffer?[me,$e]=[Q.byteOffset,Q.byteLength]:[me,$e]=xn(Q);let Fe=0,Ie=0,Re=[],Ge=[],nt=[];try{if([Ie,Re]=await eo(ae),(ae==null?void 0:ae.externalData)&&Se.mountExternalData){let li=[];for(let Nn of ae.externalData){let is=typeof Nn=="string"?Nn:Nn.path;li.push(De(typeof Nn=="string"?Nn:Nn.data).then(bs=>{Se.mountExternalData(is,bs)}))}await Promise.all(li)}for(let li of(ae==null?void 0:ae.executionProviders)??[])if((typeof li=="string"?li:li.name)==="webnn"){if(Se.shouldTransferToMLTensor=!1,typeof li!="string"){let Nn=li,is=Nn==null?void 0:Nn.context,bs=Nn==null?void 0:Nn.gpuDevice,Ts=Nn==null?void 0:Nn.deviceType,Ra=Nn==null?void 0:Nn.powerPreference;is?Se.currentContext=is:bs?Se.currentContext=await Se.webnnCreateMLContext(bs):Se.currentContext=await Se.webnnCreateMLContext({deviceType:Ts,powerPreference:Ra})}else Se.currentContext=await Se.webnnCreateMLContext();break}Fe=await Se._OrtCreateSession(me,$e,Ie),(ht=Se.webgpuOnCreateSession)==null||ht.call(Se,Fe),Fe===0&&Tt("Can't create a session."),(rt=Se.jsepOnCreateSession)==null||rt.call(Se),Se.currentContext&&(Se.webnnRegisterMLContext(Fe,Se.currentContext),Se.currentContext=void 0,Se.shouldTransferToMLTensor=!0);let[Bt,Be]=Ei(Fe),xt=!!(ae!=null&&ae.enableGraphCapture),Xn=[],dn=[],un=[],Jn=[],qt=[];for(let li=0;li<Bt;li++){let[Nn,is,bs]=Gs(Fe,li);Nn===0&&Tt("Can't get an input name."),Ge.push(Nn);let Ts=Se.UTF8ToString(Nn);Xn.push(Ts),un.push(is===0?{name:Ts,isTensor:!1}:{name:Ts,isTensor:!0,type:ai(is),shape:bs})}for(let li=0;li<Be;li++){let[Nn,is,bs]=Gs(Fe,li+Bt);Nn===0&&Tt("Can't get an output name."),nt.push(Nn);let Ts=Se.UTF8ToString(Nn);dn.push(Ts),Jn.push(is===0?{name:Ts,isTensor:!1}:{name:Ts,isTensor:!0,type:ai(is),shape:bs})}return yn.set(Fe,[Fe,Ge,nt,null,xt,!1]),[Fe,Xn,dn,un,Jn]}catch(Bt){throw Ge.forEach(Be=>Se._OrtFree(Be)),nt.forEach(Be=>Se._OrtFree(Be)),Fe!==0&&Se._OrtReleaseSession(Fe)!==0&&Tt("Can't release session."),Bt}finally{Se._free(me),Ie!==0&&Se._OrtReleaseSessionOptions(Ie)!==0&&Tt("Can't release session options."),Re.forEach(Bt=>Se._free(Bt)),(Je=Se.unmountExternalData)==null||Je.call(Se)}},to=Q=>{var Ge,nt,ht;let ae=yt(),me=yn.get(Q);if(!me)throw new Error(`cannot release session. invalid session id: ${Q}`);let[$e,Se,Fe,Ie,Re]=me;Ie&&(Re&&ae._OrtClearBoundOutputs(Ie.handle)!==0&&Tt("Can't clear bound outputs."),ae._OrtReleaseBinding(Ie.handle)!==0&&Tt("Can't release IO binding.")),(Ge=ae.jsepOnReleaseSession)==null||Ge.call(ae,Q),(nt=ae.webnnOnReleaseSession)==null||nt.call(ae,Q),(ht=ae.webgpuOnReleaseSession)==null||ht.call(ae,Q),Se.forEach(rt=>ae._OrtFree(rt)),Fe.forEach(rt=>ae._OrtFree(rt)),ae._OrtReleaseSession($e)!==0&&Tt("Can't release session."),yn.delete(Q)},or=async(Q,ae,me,$e,Se,Fe,Ie=!1)=>{if(!Q){ae.push(0);return}let Re=yt(),Ge=Re.PTR_SIZE,nt=Q[0],ht=Q[1],rt=Q[3],Je=rt,Bt,Be;if(nt==="string"&&(rt==="gpu-buffer"||rt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ie&&rt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Fe} when enableGraphCapture is true.`);if(rt==="gpu-buffer"){let dn=Q[2].gpuBuffer;Be=ki(Xi(nt),ht);{let un=Re.jsepRegisterBuffer;if(!un)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Bt=un($e,Fe,dn,Be)}}else if(rt==="ml-tensor"){let dn=Q[2].mlTensor;Be=ki(Xi(nt),ht);let un=Re.webnnRegisterMLTensor;if(!un)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Bt=un($e,dn,Xi(nt),ht)}else{let dn=Q[2];if(Array.isArray(dn)){Be=Ge*dn.length,Bt=Re._malloc(Be),me.push(Bt);for(let un=0;un<dn.length;un++){if(typeof dn[un]!="string")throw new TypeError(`tensor data at index ${un} is not a string`);Re.setValue(Bt+un*Ge,En(dn[un],me),"*")}}else{let un=Re.webnnIsGraphInput,Jn=Re.webnnIsGraphOutput;if(nt!=="string"&&un&&Jn){let qt=Re.UTF8ToString(Se);if(un($e,qt)||Jn($e,qt)){let li=Xi(nt);Be=ki(li,ht),Je="ml-tensor";let Nn=Re.webnnCreateTemporaryTensor,is=Re.webnnUploadTensor;if(!Nn||!is)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let bs=await Nn($e,li,ht);is(bs,new Uint8Array(dn.buffer,dn.byteOffset,dn.byteLength)),Bt=bs}else Be=dn.byteLength,Bt=Re._malloc(Be),me.push(Bt),Re.HEAPU8.set(new Uint8Array(dn.buffer,dn.byteOffset,Be),Bt)}else Be=dn.byteLength,Bt=Re._malloc(Be),me.push(Bt),Re.HEAPU8.set(new Uint8Array(dn.buffer,dn.byteOffset,Be),Bt)}}let xt=Re.stackSave(),Xn=Re.stackAlloc(4*ht.length);try{ht.forEach((un,Jn)=>Re.setValue(Xn+Jn*Ge,un,Ge===4?"i32":"i64"));let dn=Re._OrtCreateTensor(Xi(nt),Bt,Be,Xn,ht.length,Pi(Je));dn===0&&Tt(`Can't create tensor for input/output. session=${$e}, index=${Fe}.`),ae.push(dn)}finally{Re.stackRestore(xt)}},Xe=async(Q,ae,me,$e,Se,Fe)=>{var js,Sl,Ec;let Ie=yt(),Re=Ie.PTR_SIZE,Ge=yn.get(Q);if(!Ge)throw new Error(`cannot run inference. invalid session id: ${Q}`);let nt=Ge[0],ht=Ge[1],rt=Ge[2],Je=Ge[3],Bt=Ge[4];Ge[5];let Be=ae.length,xt=$e.length,Xn=0,dn=[],un=[],Jn=[],qt=[],li=[],Nn=Ie.stackSave(),is=Ie.stackAlloc(Be*Re),bs=Ie.stackAlloc(Be*Re),Ts=Ie.stackAlloc(xt*Re),Ra=Ie.stackAlloc(xt*Re);try{[Xn,dn]=us(Fe),wt("wasm prepareInputOutputTensor");for(let Sn=0;Sn<Be;Sn++)await or(me[Sn],un,qt,Q,ht[ae[Sn]],ae[Sn],Bt);for(let Sn=0;Sn<xt;Sn++)await or(Se[Sn],Jn,qt,Q,rt[$e[Sn]],Be+$e[Sn],Bt);gt("wasm prepareInputOutputTensor");for(let Sn=0;Sn<Be;Sn++)Ie.setValue(is+Sn*Re,un[Sn],"*"),Ie.setValue(bs+Sn*Re,ht[ae[Sn]],"*");for(let Sn=0;Sn<xt;Sn++)Ie.setValue(Ts+Sn*Re,Jn[Sn],"*"),Ie.setValue(Ra+Sn*Re,rt[$e[Sn]],"*");(js=Ie.jsepOnRunStart)==null||js.call(Ie,nt),(Sl=Ie.webnnOnRunStart)==null||Sl.call(Ie,nt);let ss;ss=await Ie._OrtRun(nt,bs,is,Be,Ra,xt,Ts,Xn),ss!==0&&Tt("failed to call OrtRun().");let Dr=[],Tc=[];wt("wasm ProcessOutputTensor");for(let Sn=0;Sn<xt;Sn++){let gr=Number(Ie.getValue(Ts+Sn*Re,"*"));if(gr===Jn[Sn]||li.includes(Jn[Sn])){Dr.push(Se[Sn]),gr!==Jn[Sn]&&Ie._OrtReleaseTensor(gr)!==0&&Tt("Can't release tensor.");continue}let Hd=Ie.stackSave(),Wr=Ie.stackAlloc(4*Re),Qo=!1,Hi,Ds=0;try{Ie._OrtGetTensorData(gr,Wr,Wr+Re,Wr+2*Re,Wr+3*Re)!==0&&Tt(`Can't access output tensor data on index ${Sn}.`);let Cl=Re===4?"i32":"i64",$s=Number(Ie.getValue(Wr,Cl));Ds=Ie.getValue(Wr+Re,"*");let jc=Ie.getValue(Wr+Re*2,"*"),Wd=Number(Ie.getValue(Wr+Re*3,Cl)),Ur=[];for(let Wi=0;Wi<Wd;Wi++)Ur.push(Number(Ie.getValue(jc+Wi*Re,Cl)));Ie._OrtFree(jc)!==0&&Tt("Can't free memory for tensor dims.");let vr=Ur.reduce((Wi,bi)=>Wi*bi,1);Hi=ai($s);let $r=Je==null?void 0:Je.outputPreferredLocations[$e[Sn]];if(Hi==="string"){if($r==="gpu-buffer"||$r==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Wi=[];for(let bi=0;bi<vr;bi++){let xr=Ie.getValue(Ds+bi*Re,"*"),Dc=Ie.getValue(Ds+(bi+1)*Re,"*"),$c=bi===vr-1?void 0:Dc-xr;Wi.push(Ie.UTF8ToString(xr,$c))}Dr.push([Hi,Ur,Wi,"cpu"])}else if($r==="gpu-buffer"&&vr>0){let Wi=Ie.jsepGetBuffer;if(!Wi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bi=Wi(Ds),xr=ki($s,vr);if(xr===void 0||!rr(Hi))throw new Error(`Unsupported data type: ${Hi}`);Qo=!0,Dr.push([Hi,Ur,{gpuBuffer:bi,download:Ie.jsepCreateDownloader(bi,xr,Hi),dispose:()=>{Ie._OrtReleaseTensor(gr)!==0&&Tt("Can't release tensor.")}},"gpu-buffer"])}else if($r==="ml-tensor"&&vr>0){let Wi=Ie.webnnEnsureTensor,bi=Ie.webnnIsGraphInputOutputTypeSupported;if(!Wi||!bi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(ki($s,vr)===void 0||!hs(Hi))throw new Error(`Unsupported data type: ${Hi}`);if(!bi(Q,Hi,!1))throw new Error(`preferredLocation "ml-tensor" for ${Hi} output is not supported by current WebNN Context.`);let xr=await Wi(Q,Ds,$s,Ur,!1);Qo=!0,Dr.push([Hi,Ur,{mlTensor:xr,download:Ie.webnnCreateMLTensorDownloader(Ds,Hi),dispose:()=>{Ie.webnnReleaseTensorId(Ds),Ie._OrtReleaseTensor(gr)}},"ml-tensor"])}else if($r==="ml-tensor-cpu-output"&&vr>0){let Wi=Ie.webnnCreateMLTensorDownloader(Ds,Hi)(),bi=Dr.length;Qo=!0,Tc.push((async()=>{let xr=[bi,await Wi];return Ie.webnnReleaseTensorId(Ds),Ie._OrtReleaseTensor(gr),xr})()),Dr.push([Hi,Ur,[],"cpu"])}else{let Wi=Bs(Hi),bi=new Wi(vr);new Uint8Array(bi.buffer,bi.byteOffset,bi.byteLength).set(Ie.HEAPU8.subarray(Ds,Ds+bi.byteLength)),Dr.push([Hi,Ur,bi,"cpu"])}}finally{Ie.stackRestore(Hd),Hi==="string"&&Ds&&Ie._free(Ds),Qo||Ie._OrtReleaseTensor(gr)}}Je&&!Bt&&(Ie._OrtClearBoundOutputs(Je.handle)!==0&&Tt("Can't clear bound outputs."),yn.set(Q,[nt,ht,rt,Je,Bt,!1]));for(let[Sn,gr]of await Promise.all(Tc))Dr[Sn][2]=gr;return gt("wasm ProcessOutputTensor"),Dr}finally{(Ec=Ie.webnnOnRunEnd)==null||Ec.call(Ie,nt),Ie.stackRestore(Nn),un.forEach(ss=>Ie._OrtReleaseTensor(ss)),Jn.forEach(ss=>Ie._OrtReleaseTensor(ss)),qt.forEach(ss=>Ie._free(ss)),Xn!==0&&Ie._OrtReleaseRunOptions(Xn),dn.forEach(ss=>Ie._free(ss))}},Es=Q=>{let ae=yt(),me=yn.get(Q);if(!me)throw new Error("invalid session id");let $e=me[0],Se=ae._OrtEndProfiling($e);Se===0&&Tt("Can't get an profile file name."),ae._OrtFree(Se)},kt=Q=>{let ae=[];for(let me of Q){let $e=me[2];!Array.isArray($e)&&"buffer"in $e&&ae.push($e.buffer)}return ae}}),Me,Ze,Pt,fn,_n,si,Qn,Mi,fi,Gi,ei,mr,no,_o,jr,Gd,wo,yo,Sc=c(()=>{vn(),be(),Hn(),On(),Me=()=>!!N.wasm.proxy&&typeof document<"u",Pt=!1,fn=!1,_n=!1,Mi=new Map,fi=(Q,ae)=>{let me=Mi.get(Q);me?me.push(ae):Mi.set(Q,[ae])},Gi=()=>{if(Pt||!fn||_n||!Ze)throw new Error("worker not ready")},ei=Q=>{switch(Q.data.type){case"init-wasm":Pt=!1,Q.data.err?(_n=!0,Qn[1](Q.data.err)):(fn=!0,Qn[0]()),si&&(URL.revokeObjectURL(si),si=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let ae=Mi.get(Q.data.type);Q.data.err?ae.shift()[1](Q.data.err):ae.shift()[0](Q.data.out);break}}},mr=async()=>{if(!fn){if(Pt)throw new Error("multiple calls to 'initWasm()' detected.");if(_n)throw new Error("previous call to 'initWasm()' failed.");if(Pt=!0,Me())return new Promise((Q,ae)=>{Ze==null||Ze.terminate(),Mt().then(([me,$e])=>{try{Ze=$e,Ze.onerror=Fe=>ae(Fe),Ze.onmessage=ei,Qn=[Q,ae];let Se={type:"init-wasm",in:N};if(!Se.in.wasm.wasmPaths&&me){let Fe=Mn();Fe&&(Se.in.wasm.wasmPaths=Fe)}Ze.postMessage(Se),si=me}catch(Se){ae(Se)}},ae)});try{await at(N.wasm),await wn(N),fn=!0}catch(Q){throw _n=!0,Q}finally{Pt=!1}}},no=async Q=>{if(Me())return Gi(),new Promise((ae,me)=>{fi("init-ep",[ae,me]);let $e={type:"init-ep",in:{epName:Q,env:N}};Ze.postMessage($e)});await ii(N,Q)},_o=async Q=>Me()?(Gi(),new Promise((ae,me)=>{fi("copy-from",[ae,me]);let $e={type:"copy-from",in:{buffer:Q}};Ze.postMessage($e,[Q.buffer])})):xn(Q),jr=async(Q,ae)=>{if(Me()){if(ae!=null&&ae.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Gi(),new Promise((me,$e)=>{fi("create",[me,$e]);let Se={type:"create",in:{model:Q,options:{...ae}}},Fe=[];Q instanceof Uint8Array&&Fe.push(Q.buffer),Ze.postMessage(Se,Fe)})}else return Hs(Q,ae)},Gd=async Q=>{if(Me())return Gi(),new Promise((ae,me)=>{fi("release",[ae,me]);let $e={type:"release",in:Q};Ze.postMessage($e)});to(Q)},wo=async(Q,ae,me,$e,Se,Fe)=>{if(Me()){if(me.some(Ie=>Ie[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Se.some(Ie=>Ie))throw new Error("pre-allocated output tensor is not supported for proxy.");return Gi(),new Promise((Ie,Re)=>{fi("run",[Ie,Re]);let Ge=me,nt={type:"run",in:{sessionId:Q,inputIndices:ae,inputs:Ge,outputIndices:$e,options:Fe}};Ze.postMessage(nt,kt(Ge))})}else return Xe(Q,ae,me,$e,Se,Fe)},yo=async Q=>{if(Me())return Gi(),new Promise((ae,me)=>{fi("end-profiling",[ae,me]);let $e={type:"end-profiling",in:Q};Ze.postMessage($e)});Es(Q)}}),bl,So,Ia,_l=c(()=>{vn(),Sc(),Wt(),oi(),ut(),bl=(Q,ae)=>{switch(Q.location){case"cpu":return[Q.type,Q.dims,Q.data,"cpu"];case"gpu-buffer":return[Q.type,Q.dims,{gpuBuffer:Q.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Q.type,Q.dims,{mlTensor:Q.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Q.location} for ${ae()}`)}},So=Q=>{switch(Q[3]){case"cpu":return new Te(Q[0],Q[2],Q[1]);case"gpu-buffer":{let ae=Q[0];if(!rr(ae))throw new Error(`not supported data type: ${ae} for deserializing GPU tensor`);let{gpuBuffer:me,download:$e,dispose:Se}=Q[2];return Te.fromGpuBuffer(me,{dataType:ae,dims:Q[1],download:$e,dispose:Se})}case"ml-tensor":{let ae=Q[0];if(!hs(ae))throw new Error(`not supported data type: ${ae} for deserializing MLTensor tensor`);let{mlTensor:me,download:$e,dispose:Se}=Q[2];return Te.fromMLTensor(me,{dataType:ae,dims:Q[1],download:$e,dispose:Se})}default:throw new Error(`invalid data location: ${Q[3]}`)}},Ia=class{async fetchModelAndCopyToWasmMemory(Q){return _o(await De(Q))}async loadModel(Q,ae){bt();let me;typeof Q=="string"?me=await this.fetchModelAndCopyToWasmMemory(Q):me=Q,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await jr(me,ae),et()}async dispose(){return Gd(this.sessionId)}async run(Q,ae,me){bt();let $e=[],Se=[];Object.entries(Q).forEach(rt=>{let Je=rt[0],Bt=rt[1],Be=this.inputNames.indexOf(Je);if(Be===-1)throw new Error(`invalid input '${Je}'`);$e.push(Bt),Se.push(Be)});let Fe=[],Ie=[];Object.entries(ae).forEach(rt=>{let Je=rt[0],Bt=rt[1],Be=this.outputNames.indexOf(Je);if(Be===-1)throw new Error(`invalid output '${Je}'`);Fe.push(Bt),Ie.push(Be)});let Re=$e.map((rt,Je)=>bl(rt,()=>`input "${this.inputNames[Se[Je]]}"`)),Ge=Fe.map((rt,Je)=>rt?bl(rt,()=>`output "${this.outputNames[Ie[Je]]}"`):null),nt=await wo(this.sessionId,Se,Re,Ie,Ge,me),ht={};for(let rt=0;rt<nt.length;rt++)ht[this.outputNames[Ie[rt]]]=Fe[rt]??So(nt[rt]);return et(),ht}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Gr={};h(Gr,{OnnxruntimeWebAssemblyBackend:()=>Hr,initializeFlags:()=>io,wasmBackend:()=>Co});var io,Hr,Co,Cc=c(()=>{vn(),Sc(),_l(),io=()=>{(typeof N.wasm.initTimeout!="number"||N.wasm.initTimeout<0)&&(N.wasm.initTimeout=0);let Q=N.wasm.simd;if(typeof Q!="boolean"&&Q!==void 0&&Q!=="fixed"&&Q!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Q}". Reset it to \`false\` and ignore SIMD feature checking.`),N.wasm.simd=!1),typeof N.wasm.proxy!="boolean"&&(N.wasm.proxy=!1),typeof N.wasm.trace!="boolean"&&(N.wasm.trace=!1),typeof N.wasm.numThreads!="number"||!Number.isInteger(N.wasm.numThreads)||N.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)N.wasm.numThreads=1;else{let ae=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;N.wasm.numThreads=Math.min(4,Math.ceil((ae||1)/2))}},Hr=class{async init(Q){io(),await mr(),await no(Q)}async createInferenceSessionHandler(Q,ae){let me=new Ia;return await me.loadModel(Q,ae),me}},Co=new Hr}),kc={};h(kc,{InferenceSession:()=>vt,TRACE:()=>Ee,TRACE_EVENT_BEGIN:()=>wt,TRACE_EVENT_END:()=>gt,TRACE_FUNC_BEGIN:()=>bt,TRACE_FUNC_END:()=>et,Tensor:()=>Te,default:()=>yl,env:()=>N,registerBackend:()=>k}),vn(),vn(),vn();var wl="1.26.0",yl=Tn;{let Q=(Cc(),g(Gr)).wasmBackend;k("cpu",Q,10),k("wasm",Q,10)}return Object.defineProperty(N.versions,"web",{value:wl,enumerable:!0}),g(kc)})();n.exports=t})(qb)),qb.exports}var xS;function TI(){return xS||(xS=1,(function(n){var e=il&&il.__createBinding||(Object.create?(function(S,T,I,A){A===void 0&&(A=I);var M=Object.getOwnPropertyDescriptor(T,I);(!M||("get"in M?!T.__esModule:M.writable||M.configurable))&&(M={enumerable:!0,get:function(){return T[I]}}),Object.defineProperty(S,A,M)}):(function(S,T,I,A){A===void 0&&(A=I),S[A]=T[I]})),t=il&&il.__setModuleDefault||(Object.create?(function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}):function(S,T){S.default=T}),i=il&&il.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var I in S)I!=="default"&&Object.prototype.hasOwnProperty.call(S,I)&&e(T,S,I);return t(T,S),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=i(EI()),a=Qy(),u=e0(),l=Jm(),c=lb(),h=fT(),m=mT();n.DEFAULT_MODEL="legacy",n.ort=s;const g="vad.worklet.bundle.min.js",v="silero_vad_v5.onnx",E="silero_vad_legacy.onnx",k=S=>({...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:S,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async T=>{T.getTracks().forEach(I=>{I.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 C=S=>"audioWorklet"in S&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(S,T,I,A,M){await I.audioWorklet.addModule(S),T.processorOptions={...T.processorOptions??{},frameSamples:A};const N=new AudioWorkletNode(I,"vad-helper-worklet",T);return N.port.onmessage=async L=>{const U=L.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case c.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const J=new Float32Array(U.data);await M(J);break}}},N}async function b(S,T,I){const A=new m.Resampler({nativeSampleRate:S.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const N=S.createScriptProcessor(4096,1,1);let L=!1;return N.onaudioprocess=async U=>{if(!L){L=!0;try{const J=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const q=A.process(J);for(const le of q)await I(le)}catch(J){console.error("Error processing audio:",J)}finally{L=!1}}},N.connect(S.destination),N}class w{constructor(T,I,A,M,N=!1,L=null,U=null,J=null,Z=null,q=null,le=null,ie="uninitialized",he=!1){this.options=T,this.frameProcessor=I,this.model=A,this.frameSamples=M,this.listening=N,this.errored=L,this._stream=U,this._audioContext=J,this._vadNode=Z,this._mediaStreamAudioSourceNode=q,this._audioProcessorAdapterType=le,this.initializationState=ie,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=ve=>{this.initializationState="errored",this.errored=ve},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(ve){throw ve instanceof Error?this.setErrored(ve.message):this.setErrored(String(ve)),ve}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?C(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await b(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:ve,audioContext:fe,vadNode:B}=this.getAudioInstances();this._stream=await this.options.resumeStream(ve);const K=new MediaStreamAudioSourceNode(fe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=K,K.connect(B);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:ve,mediaStreamAudioSourceNode:fe}=this.getAudioInstances();await this.options.pauseStream(ve),fe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var fe;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:ve}=this.getAudioInstances();ve instanceof AudioWorkletNode&&ve.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((fe=this._audioContext)==null?void 0:fe.close())},this.setOptions=ve=>{this.frameProcessor.setOptions(ve)},this.processFrame=async ve=>{await this.frameProcessor.process(ve,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=ve=>{switch(ve.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(ve.probs,ve.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(ve.audio);break}}}static async new(T={}){const I={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,u.validateOptions)(I),n.ort.env.wasm.wasmPaths=I.onnxWASMBasePath,I.ortConfig!==void 0&&I.ortConfig(n.ort);const A=I.model==="v5"?v:E,M=I.baseAssetPath+A,N=I.model==="v5"?h.SileroV5.new:h.SileroLegacy.new;let L;try{L=await N(n.ort,()=>(0,a.defaultModelFetcher)(M))}catch(le){throw console.error(`Encountered an error while loading model file ${M}`),le}const U=I.model==="v5"?512:1536,J=U/16,Z=new u.FrameProcessor(L.process,L.reset_state,{positiveSpeechThreshold:I.positiveSpeechThreshold,negativeSpeechThreshold:I.negativeSpeechThreshold,redemptionMs:I.redemptionMs,preSpeechPadMs:I.preSpeechPadMs,minSpeechMs:I.minSpeechMs,submitUserSpeechOnPause:I.submitUserSpeechOnPause},J),q=new w(I,Z,L,U);if(I.startOnLoad)try{await q.start()}catch(le){throw console.error("Error starting micVad",le),le}return q}}n.MicVAD=w})(il)),il}var bS;function jI(){return bS||(bS=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=uT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=Qy();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var i=e0();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var s=lb();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=CI();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const u=kI();n.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var l=TI();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}})})(Wb)),Wb}var DI=jI();function fv(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 _t={debug:(n,e,t)=>fv(n,"debug",e,t),info:(n,e,t)=>fv(n,"info",e,t),warn:(n,e,t)=>fv(n,"warn",e,t),error:(n,e,t,i)=>fv(n,"error",e,t,i)},vT=16e3,$I=6,Ch=vT*$I,NI=400,AI=vT*NI/1e3,_S=300,wS=2e3,yS=1500,SS=3e3,II=600,xT=.5,bT=.35,CS=.85,kS=.7;let tr=null,Ko=!1,pr=!1;const ww=new Set;function mv(n){for(const e of Array.from(ww))try{e(n)}catch(t){_t.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Kb=0;const ES=2;let Bh=!1,_T=!1;function wT(n){n.addEventListener("message",e=>{var i;if(((i=e.data)==null?void 0:i.type)!=="log")return;const t=e.data.level||"info";_t[t]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{_t.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),RI(`error:${e.message||"unknown"}`)})}function $x(){return tr||(tr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),wT(tr),_t.info("speech","worker spawned"),tr)}let gv=!1;function RI(n){if(!Bh){if(gv){_t.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(gv=!0,Kb+=1,_T=!0,_t.warn("speech","respawnWorker: starting",{reason:n,attempt:Kb}),mv({reason:n,respawned:!1,finalOnly:!0}),Kb>ES){if(Bh=!0,_t.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:ES}),tr)try{tr.terminate()}catch{}tr=null,Ko=!1,pr=!1,mv({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),gv=!1;return}if(tr)try{tr.terminate()}catch{}tr=null,Ko=!1,pr=!1;try{tr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),wT(tr),pr=!0,tr.postMessage({type:"load"}),_t.info("speech","respawnWorker: new worker spawned, load posted"),mv({reason:n,respawned:!0,finalOnly:!0})}catch(e){Bh=!0,_t.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),mv({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{gv=!1}}}function PI(n,e){if(Ko||pr)return;pr=!0;const t=$x();_t.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"&&(Ko=!0,pr=!1,_t.info("speech","preloadModel: ready"),t.removeEventListener("message",i))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(pr=!1,_t.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 MI(){_t.info("speech","resetModel: clearing load flags"),Ko=!1,pr=!1}function OI(){if(_t.info("speech","releaseModel: terminating worker"),tr)try{tr.terminate()}catch{}tr=null,Ko=!1,pr=!1}function cb(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function LI(n){const e=$x();return!Ko&&!pr&&(pr=!0,e.postMessage({type:"load"})),new Promise((t,i)=>{const s=a=>{var u,l,c;((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")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(Ko=!0,pr=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function yT(n){let e=$x(),t=!1,i=null,s=null,a=null,u=null,l=null;const c=[],h=new Set;let m=null,g=0,v=!1,E=0,k=!1,C=!1,x=0,b=0,w=0,S=-1,T=_S,I=0,A=null,M="",N="",L=!1,U=0;function J(ce,ge){const Oe=Math.min(ce.length,ge.length);let We=0;for(;We<Oe&&ce.charCodeAt(We)===ge.charCodeAt(We);)We++;return We}function Z(ce){const ge=J(M,ce);return M=ce,ge>N.length&&(N=ce.slice(0,ge)),N.length>ce.length&&(N=ce),N}const q=()=>(m||(m=new Float32Array(Ch)),m),le=()=>{g=0},ie=ce=>{const ge=q(),Oe=ce.length;if(Oe>=Ch){ge.set(ce.subarray(Oe-Ch)),g=Ch;return}if(g+Oe<=Ch){ge.set(ce,g),g+=Oe;return}const We=g+Oe-Ch;ge.copyWithin(0,We,g),g-=We,ge.set(ce,g),g+=Oe},he=()=>{A&&(clearTimeout(A),A=null)},ve=()=>{he(),v=!1,k=!1,C=!1,T=_S,M="",N="",L=!1,U=0,le()},fe=()=>{if(t||!v||C||k||A)return;if(g<AI){A=setTimeout(()=>{A=null,fe()},T);return}const ce=performance.now()-x;if(ce<T&&x!==0){A=setTimeout(()=>{A=null,fe()},T-ce);return}if(_T||Bh||n.partialsEnabled&&!n.partialsEnabled())return;const ge=q(),Oe=new Float32Array(g);Oe.set(ge.subarray(0,g)),b+=1,w=b,k=!0,I=performance.now(),x=I,e.postMessage({type:"transcribe-partial",audio:Oe,seq:b},[Oe.buffer])},B=ce=>ce.length===0?Promise.resolve():Bh?(_t.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ge=>{c.push(ge),b+=1;const Oe=b;S=Oe,e.postMessage({type:"transcribe",audio:ce,seq:Oe},[ce.buffer])}),K=ce=>{const ge=B(ce);return h.add(ge),ge.finally(()=>{h.delete(ge)}),ge},W=ce=>{var ge,Oe,We,xe,te;if(ce.data.type==="result"){const Ae=ce.data.text,Te=ce.data.seq??0;Te&&Te<S&&_t.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Te,latestFinalSeq:S}),!t&&Ae&&n.onFinal(Ae),(ge=c.shift())==null||ge()}else if(ce.data.type==="partial"){const Ae=ce.data.seq??0,Te=ce.data.text??"",je=performance.now()-I;k=!1,je>=SS?(C=!0,_t.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(je),seq:Ae})):je>=yS&&(T=Math.min(T*2,wS),_t.warn("speech","partials.slowdown",{elapsedMs:Math.round(je),newIntervalMs:T,seq:Ae})),L||(L=!0,je>II&&T<500&&(T=500,_t.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(je),newIntervalMs:500})));const Ee=Ae!==w||Ae<=S;if(!t&&!Ee&&Te){const Qe=Z(Te);Qe&&((Oe=n.onPartial)==null||Oe.call(n,Qe),U===0&&(U=performance.now(),_t.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-E)})))}fe()}else if(ce.data.type==="partial-error"){const Ae=performance.now()-I;k=!1,Ae>=SS?(C=!0,_t.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ae),seq:ce.data.seq})):Ae>=yS&&(T=Math.min(T*2,wS),_t.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ae),newIntervalMs:T,seq:ce.data.seq})),_t.warn("speech","partial encode failed",{error:ce.data.error,seq:ce.data.seq}),fe()}else ce.data.type==="error"?(t||n.onError(ce.data.error),(We=c.shift())==null||We()):ce.data.type==="status"?(t||(xe=n.onModelStatus)==null||xe.call(n,ce.data.status,ce.data.message),ce.data.status==="ready"&&(Ko=!0,pr=!1)):ce.data.type==="progress"&&(t||(te=n.onProgress)==null||te.call(n,ce.data.pct))};e.addEventListener("message",W);const ee=ce=>{var ge,Oe;if(!t){for(_t.warn("speech","createRecognition: worker death event",ce),(ge=n.onStatusChange)==null||ge.call(n,"restarting");c.length;)(Oe=c.shift())==null||Oe();if(h.clear(),he(),k=!1,ce.respawned){try{e.removeEventListener("message",W)}catch{}e=$x(),e.addEventListener("message",W)}}};return ww.add(ee),{start:async()=>{if(!t){if(Bh){n.onError("Speech recognition disabled — please reload the app.");return}!Ko&&!pr&&(pr=!0,_t.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),_t.info("speech","createRecognition.start: initializing VAD",{modelReady:Ko,modelLoading:pr});try{const ce=new URL("vad/",document.baseURI).href;_t.info("speech","vad: asset base resolved",{vadBase:ce}),bI();const ge=n.inputDeviceId||null,Oe={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ge&&(Oe.deviceId={exact:ge}),_t.info("speech","getUserMedia",{hasDeviceId:!!ge,deviceIdPrefix:ge?ge.slice(0,8):null});const We=await navigator.mediaDevices.getUserMedia({audio:Oe});s=We,a=new AudioContext;for(const xe of We.getAudioTracks())xe.addEventListener("ended",()=>{t||(_t.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(xe){_t.warn("speech","analyser init failed",{error:xe instanceof Error?xe.message:String(xe)}),l=null,u=null}i=await DI.MicVAD.new({audioContext:a,getStream:async()=>We,resumeStream:async()=>We,pauseStream:async()=>{},baseAssetPath:ce,onnxWASMBasePath:ce,model:"v5",positiveSpeechThreshold:xT,negativeSpeechThreshold:bT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(xe,te)=>{var Ae;t||((Ae=n.onFrame)==null||Ae.call(n,xe),v&&(ie(te),fe()))},onSpeechStart:()=>{var xe;t||(ve(),v=!0,E=performance.now(),(xe=n.onSpeechStart)==null||xe.call(n))},onSpeechEnd:xe=>{var te;t||((te=n.onStatusChange)==null||te.call(n,"transcribing"),ve(),K(xe))},onVADMisfire:()=>{var xe,te;t||((xe=n.onStatusChange)==null||xe.call(n,"idle"),ve(),(te=n.onMisfire)==null||te.call(n))}}),_t.info("speech","vad: ort wasm files loaded",{files:xI()}),i.start()}catch(ce){const ge=ce instanceof Error?ce.message:"Microphone access denied",Oe=ce instanceof Error?ce.stack:"";if(_t.error("speech","createRecognition.start: VAD init failed",{error:ge,stack:Oe}),u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(We=>We.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(ge)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(ve();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(ce=>ce.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ce,ge)=>{if(i)try{i.setOptions({positiveSpeechThreshold:ce,negativeSpeechThreshold:ge})}catch(Oe){_t.warn("speech","setVadThresholds failed",{error:Oe instanceof Error?Oe.message:String(Oe)})}},getAnalyser:()=>u,destroy:()=>{if(t=!0,ve(),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(ce=>ce.stop())}catch{}s=null}ww.delete(ee),e.removeEventListener("message",W)}}}let Cm=null;const yw=new Set,Sw=new Set;function zI(){for(const n of yw)try{n()}catch{}}function Cw(){for(const n of Sw)try{n()}catch{}}function BI(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 FI(n){if(!window.speechSynthesis)return;const e=BI(n);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Cm=performance.now(),zI()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Cm=null,Cw())},t.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Cm=null,Cw())},window.speechSynthesis.speak(t)}function ST(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Cm=null,Cw())}function CT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function GI(){return Cm}function HI(n){return yw.add(n),()=>{yw.delete(n)}}function WI(n){return Sw.add(n),()=>{Sw.delete(n)}}function UI(n){CT()&&(n.setVadThresholds(CS,kS),_t.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=HI(()=>{n.setVadThresholds(CS,kS),_t.info("voice","tts.duck.on")}),t=WI(()=>{n.setVadThresholds(xT,bT),_t.info("voice","tts.duck.off")});return()=>{e(),t()}}const VI=[{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 qI(n){const e=n.trim();return VI.find(t=>t.match.test(e))??null}const KI=4e4;let Nd=null;function Fh(){Nd&&clearTimeout(Nd),Nd=setTimeout(()=>{Nd=null,Yt.getState().stopRecording()},KI)}function vv(){Nd&&(clearTimeout(Nd),Nd=null)}let vc=null,dc=null;const YI=.04,XI=.3;let Nx=0,kw=0;function JI(n){dc!==null&&cancelAnimationFrame(dc);const e=()=>{if(vc===null||Yt.getState().submitCountdownStartAt===null){dc=null;return}const t=performance.now();if(t-kw<200&&Nx>XI){const s=t-n;_t.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Nx.toFixed(2),msIntoCountdown:Math.round(s)}),ac(),Fh();return}const i=ZI();if(i){const s=new Uint8Array(i.fftSize);i.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const u=Math.sqrt(a/s.length);if(u>YI){const l=t-n;_t.info("voice","submit.preempted_by_voice",{reason:"rms",rms:u.toFixed(3),msIntoCountdown:Math.round(l)}),ac(),Fh();return}}dc=requestAnimationFrame(e)};dc=requestAnimationFrame(e)}function TS(n){vc&&clearTimeout(vc);const e=Yt.getState().submitDelayMs,t=performance.now();Yt.setState({submitCountdownStartAt:t}),vc=setTimeout(()=>{var s;vc=null,Yt.setState({submitCountdownStartAt:null});const i=It.getState().tabs.find(a=>a.id===n);if((i==null?void 0:i.status)==="dormant"){const a=(s=Cn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(Cn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:a}),Cn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){_t.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Fh()},e),JI(t)}function ac(){dc!==null&&(cancelAnimationFrame(dc),dc=null),vc&&(clearTimeout(vc),vc=null),Yt.getState().submitCountdownStartAt!==null&&Yt.setState({submitCountdownStartAt:null})}let gs=null,dr=null,Vf=null;function ZI(){var n;return((n=gs==null?void 0:gs.getAnalyser)==null?void 0:n.call(gs))??null}const xv=1e4;let km=null;function bv(){km&&(clearTimeout(km),km=null)}let lx=null,cx=null;function _v(){lx=null,cx&&(cx(),cx=null)}const QI=1500,eR=9e4;let qf=0,dx=null,Ew=-1;function Kf(){dx&&(clearTimeout(dx),dx=null,Ew=-1)}const tR=1800*1e3;let Em=null,wv=!1;function jS(){Em&&(clearTimeout(Em),Em=null)}const nR=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Yt=Ci((n,e)=>{function t(){jS(),Em=setTimeout(()=>{if(Em=null,e().isRecording||gs){t();return}_t.info("voice","model idle timeout: releasing worker"),Kf(),qf++,OI(),n({modelStatus:"idle",loadingProgress:0,error:null,errorKind:null})},tR)}function i(){return e().modelStatus==="error"?e().resetAndRetryModel():e().initModel(),new Promise((s,a)=>{let u=()=>{};const l=c=>c.modelStatus==="ready"?(u(),s(),!0):c.modelStatus==="error"?(u(),a(new Error(c.error??"Model load failed")),!0):!1;l(e())||(u=Yt.subscribe(c=>{l(c)}))})}return{isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;_t.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const s=++qf,a=()=>{s===qf&&(Kf(),Ew=s,dx=setTimeout(()=>{Ew===s&&e().modelStatus==="loading"&&(_t.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},eR))};a(),PI((u,l)=>{s===qf&&(u==="ready"?(Kf(),_t.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null}),!e().isRecording&&!gs&&t()):u==="error"?(Kf(),_t.error("voice","modelStatus -> error",{msg:l}),n({modelStatus:"error",error:l,errorKind:"load"})):(a(),n({modelStatus:"loading"})))},u=>{s===qf&&(a(),n({loadingProgress:Math.round(u)}))})},resetAndRetryModel:()=>{_t.info("voice","mic.gate.retry"),Kf(),MI(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(s,a)=>{if(e().isRecording)return;if(gs){_t.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!cb()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}if(e().modelStatus!=="ready"){if(wv)return;wv=!0,i().then(()=>{wv=!1,e().startRecording(s,a)}).catch(l=>{wv=!1;const c=l instanceof Error?l.message:String(l);_t.error("voice","startRecording: model load failed",{error:c}),Le.error(`Could not load speech model: ${c}`)});return}jS();const u=l=>{try{const c=yT({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=>{Nx=h.isSpeech,kw=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),vv(),ac(),CT()){const m=GI(),g=m!==null?performance.now()-m:null;ST(),n({lastBargeInAt:performance.now()}),_t.info("voice","barge-in",{tabId:s,utteranceOffsetMs:g})}else _t.debug("voice","barge-in.no-op",{tabId:s})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Fh();const h=e().lastBargeInAt;h!==null&&performance.now()-h<600&&_t.warn("voice","barge-in.misfire",{tabId:s,sinceBargeInMs:Math.round(performance.now()-h)})},onFinal:h=>{var k;Fh();const m=h.trim();if(!m||nR.has(m)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Vf){Vf(m),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((k=It.getState().tabs.find(C=>C.id===s))==null?void 0:k.status)==="dormant"){Cn.getState().setPendingVoiceText(s,m),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&TS(s);const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}const v=qI(m);if(v){_t.info("voice","voice-command",{tabId:s,label:v.label,transcript:m}),window.api.pty.write({tabId:s,data:v.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),ac();const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}window.api.pty.write({tabId:s,data:m}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&TS(s);const E=window;E.__transcripts&&(E.__transcripts.push({tabId:s,text:m}),E.__transcripts.length>500&&E.__transcripts.shift())},onError:h=>{_t.error("voice","recognition error",{err:h}),ac(),n({error:h,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),dr==null||dr(),dr=null,vv(),gs==null||gs.destroy(),gs=null,Vf=null,Le.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)})});gs=c,Vf=(a==null?void 0:a.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Fh(),c.start().then(()=>{gs===c&&(dr==null||dr(),dr=UI(c))}).catch(h=>{const m=h instanceof Error?h.message:String(h);_t.error("voice","handle.start() failed",{error:m}),Le.error(`Could not start mic: ${m}`)})}catch(c){n({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,c,h;return((h=(c=(l=window.api)==null?void 0:l.voice)==null?void 0:c.getDevicePref)==null?void 0:h.call(c))??Promise.resolve(null)}).then(l=>u((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{_t.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),u(null)})},stopRecording:()=>{const s=gs;s&&(vv(),ac(),Nx=0,kw=0,dr==null||dr(),dr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t(),s.stop().finally(()=>{s.destroy(),gs===s&&(gs=null,Vf=null),e().hotkeyState==="stopping"&&(bv(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const s=gs;if(!s)return;vv(),dr==null||dr(),dr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await s.stop()}catch(l){_t.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}s.destroy(),gs===s&&(gs=null);const{useSessions:a}=await ti(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>jA);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=>{_t.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:()=>ac(),setPartialsEnabled:s=>{e().partialsEnabled!==s&&(n({partialsEnabled:s}),s||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:s=>{e().permissionState!==s&&(_t.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"?_t.warn("voice-turn","voice-turn.load_failed"):s==="runtime_error"?_t.warn("voice-turn","voice-turn.runtime_error"):s==="disabled"&&_t.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 c=e(),{canRecord:h,reason:m}=kT(c);if(s==="down"){if(m==="error"||m==="load-timeout"){c.resetAndRetryModel(),_t.info("voice-hotkey","down.retry",{source:a,reason:m});return}if(!h&&m!=="loading"){_t.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:m});return}if(c.hotkeyState==="recording"||c.isRecording){(u==="toggle"||a==="global")&&(n({hotkeyState:"stopping"}),bv(),km=setTimeout(()=>{e().hotkeyState==="stopping"&&(_t.warn("voice-hotkey","drain-timeout",{durationMs:xv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},xv),c.stopRecording());return}if(m==="loading"){c.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),_t.info("voice-hotkey","armed",{source:a,modelStatus:c.modelStatus})),_v(),lx={tabId:l,source:a,mode:u},cx=Yt.subscribe((g,v)=>{if(lx&&g.modelStatus==="ready"&&v.modelStatus!=="ready"&&g.hotkeyState==="armed"){const E=lx;if(_v(),!E.tabId){_t.warn("voice-hotkey","armed-promote-no-tab",{source:E.source}),n({hotkeyState:"idle"});return}_t.info("voice-hotkey","armed-promote",E),n({hotkeyState:"recording"}),Yt.getState().startRecording(E.tabId)}});return}if(!l){_t.warn("voice-hotkey","no-active-tab",{source:a});return}_t.info("voice-hotkey","start",{source:a,mode:u,tabId:l}),c.startRecording(l),e().isRecording?n({hotkeyState:"recording"}):(_t.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(u!=="hold"||a==="global")){if(c.hotkeyState==="armed"){_v(),_t.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),bv(),km=setTimeout(()=>{e().hotkeyState==="stopping"&&(_t.warn("voice-hotkey","drain-timeout",{durationMs:xv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},xv),c.stopRecording())}},destroyHotkey:()=>{const s=e();if(_v(),ac(),s.hotkeyState==="recording"){_t.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{s.stopRecording()}catch{}}else(s.hotkeyState==="armed"||s.hotkeyState==="stopping")&&(bv(),n({hotkeyState:"destroyed"}))}}}),iR=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),kT=n=>cb()?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"&&Yt.setState({ttsEnabled:n})}).catch(n=>{_t.warn("voice","getTtsEnabled failed",{error:n instanceof Error?n.message:String(n)})});if(typeof window<"u"){const n=window;n.__voice=Yt,n.__transcripts=[]}const Om=6e4,sR=3e5,rR=.25,oR=5e3,Yh=Ci(()=>({data:null,refreshing:!1}));let DS=!1,ux=null,Yb=Om,yv=!1,ul=null;function aR(n,e){if(n.kind==="ok")return{delayMs:Om,nextBackoffMs:Om};const t=Math.min(e*2,sR),i=t*rR;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 $S(){return O2(window.api.billing.fetch(),oR,"billing.fetch")}function NS(n){Yh.setState({data:n,refreshing:!1})}async function t0(){Yh.setState({refreshing:!0});let n=Om;try{const e=await $S();ul&&(ul.cancel(),ul=null),NS(e);const{delayMs:t,nextBackoffMs:i}=aR(e,Yb);Yb=i,n=t}catch(e){Yb=Om,Yh.setState({refreshing:!1});const t=L2({error:e,retry:$S,onRetrySuccess:i=>{ul=null,NS(i)},onStillFailing:i=>{ul=null,yv||(yv=!0,Le.warn(`Billing usage fetch: ${i}`))}});if(t)ul=t;else if(!yv){yv=!0;const i=e instanceof Error?e.message:String(e);Le.warn(`Billing usage fetch failed: ${i}`)}}ux=setTimeout(t0,n)}function lR(){DS||(DS=!0,t0())}function ET(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 TT(){ux!==null&&(clearTimeout(ux),ux=null),ul&&(ul.cancel(),ul=null),t0()}function Lm(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 zm(n){const e=/(opus|sonnet|haiku|fable)/i.exec(n);return e?e[1].toLowerCase():null}const Sv=new Map,cR=3e4;function n0(n){const[e,t]=R.useState(()=>{var i;return n?((i=Sv.get(n))==null?void 0:i.value)??null:null});return R.useEffect(()=>{if(!n){t(null);return}let i=!1;return(async()=>{const a=Sv.get(n);if(a&&Date.now()-a.ts<cR){i||t(a.value);return}try{const u=await window.api.app.gitBranch(n);if(i)return;Sv.set(n,{value:u,ts:Date.now()}),t(u)}catch{if(i)return;Sv.set(n,{value:null,ts:Date.now()}),t(null)}})(),()=>{i=!0}},[n]),e}const dR="~/.claude/session-manager/ui-chrome-prefs.json",jT=$a(dR),uR=180,hR=480,Tw=252,bd={sidebarWidth:Tw,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function jw(n){return Math.min(hR,Math.max(uR,n))}let uc=null,hx={};function pR(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};jT.patch(i).catch(()=>{})};n().hydrated||!uc?e():uc.then(e)}function kh(n,e,t){n(t),!e().hydrated&&uc&&Object.assign(hx,t),pR(e)}const ds=Ci((n,e)=>({...bd,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():uc||(uc=(async()=>{try{const t=await jT.read();if(Object.keys(t).length>0){n({sidebarWidth:typeof t.sidebarWidth=="number"?jw(t.sidebarWidth):bd.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed??bd.sidebarCollapsed,collapsedGroups:Array.isArray(t.collapsedGroups)?t.collapsedGroups:bd.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed??bd.learningPanelCollapsed,tourCompletedAt:typeof t.tourCompletedAt=="number"?t.tourCompletedAt:bd.tourCompletedAt,density:t.density==="compact"?"compact":bd.density,...hx,hydrated:!0});return}}catch{}n({...hx,hydrated:!0})})().finally(()=>{uc=null,hx={}}),uc),setSidebarWidth:t=>kh(n,e,{sidebarWidth:jw(t)}),setSidebarCollapsed:t=>kh(n,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>kh(n,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>kh(n,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>kh(n,e,{tourCompletedAt:t}),setDensity:t=>kh(n,e,{density:t})})),fR=52;function mR(n){return new Set(n.filter(e=>e==="Workspace"||e==="Claude Code"||e==="Session Manager"))}function gR(){const n=It(t=>{var i;return((i=t.tabs.find(s=>s.id===t.activeTabId))==null?void 0:i.cwd)??null});return{scheduler:Er(t=>{var i;return(((i=t.snapshot)==null?void 0:i.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function vR({active:n,onNavigate:e,onNewSession:t}){const i=ds(q=>q.hydrated),s=ds(q=>q.hydrate);R.useEffect(()=>{i||s()},[i,s]);const a=ds(q=>q.collapsedGroups),u=ds(q=>q.setCollapsedGroups),l=R.useMemo(()=>mR(a),[a]),c=R.useCallback(q=>{const le=new Set(l);le.has(q)?le.delete(q):le.add(q),u(Array.from(le))},[l,u]),h=ds(q=>q.sidebarCollapsed),m=ds(q=>q.setSidebarCollapsed),g=R.useCallback(()=>{m(!h)},[h,m]),v=It(q=>q.tabs),E=It(q=>q.activeTabId),k=v.find(q=>q.id===E)??null,C=gR(),x=An(q=>q.navFace),b=AA(x),w=b.filter(q=>q.group==="Workspace"),S=b.filter(q=>q.group==="Claude Code"),T=b.filter(q=>q.group==="Session Manager"),I=x==="home"&&!h,A=ds(q=>q.sidebarWidth),M=ds(q=>q.setSidebarWidth),[N,L]=R.useState(A),U=R.useRef(N);U.current=N,R.useEffect(()=>{L(A)},[A]);const J=R.useCallback(q=>{q.preventDefault();const le=q.clientX,ie=U.current;let he=ie;const ve=B=>{he=jw(ie+(B.clientX-le)),L(he)},fe=()=>{window.removeEventListener("pointermove",ve),window.removeEventListener("pointerup",fe),document.body.style.cursor="",document.body.style.userSelect="",M(he)};window.addEventListener("pointermove",ve),window.addEventListener("pointerup",fe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[M]),Z=R.useCallback(()=>{L(Tw),M(Tw)},[M]);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?fR:N},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[r.jsx(xR,{tab:k,navFace:x,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:I?r.jsxs(r.Fragment,{children:[r.jsx(Xb,{label:"Workspace",desc:Gb.Workspace,collapsed:l.has("Workspace"),count:w.length,onToggle:()=>c("Workspace")}),!l.has("Workspace")&&w.map(q=>r.jsx(Cv,{item:q,active:n===q.key,live:q.liveKind?C[q.liveKind]:!1,onClick:()=>e(q.key),rail:!1},q.key)),r.jsx(Xb,{label:"Claude Code",desc:Gb["Claude Code"],collapsed:l.has("Claude Code"),count:S.length,onToggle:()=>c("Claude Code")}),!l.has("Claude Code")&&S.map(q=>r.jsx(Cv,{item:q,active:n===q.key,live:!1,onClick:()=>e(q.key),rail:!1},q.key)),r.jsx(Xb,{label:"Session Manager",desc:Gb["Session Manager"],collapsed:l.has("Session Manager"),count:T.length,onToggle:()=>c("Session Manager")}),!l.has("Session Manager")&&T.map(q=>r.jsx(Cv,{item:q,active:n===q.key,live:!1,onClick:()=>e(q.key),rail:!1},q.key))]}):r.jsx("div",{className:"pt-2",children:b.map(q=>r.jsx(Cv,{item:q,active:n===q.key,live:q.liveKind?C[q.liveKind]:!1,onClick:()=>e(q.key),rail:h},q.key))})}),r.jsx(bR,{rail:h,navFace:x}),!h&&r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:J,onDoubleClick:Z,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 xR({tab:n,navFace:e,onNewSession:t,rail:i,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",u=n0((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(Si,{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(Si,{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(Si,{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(Si,{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(Si,{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(Si,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Xb({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 Cv({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(Si,{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 bR({rail:n,navFace:e}){const t=Yt(c=>c.isRecording),i=It(c=>c.tabs),s=It(c=>c.activeTabId),a=i.find(c=>c.id===s)??null,[u,l]=R.useState(null);return R.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return I2(a.presetId).then(h=>{c||l((h==null?void 0:h.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!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 · ${Lm(u)}`:"Claude Code"})]})}function _R(n,e,t){return e?n.map(i=>i.id===e?{...i,lastActivityAt:t}:i):n}function wR(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 yR(n,e,t){const i=Date.now(),s={...n,lastEventAt:t!=null&&t.replay?n.lastEventAt:i},a=[],u=(l,c)=>l.length>c?l.slice(0,c-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,c=l.input,h={};for(const m of["command","file_path","pattern","url","query","subagent_type","description"])c&&m in c&&(h[m]=c[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),v=typeof(m==null?void 0:m.file_path)=="string"?m.file_path:void 0,E=typeof(m==null?void 0:m.command)=="string"?m.command:void 0,k=v?v.split("/").pop()??v:E?u(E,28):"";a.push({id:0,kind:"tool-use",at:i,label:k?`${l.name} · ${k}`:l.name,target:v??E,toolName:l.name}),g&&v&&a.push({id:0,kind:"file-edit",at:i,label:`${l.name} · ${u(v.split("/").pop()??v,34)}`,target:v,toolName:l.name})}break}case"plan":{const l=e.data,c=typeof l=="string"?l:(l==null?void 0:l.plan)??JSON.stringify(l);s.plans=[{at:i,content:c??""},...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,c=(n.usage.inputTokens||0)+(n.usage.outputTokens||0),h=l.input_tokens??l.inputTokens??0,m=l.output_tokens??l.outputTokens??0,g=c+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(c/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=_R(n.agents,l==null?void 0:l.toolUseId,i);break}}return{next:s,newActivity:a}}const px=Ci((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]:wR(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 c=e().tabs[t];if(!c)return;if(!l.ok){const{toast:m}=await ti(async()=>{const{toast:g}=await Promise.resolve().then(()=>P2);return{toast:g}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[t]:{...c,path:null}}});return}n({tabs:{...e().tabs,[t]:{...c,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 c of i){const{next:h,newActivity:m}=yR(u,c,s);u=h,l=l.concat(m)}if(l.length>0){let c=a.activitySeq;const h=l.map(m=>({...m,id:++c}));u={...u,activitySeq:c,activityRing:[...a.activityRing,...h].slice(-32)}}n({tabs:{...e().tabs,[t]:u}})}}));function SR(n){const e=px(s=>s.subscribe),t=px(s=>s.unsubscribe),i=px(s=>n?s.tabs[n.id]:void 0);return R.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 DT(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 Dw(n){return!n||typeof n.utilization!="number"||Number.isNaN(n.utilization)?null:Math.round(n.utilization)}function AS(n,e){const t=Dw(e);if(t==null)return`${n} — usage unavailable`;const i=DT((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 mq(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 $T=R.createContext(null);function CR({panelId:n,children:e}){return r.jsx($T.Provider,{value:n,children:e})}function Zm(n){const e=R.useContext($T),t=n??e;return An(i=>t==null||i.focusedPanelId===t)}function i0(n){const e=Zm(n),t=R.useRef(e);return t.current=e,t}const kR=5e3;let jd=null;const $w=new Set;let Jb=0,Tm=null;function ER(){$w.forEach(n=>n())}async function Ax(){try{jd=await window.api.schedule.sessionSlots(),ER()}catch{}}const TR=0,jR=10;async function gq(n){jd||await Ax();const e=jd?jd.min:TR,t=jd?jd.max:jR,i=Math.min(t,Math.max(e,Math.round(n)));await window.api.schedule.setSessionSlots(i),await Ax()}function DR(){Tm==null&&(Ax(),Tm=setInterval(()=>{Ax()},kR))}function $R(){Tm!=null&&(clearInterval(Tm),Tm=null)}function s0(n){const e=Zm(n),[,t]=R.useState(0);return R.useEffect(()=>{const i=()=>t(s=>s+1);return $w.add(i),()=>{$w.delete(i)}},[]),R.useEffect(()=>{if(e)return Jb+=1,DR(),()=>{Jb-=1,Jb<=0&&$R()}},[e]),jd}let Rh=null;const Nw=new Set;let Zb=0,fx=null,Aw=!1;const NR=360*60*1e3;let mx=null;function IS(n){Rh=n.check||!(Rh!=null&&Rh.check)?n:{...n,check:Rh.check},Nw.forEach(e=>e())}function AR(){if(Aw)return;Aw=!0,fx=window.api.updater.onStatus(IS);const n=()=>{window.api.updater.status().then(IS).catch(()=>{})};n(),mx=setInterval(n,NR)}function IR(){Aw=!1,mx!=null&&(clearInterval(mx),mx=null),fx&&(fx(),fx=null)}function RR(){const[,n]=R.useState(0);return R.useEffect(()=>{const e=()=>n(t=>t+1);return Nw.add(e),Zb+=1,AR(),()=>{Nw.delete(e),Zb-=1,Zb<=0&&IR()}},[]),Rh}function PR({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 MR({onNavigate:n}){const e=It(ie=>ie.tabs),t=It(ie=>ie.activeTabId),i=e.find(ie=>ie.id===t)??null,s=SR(i),a=(s==null?void 0:s.lastEventAt)??0,u=Yh(ie=>ie.data),l=Er(ie=>{var he;return((he=ie.snapshot)==null?void 0:he.paused)??null}),c=n0((i==null?void 0:i.cwd)??null),h=s0(),m=RR(),g=(m==null?void 0:m.check)??null,v=Ni(ie=>ie.show),[,E]=R.useState(0);R.useEffect(()=>{const ie=setInterval(()=>E(he=>he+1),6e4);return()=>clearInterval(ie)},[]);const k=async()=>{const ie=(m==null?void 0:m.latest)??"";try{const he=await window.api.updater.install(!1),ve=(he==null?void 0:he.status)??await window.api.updater.status();(ve==null?void 0:ve.state)==="deferred"&&v("info",`Update v${ie} will install when ${ve.busyReason??"running jobs"} finish`)}catch(he){v("error",he instanceof Error?he.message:String(he))}},C=(s==null?void 0:s.todos)??[],[x,b]=R.useState(!1),w=R.useRef(null);R.useEffect(()=>{if(!x)return;const ie=he=>{w.current&&!w.current.contains(he.target)&&b(!1)};return document.addEventListener("mousedown",ie),()=>document.removeEventListener("mousedown",ie)},[x]),R.useEffect(()=>{C.length===0&&b(!1)},[C.length]);const S=ET(u),T=(S==null?void 0:S.usage.five_hour)??null,I=(S==null?void 0:S.usage.seven_day)??null,A=Dw(T),M=Dw(I),N=(u==null?void 0:u.kind)==="ok"||(u==null?void 0:u.kind)==="ok-stale",L=a>0?zR(Date.now()-a):"—",U=(h==null?void 0:h.total)??5,J=h?Math.min(Math.max(h.inUse,0),h.total):0,Z=h?`${J} / ${U}`:`— / ${U}`,q=h&&h.holders.length>0?`
|
|
2934
2934
|
`+h.holders.slice(0,5).map(ie=>ie.owner).join(`
|
|
2935
|
-
`):"",le=`${Z} Claude sessions running${q}`;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:N?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:N?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:AS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:A!=null?`${A}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:AS("Weekly window (all models)",I),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:M!=null?`${M}%`:"—"})]}),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,c&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),C.length>0&&r.jsx(OR,{ref:w,todos:C,open:x,onToggle:()=>b(ie=>!ie)}),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:le,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(PR,{total:U,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 ie=g.downloadUrl;ie&&window.api.shell.open({as:"external",url:ie}).catch(()=>{v("error",`Couldn't open URL: ${ie}`)})},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.140.0"]})]})}const OR=R.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(LR,{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 LR({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 zR(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 BR({onClose:n,onSent:e}){const t=It(M=>M.tabs),[i,s]=R.useState(""),[a,u]=R.useState(()=>Object.fromEntries(t.map(M=>[M.id,!0]))),[l,c]=R.useState(!1),[h,m]=R.useState({}),g=R.useRef(null),v=R.useRef(e);R.useEffect(()=>{v.current=e},[e]),R.useEffect(()=>{u(M=>{const N={};for(const L of t)N[L.id]=M[L.id]??!0;return N})},[t]),R.useEffect(()=>{var M;(M=g.current)==null||M.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(N=>{m(L=>N.tabId in L?{...L,[N.tabId]:"skipped"}:L)}),[]),R.useEffect(()=>{if(Object.keys(h).length===0)return;const M=Object.values(h).filter(L=>L==="sent").length,N=window.setTimeout(()=>v.current(M),1500);return()=>window.clearTimeout(N)},[h]);const E=t.filter(M=>a[M.id]).map(M=>M.id),k=E.length,C=Object.keys(h).length>0,x=i.length>0&&k>0&&!l&&!C,b=()=>{if(!x)return;c(!0);const M=It.getState().tabs,N=new Set(M.map(U=>U.id)),L={};for(const U of E)N.has(U)?(window.api.pty.write({tabId:U,data:i+"\r"}),L[U]="sent"):L[U]="skipped";m(L),c(!1)},w=M=>{if(M.key==="Escape"){M.preventDefault(),M.stopPropagation(),n();return}M.key==="Enter"&&(M.metaKey||M.ctrlKey)&&(M.preventDefault(),b())},S=t.length>0&&t.every(M=>a[M.id]),T=()=>{const M=!S;u(Object.fromEntries(t.map(N=>[N.id,M])))},I=Object.values(h).some(M=>M==="skipped"),A=C?I?"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:w,"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:M=>s(M.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:S,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(M=>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[M.id],onChange:N=>u(L=>({...L,[M.id]:N.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:M.label}),h[M.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[M.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},M.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:b,disabled:!x,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:A})]})]})}function FR({tabId:n,cwd:e,onClose:t}){const i=Sm(k=>k.watchersForTab(n)),s=Sm(k=>k.add),a=Sm(k=>k.remove),u=R.useRef(null),[l,c]=R.useState(""),[h,m]=R.useState(""),[g,v]=R.useState(!1);R.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),R.useEffect(()=>{const k=C=>{u.current&&!u.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const E=async()=>{const k=h.trim();if(!k||g)return;v(!0);const C=await s({tabId:n,label:l.trim(),command:k,cwd:e});v(!1),C&&(c(""),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=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),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"&&E()},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:E,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 C=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:(C==null?void 0:C.line)??"",children:C?C.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2935
|
+
`):"",le=`${Z} Claude sessions running${q}`;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:N?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:N?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:AS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:A!=null?`${A}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:AS("Weekly window (all models)",I),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:M!=null?`${M}%`:"—"})]}),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,c&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),C.length>0&&r.jsx(OR,{ref:w,todos:C,open:x,onToggle:()=>b(ie=>!ie)}),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:le,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(PR,{total:U,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 ie=g.downloadUrl;ie&&window.api.shell.open({as:"external",url:ie}).catch(()=>{v("error",`Couldn't open URL: ${ie}`)})},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.141.0"]})]})}const OR=R.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(LR,{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 LR({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 zR(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 BR({onClose:n,onSent:e}){const t=It(M=>M.tabs),[i,s]=R.useState(""),[a,u]=R.useState(()=>Object.fromEntries(t.map(M=>[M.id,!0]))),[l,c]=R.useState(!1),[h,m]=R.useState({}),g=R.useRef(null),v=R.useRef(e);R.useEffect(()=>{v.current=e},[e]),R.useEffect(()=>{u(M=>{const N={};for(const L of t)N[L.id]=M[L.id]??!0;return N})},[t]),R.useEffect(()=>{var M;(M=g.current)==null||M.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(N=>{m(L=>N.tabId in L?{...L,[N.tabId]:"skipped"}:L)}),[]),R.useEffect(()=>{if(Object.keys(h).length===0)return;const M=Object.values(h).filter(L=>L==="sent").length,N=window.setTimeout(()=>v.current(M),1500);return()=>window.clearTimeout(N)},[h]);const E=t.filter(M=>a[M.id]).map(M=>M.id),k=E.length,C=Object.keys(h).length>0,x=i.length>0&&k>0&&!l&&!C,b=()=>{if(!x)return;c(!0);const M=It.getState().tabs,N=new Set(M.map(U=>U.id)),L={};for(const U of E)N.has(U)?(window.api.pty.write({tabId:U,data:i+"\r"}),L[U]="sent"):L[U]="skipped";m(L),c(!1)},w=M=>{if(M.key==="Escape"){M.preventDefault(),M.stopPropagation(),n();return}M.key==="Enter"&&(M.metaKey||M.ctrlKey)&&(M.preventDefault(),b())},S=t.length>0&&t.every(M=>a[M.id]),T=()=>{const M=!S;u(Object.fromEntries(t.map(N=>[N.id,M])))},I=Object.values(h).some(M=>M==="skipped"),A=C?I?"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:w,"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:M=>s(M.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:S,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(M=>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[M.id],onChange:N=>u(L=>({...L,[M.id]:N.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:M.label}),h[M.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[M.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},M.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:b,disabled:!x,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:A})]})]})}function FR({tabId:n,cwd:e,onClose:t}){const i=Sm(k=>k.watchersForTab(n)),s=Sm(k=>k.add),a=Sm(k=>k.remove),u=R.useRef(null),[l,c]=R.useState(""),[h,m]=R.useState(""),[g,v]=R.useState(!1);R.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),R.useEffect(()=>{const k=C=>{u.current&&!u.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const E=async()=>{const k=h.trim();if(!k||g)return;v(!0);const C=await s({tabId:n,label:l.trim(),command:k,cwd:e});v(!1),C&&(c(""),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=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),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"&&E()},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:E,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 C=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:(C==null?void 0:C.line)??"",children:C?C.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2936
2936
|
* dockview-core
|
|
2937
2937
|
* @version 6.6.1
|
|
2938
2938
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3050,7 +3050,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3050
3050
|
|
|
3051
3051
|
${t}`}const _m={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},AF=["popover","review","diff"],u$=["popover","review"];function IF(n,e){switch(e.type){case"SELECT":return{..._m,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{..._m,editCount:n.editCount};case"LISTEN":return u$.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 AF.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:{..._m,editCount:n.editCount+1};case"RESET_FILE":return{..._m,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function RF(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 PF(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 MF="sonnet";function OF(n,e){const[t,i]=R.useReducer(IF,_m),s=R.useRef(0),a=R.useRef(null),u=R.useRef(n),l=R.useRef(new Map);R.useEffect(()=>window.api.docEdit.onSessionResult(S=>{const T=l.current.get(S.requestId);T&&(l.current.delete(S.requestId),T(S))}),[]),R.useEffect(()=>{u.current!==n&&(u.current=n,s.current+=1,c(),i({type:"RESET_FILE"}))},[n]);function c(){const S=a.current;S&&(a.current=null,S.stop().catch(()=>{}),S.destroy(),Yt.setState({externalRecording:!1}))}const h=R.useCallback(S=>{s.current+=1,c(),i({type:"SELECT",selection:S})},[]),m=R.useCallback(()=>{s.current+=1,c(),i({type:"CANCEL"})},[]),g=R.useCallback(()=>{if(!u$.includes(t.phase))return;if(Yt.getState().isRecording){Le.error("Microphone is already in use");return}if(!cb()){Le.error("Microphone or Web Worker not available");return}const S=++s.current;i({type:"LISTEN"}),Yt.setState({externalRecording:!0});const T=()=>{a.current===I&&(a.current=null),Yt.setState({externalRecording:!1})},I=yT({onFinal:A=>{if(s.current!==S)return;I.stop().catch(()=>{}),I.destroy(),T();const M=A.trim();if(!M){i({type:"CANCEL"});return}i({type:"HEARD",transcript:M})},onError:A=>{s.current===S&&(I.destroy(),T(),Le.error(`Microphone error: ${A}`),i({type:"CANCEL"}))},onModelStatus:(A,M)=>{s.current===S&&i({type:"MODEL_STATUS",status:A,message:M})},onProgress:A=>{s.current===S&&i({type:"MODEL_STATUS",status:"loading",message:`${A}%`})}});a.current=I,I.start().catch(A=>{s.current===S&&(I.destroy(),T(),Le.error(`Could not start mic: ${A instanceof Error?A.message:String(A)}`),i({type:"CANCEL"}))})},[t.phase]),v=R.useCallback(()=>{const S=RF(n,It.getState().tabs);if(!S)return null;const T=PF(S,It.getState().tabs,px.getState().tabs);return!T||Cn.getState().get(T.id).running?null:T},[n]),E=R.useCallback((S,T,I,A,M,N)=>{const L=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{l.current.set(L,U),window.api.docEdit.runInSession({tabId:S,sessionId:T,cwd:I,before:A,instruction:M,documentText:N,requestId:L})})},[]),k=R.useCallback(async(S,T)=>{const I=t.selection;if(!I)return;const A=++s.current;i({type:"RUN",instruction:S,recordInstruction:T});const M=NF(e);try{const N=v(),L=N?await E(N.id,N.sessionId,N.cwd,I.text,S,M):await window.api.docEdit.run({path:n,before:I.text,instruction:S,documentText:M});if(s.current!==A)return;if(!L.ok){Le.error(L.error||"Edit failed"),i({type:"RUN_ERR"});return}i({type:"RUN_OK",diff:{before:I.text,after:L.after??""}})}catch(N){if(s.current!==A)return;Le.error(N instanceof Error?N.message:"Edit failed"),i({type:"RUN_ERR"})}},[n,t.selection,e,v,E]),C=R.useCallback(S=>{k(S,!0)},[k]),x=R.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),b=R.useCallback(()=>{const S=t.instruction;S&&k(`${S}
|
|
3052
3052
|
|
|
3053
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),w=R.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const I=DF(S,T.before,T.after);return I.ok?(s.current+=1,i({type:"ACCEPT"})):Le.error(I.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),I},[t.diff]);return{state:t,select:h,cancel:m,listen:g,sendHeard:x,run:C,retry:b,accept:w}}const LF=[{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."}],Xk=320,rm=8;function zF(){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 BF(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,rm),Math.max(rm,e-Xk-rm)),i=Math.max(n.top-rm,rm);return{position:"fixed",left:t,top:i,width:Xk,transform:"translateY(-100%)",zIndex:ZA.dialog}}function FF({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:c,onSendHeard:h,onCancel:m,onAccept:g,onReject:v,onRetry:E}){const[k,C]=R.useState(""),[x,b]=R.useState(!1),w=Ni(A=>A.show),S=R.useRef(null);R.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await Yo(t)){w("error","Copy failed");return}b(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>b(!1),1500)},I=()=>{const A=k.trim();A&&(l(A),C(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:BF(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:x?"Copied":"Copy"}),r.jsx("button",{onClick:c,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),LF.map(A=>r.jsx("button",{onClick:()=>u(A.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:A.label},A.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:A=>C(A.target.value),onKeyDown:A=>{A.key==="Enter"?I():A.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(zF,{}),"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:c,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:v,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:E,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 GF(){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 Jk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:c,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:Lm(MF)})]}),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(GF,{}),"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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function HF(){const n=It(t=>t.tabs),e=It(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function WF({path:n,onRenamed:e,onDeleted:t}){const[i,s]=R.useState(!1),[a,u]=R.useState(!1),[l,c]=R.useState(""),[h,m]=R.useState(!1),g=In(U=>U.buffers[n]),v=In(U=>U.openFile),E=In(U=>U.renameOpenFile),k=In(U=>U.closeFile),C=HF(),x=bo(n),b=()=>s(!1),w=()=>{c(x),u(!0),b()},S=async()=>{const U=l.trim();if(!U||U===x){u(!1);return}try{const J=await window.api.files.rename(n,U);if(J.ok){const Z=n.slice(0,n.lastIndexOf("/")),q=J.newPath??`${Z}/${U}`;E(n,q),e==null||e(n,q),Le.info(`Renamed to ${U}`)}else Le.error(J.error??`Couldn't rename ${x}`)}catch(J){Le.error(J instanceof Error?J.message:`Couldn't rename ${x}`)}u(!1)},T=async()=>{b();try{const U=await window.api.files.duplicate(n);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${bo(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${x}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${x}`)}},I=async()=>{try{const U=await window.api.files.delete(n);U.ok?(k(n),t==null||t(n),Le.info(`Deleted ${x}`)):Le.error(U.error??`Couldn't delete ${x}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{b();const U=g??"";await Yo(U)?Le.info(`Copied ${U.length} chars`):Le.error(`Couldn't copy ${x}`)},M=()=>{if(b(),!C){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${n} `}),Le.info(`Added ${x} to Claude context`)},N=()=>{b(),window.api.shell.open({as:"openPath",path:n}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${x}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${x}`))},L=()=>{b(),window.api.shell.open({as:"revealPath",path:n}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${x}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${x}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(U=>!U),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:b}),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(R_,{children:"Edit"}),r.jsx(Sd,{label:"Rename",onClick:w}),r.jsx(Sd,{label:"Duplicate",onClick:T}),r.jsx(Sd,{label:"Delete document",danger:!0,onClick:()=>{b(),m(!0)}}),r.jsx(Zk,{}),r.jsx(R_,{children:"Open"}),r.jsx(Sd,{label:"Open in default app",onClick:N}),r.jsx(Sd,{label:"Reveal in OS",onClick:L}),r.jsx(Zk,{}),r.jsx(R_,{children:"Export"}),r.jsx(Sd,{label:"Copy as Markdown",onClick:A}),r.jsx(Sd,{label:"Add to Claude context",onClick:M,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(UF,{value:l,onChange:c,onCancel:()=>u(!1),onConfirm:()=>void S()}),h&&r.jsx(VF,{name:x,onCancel:()=>m(!1),onConfirm:()=>void I()})]})}function R_({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 Sd({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 Zk(){return r.jsx("div",{className:"my-1 border-t border-line"})}function UF({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 VF({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 qF(){const[n,e]=R.useState(!1),t=Rd();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($h,{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($h,{label:"Word wrap",children:r.jsx(Yv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx($h,{label:"Minimap",children:r.jsx(Yv,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx($h,{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($h,{label:"Autosave",children:r.jsx(Yv,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx($h,{label:"Wide measure",children:r.jsx(Yv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function $h({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 Yv({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 KF=R.lazy(()=>ti(()=>import("./TiptapBody-DApeu7x8.js").then(n=>n.a),[],import.meta.url).then(n=>({default:n.TiptapBody})));function Xv(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 om(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 Jv(n){return iD(n)||sD(n)}function YF(){const n=i0(),e=In(_e=>_e.openFiles),t=In(_e=>_e.activeFilePath),i=In(_e=>_e.dirty),s=In(_e=>_e.viewMode),a=In(_e=>_e.buffers),u=In(_e=>_e.setActive),l=In(_e=>_e.closeFile),c=In(_e=>_e.closeOthers),h=In(_e=>_e.closeToTheRight),m=In(_e=>_e.closeAll),g=In(_e=>_e.loadBuffer),v=In(_e=>_e.setBuffer),E=In(_e=>_e.markSaved),k=In(_e=>_e.setViewMode),C=Rd(),[x,b]=R.useState({}),[w,S]=R.useState({}),[T,I]=R.useState(null),[A,M]=R.useState(null),[N,L]=R.useState(!1),[U,J]=R.useState(!1),[Z,q]=R.useState(!0),le=R.useRef(null),ie=R.useRef(null),he=R.useRef(void 0),ve=R.useRef(null),fe=R.useRef(null),B=OF(t??"",a[t??""]??""),K=R.useCallback((_e,ot)=>{v(_e,ot),om(_e)&&ka.getState().setDraft(_e,ot)},[v]),W=R.useCallback(_e=>{le.current=_e},[]),ee=R.useCallback(()=>le.current,[]);R.useEffect(()=>{pL()},[]),R.useEffect(()=>{const _e=t;if(!_e||Jv(_e))return;if(In.getState().hasBuffer(_e)){b(it=>it[_e]==="ready"?it:{...it,[_e]:"ready"});return}let ot=!1;return b(it=>({...it,[_e]:"loading"})),om(_e)?((async()=>{if(await ka.getState().loadText(_e,!0),ot)return;const it=ka.getState().files[_e];if(!it||it.loadError&&!it.exists){b(Lt=>({...Lt,[_e]:{error:(it==null?void 0:it.loadError)??"failed to read"}}));return}g(_e,it.diskRaw),it.dirty&&In.getState().setBuffer(_e,it.draftRaw),b(Lt=>({...Lt,[_e]:"ready"}))})(),()=>{ot=!0}):(window.api.files.read(_e).then(it=>{ot||(it.binary?b(Lt=>({...Lt,[_e]:{binary:!0,size:it.size??0,mime:it.mime??"application/octet-stream",reason:it.error??"Binary file"}})):it.ok?(g(_e,it.text),b(Lt=>({...Lt,[_e]:"ready"}))):b(Lt=>({...Lt,[_e]:{error:it.error??"failed to read"}})))}),()=>{ot=!0})},[t,g]),R.useEffect(()=>{M(null)},[t]);const ce=R.useCallback(async(_e,ot=!1)=>{const it=In.getState().buffers[_e];if(it==null)return;ot&&L(!0);const Lt=om(_e);let bn;if(Lt){const Tn=ka.getState();if(Tn.setDraft(_e,it),bn=await Tn.saveText(_e),!bn.ok&&bn.error==="conflict"){ot&&L(!1);return}}else bn=await window.api.files.write(_e,it);bn.ok?(E(_e),S(Tn=>({...Tn,[_e]:(Tn[_e]??0)+1})),ot||Le.info(`Saved ${bo(_e)}`)):Le.error(bn.error??`Couldn't save ${bo(_e)}`),ot&&L(!1)},[E]);R.useEffect(()=>{if(!C.autosave)return;const _e=t;if(!(!_e||Jv(_e)||om(_e)||!i[_e]))return window.clearTimeout(he.current),he.current=window.setTimeout(()=>{ce(_e,!0)},1200),()=>window.clearTimeout(he.current)},[C.autosave,t,i,a,ce]);const ge=R.useCallback(_e=>{_e.length&&(b(ot=>Xv(ot,_e)),S(ot=>Xv(ot,_e)))},[]),Oe=R.useCallback((_e,ot)=>{b(it=>_e in it?{...Xv(it,[_e]),[ot]:it[_e]}:it),S(it=>_e in it?{...Xv(it,[_e]),[ot]:it[_e]}:it)},[]),We=R.useCallback(_e=>{i[_e]?I({kind:"one",path:_e}):(l(_e),ge([_e]))},[i,l,ge]),xe=R.useCallback(_e=>{e.some(it=>it.path!==_e&&i[it.path])?I({kind:"others",path:_e}):(c(_e),ge(e.filter(it=>it.path!==_e).map(it=>it.path)))},[e,i,c,ge]),te=R.useCallback(_e=>{const ot=e.findIndex(Lt=>Lt.path===_e);ot!==-1&&e.slice(ot+1).some(Lt=>i[Lt.path])?I({kind:"right",path:_e}):(h(_e),ge(ot!==-1?e.slice(ot+1).map(Lt=>Lt.path):[]))},[e,i,h,ge]);R.useEffect(()=>{const _e=ot=>{if(n.current)if((ot.metaKey||ot.ctrlKey)&&(ot.key==="s"||ot.key==="S")){const it=In.getState().activeFilePath;it&&!Jv(it)&&(ot.preventDefault(),ce(it))}else if((ot.metaKey||ot.ctrlKey)&&ot.shiftKey&&(ot.key==="f"||ot.key==="F"))ot.preventDefault(),J(it=>!it);else if((ot.metaKey||ot.ctrlKey)&&ot.shiftKey&&(ot.key==="w"||ot.key==="W")){const it=In.getState().activeFilePath;it&&In.getState().openFiles.length>1&&(ot.preventDefault(),xe(it))}else ot.key==="Escape"&&B.state.phase!=="idle"?B.cancel():ot.key==="Escape"&&U&&J(!1)};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},[ce,U,xe,B.state.phase,B.cancel]),R.useEffect(()=>{if(B.state.phase==="idle")return;const _e=ot=>{var Lt,bn;const it=ot.target;(Lt=fe.current)!=null&&Lt.contains(it)||(bn=ve.current)!=null&&bn.contains(it)||B.cancel()};return window.addEventListener("mousedown",_e),()=>window.removeEventListener("mousedown",_e)},[B.state.phase,B.cancel]),R.useEffect(()=>{B.cancel()},[t,B.cancel]);const Ae=R.useCallback(()=>{e.some(ot=>i[ot.path])?I({kind:"all",path:""}):(m(),b({}),S({}))},[e,i,m]),Te=()=>{if(T){if(T.kind==="one")l(T.path),ge([T.path]);else if(T.kind==="others"){const _e=e.filter(ot=>ot.path!==T.path).map(ot=>ot.path);c(T.path),ge(_e)}else if(T.kind==="right"){const _e=e.findIndex(it=>it.path===T.path),ot=_e!==-1?e.slice(_e+1).map(it=>it.path):[];h(T.path),ge(ot)}else m(),b({}),S({});I(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 je=t,Ee=je?bo(je):"",Qe=je?x[je]:void 0,bt=je?aD(je):!1,et=je?cL(je):!1,wt=je&&bt?s[je]??dL(je):"edit",gt=!!je&&!Jv(je)&&Qe==="ready",cn=gt,on=et?["edit","wysiwyg","preview","split"]:bt?["edit","preview"]:[],dt=je&&r.jsx(hF,{path:je,name:Ee,value:a[je]??"",onChange:_e=>K(je,_e),onSave:()=>void ce(je),onReady:W,onCursor:M}),vt=N?"Saving…":je&&i[je]?C.autosave&&!om(je)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&r.jsx(Z4,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:We,onCloseOthers:xe,onCloseToTheRight:te,onCloseAll:Ae}),je&&!U&&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:Ee}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:je}),gt&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",vt]}),ll(je)&&(wt==="preview"||wt==="split")&&r.jsx("button",{onClick:()=>q(_e=>!_e),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),ll(je)&&(wt==="preview"||wt==="split")&&r.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),on.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:on.map(_e=>r.jsx("button",{onClick:()=>k(je,_e),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${wt===_e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:_e},_e))}),r.jsx("div",{className:"flex-1"}),r.jsx(WF,{path:je,onRenamed:Oe,onDeleted:_e=>ge([_e])}),gt&&r.jsx(qF,{}),r.jsx("button",{onClick:()=>J(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&r.jsx("button",{onClick:()=>J(!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:je?iD(je)?r.jsx(wF,{path:je,name:Ee}):sD(je)?r.jsx(yF,{path:je}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(jF,{path:je,name:Ee,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…"}):wt==="wysiwyg"&&ll(je)?r.jsx(R.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(KF,{value:a[je]??"",onChange:_e=>K(je,_e)},je)}):wt==="split"&&ll(je)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[Z&&r.jsx(qk,{text:a[je]??"",scrollRef:ie}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(Uk,{getEditor:ee}),r.jsx("div",{className:"flex-1 min-h-0",children:dt})]}),r.jsx("div",{ref:ve,className:"flex-1 min-w-0",children:r.jsx(Wx,{ref:ie,text:a[je]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!U&&C.assistantRail&&r.jsx(Jk,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)},onReject:B.cancel,onRetry:B.retry})]}):wt==="preview"&&ll(je)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[Z&&r.jsx(qk,{text:a[je]??"",scrollRef:ie}),r.jsx("div",{ref:ve,className:"flex-1 min-w-0",children:r.jsx(Wx,{ref:ie,text:a[je]??"",wideMeasure:C.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!U&&C.assistantRail&&r.jsx(Jk,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)},onReject:B.cancel,onRetry:B.retry})]}):wt==="preview"&&nD(je)?r.jsx(bF,{path:je,dirty:!!i[je],reloadToken:w[je]??0}):wt==="preview"&&rD(je)?r.jsx(CF,{path:je,text:a[je]??""}):wt==="preview"&&oD(je)?r.jsx(TF,{path:je,text:a[je]??""}):ll(je)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(Uk,{getEditor:ee}),r.jsx("div",{className:"flex-1 min-h-0",children:dt})]}):dt:null}),cn&&r.jsx(vF,{text:a[je]??"",cursor:A,language:Qr(je)||void 0}),je&&ll(je)&&(wt==="preview"||wt==="split")&&B.state.phase!=="idle"&&B.state.selection&&r.jsx("div",{ref:fe,children:r.jsx(FF,{phase:B.state.phase,rect:B.state.selection.rect,selectedText:B.state.selection.text,diff:B.state.diff,transcript:B.state.transcript,modelStatus:B.state.modelStatus,onQuickAction:B.run,onRunCustom:B.run,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onReject:B.cancel,onRetry:B.retry,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)}})}),T&&r.jsx(XF,{message:T.kind==="one"?`Discard unsaved changes to ${bo(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:()=>I(null),onConfirm:Te})]})}const py=R.memo(YF);function XF({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 JF="~/.claude/session-manager/projects-prefs.json";let Qk=Promise.resolve(),Zv=null;function eE(n){const e=Qk.then(n);return Qk=e.catch(()=>{}),e}const h$=()=>$a(JF);async function tE(){const n=(await h$().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const P_=Ci(n=>({pinned:{},hydrated:!1,hydrate:()=>Zv||(Zv=eE(async()=>{try{n({pinned:await tE(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Zv),togglePin:e=>{eE(async()=>{let t;try{t=await tE()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Le.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 h$().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),Le.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function ZF(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function QF(n,e,t){const i=R.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(ZF))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;R.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 M0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function p$(n){return n.split(/[\\/]+/).filter(Boolean)}function f$(n){const e=p$(n);return e.length?e[e.length-1]:n}function nE(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 m$(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=M0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const iE=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Um(n,e){return iE(n).startsWith(iE(e)+"/")}const fy="reveal:";function wq(n){An.getState().openPanel("projects",fy+n)}function eG(n){return n.startsWith(fy)&&n.slice(fy.length)||null}const tG=/^[A-Za-z]:$/;function sE(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(tG.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function g$(n,e){const t=sE(n),i=sE(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function nG(n){const e=await ig(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function iG(n,e){return Od(n,{fileTreeExpanded:[...e].slice(0,500)})}async function sG(){const n=await wb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function rG(n){yb({fileTreeShowHidden:n}).catch(()=>{})}function M_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Um(s,e)){t=!0;continue}i.add(s)}return t?i:n}const rE=(n,e)=>`${e?1:0}:${n}`,O_={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:"!"}},oG=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 aG(n){const e=Qr(n);return oG.has(e)||tD.has(e)||e==="pdf"}function lG(n,e){if(e)return"#d97757";switch(Qr(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 am(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const oE=64,cG=250,dG={depth:0};function L_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function uG({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=i0(),l=Zm(),[c,h]=R.useState([]),m=R.useRef(c);m.current=c;const[g,v]=R.useState(null),E=R.useRef(null),k=R.useRef(null),[C,x]=R.useState(0),[b,w]=R.useState(null),[S,T]=R.useState(null),I=R.useRef(null),[A,M]=R.useState(0),N=R.useRef(a);N.current=a;const[L,U]=R.useState(new Set),J=R.useRef(L);J.current=L;const Z=R.useRef(!1),[q,le]=R.useState(""),[ie,he]=R.useState(!0),ve=R.useRef(!1);R.useEffect(()=>{let st=!1;return sG().then(St=>{!st&&!ve.current&&he(St)}),()=>{st=!0}},[]);const fe=R.useCallback(st=>{ve.current=!0,he(St=>{const Mt=typeof st=="function"?st(St):st;return rG(Mt),Mt})},[]),[B,K]=R.useState(!1),[W,ee]=R.useState(null),[ce,ge]=R.useState({}),[Oe,We]=R.useState(null),[xe,te]=R.useState(null),[Ae,Te]=R.useState(""),[je,Ee]=R.useState(null),[Qe,bt]=R.useState(""),[et,wt]=R.useState(null),gt=R.useRef(null),cn=R.useRef(null),on=R.useRef(0),dt=R.useCallback(async()=>{if(!n)return;const st=++on.current;K(!0),ee(null);const St=await window.api.files.list(n,ie);on.current===st&&(St.ok?h(St.entries.map(Mt=>({...Mt}))):(ee(St.error??"failed to list"),h([])),T(rE(n,ie)),K(!1))},[n,ie]),vt=R.useCallback(async st=>{const St=on.current,Mt=new Map;for(const Gn of st){const On=p$(Gn).length,kn=Mt.get(On);kn?kn.push(Gn):Mt.set(On,[Gn])}const pn=[];for(const Gn of[...Mt.keys()].sort((On,kn)=>On-kn)){const On=Mt.get(Gn),kn=await Promise.all(On.map(async $n=>({p:$n,result:await window.api.files.list($n,ie)})));if(on.current!==St)return pn;for(const{p:$n,result:Yn}of kn)Yn.ok?h(pi=>wm(pi,$n,Yn.entries.map(Yi=>({...Yi})),J.current)):pn.push($n)}return pn},[ie]),_e=R.useCallback(async st=>(await dt(),st.length?vt(st):[]),[dt,vt]);R.useEffect(()=>{le(""),te(null),We(null),Ee(null),wt(null),ge({}),v(null);let st=!1;return Z.current=!1,(async()=>{const[St]=await Promise.all([nG(n),dt()]);if(st)return;if(!Z.current){const pn=new Set(St);J.current=pn,U(pn)}if(w(n),!St.length)return;const Mt=await vt(St);st||!Mt.length||jn(pn=>{const Gn=new Set;let On=!1;for(const kn of pn){if(Mt.some($n=>kn===$n||Um(kn,$n))){On=!0;continue}Gn.add(kn)}return On?Gn:pn})})(),am(n).then(St=>{st||ge(St)}),()=>{st=!0}},[n]);const ot=R.useRef(!0);R.useEffect(()=>{if(ot.current){ot.current=!1;return}_e([...J.current])},[ie]),R.useEffect(()=>{if(!n||!l)return;am(n).then(ge);const st=window.setInterval(()=>{am(n).then(ge)},5e3);return()=>window.clearInterval(st)},[n,l]);const it=R.useMemo(()=>{if(!n)return[];const st=[...L].filter(St=>St!==n);return[n,...st.slice(-63)]},[n,L]),Lt=R.useRef(!1);R.useEffect(()=>{!n||L.size+1<=oE||Lt.current||(Lt.current=!0,console.warn(`FileTree: watching only ${oE} of ${L.size+1} folders (cap reached)`))},[n,L]);const bn=R.useRef(new Map),Tn=R.useRef(new Set),vn=R.useRef(!1);vn.current=xe!==null||je!==null;const oi=R.useRef(()=>{});oi.current=st=>{if(!(st!==L_(n)&&!J.current.has(st))){if(vn.current){Tn.current.add(st);return}st===L_(n)?_e([...J.current]):Vt(st)}},QF(it,st=>{if(st!==L_(n)&&!J.current.has(st))return;const St=bn.current,Mt=St.get(st);Mt&&clearTimeout(Mt),St.set(st,setTimeout(()=>{St.delete(st),oi.current(st)},cG))},dG),R.useEffect(()=>{if(xe!==null||je!==null)return;const st=[...Tn.current];Tn.current.clear();for(const St of st)oi.current(St)},[xe,je]),R.useEffect(()=>{const st=bn.current,St=Tn.current;return()=>{for(const Mt of st.values())clearTimeout(Mt);st.clear(),St.clear()}},[n]),R.useEffect(()=>{if(!Oe)return;const st=()=>We(null),St=Mt=>{u.current&&Mt.key==="Escape"&&We(null)};return window.addEventListener("mousedown",st),window.addEventListener("keydown",St),()=>{window.removeEventListener("mousedown",st),window.removeEventListener("keydown",St)}},[Oe]),R.useEffect(()=>{xe&&setTimeout(()=>{var st;return(st=gt.current)==null?void 0:st.select()},30)},[xe]),R.useEffect(()=>{je&&setTimeout(()=>{var st;return(st=cn.current)==null?void 0:st.focus()},30)},[je]);const jn=R.useCallback(st=>{const St=J.current,Mt=st(St);Mt!==St&&(Z.current=!0,J.current=Mt,U(Mt),iG(n,Mt).catch(()=>{J.current===Mt&&(J.current=St,U(St),Le.error("Couldn't save folder expansion — reverted."))}))},[n]),Dn=R.useCallback(async st=>{if(L.has(st.path)){jn(Mt=>M_(Mt,st.path));return}if(jn(Mt=>new Set(Mt).add(st.path)),st.children)return;const St=await window.api.files.list(st.path,ie);St.ok&&h(Mt=>wm(Mt,st.path,St.entries.map(pn=>({...pn})),J.current))},[L,ie,jn]),Vt=R.useCallback(async st=>{if(st===n){await dt();return}const St=await window.api.files.list(st,ie);St.ok&&h(Mt=>wm(Mt,st,St.entries.map(pn=>({...pn})),J.current))},[n,dt,ie]),Li=R.useCallback(async(st,St)=>{const Mt=()=>{var Dt;return(Dt=N.current)==null?void 0:Dt.call(N,st.token)};if(!St.length){v(null),Mt();return}const pn=on.current,Gn=St.slice(0,-1).map((Dt,Zn)=>m$(n,...St.slice(0,Zn+1))),On=await Promise.all(Gn.map(Dt=>window.api.files.list(Dt,ie)));if(on.current!==pn){I.current=null,M(Dt=>Dt+1);return}let kn=m.current;const $n=[];let Yn=null,pi="not found";for(let Dt=0;Dt<St.length;Dt++){const Zn=kn.find(Hn=>Hn.name===St[Dt]);if(!Zn)break;if(Dt===St.length-1){Yn=Zn;break}const at=On[Dt];if(!Zn.isDirectory)break;if(!at.ok){pi=at.error??"could not list its folder";break}const yt=at.entries.map(Hn=>({...Hn}));$n.push({path:Zn.path,children:yt}),kn=yt}if(!Yn){Le.error(`Couldn't reveal ${st.path}: ${pi}`),Mt();return}const Yi=$n.map(Dt=>Dt.path);jn(Dt=>Yi.every(Zn=>Dt.has(Zn))?Dt:new Set([...Dt,...Yi])),h(Dt=>$n.reduce((Zn,at)=>wm(Zn,at.path,at.children,J.current),Dt)),le(""),ee(null),v(Yn.path),x(Dt=>Dt+1),Mt()},[n,ie,jn]);R.useEffect(()=>{var St;if(!s||I.current===s.token||b!==n||S!==rE(n,ie)||B)return;const st=g$(s.path,n);if(!st){I.current=s.token,Le.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(St=N.current)==null||St.call(N,s.token);return}if(st.some(Mt=>Mt.startsWith("."))&&(ve.current=!0,!ie)){he(!0);return}I.current=s.token,Li(s,st)},[s,b,S,B,n,ie,A,Li]),R.useEffect(()=>{if(!C)return;const st=k.current,St=E.current;st&&St&&ng(st,St,{block:"nearest"})},[C]);const xi=R.useCallback(st=>{if(st.isDirectory){Dn(st);return}aG(st.name)&&e?e(st.path):window.api.shell.open({as:"openPath",path:st.path})},[Dn,e]),zi=R.useCallback(st=>{if(t){t(st);return}if(i){const St=Um(st,n)?st.slice(n.replace(/[\\/]+$/,"").length+1):st;window.api.pty.write({tabId:i,data:`@${St} `})}},[t,i,n]),qi=R.useCallback((st,St)=>{st.preventDefault(),st.stopPropagation(),We({x:st.clientX,y:st.clientY,node:St})},[]),ct=st=>{te(st.path),Te(st.name)},Mn=async()=>{if(!xe)return;const st=Ae.trim();if(!st){te(null);return}const St=await window.api.files.rename(xe,st);if(te(null),St.ok){const Mt=nE(xe);jn(pn=>M_(pn,xe)),await Vt(Mt||n),am(n).then(ge)}else{const Mt=St.error??"rename failed";ee(Mt),Le.error(Mt)}},qn=async()=>{if(!je)return;const st=Qe.trim();if(!st){Ee(null),bt("");return}const St=await window.api.files.create(je.parent,st,je.kind);if(Ee(null),bt(""),St.ok)await Vt(je.parent),je.kind==="folder"&&jn(Mt=>new Set(Mt).add(je.parent));else{const Mt=St.error??"create failed";ee(Mt),Le.error(Mt)}},_i=async()=>{if(!et)return;const st=await window.api.files.delete(et.path),St=nE(et.path);if(wt(null),st.ok)jn(Mt=>M_(Mt,et.path)),await Vt(St||n),am(n).then(ge);else{const Mt=st.error??"delete failed";ee(Mt),Le.error(Mt)}},hi=R.useMemo(()=>{if(!q.trim())return c;const st=q.toLowerCase();return c.filter(St=>St.name.toLowerCase().includes(st))},[c,q]),Ki=(n?f$(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(x$,{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:Ki}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:dt,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:B,children:r.jsx(xG,{size:12,className:B?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:q,onChange:st=>le(st.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:()=>Ee({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(bG,{size:12})}),r.jsx("button",{onClick:()=>Ee({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(_G,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>fe(st=>!st),className:`p-1.5 rounded transition-colors ${ie?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:ie?"Hide hidden files":"Show hidden files",children:ie?r.jsx(wG,{size:12}):r.jsx(yG,{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&&hi.length===0&&!B&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:q?"no matches":"empty folder"}),!W&&r.jsx(v$,{nodes:hi,depth:0,expanded:L,gitStatus:ce,renaming:xe,selected:g,selectedRowRef:E,onSelect:v,renameValue:Ae,renameInputRef:gt,onRenameChange:Te,onRenameCommit:Mn,onRenameCancel:()=>te(null),onToggleDir:Dn,onFileClick:xi,onSendToChat:zi,onContextMenu:qi})]}),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"}),Oe&&r.jsx(hG,{x:Oe.x,y:Oe.y,node:Oe.node,onClose:()=>We(null),onRename:()=>{ct(Oe.node),We(null)},onDelete:()=>{wt(Oe.node),We(null)},onNewFile:()=>{Ee({parent:Oe.node.path,kind:"file"}),We(null)},onNewFolder:()=>{Ee({parent:Oe.node.path,kind:"folder"}),We(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Oe.node.path}),We(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Oe.node.path}),We(null)},onCopyPath:()=>{const st=Oe.node.path;Yo(st).then(St=>{St||Le.error("Couldn't copy path")}),We(null)},onSendToChat:()=>{zi(Oe.node.path),We(null)}}),je&&r.jsx(aE,{title:`New ${je.kind}`,subtitle:`in ${pG(je.parent)}`,onCancel:()=>{Ee(null),bt("")},onConfirm:qn,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:cn,value:Qe,onChange:st=>bt(st.target.value),onKeyDown:st=>{st.key==="Enter"&&qn(),st.key==="Escape"&&(Ee(null),bt(""))},placeholder:je.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"})}),et&&r.jsx(aE,{title:`Delete ${et.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>wt(null),onConfirm:_i,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:['"',et.name,'"']})," to the trash?",et.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function v$(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(c=>{const h=i.has(c.path),m=a===c.path,g=u===c.path,v=s[c.path],E=lG(c.name,c.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:g?n.selectedRowRef:void 0,"data-path":c.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(c.path),c.isDirectory?n.onToggleDir(c):n.onFileClick(c))},onDoubleClick:()=>{c.isDirectory||window.api.shell.open({as:"openPath",path:c.path})},onContextMenu:k=>l(k,c),children:[c.isDirectory?r.jsx(vG,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),c.isDirectory?h?r.jsx(mG,{size:12,color:E}):r.jsx(x$,{size:12,color:E}):r.jsx(gG,{size:12,color:E}),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 ${c.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:c.name}),v&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:O_[v].color,backgroundColor:`${O_[v].color}20`},title:v,children:O_[v].label}),!c.isDirectory&&r.jsx("button",{onClick:k=>{k.stopPropagation(),n.onSendToChat(c.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(SG,{size:10})})]}),c.isDirectory&&h&&c.children&&r.jsx(v$,{...n,nodes:c.children,depth:t+1})]},c.path)})})}function hG(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(nc,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(nc,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(nc,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(z_,{}),r.jsx(nc,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(nc,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(z_,{}),r.jsx(nc,{label:"New file",onClick:n.onNewFile}),r.jsx(nc,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(z_,{}),r.jsx(nc,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function nc({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 z_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function aE(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 pG(n){return f$(n)}function wm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:fG(s.children,t,i)}:s.children?{...s,children:wm(s.children,e,t,i)}:s)}function fG(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 Aa({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 x$({size:n,className:e,color:t}){return r.jsx(Aa,{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 mG({size:n,className:e,color:t}){return r.jsx(Aa,{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 gG({size:n,className:e,color:t}){return r.jsxs(Aa,{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 vG({size:n,className:e}){return r.jsx(Aa,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function xG({size:n,className:e}){return r.jsxs(Aa,{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 bG({size:n,className:e}){return r.jsxs(Aa,{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 _G({size:n,className:e}){return r.jsxs(Aa,{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 wG({size:n,className:e}){return r.jsxs(Aa,{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 yG({size:n,className:e}){return r.jsxs(Aa,{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 SG({size:n,className:e}){return r.jsxs(Aa,{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 Am(n,e){if(!e)return n;const t=M0(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 B_(n){yb(n).catch(()=>Le.error("Couldn't save File Explorer layout."))}const F_=33,CG=20,kG=60,EG=32;function lE(n){return Math.min(kG,Math.max(CG,n))}function TG(){const n=It(B=>B.tabs),e=It(B=>B.activeTabId),t=n.find(B=>B.id===e)??null,i=An(B=>B.navFace),s=fb(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=R.useState(F_),[c,h]=R.useState(!1),m=R.useRef(!1),[g,v]=R.useState(!1),E=R.useRef(u);E.current=u;const k=R.useRef(c);k.current=c;const C=R.useRef(null),x=R.useRef(null),b=R.useRef(!1),{projects:w,openProject:S,archiveProjectByCwd:T}=Bd(),I=P_(B=>B.pinned),A=P_(B=>B.togglePin);R.useEffect(()=>{P_.getState().hydrate()},[]),R.useEffect(()=>{let B=!1;return wb().then(K=>{B||m.current||(typeof K.projectsSplitPct=="number"&&Number.isFinite(K.projectsSplitPct)&&l(lE(K.projectsSplitPct)),typeof K.projectsFileTreeCollapsed=="boolean"&&!b.current&&h(K.projectsFileTreeCollapsed))}),()=>{B=!0}},[]);const M=R.useRef(0),[N,L]=R.useState(null),[U,J]=R.useState(null);qA("projects",B=>{const K=eG(B);K&&L({path:K,token:++M.current})});const Z=(t==null?void 0:t.cwd)??null;R.useEffect(()=>{if(!N)return;const{path:B}=N,K=ge=>!!ge&&g$(B,ge)!==null,W=i==="home"?s:Z,ee=i==="home"?{face:"project",root:Z}:{face:"home",root:s};let ce=null;if(K(W))ce={face:i,root:W};else{if(s===null)return;K(ee.root)&&(ce={face:ee.face,root:ee.root})}if(L(null),!ce){window.api.shell.open({as:"revealPath",path:B}).then(ge=>{ge.ok||Le.error(`Couldn't reveal ${B}: ${ge.error??"unknown error"}`)},ge=>Le.error(`Couldn't reveal ${B}: ${ge instanceof Error?ge.message:String(ge)}`));return}ce.face!==i&&An.getState().setNavFace(ce.face),b.current=!0,h(!1),J({...N,root:ce.root})},[N,i,s,Z]),R.useEffect(()=>{J(B=>B&&a!==null&&B.root!==a?null:B)},[a]);const q=R.useCallback(B=>{J(K=>K&&K.token===B?null:K)},[]),le=[...w].sort((B,K)=>(I[K.cwd]?1:0)-(I[B.cwd]?1:0));R.useEffect(()=>{if(!g)return;const B=K=>{x.current&&!x.current.contains(K.target)&&v(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[g]);const ie=R.useCallback(B=>{In.getState().openFile(B)},[]),he=R.useCallback(B=>{B.preventDefault(),m.current=!0;const K=B.clientX,W=E.current;let ee=W;const ce=Oe=>{const We=C.current;if(!We)return;const xe=We.getBoundingClientRect(),te=Oe.clientX-K;ee=lE(W+te/xe.width*100),l(ee)},ge=()=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",ge),document.body.style.cursor="",document.body.style.userSelect="",B_({projectsSplitPct:ee})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",ge),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),ve=R.useCallback(()=>{m.current=!0,l(F_),B_({projectsSplitPct:F_})},[]),fe=R.useCallback(()=>{m.current=!0;const B=!k.current;h(B),B_({projectsFileTreeCollapsed:B})},[]);return c?r.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:fe,"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:EG},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(py,{})})]}):r.jsxs("div",{ref:C,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:x,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>v(B=>!B),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?Am(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),r.jsx("button",{onClick:fe,"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:le.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):le.map(B=>{const K=Am(B.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(Zy,{content:I[B.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>A(B.cwd),className:`shrink-0 text-sm leading-none transition-colors ${I[B.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:I[B.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{S(B.cwd),v(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:K}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${K}?`)&&await T(B)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},B.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:Am(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(uG,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:ie,reveal:U&&U.root===a?U:null,onRevealDone:q})})]}):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:ve,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(py,{})})]})}const jG=R.memo(TG),DG={"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."]},"claude-config":{headline:"Your ~/.claude — every file the claude CLI reads on this machine, in one place",intro:"Claude config gathers the user-scope Claude Code files that apply to every project on this machine. Each tab edits the real file on disk; a project's own files are edited from that project's Claude config instead.",sections:[{title:"Tabs",items:[{term:"CLAUDE.md",body:"~/.claude/CLAUDE.md — house rules every session starts with."},{term:"Settings",body:"~/.claude/settings.json — permissions, hooks, env and every other key."},{term:"MCP",body:"MCP servers from ~/.claude.json › mcpServers."},{term:"Skills",body:"Skills in ~/.claude/skills and commands in ~/.claude/commands."},{term:"Plugins",body:"Installed plugins; on/off is saved in settings.json › enabledPlugins."},{term:"Agents",body:"Agent personas in ~/.claude/agents."}]}]},"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 $G({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 NG({active:n}){const e=ds(g=>g.learningPanelCollapsed),t=ds(g=>g.setLearningPanelCollapsed),i=ds(g=>g.hydrated),s=ds(g=>g.hydrate);R.useEffect(()=>{i||s()},[i,s]);const[a,u]=R.useState(()=>!e),l=R.useRef(null);R.useEffect(()=>{i&&u(!e)},[i]);const c=R.useCallback(()=>{u(g=>{const v=!g;return t(!v),v})},[t]);R.useEffect(()=>{if(!a)return;const g=v=>{var E;(E=l.current)!=null&&E.contains(v.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a,t]);const h=R.useRef(!1);R.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const m=DG[n];return m?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:c,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($G,{content:m})})]}):null}function AG({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(NG,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const IG=R.lazy(()=>ti(()=>import("./History--JwsFnbn.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url).then(n=>({default:n.History}))),RG=R.lazy(()=>ti(()=>import("./Scheduler-YT3j8SUa.js"),__vite__mapDeps([5,2,3,4]),import.meta.url).then(n=>({default:n.Scheduler}))),PG=R.lazy(()=>ti(()=>import("./ProjectClaudeConfig-sdlA-fUb.js"),__vite__mapDeps([6,7,8,1,9,10,3,4]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),lm=R.lazy(()=>ti(()=>import("./HomeClaudeConfig-ijEXs--3.js"),__vite__mapDeps([11,7,8,1,9,3,4]),import.meta.url).then(n=>({default:n.HomeClaudeConfig}))),MG=R.lazy(()=>ti(()=>import("./AppSettings-CMFEM68R.js"),__vite__mapDeps([12,8,10,1,3,4]),import.meta.url).then(n=>({default:n.AppSettings}))),OG=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function ol({children:n}){return r.jsx(R.Suspense,{fallback:OG,children:n})}const LG={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."},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."}},cE=new Map;function zG(n,e){const t=cE.get(n);if(t&&t.ctx===e)return t.node;const i=BG(n,e);return cE.set(n,{ctx:e,node:i}),i}function BG(n,e){switch(n){case"overview":return r.jsx(JO,{onNavigate:e.onNavigate});case"project-home":return r.jsx(K4,{});case"editor":return r.jsx(py,{});case"projects":return r.jsx(jG,{});case"claude-config":return r.jsx(ol,{children:r.jsx(lm,{})});case"system-prompt":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"settings":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"extensions":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"agent-library":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})})}const t=LG[n],i=(()=>{switch(n){case"history":return r.jsx(ol,{children:r.jsx(IG,{})});case"scheduler":return r.jsx(ol,{children:r.jsx(RG,{navigate:e.onNavigate})});case"memory":return r.jsx(ol,{children:r.jsx(PG,{})});case"app-settings":return r.jsx(ol,{children:r.jsx(MG,{})});default:return null}})();if(!i)return null;const s=MA[n];return t&&s?r.jsx(AG,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class FG extends R.Component{constructor(){super(...arguments);ri(this,"state",{error:null});ri(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 G_={exports:{}},dE;function GG(){return dE||(dE=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,c){var h=this&&this.__decorate||function(w,S,T,I){var A,M=arguments.length,N=M<3?S:I===null?I=Object.getOwnPropertyDescriptor(S,T):I;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(w,S,T,I);else for(var L=w.length-1;L>=0;L--)(A=w[L])&&(N=(M<3?A(N):M>3?A(S,T,N):A(S,T))||N);return M>3&&N&&Object.defineProperty(S,T,N),N},m=this&&this.__param||function(w,S){return function(T,I){S(T,I,w)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const g=c(9042),v=c(9924),E=c(844),k=c(4725),C=c(2585),x=c(3656);let b=l.AccessibilityManager=class extends E.Disposable{constructor(w,S,T,I){super(),this._terminal=w,this._coreBrowserService=T,this._renderService=I,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 A=0;A<this._terminal.rows;A++)this._rowElements[A]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[A]);if(this._topBoundaryFocusListener=A=>this._handleBoundaryFocus(A,0),this._bottomBoundaryFocusListener=A=>this._handleBoundaryFocus(A,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 v.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((A=>this._handleResize(A.rows)))),this.register(this._terminal.onRender((A=>this._refreshRows(A.start,A.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((A=>this._handleChar(A)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3053
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),w=R.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const I=DF(S,T.before,T.after);return I.ok?(s.current+=1,i({type:"ACCEPT"})):Le.error(I.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),I},[t.diff]);return{state:t,select:h,cancel:m,listen:g,sendHeard:x,run:C,retry:b,accept:w}}const LF=[{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."}],Xk=320,rm=8;function zF(){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 BF(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,rm),Math.max(rm,e-Xk-rm)),i=Math.max(n.top-rm,rm);return{position:"fixed",left:t,top:i,width:Xk,transform:"translateY(-100%)",zIndex:ZA.dialog}}function FF({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:c,onSendHeard:h,onCancel:m,onAccept:g,onReject:v,onRetry:E}){const[k,C]=R.useState(""),[x,b]=R.useState(!1),w=Ni(A=>A.show),S=R.useRef(null);R.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await Yo(t)){w("error","Copy failed");return}b(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>b(!1),1500)},I=()=>{const A=k.trim();A&&(l(A),C(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:BF(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:x?"Copied":"Copy"}),r.jsx("button",{onClick:c,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),LF.map(A=>r.jsx("button",{onClick:()=>u(A.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:A.label},A.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:A=>C(A.target.value),onKeyDown:A=>{A.key==="Enter"?I():A.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(zF,{}),"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:c,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:v,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:E,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 GF(){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 Jk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:c,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:Lm(MF)})]}),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(GF,{}),"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:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function HF(){const n=It(t=>t.tabs),e=It(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function WF({path:n,onRenamed:e,onDeleted:t}){const[i,s]=R.useState(!1),[a,u]=R.useState(!1),[l,c]=R.useState(""),[h,m]=R.useState(!1),g=In(U=>U.buffers[n]),v=In(U=>U.openFile),E=In(U=>U.renameOpenFile),k=In(U=>U.closeFile),C=HF(),x=bo(n),b=()=>s(!1),w=()=>{c(x),u(!0),b()},S=async()=>{const U=l.trim();if(!U||U===x){u(!1);return}try{const J=await window.api.files.rename(n,U);if(J.ok){const Z=n.slice(0,n.lastIndexOf("/")),q=J.newPath??`${Z}/${U}`;E(n,q),e==null||e(n,q),Le.info(`Renamed to ${U}`)}else Le.error(J.error??`Couldn't rename ${x}`)}catch(J){Le.error(J instanceof Error?J.message:`Couldn't rename ${x}`)}u(!1)},T=async()=>{b();try{const U=await window.api.files.duplicate(n);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${bo(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${x}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${x}`)}},I=async()=>{try{const U=await window.api.files.delete(n);U.ok?(k(n),t==null||t(n),Le.info(`Deleted ${x}`)):Le.error(U.error??`Couldn't delete ${x}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{b();const U=g??"";await Yo(U)?Le.info(`Copied ${U.length} chars`):Le.error(`Couldn't copy ${x}`)},M=()=>{if(b(),!C){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${n} `}),Le.info(`Added ${x} to Claude context`)},N=()=>{b(),window.api.shell.open({as:"openPath",path:n}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${x}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${x}`))},L=()=>{b(),window.api.shell.open({as:"revealPath",path:n}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${x}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${x}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(U=>!U),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:b}),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(R_,{children:"Edit"}),r.jsx(Sd,{label:"Rename",onClick:w}),r.jsx(Sd,{label:"Duplicate",onClick:T}),r.jsx(Sd,{label:"Delete document",danger:!0,onClick:()=>{b(),m(!0)}}),r.jsx(Zk,{}),r.jsx(R_,{children:"Open"}),r.jsx(Sd,{label:"Open in default app",onClick:N}),r.jsx(Sd,{label:"Reveal in OS",onClick:L}),r.jsx(Zk,{}),r.jsx(R_,{children:"Export"}),r.jsx(Sd,{label:"Copy as Markdown",onClick:A}),r.jsx(Sd,{label:"Add to Claude context",onClick:M,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(UF,{value:l,onChange:c,onCancel:()=>u(!1),onConfirm:()=>void S()}),h&&r.jsx(VF,{name:x,onCancel:()=>m(!1),onConfirm:()=>void I()})]})}function R_({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 Sd({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 Zk(){return r.jsx("div",{className:"my-1 border-t border-line"})}function UF({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 VF({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 qF(){const[n,e]=R.useState(!1),t=Rd();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($h,{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($h,{label:"Word wrap",children:r.jsx(Yv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx($h,{label:"Minimap",children:r.jsx(Yv,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx($h,{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($h,{label:"Autosave",children:r.jsx(Yv,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx($h,{label:"Wide measure",children:r.jsx(Yv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function $h({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 Yv({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 KF=R.lazy(()=>ti(()=>import("./TiptapBody-BrcWVpiW.js").then(n=>n.a),[],import.meta.url).then(n=>({default:n.TiptapBody})));function Xv(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 om(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 Jv(n){return iD(n)||sD(n)}function YF(){const n=i0(),e=In(_e=>_e.openFiles),t=In(_e=>_e.activeFilePath),i=In(_e=>_e.dirty),s=In(_e=>_e.viewMode),a=In(_e=>_e.buffers),u=In(_e=>_e.setActive),l=In(_e=>_e.closeFile),c=In(_e=>_e.closeOthers),h=In(_e=>_e.closeToTheRight),m=In(_e=>_e.closeAll),g=In(_e=>_e.loadBuffer),v=In(_e=>_e.setBuffer),E=In(_e=>_e.markSaved),k=In(_e=>_e.setViewMode),C=Rd(),[x,b]=R.useState({}),[w,S]=R.useState({}),[T,I]=R.useState(null),[A,M]=R.useState(null),[N,L]=R.useState(!1),[U,J]=R.useState(!1),[Z,q]=R.useState(!0),le=R.useRef(null),ie=R.useRef(null),he=R.useRef(void 0),ve=R.useRef(null),fe=R.useRef(null),B=OF(t??"",a[t??""]??""),K=R.useCallback((_e,ot)=>{v(_e,ot),om(_e)&&ka.getState().setDraft(_e,ot)},[v]),W=R.useCallback(_e=>{le.current=_e},[]),ee=R.useCallback(()=>le.current,[]);R.useEffect(()=>{pL()},[]),R.useEffect(()=>{const _e=t;if(!_e||Jv(_e))return;if(In.getState().hasBuffer(_e)){b(it=>it[_e]==="ready"?it:{...it,[_e]:"ready"});return}let ot=!1;return b(it=>({...it,[_e]:"loading"})),om(_e)?((async()=>{if(await ka.getState().loadText(_e,!0),ot)return;const it=ka.getState().files[_e];if(!it||it.loadError&&!it.exists){b(Lt=>({...Lt,[_e]:{error:(it==null?void 0:it.loadError)??"failed to read"}}));return}g(_e,it.diskRaw),it.dirty&&In.getState().setBuffer(_e,it.draftRaw),b(Lt=>({...Lt,[_e]:"ready"}))})(),()=>{ot=!0}):(window.api.files.read(_e).then(it=>{ot||(it.binary?b(Lt=>({...Lt,[_e]:{binary:!0,size:it.size??0,mime:it.mime??"application/octet-stream",reason:it.error??"Binary file"}})):it.ok?(g(_e,it.text),b(Lt=>({...Lt,[_e]:"ready"}))):b(Lt=>({...Lt,[_e]:{error:it.error??"failed to read"}})))}),()=>{ot=!0})},[t,g]),R.useEffect(()=>{M(null)},[t]);const ce=R.useCallback(async(_e,ot=!1)=>{const it=In.getState().buffers[_e];if(it==null)return;ot&&L(!0);const Lt=om(_e);let bn;if(Lt){const Tn=ka.getState();if(Tn.setDraft(_e,it),bn=await Tn.saveText(_e),!bn.ok&&bn.error==="conflict"){ot&&L(!1);return}}else bn=await window.api.files.write(_e,it);bn.ok?(E(_e),S(Tn=>({...Tn,[_e]:(Tn[_e]??0)+1})),ot||Le.info(`Saved ${bo(_e)}`)):Le.error(bn.error??`Couldn't save ${bo(_e)}`),ot&&L(!1)},[E]);R.useEffect(()=>{if(!C.autosave)return;const _e=t;if(!(!_e||Jv(_e)||om(_e)||!i[_e]))return window.clearTimeout(he.current),he.current=window.setTimeout(()=>{ce(_e,!0)},1200),()=>window.clearTimeout(he.current)},[C.autosave,t,i,a,ce]);const ge=R.useCallback(_e=>{_e.length&&(b(ot=>Xv(ot,_e)),S(ot=>Xv(ot,_e)))},[]),Oe=R.useCallback((_e,ot)=>{b(it=>_e in it?{...Xv(it,[_e]),[ot]:it[_e]}:it),S(it=>_e in it?{...Xv(it,[_e]),[ot]:it[_e]}:it)},[]),We=R.useCallback(_e=>{i[_e]?I({kind:"one",path:_e}):(l(_e),ge([_e]))},[i,l,ge]),xe=R.useCallback(_e=>{e.some(it=>it.path!==_e&&i[it.path])?I({kind:"others",path:_e}):(c(_e),ge(e.filter(it=>it.path!==_e).map(it=>it.path)))},[e,i,c,ge]),te=R.useCallback(_e=>{const ot=e.findIndex(Lt=>Lt.path===_e);ot!==-1&&e.slice(ot+1).some(Lt=>i[Lt.path])?I({kind:"right",path:_e}):(h(_e),ge(ot!==-1?e.slice(ot+1).map(Lt=>Lt.path):[]))},[e,i,h,ge]);R.useEffect(()=>{const _e=ot=>{if(n.current)if((ot.metaKey||ot.ctrlKey)&&(ot.key==="s"||ot.key==="S")){const it=In.getState().activeFilePath;it&&!Jv(it)&&(ot.preventDefault(),ce(it))}else if((ot.metaKey||ot.ctrlKey)&&ot.shiftKey&&(ot.key==="f"||ot.key==="F"))ot.preventDefault(),J(it=>!it);else if((ot.metaKey||ot.ctrlKey)&&ot.shiftKey&&(ot.key==="w"||ot.key==="W")){const it=In.getState().activeFilePath;it&&In.getState().openFiles.length>1&&(ot.preventDefault(),xe(it))}else ot.key==="Escape"&&B.state.phase!=="idle"?B.cancel():ot.key==="Escape"&&U&&J(!1)};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},[ce,U,xe,B.state.phase,B.cancel]),R.useEffect(()=>{if(B.state.phase==="idle")return;const _e=ot=>{var Lt,bn;const it=ot.target;(Lt=fe.current)!=null&&Lt.contains(it)||(bn=ve.current)!=null&&bn.contains(it)||B.cancel()};return window.addEventListener("mousedown",_e),()=>window.removeEventListener("mousedown",_e)},[B.state.phase,B.cancel]),R.useEffect(()=>{B.cancel()},[t,B.cancel]);const Ae=R.useCallback(()=>{e.some(ot=>i[ot.path])?I({kind:"all",path:""}):(m(),b({}),S({}))},[e,i,m]),Te=()=>{if(T){if(T.kind==="one")l(T.path),ge([T.path]);else if(T.kind==="others"){const _e=e.filter(ot=>ot.path!==T.path).map(ot=>ot.path);c(T.path),ge(_e)}else if(T.kind==="right"){const _e=e.findIndex(it=>it.path===T.path),ot=_e!==-1?e.slice(_e+1).map(it=>it.path):[];h(T.path),ge(ot)}else m(),b({}),S({});I(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 je=t,Ee=je?bo(je):"",Qe=je?x[je]:void 0,bt=je?aD(je):!1,et=je?cL(je):!1,wt=je&&bt?s[je]??dL(je):"edit",gt=!!je&&!Jv(je)&&Qe==="ready",cn=gt,on=et?["edit","wysiwyg","preview","split"]:bt?["edit","preview"]:[],dt=je&&r.jsx(hF,{path:je,name:Ee,value:a[je]??"",onChange:_e=>K(je,_e),onSave:()=>void ce(je),onReady:W,onCursor:M}),vt=N?"Saving…":je&&i[je]?C.autosave&&!om(je)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&r.jsx(Z4,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:We,onCloseOthers:xe,onCloseToTheRight:te,onCloseAll:Ae}),je&&!U&&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:Ee}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:je}),gt&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",vt]}),ll(je)&&(wt==="preview"||wt==="split")&&r.jsx("button",{onClick:()=>q(_e=>!_e),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${Z?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),ll(je)&&(wt==="preview"||wt==="split")&&r.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),on.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:on.map(_e=>r.jsx("button",{onClick:()=>k(je,_e),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${wt===_e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:_e},_e))}),r.jsx("div",{className:"flex-1"}),r.jsx(WF,{path:je,onRenamed:Oe,onDeleted:_e=>ge([_e])}),gt&&r.jsx(qF,{}),r.jsx("button",{onClick:()=>J(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&r.jsx("button",{onClick:()=>J(!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:je?iD(je)?r.jsx(wF,{path:je,name:Ee}):sD(je)?r.jsx(yF,{path:je}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(jF,{path:je,name:Ee,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…"}):wt==="wysiwyg"&&ll(je)?r.jsx(R.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(KF,{value:a[je]??"",onChange:_e=>K(je,_e)},je)}):wt==="split"&&ll(je)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[Z&&r.jsx(qk,{text:a[je]??"",scrollRef:ie}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(Uk,{getEditor:ee}),r.jsx("div",{className:"flex-1 min-h-0",children:dt})]}),r.jsx("div",{ref:ve,className:"flex-1 min-w-0",children:r.jsx(Wx,{ref:ie,text:a[je]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!U&&C.assistantRail&&r.jsx(Jk,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)},onReject:B.cancel,onRetry:B.retry})]}):wt==="preview"&&ll(je)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[Z&&r.jsx(qk,{text:a[je]??"",scrollRef:ie}),r.jsx("div",{ref:ve,className:"flex-1 min-w-0",children:r.jsx(Wx,{ref:ie,text:a[je]??"",wideMeasure:C.wideMeasure,onSelect:B.select,onDismissSelection:B.cancel})}),!U&&C.assistantRail&&r.jsx(Jk,{phase:B.state.phase,transcript:B.state.transcript,diff:B.state.diff,editCount:B.state.editCount,modelStatus:B.state.modelStatus,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)},onReject:B.cancel,onRetry:B.retry})]}):wt==="preview"&&nD(je)?r.jsx(bF,{path:je,dirty:!!i[je],reloadToken:w[je]??0}):wt==="preview"&&rD(je)?r.jsx(CF,{path:je,text:a[je]??""}):wt==="preview"&&oD(je)?r.jsx(TF,{path:je,text:a[je]??""}):ll(je)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(Uk,{getEditor:ee}),r.jsx("div",{className:"flex-1 min-h-0",children:dt})]}):dt:null}),cn&&r.jsx(vF,{text:a[je]??"",cursor:A,language:Qr(je)||void 0}),je&&ll(je)&&(wt==="preview"||wt==="split")&&B.state.phase!=="idle"&&B.state.selection&&r.jsx("div",{ref:fe,children:r.jsx(FF,{phase:B.state.phase,rect:B.state.selection.rect,selectedText:B.state.selection.text,diff:B.state.diff,transcript:B.state.transcript,modelStatus:B.state.modelStatus,onQuickAction:B.run,onRunCustom:B.run,onListen:B.listen,onSendHeard:B.sendHeard,onCancel:B.cancel,onReject:B.cancel,onRetry:B.retry,onAccept:()=>{const _e=B.accept(a[je]??"");_e.ok&&K(je,_e.next)}})}),T&&r.jsx(XF,{message:T.kind==="one"?`Discard unsaved changes to ${bo(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:()=>I(null),onConfirm:Te})]})}const py=R.memo(YF);function XF({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 JF="~/.claude/session-manager/projects-prefs.json";let Qk=Promise.resolve(),Zv=null;function eE(n){const e=Qk.then(n);return Qk=e.catch(()=>{}),e}const h$=()=>$a(JF);async function tE(){const n=(await h$().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const P_=Ci(n=>({pinned:{},hydrated:!1,hydrate:()=>Zv||(Zv=eE(async()=>{try{n({pinned:await tE(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Zv),togglePin:e=>{eE(async()=>{let t;try{t=await tE()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Le.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 h$().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),Le.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function ZF(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function QF(n,e,t){const i=R.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(ZF))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;R.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 M0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function p$(n){return n.split(/[\\/]+/).filter(Boolean)}function f$(n){const e=p$(n);return e.length?e[e.length-1]:n}function nE(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 m$(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=M0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const iE=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Um(n,e){return iE(n).startsWith(iE(e)+"/")}const fy="reveal:";function wq(n){An.getState().openPanel("projects",fy+n)}function eG(n){return n.startsWith(fy)&&n.slice(fy.length)||null}const tG=/^[A-Za-z]:$/;function sE(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(tG.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function g$(n,e){const t=sE(n),i=sE(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function nG(n){const e=await ig(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function iG(n,e){return Od(n,{fileTreeExpanded:[...e].slice(0,500)})}async function sG(){const n=await wb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function rG(n){yb({fileTreeShowHidden:n}).catch(()=>{})}function M_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Um(s,e)){t=!0;continue}i.add(s)}return t?i:n}const rE=(n,e)=>`${e?1:0}:${n}`,O_={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:"!"}},oG=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 aG(n){const e=Qr(n);return oG.has(e)||tD.has(e)||e==="pdf"}function lG(n,e){if(e)return"#d97757";switch(Qr(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 am(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const oE=64,cG=250,dG={depth:0};function L_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function uG({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=i0(),l=Zm(),[c,h]=R.useState([]),m=R.useRef(c);m.current=c;const[g,v]=R.useState(null),E=R.useRef(null),k=R.useRef(null),[C,x]=R.useState(0),[b,w]=R.useState(null),[S,T]=R.useState(null),I=R.useRef(null),[A,M]=R.useState(0),N=R.useRef(a);N.current=a;const[L,U]=R.useState(new Set),J=R.useRef(L);J.current=L;const Z=R.useRef(!1),[q,le]=R.useState(""),[ie,he]=R.useState(!0),ve=R.useRef(!1);R.useEffect(()=>{let st=!1;return sG().then(St=>{!st&&!ve.current&&he(St)}),()=>{st=!0}},[]);const fe=R.useCallback(st=>{ve.current=!0,he(St=>{const Mt=typeof st=="function"?st(St):st;return rG(Mt),Mt})},[]),[B,K]=R.useState(!1),[W,ee]=R.useState(null),[ce,ge]=R.useState({}),[Oe,We]=R.useState(null),[xe,te]=R.useState(null),[Ae,Te]=R.useState(""),[je,Ee]=R.useState(null),[Qe,bt]=R.useState(""),[et,wt]=R.useState(null),gt=R.useRef(null),cn=R.useRef(null),on=R.useRef(0),dt=R.useCallback(async()=>{if(!n)return;const st=++on.current;K(!0),ee(null);const St=await window.api.files.list(n,ie);on.current===st&&(St.ok?h(St.entries.map(Mt=>({...Mt}))):(ee(St.error??"failed to list"),h([])),T(rE(n,ie)),K(!1))},[n,ie]),vt=R.useCallback(async st=>{const St=on.current,Mt=new Map;for(const Gn of st){const On=p$(Gn).length,kn=Mt.get(On);kn?kn.push(Gn):Mt.set(On,[Gn])}const pn=[];for(const Gn of[...Mt.keys()].sort((On,kn)=>On-kn)){const On=Mt.get(Gn),kn=await Promise.all(On.map(async $n=>({p:$n,result:await window.api.files.list($n,ie)})));if(on.current!==St)return pn;for(const{p:$n,result:Yn}of kn)Yn.ok?h(pi=>wm(pi,$n,Yn.entries.map(Yi=>({...Yi})),J.current)):pn.push($n)}return pn},[ie]),_e=R.useCallback(async st=>(await dt(),st.length?vt(st):[]),[dt,vt]);R.useEffect(()=>{le(""),te(null),We(null),Ee(null),wt(null),ge({}),v(null);let st=!1;return Z.current=!1,(async()=>{const[St]=await Promise.all([nG(n),dt()]);if(st)return;if(!Z.current){const pn=new Set(St);J.current=pn,U(pn)}if(w(n),!St.length)return;const Mt=await vt(St);st||!Mt.length||jn(pn=>{const Gn=new Set;let On=!1;for(const kn of pn){if(Mt.some($n=>kn===$n||Um(kn,$n))){On=!0;continue}Gn.add(kn)}return On?Gn:pn})})(),am(n).then(St=>{st||ge(St)}),()=>{st=!0}},[n]);const ot=R.useRef(!0);R.useEffect(()=>{if(ot.current){ot.current=!1;return}_e([...J.current])},[ie]),R.useEffect(()=>{if(!n||!l)return;am(n).then(ge);const st=window.setInterval(()=>{am(n).then(ge)},5e3);return()=>window.clearInterval(st)},[n,l]);const it=R.useMemo(()=>{if(!n)return[];const st=[...L].filter(St=>St!==n);return[n,...st.slice(-63)]},[n,L]),Lt=R.useRef(!1);R.useEffect(()=>{!n||L.size+1<=oE||Lt.current||(Lt.current=!0,console.warn(`FileTree: watching only ${oE} of ${L.size+1} folders (cap reached)`))},[n,L]);const bn=R.useRef(new Map),Tn=R.useRef(new Set),vn=R.useRef(!1);vn.current=xe!==null||je!==null;const oi=R.useRef(()=>{});oi.current=st=>{if(!(st!==L_(n)&&!J.current.has(st))){if(vn.current){Tn.current.add(st);return}st===L_(n)?_e([...J.current]):Vt(st)}},QF(it,st=>{if(st!==L_(n)&&!J.current.has(st))return;const St=bn.current,Mt=St.get(st);Mt&&clearTimeout(Mt),St.set(st,setTimeout(()=>{St.delete(st),oi.current(st)},cG))},dG),R.useEffect(()=>{if(xe!==null||je!==null)return;const st=[...Tn.current];Tn.current.clear();for(const St of st)oi.current(St)},[xe,je]),R.useEffect(()=>{const st=bn.current,St=Tn.current;return()=>{for(const Mt of st.values())clearTimeout(Mt);st.clear(),St.clear()}},[n]),R.useEffect(()=>{if(!Oe)return;const st=()=>We(null),St=Mt=>{u.current&&Mt.key==="Escape"&&We(null)};return window.addEventListener("mousedown",st),window.addEventListener("keydown",St),()=>{window.removeEventListener("mousedown",st),window.removeEventListener("keydown",St)}},[Oe]),R.useEffect(()=>{xe&&setTimeout(()=>{var st;return(st=gt.current)==null?void 0:st.select()},30)},[xe]),R.useEffect(()=>{je&&setTimeout(()=>{var st;return(st=cn.current)==null?void 0:st.focus()},30)},[je]);const jn=R.useCallback(st=>{const St=J.current,Mt=st(St);Mt!==St&&(Z.current=!0,J.current=Mt,U(Mt),iG(n,Mt).catch(()=>{J.current===Mt&&(J.current=St,U(St),Le.error("Couldn't save folder expansion — reverted."))}))},[n]),Dn=R.useCallback(async st=>{if(L.has(st.path)){jn(Mt=>M_(Mt,st.path));return}if(jn(Mt=>new Set(Mt).add(st.path)),st.children)return;const St=await window.api.files.list(st.path,ie);St.ok&&h(Mt=>wm(Mt,st.path,St.entries.map(pn=>({...pn})),J.current))},[L,ie,jn]),Vt=R.useCallback(async st=>{if(st===n){await dt();return}const St=await window.api.files.list(st,ie);St.ok&&h(Mt=>wm(Mt,st,St.entries.map(pn=>({...pn})),J.current))},[n,dt,ie]),Li=R.useCallback(async(st,St)=>{const Mt=()=>{var Dt;return(Dt=N.current)==null?void 0:Dt.call(N,st.token)};if(!St.length){v(null),Mt();return}const pn=on.current,Gn=St.slice(0,-1).map((Dt,Zn)=>m$(n,...St.slice(0,Zn+1))),On=await Promise.all(Gn.map(Dt=>window.api.files.list(Dt,ie)));if(on.current!==pn){I.current=null,M(Dt=>Dt+1);return}let kn=m.current;const $n=[];let Yn=null,pi="not found";for(let Dt=0;Dt<St.length;Dt++){const Zn=kn.find(Hn=>Hn.name===St[Dt]);if(!Zn)break;if(Dt===St.length-1){Yn=Zn;break}const at=On[Dt];if(!Zn.isDirectory)break;if(!at.ok){pi=at.error??"could not list its folder";break}const yt=at.entries.map(Hn=>({...Hn}));$n.push({path:Zn.path,children:yt}),kn=yt}if(!Yn){Le.error(`Couldn't reveal ${st.path}: ${pi}`),Mt();return}const Yi=$n.map(Dt=>Dt.path);jn(Dt=>Yi.every(Zn=>Dt.has(Zn))?Dt:new Set([...Dt,...Yi])),h(Dt=>$n.reduce((Zn,at)=>wm(Zn,at.path,at.children,J.current),Dt)),le(""),ee(null),v(Yn.path),x(Dt=>Dt+1),Mt()},[n,ie,jn]);R.useEffect(()=>{var St;if(!s||I.current===s.token||b!==n||S!==rE(n,ie)||B)return;const st=g$(s.path,n);if(!st){I.current=s.token,Le.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(St=N.current)==null||St.call(N,s.token);return}if(st.some(Mt=>Mt.startsWith("."))&&(ve.current=!0,!ie)){he(!0);return}I.current=s.token,Li(s,st)},[s,b,S,B,n,ie,A,Li]),R.useEffect(()=>{if(!C)return;const st=k.current,St=E.current;st&&St&&ng(st,St,{block:"nearest"})},[C]);const xi=R.useCallback(st=>{if(st.isDirectory){Dn(st);return}aG(st.name)&&e?e(st.path):window.api.shell.open({as:"openPath",path:st.path})},[Dn,e]),zi=R.useCallback(st=>{if(t){t(st);return}if(i){const St=Um(st,n)?st.slice(n.replace(/[\\/]+$/,"").length+1):st;window.api.pty.write({tabId:i,data:`@${St} `})}},[t,i,n]),qi=R.useCallback((st,St)=>{st.preventDefault(),st.stopPropagation(),We({x:st.clientX,y:st.clientY,node:St})},[]),ct=st=>{te(st.path),Te(st.name)},Mn=async()=>{if(!xe)return;const st=Ae.trim();if(!st){te(null);return}const St=await window.api.files.rename(xe,st);if(te(null),St.ok){const Mt=nE(xe);jn(pn=>M_(pn,xe)),await Vt(Mt||n),am(n).then(ge)}else{const Mt=St.error??"rename failed";ee(Mt),Le.error(Mt)}},qn=async()=>{if(!je)return;const st=Qe.trim();if(!st){Ee(null),bt("");return}const St=await window.api.files.create(je.parent,st,je.kind);if(Ee(null),bt(""),St.ok)await Vt(je.parent),je.kind==="folder"&&jn(Mt=>new Set(Mt).add(je.parent));else{const Mt=St.error??"create failed";ee(Mt),Le.error(Mt)}},_i=async()=>{if(!et)return;const st=await window.api.files.delete(et.path),St=nE(et.path);if(wt(null),st.ok)jn(Mt=>M_(Mt,et.path)),await Vt(St||n),am(n).then(ge);else{const Mt=st.error??"delete failed";ee(Mt),Le.error(Mt)}},hi=R.useMemo(()=>{if(!q.trim())return c;const st=q.toLowerCase();return c.filter(St=>St.name.toLowerCase().includes(st))},[c,q]),Ki=(n?f$(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(x$,{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:Ki}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:dt,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:B,children:r.jsx(xG,{size:12,className:B?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:q,onChange:st=>le(st.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:()=>Ee({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(bG,{size:12})}),r.jsx("button",{onClick:()=>Ee({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(_G,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>fe(st=>!st),className:`p-1.5 rounded transition-colors ${ie?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:ie?"Hide hidden files":"Show hidden files",children:ie?r.jsx(wG,{size:12}):r.jsx(yG,{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&&hi.length===0&&!B&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:q?"no matches":"empty folder"}),!W&&r.jsx(v$,{nodes:hi,depth:0,expanded:L,gitStatus:ce,renaming:xe,selected:g,selectedRowRef:E,onSelect:v,renameValue:Ae,renameInputRef:gt,onRenameChange:Te,onRenameCommit:Mn,onRenameCancel:()=>te(null),onToggleDir:Dn,onFileClick:xi,onSendToChat:zi,onContextMenu:qi})]}),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"}),Oe&&r.jsx(hG,{x:Oe.x,y:Oe.y,node:Oe.node,onClose:()=>We(null),onRename:()=>{ct(Oe.node),We(null)},onDelete:()=>{wt(Oe.node),We(null)},onNewFile:()=>{Ee({parent:Oe.node.path,kind:"file"}),We(null)},onNewFolder:()=>{Ee({parent:Oe.node.path,kind:"folder"}),We(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Oe.node.path}),We(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Oe.node.path}),We(null)},onCopyPath:()=>{const st=Oe.node.path;Yo(st).then(St=>{St||Le.error("Couldn't copy path")}),We(null)},onSendToChat:()=>{zi(Oe.node.path),We(null)}}),je&&r.jsx(aE,{title:`New ${je.kind}`,subtitle:`in ${pG(je.parent)}`,onCancel:()=>{Ee(null),bt("")},onConfirm:qn,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:cn,value:Qe,onChange:st=>bt(st.target.value),onKeyDown:st=>{st.key==="Enter"&&qn(),st.key==="Escape"&&(Ee(null),bt(""))},placeholder:je.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"})}),et&&r.jsx(aE,{title:`Delete ${et.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>wt(null),onConfirm:_i,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:['"',et.name,'"']})," to the trash?",et.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function v$(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(c=>{const h=i.has(c.path),m=a===c.path,g=u===c.path,v=s[c.path],E=lG(c.name,c.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:g?n.selectedRowRef:void 0,"data-path":c.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(c.path),c.isDirectory?n.onToggleDir(c):n.onFileClick(c))},onDoubleClick:()=>{c.isDirectory||window.api.shell.open({as:"openPath",path:c.path})},onContextMenu:k=>l(k,c),children:[c.isDirectory?r.jsx(vG,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),c.isDirectory?h?r.jsx(mG,{size:12,color:E}):r.jsx(x$,{size:12,color:E}):r.jsx(gG,{size:12,color:E}),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 ${c.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:c.name}),v&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:O_[v].color,backgroundColor:`${O_[v].color}20`},title:v,children:O_[v].label}),!c.isDirectory&&r.jsx("button",{onClick:k=>{k.stopPropagation(),n.onSendToChat(c.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(SG,{size:10})})]}),c.isDirectory&&h&&c.children&&r.jsx(v$,{...n,nodes:c.children,depth:t+1})]},c.path)})})}function hG(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(nc,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(nc,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(nc,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(z_,{}),r.jsx(nc,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(nc,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(z_,{}),r.jsx(nc,{label:"New file",onClick:n.onNewFile}),r.jsx(nc,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(z_,{}),r.jsx(nc,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function nc({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 z_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function aE(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 pG(n){return f$(n)}function wm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:fG(s.children,t,i)}:s.children?{...s,children:wm(s.children,e,t,i)}:s)}function fG(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 Aa({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 x$({size:n,className:e,color:t}){return r.jsx(Aa,{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 mG({size:n,className:e,color:t}){return r.jsx(Aa,{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 gG({size:n,className:e,color:t}){return r.jsxs(Aa,{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 vG({size:n,className:e}){return r.jsx(Aa,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function xG({size:n,className:e}){return r.jsxs(Aa,{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 bG({size:n,className:e}){return r.jsxs(Aa,{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 _G({size:n,className:e}){return r.jsxs(Aa,{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 wG({size:n,className:e}){return r.jsxs(Aa,{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 yG({size:n,className:e}){return r.jsxs(Aa,{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 SG({size:n,className:e}){return r.jsxs(Aa,{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 Am(n,e){if(!e)return n;const t=M0(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 B_(n){yb(n).catch(()=>Le.error("Couldn't save File Explorer layout."))}const F_=33,CG=20,kG=60,EG=32;function lE(n){return Math.min(kG,Math.max(CG,n))}function TG(){const n=It(B=>B.tabs),e=It(B=>B.activeTabId),t=n.find(B=>B.id===e)??null,i=An(B=>B.navFace),s=fb(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=R.useState(F_),[c,h]=R.useState(!1),m=R.useRef(!1),[g,v]=R.useState(!1),E=R.useRef(u);E.current=u;const k=R.useRef(c);k.current=c;const C=R.useRef(null),x=R.useRef(null),b=R.useRef(!1),{projects:w,openProject:S,archiveProjectByCwd:T}=Bd(),I=P_(B=>B.pinned),A=P_(B=>B.togglePin);R.useEffect(()=>{P_.getState().hydrate()},[]),R.useEffect(()=>{let B=!1;return wb().then(K=>{B||m.current||(typeof K.projectsSplitPct=="number"&&Number.isFinite(K.projectsSplitPct)&&l(lE(K.projectsSplitPct)),typeof K.projectsFileTreeCollapsed=="boolean"&&!b.current&&h(K.projectsFileTreeCollapsed))}),()=>{B=!0}},[]);const M=R.useRef(0),[N,L]=R.useState(null),[U,J]=R.useState(null);qA("projects",B=>{const K=eG(B);K&&L({path:K,token:++M.current})});const Z=(t==null?void 0:t.cwd)??null;R.useEffect(()=>{if(!N)return;const{path:B}=N,K=ge=>!!ge&&g$(B,ge)!==null,W=i==="home"?s:Z,ee=i==="home"?{face:"project",root:Z}:{face:"home",root:s};let ce=null;if(K(W))ce={face:i,root:W};else{if(s===null)return;K(ee.root)&&(ce={face:ee.face,root:ee.root})}if(L(null),!ce){window.api.shell.open({as:"revealPath",path:B}).then(ge=>{ge.ok||Le.error(`Couldn't reveal ${B}: ${ge.error??"unknown error"}`)},ge=>Le.error(`Couldn't reveal ${B}: ${ge instanceof Error?ge.message:String(ge)}`));return}ce.face!==i&&An.getState().setNavFace(ce.face),b.current=!0,h(!1),J({...N,root:ce.root})},[N,i,s,Z]),R.useEffect(()=>{J(B=>B&&a!==null&&B.root!==a?null:B)},[a]);const q=R.useCallback(B=>{J(K=>K&&K.token===B?null:K)},[]),le=[...w].sort((B,K)=>(I[K.cwd]?1:0)-(I[B.cwd]?1:0));R.useEffect(()=>{if(!g)return;const B=K=>{x.current&&!x.current.contains(K.target)&&v(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[g]);const ie=R.useCallback(B=>{In.getState().openFile(B)},[]),he=R.useCallback(B=>{B.preventDefault(),m.current=!0;const K=B.clientX,W=E.current;let ee=W;const ce=Oe=>{const We=C.current;if(!We)return;const xe=We.getBoundingClientRect(),te=Oe.clientX-K;ee=lE(W+te/xe.width*100),l(ee)},ge=()=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",ge),document.body.style.cursor="",document.body.style.userSelect="",B_({projectsSplitPct:ee})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",ge),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),ve=R.useCallback(()=>{m.current=!0,l(F_),B_({projectsSplitPct:F_})},[]),fe=R.useCallback(()=>{m.current=!0;const B=!k.current;h(B),B_({projectsFileTreeCollapsed:B})},[]);return c?r.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:fe,"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:EG},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(py,{})})]}):r.jsxs("div",{ref:C,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:x,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>v(B=>!B),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?Am(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),r.jsx("button",{onClick:fe,"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:le.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):le.map(B=>{const K=Am(B.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(Zy,{content:I[B.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>A(B.cwd),className:`shrink-0 text-sm leading-none transition-colors ${I[B.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:I[B.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{S(B.cwd),v(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:K}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${K}?`)&&await T(B)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},B.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:Am(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(uG,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:ie,reveal:U&&U.root===a?U:null,onRevealDone:q})})]}):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:ve,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(py,{})})]})}const jG=R.memo(TG),DG={"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."]},"claude-config":{headline:"Your ~/.claude — every file the claude CLI reads on this machine, in one place",intro:"Claude config gathers the user-scope Claude Code files that apply to every project on this machine. Each tab edits the real file on disk; a project's own files are edited from that project's Claude config instead.",sections:[{title:"Tabs",items:[{term:"CLAUDE.md",body:"~/.claude/CLAUDE.md — house rules every session starts with."},{term:"Settings",body:"~/.claude/settings.json — permissions, hooks, env and every other key."},{term:"MCP",body:"MCP servers from ~/.claude.json › mcpServers."},{term:"Skills",body:"Skills in ~/.claude/skills and commands in ~/.claude/commands."},{term:"Plugins",body:"Installed plugins; on/off is saved in settings.json › enabledPlugins."},{term:"Agents",body:"Agent personas in ~/.claude/agents."}]}]},"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 $G({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 NG({active:n}){const e=ds(g=>g.learningPanelCollapsed),t=ds(g=>g.setLearningPanelCollapsed),i=ds(g=>g.hydrated),s=ds(g=>g.hydrate);R.useEffect(()=>{i||s()},[i,s]);const[a,u]=R.useState(()=>!e),l=R.useRef(null);R.useEffect(()=>{i&&u(!e)},[i]);const c=R.useCallback(()=>{u(g=>{const v=!g;return t(!v),v})},[t]);R.useEffect(()=>{if(!a)return;const g=v=>{var E;(E=l.current)!=null&&E.contains(v.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[a,t]);const h=R.useRef(!1);R.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const m=DG[n];return m?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:c,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($G,{content:m})})]}):null}function AG({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(NG,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const IG=R.lazy(()=>ti(()=>import("./History-DJMiuXyK.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url).then(n=>({default:n.History}))),RG=R.lazy(()=>ti(()=>import("./Scheduler-cyr61UAC.js"),__vite__mapDeps([5,2,3,4]),import.meta.url).then(n=>({default:n.Scheduler}))),PG=R.lazy(()=>ti(()=>import("./ProjectClaudeConfig-BWPpypf9.js"),__vite__mapDeps([6,7,8,1,9,10,3,4]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),lm=R.lazy(()=>ti(()=>import("./HomeClaudeConfig-CTp2tkZ4.js"),__vite__mapDeps([11,7,8,1,9,3,4]),import.meta.url).then(n=>({default:n.HomeClaudeConfig}))),MG=R.lazy(()=>ti(()=>import("./AppSettings-DExeJhqQ.js"),__vite__mapDeps([12,8,10,1,3,4]),import.meta.url).then(n=>({default:n.AppSettings}))),OG=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function ol({children:n}){return r.jsx(R.Suspense,{fallback:OG,children:n})}const LG={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."},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."}},cE=new Map;function zG(n,e){const t=cE.get(n);if(t&&t.ctx===e)return t.node;const i=BG(n,e);return cE.set(n,{ctx:e,node:i}),i}function BG(n,e){switch(n){case"overview":return r.jsx(JO,{onNavigate:e.onNavigate});case"project-home":return r.jsx(K4,{});case"editor":return r.jsx(py,{});case"projects":return r.jsx(jG,{});case"claude-config":return r.jsx(ol,{children:r.jsx(lm,{})});case"system-prompt":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"settings":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"extensions":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})});case"agent-library":return r.jsx(ol,{children:r.jsx(lm,{initialTab:Dd[n]})})}const t=LG[n],i=(()=>{switch(n){case"history":return r.jsx(ol,{children:r.jsx(IG,{})});case"scheduler":return r.jsx(ol,{children:r.jsx(RG,{navigate:e.onNavigate})});case"memory":return r.jsx(ol,{children:r.jsx(PG,{})});case"app-settings":return r.jsx(ol,{children:r.jsx(MG,{})});default:return null}})();if(!i)return null;const s=MA[n];return t&&s?r.jsx(AG,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class FG extends R.Component{constructor(){super(...arguments);ri(this,"state",{error:null});ri(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 G_={exports:{}},dE;function GG(){return dE||(dE=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,c){var h=this&&this.__decorate||function(w,S,T,I){var A,M=arguments.length,N=M<3?S:I===null?I=Object.getOwnPropertyDescriptor(S,T):I;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(w,S,T,I);else for(var L=w.length-1;L>=0;L--)(A=w[L])&&(N=(M<3?A(N):M>3?A(S,T,N):A(S,T))||N);return M>3&&N&&Object.defineProperty(S,T,N),N},m=this&&this.__param||function(w,S){return function(T,I){S(T,I,w)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const g=c(9042),v=c(9924),E=c(844),k=c(4725),C=c(2585),x=c(3656);let b=l.AccessibilityManager=class extends E.Disposable{constructor(w,S,T,I){super(),this._terminal=w,this._coreBrowserService=T,this._renderService=I,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 A=0;A<this._terminal.rows;A++)this._rowElements[A]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[A]);if(this._topBoundaryFocusListener=A=>this._handleBoundaryFocus(A,0),this._bottomBoundaryFocusListener=A=>this._handleBoundaryFocus(A,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 v.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((A=>this._handleResize(A.rows)))),this.register(this._terminal.onRender((A=>this._refreshRows(A.start,A.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((A=>this._handleChar(A)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3054
3054
|
`)))),this.register(this._terminal.onA11yTab((A=>this._handleTab(A)))),this.register(this._terminal.onKey((A=>this._handleKey(A.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,x.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,E.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(w){for(let S=0;S<w;S++)this._handleChar(" ")}_handleChar(w){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==w&&(this._charsToAnnounce+=w):this._charsToAnnounce+=w,w===`
|
|
3055
3055
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(w){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(w)||this._charsToConsume.push(w)}_refreshRows(w,S){this._liveRegionDebouncer.refresh(w,S,this._terminal.rows)}_renderRows(w,S){const T=this._terminal.buffer,I=T.lines.length.toString();for(let A=w;A<=S;A++){const M=T.lines.get(T.ydisp+A),N=[],L=(M==null?void 0:M.translateToString(!0,void 0,void 0,N))||"",U=(T.ydisp+A+1).toString(),J=this._rowElements[A];J&&(L.length===0?(J.innerText=" ",this._rowColumns.set(J,[0,1])):(J.textContent=L,this._rowColumns.set(J,N)),J.setAttribute("aria-posinset",U),J.setAttribute("aria-setsize",I))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(w,S){const T=w.target,I=this._rowElements[S===0?1:this._rowElements.length-2];if(T.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||w.relatedTarget!==I)return;let A,M;if(S===0?(A=T,M=this._rowElements.pop(),this._rowContainer.removeChild(M)):(A=this._rowElements.shift(),M=T,this._rowContainer.removeChild(A)),A.removeEventListener("focus",this._topBoundaryFocusListener),M.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const N=this._createAccessibilityTreeNode();this._rowElements.unshift(N),this._rowContainer.insertAdjacentElement("afterbegin",N)}else{const N=this._createAccessibilityTreeNode();this._rowElements.push(N),this._rowContainer.appendChild(N)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),w.preventDefault(),w.stopImmediatePropagation()}_handleSelectionChange(){var L;if(this._rowElements.length===0)return;const w=document.getSelection();if(!w)return;if(w.isCollapsed)return void(this._rowContainer.contains(w.anchorNode)&&this._terminal.clearSelection());if(!w.anchorNode||!w.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:w.anchorNode,offset:w.anchorOffset},T={node:w.focusNode,offset:w.focusOffset};if((S.node.compareDocumentPosition(T.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===T.node&&S.offset>T.offset)&&([S,T]=[T,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const I=this._rowElements.slice(-1)[0];if(T.node.compareDocumentPosition(I)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(T={node:I,offset:((L=I.textContent)==null?void 0:L.length)??0}),!this._rowContainer.contains(T.node))return;const A=({node:U,offset:J})=>{const Z=U instanceof Text?U.parentNode:U;let q=parseInt(Z==null?void 0:Z.getAttribute("aria-posinset"),10)-1;if(isNaN(q))return console.warn("row is invalid. Race condition?"),null;const le=this._rowColumns.get(Z);if(!le)return console.warn("columns is null. Race condition?"),null;let ie=J<le.length?le[J]:le.slice(-1)[0]+1;return ie>=this._terminal.cols&&(++q,ie=0),{row:q,column:ie}},M=A(S),N=A(T);if(M&&N){if(M.row>N.row||M.row===N.row&&M.column>=N.column)throw new Error("invalid range");this._terminal.select(M.column,M.row,(N.row-M.row)*this._terminal.cols-M.column+N.column)}}_handleResize(w){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>w;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const w=this._coreBrowserService.mainDocument.createElement("div");return w.setAttribute("role","listitem"),w.tabIndex=-1,this._refreshRowDimensions(w),w}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let w=0;w<this._terminal.rows;w++)this._refreshRowDimensions(this._rowElements[w])}}_refreshRowDimensions(w){w.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=b=h([m(1,C.IInstantiationService),m(2,k.ICoreBrowserService),m(3,k.IRenderService)],b)},3614:(u,l)=>{function c(v){return v.replace(/\r?\n/g,"\r")}function h(v,E){return E?"\x1B[200~"+v+"\x1B[201~":v}function m(v,E,k,C){v=h(v=c(v),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(v,!0),E.value=""}function g(v,E,k){const C=k.getBoundingClientRect(),x=v.clientX-C.left-10,b=v.clientY-C.top-10;E.style.width="20px",E.style.height="20px",E.style.left=`${x}px`,E.style.top=`${b}px`,E.style.zIndex="1000",E.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=c,l.bracketTextForPaste=h,l.copyHandler=function(v,E){v.clipboardData&&v.clipboardData.setData("text/plain",E.selectionText),v.preventDefault()},l.handlePasteEvent=function(v,E,k,C){v.stopPropagation(),v.clipboardData&&m(v.clipboardData.getData("text/plain"),E,k,C)},l.paste=m,l.moveTextAreaUnderMouseCursor=g,l.rightClickHandler=function(v,E,k,C,x){g(v,E,k),x&&C.rightClickSelect(v),E.value=C.selectionText,E.select()}},7239:(u,l,c)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const h=c(1505);l.ColorContrastCache=class{constructor(){this._color=new h.TwoKeyMap,this._css=new h.TwoKeyMap}setCss(m,g,v){this._css.set(m,g,v)}getCss(m,g){return this._css.get(m,g)}setColor(m,g,v){this._color.set(m,g,v)}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(c,h,m,g){c.addEventListener(h,m,g);let v=!1;return{dispose:()=>{v||(v=!0,c.removeEventListener(h,m,g))}}}},3551:function(u,l,c){var h=this&&this.__decorate||function(b,w,S,T){var I,A=arguments.length,M=A<3?w:T===null?T=Object.getOwnPropertyDescriptor(w,S):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(b,w,S,T);else for(var N=b.length-1;N>=0;N--)(I=b[N])&&(M=(A<3?I(M):A>3?I(w,S,M):I(w,S))||M);return A>3&&M&&Object.defineProperty(w,S,M),M},m=this&&this.__param||function(b,w){return function(S,T){w(S,T,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const g=c(3656),v=c(8460),E=c(844),k=c(2585),C=c(4725);let x=l.Linkifier=class extends E.Disposable{get currentLink(){return this._currentLink}constructor(b,w,S,T,I){super(),this._element=b,this._mouseService=w,this._renderService=S,this._bufferService=T,this._linkProviderService=I,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new v.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new v.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,E.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,E.toDisposable)((()=>{var A;this._lastMouseEvent=void 0,(A=this._activeProviderReplies)==null||A.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(b){this._lastMouseEvent=b;const w=this._positionFromMouseEvent(b,this._element,this._mouseService);if(!w)return;this._isMouseOut=!1;const S=b.composedPath();for(let T=0;T<S.length;T++){const I=S[T];if(I.classList.contains("xterm"))break;if(I.classList.contains("xterm-hover"))return}this._lastBufferCell&&w.x===this._lastBufferCell.x&&w.y===this._lastBufferCell.y||(this._handleHover(w),this._lastBufferCell=w)}_handleHover(b){if(this._activeLine!==b.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(b,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,b)||(this._clearCurrentLink(),this._askForLink(b,!0))}_askForLink(b,w){var T,I;this._activeProviderReplies&&w||((T=this._activeProviderReplies)==null||T.forEach((A=>{A==null||A.forEach((M=>{M.link.dispose&&M.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=b.y);let S=!1;for(const[A,M]of this._linkProviderService.linkProviders.entries())w?(I=this._activeProviderReplies)!=null&&I.get(A)&&(S=this._checkLinkProviderResult(A,b,S)):M.provideLinks(b.y,(N=>{var U,J;if(this._isMouseOut)return;const L=N==null?void 0:N.map((Z=>({link:Z})));(U=this._activeProviderReplies)==null||U.set(A,L),S=this._checkLinkProviderResult(A,b,S),((J=this._activeProviderReplies)==null?void 0:J.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(b.y,this._activeProviderReplies)}))}_removeIntersectingLinks(b,w){const S=new Set;for(let T=0;T<w.size;T++){const I=w.get(T);if(I)for(let A=0;A<I.length;A++){const M=I[A],N=M.link.range.start.y<b?0:M.link.range.start.x,L=M.link.range.end.y>b?this._bufferService.cols:M.link.range.end.x;for(let U=N;U<=L;U++){if(S.has(U)){I.splice(A--,1);break}S.add(U)}}}}_checkLinkProviderResult(b,w,S){var A;if(!this._activeProviderReplies)return S;const T=this._activeProviderReplies.get(b);let I=!1;for(let M=0;M<b;M++)this._activeProviderReplies.has(M)&&!this._activeProviderReplies.get(M)||(I=!0);if(!I&&T){const M=T.find((N=>this._linkAtPosition(N.link,w)));M&&(S=!0,this._handleNewLink(M))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let M=0;M<this._activeProviderReplies.size;M++){const N=(A=this._activeProviderReplies.get(M))==null?void 0:A.find((L=>this._linkAtPosition(L.link,w)));if(N){S=!0,this._handleNewLink(N);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(b){if(!this._currentLink)return;const w=this._positionFromMouseEvent(b,this._element,this._mouseService);w&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,w)&&this._currentLink.link.activate(b,this._currentLink.link.text)}_clearCurrentLink(b,w){this._currentLink&&this._lastMouseEvent&&(!b||!w||this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=w)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,E.disposeArray)(this._linkCacheDisposables))}_handleNewLink(b){if(!this._lastMouseEvent)return;const w=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);w&&this._linkAtPosition(b.link,w)&&(this._currentLink=b,this._currentLink.state={decorations:{underline:b.link.decorations===void 0||b.link.decorations.underline,pointerCursor:b.link.decorations===void 0||b.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,b.link,this._lastMouseEvent),b.link.decorations={},Object.defineProperties(b.link.decorations,{pointerCursor:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.pointerCursor},set:S=>{var T;(T=this._currentLink)!=null&&T.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.underline},set:S=>{var T,I,A;(T=this._currentLink)!=null&&T.state&&((A=(I=this._currentLink)==null?void 0:I.state)==null?void 0:A.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(b.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const T=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,I=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=T&&this._currentLink.link.range.end.y<=I&&(this._clearCurrentLink(T,I),this._lastMouseEvent)){const A=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);A&&this._askForLink(A,!1)}}))))}_linkHover(b,w,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!0),this._currentLink.state.decorations.pointerCursor&&b.classList.add("xterm-cursor-pointer")),w.hover&&w.hover(S,w.text)}_fireUnderlineEvent(b,w){const S=b.range,T=this._bufferService.buffer.ydisp,I=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-T-1,S.end.x,S.end.y-T-1,void 0);(w?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(I)}_linkLeave(b,w,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!1),this._currentLink.state.decorations.pointerCursor&&b.classList.remove("xterm-cursor-pointer")),w.leave&&w.leave(S,w.text)}_linkAtPosition(b,w){const S=b.range.start.y*this._bufferService.cols+b.range.start.x,T=b.range.end.y*this._bufferService.cols+b.range.end.x,I=w.y*this._bufferService.cols+w.x;return S<=I&&I<=T}_positionFromMouseEvent(b,w,S){const T=S.getCoords(b,w,this._bufferService.cols,this._bufferService.rows);if(T)return{x:T[0],y:T[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(b,w,S,T,I){return{x1:b,y1:w,x2:S,y2:T,cols:this._bufferService.cols,fg:I}}};l.Linkifier=x=h([m(1,C.IMouseService),m(2,C.IRenderService),m(3,k.IBufferService),m(4,C.ILinkProviderService)],x)},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,c){var h=this&&this.__decorate||function(C,x,b,w){var S,T=arguments.length,I=T<3?x:w===null?w=Object.getOwnPropertyDescriptor(x,b):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(C,x,b,w);else for(var A=C.length-1;A>=0;A--)(S=C[A])&&(I=(T<3?S(I):T>3?S(x,b,I):S(x,b))||I);return T>3&&I&&Object.defineProperty(x,b,I),I},m=this&&this.__param||function(C,x){return function(b,w){x(b,w,C)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const g=c(511),v=c(2585);let E=l.OscLinkProvider=class{constructor(C,x,b){this._bufferService=C,this._optionsService=x,this._oscLinkService=b}provideLinks(C,x){var L;const b=this._bufferService.buffer.lines.get(C-1);if(!b)return void x(void 0);const w=[],S=this._optionsService.rawOptions.linkHandler,T=new g.CellData,I=b.getTrimmedLength();let A=-1,M=-1,N=!1;for(let U=0;U<I;U++)if(M!==-1||b.hasContent(U)){if(b.loadCell(U,T),T.hasExtendedAttrs()&&T.extended.urlId){if(M===-1){M=U,A=T.extended.urlId;continue}N=T.extended.urlId!==A}else M!==-1&&(N=!0);if(N||M!==-1&&U===I-1){const J=(L=this._oscLinkService.getLinkData(A))==null?void 0:L.uri;if(J){const Z={start:{x:M+1,y:C},end:{x:U+(N||U!==I-1?0:1),y:C}};let q=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const le=new URL(J);["http:","https:"].includes(le.protocol)||(q=!0)}catch{q=!0}q||w.push({text:J,range:Z,activate:(le,ie)=>S?S.activate(le,ie,Z):k(0,ie),hover:(le,ie)=>{var he;return(he=S==null?void 0:S.hover)==null?void 0:he.call(S,le,ie,Z)},leave:(le,ie)=>{var he;return(he=S==null?void 0:S.leave)==null?void 0:he.call(S,le,ie,Z)}})}N=!1,T.hasExtendedAttrs()&&T.extended.urlId?(M=U,A=T.extended.urlId):(M=-1,A=-1)}}x(w)}};function k(C,x){if(confirm(`Do you want to navigate to ${x}?
|
|
3056
3056
|
|