claude-code-session-manager 0.130.1 → 0.130.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentLibrary-Dlhtc8Ty.js → AgentLibrary-Bfj862qf.js} +1 -1
- package/dist/assets/{AppSettings-A3KoPcmL.js → AppSettings-Bpwynea4.js} +1 -1
- package/dist/assets/{Button-DvTXa_-4.js → Button-DSoqrxCB.js} +1 -1
- package/dist/assets/{Extensions-Ddb4sQpO.js → Extensions-BziIutWV.js} +3 -3
- package/dist/assets/{History-DcnZxMoU.js → History-DzMo9Otn.js} +1 -1
- package/dist/assets/{Library-LftcMs6C.js → Library-C5wKMTSn.js} +1 -1
- package/dist/assets/{ListDetail-CnL1azR0.js → ListDetail-DDQ1S0yu.js} +1 -1
- package/dist/assets/{Memory-smN9-Yoo.js → Memory-Bq5T33d2.js} +1 -1
- package/dist/assets/{Panel-CA6TdCHv.js → Panel-B-3NWUlv.js} +1 -1
- package/dist/assets/{ProvenanceBadge-Y3DhyiJo.js → ProvenanceBadge-CUChwz4Z.js} +1 -1
- package/dist/assets/{Scheduler-Ca1qo_kp.js → Scheduler-CkGHMXvo.js} +1 -1
- package/dist/assets/{Settings-BFwlV-as.js → Settings-DGxvyajs.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-2WMsKdmr.js → SkillReferenceGraph-C6JEdypC.js} +1 -1
- package/dist/assets/{SourceChip-CeprSxwb.js → SourceChip-DcBNYYhe.js} +1 -1
- package/dist/assets/{SystemPrompt-B8TXIGXo.js → SystemPrompt-CfozyVQx.js} +1 -1
- package/dist/assets/{TiptapBody-BvxcQ_tS.js → TiptapBody-DiVYC-_O.js} +1 -1
- package/dist/assets/{Toggle-keTV_HDb.js → Toggle-Cs3k6I96.js} +1 -1
- package/dist/assets/{ViewTabs-fupn9keJ.js → ViewTabs-DFXH03tb.js} +1 -1
- package/dist/assets/{VoiceButton-5ETBv9eI.js → VoiceButton-C3NLotUZ.js} +1 -1
- package/dist/assets/{historyTotals-NAZqiuzd.js → historyTotals-f-E0L9Xw.js} +1 -1
- package/dist/assets/{index-QJxszEhM.js → index-CuAfFXNd.js} +3 -3
- package/dist/index.html +1 -1
- package/dist-web/app.js +1 -1
- package/package.json +1 -1
- package/src/main/build-info.json +4 -4
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-DiVYC-_O.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./History-DzMo9Otn.js","./Panel-B-3NWUlv.js","./historyTotals-f-E0L9Xw.js","./Scheduler-CkGHMXvo.js","./Settings-DGxvyajs.js","./Library-C5wKMTSn.js","./Button-DSoqrxCB.js","./SourceChip-DcBNYYhe.js","./ViewTabs-DFXH03tb.js","./claude-settings-schema-COigsajx.js","./ListDetail-DDQ1S0yu.js","./ProvenanceBadge-CUChwz4Z.js","./SystemPrompt-CfozyVQx.js","./Memory-Bq5T33d2.js","./VoiceButton-C3NLotUZ.js","./Extensions-BziIutWV.js","./Toggle-Cs3k6I96.js","./AppSettings-Bpwynea4.js","./AgentLibrary-Bfj862qf.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var X2=Object.defineProperty;var J2=(i,e,t)=>e in i?X2(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Vi=(i,e,t)=>J2(i,typeof e!="symbol"?e+"":e,t);import{_ as Oi}from"./monaco-editor-BsIlgG7c.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const l of s)if(l.type==="childList")for(const p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&n(p)}).observe(document,{childList:!0,subtree:!0});function t(s){const l={};return s.integrity&&(l.integrity=s.integrity),s.referrerPolicy&&(l.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?l.credentials="include":s.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(s){if(s.ep)return;s.ep=!0;const l=t(s);fetch(s.href,l)}})();function Gw(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var x_={exports:{}},mf={},y_={exports:{}},Ci={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -2929,7 +2929,7 @@ ${I}`,L=v.createShaderModule({code:P,label:r.name});ui("verbose",()=>`[WebGPU] $
|
|
|
2929
2929
|
* Licensed under the MIT License.
|
|
2930
2930
|
*/var o0;function YD(){return o0||(o0=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,s=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof ao<"u"?ao:typeof Proxy<"u"?new Proxy(Y,{get:(re,pe)=>(typeof ao<"u"?ao:re)[pe]}):Y)(function(Y){if(typeof ao<"u")return ao.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),c=(Y,re)=>()=>(Y&&(re=Y(Y=0)),re),f=(Y,re)=>{for(var pe in re)n(Y,pe,{get:re[pe],enumerable:!0})},m=(Y,re,pe,Te)=>{if(re&&typeof re=="object"||typeof re=="function")for(let we of l(re))!p.call(Y,we)&&we!==pe&&n(Y,we,{get:()=>re[we],enumerable:!(Te=s(re,we))||Te.enumerable});return Y},g=Y=>m(n({},"__esModule",{value:!0}),Y),w,T,k,C,b,x=c(()=>{w=new Map,T=[],k=(Y,re,pe)=>{if(re&&typeof re.init=="function"&&typeof re.createInferenceSessionHandler=="function"){let Te=w.get(Y);if(Te===void 0)w.set(Y,{backend:re,priority:pe});else{if(Te.priority>pe)return;if(Te.priority===pe&&Te.backend!==re)throw new Error(`cannot register backend "${Y}" using priority ${pe}`)}if(pe>=0){let we=T.indexOf(Y);we!==-1&&T.splice(we,1);for(let Le=0;Le<T.length;Le++)if(w.get(T[Le]).priority<=pe){T.splice(Le,0,Y);return}T.push(Y)}return}throw new TypeError("not a valid backend")},C=async Y=>{let re=w.get(Y);if(!re)return"backend not found.";if(re.initialized)return re.backend;if(re.aborted)return re.error;{let pe=!!re.initPromise;try{return pe||(re.initPromise=re.backend.init(Y)),await re.initPromise,re.initialized=!0,re.backend}catch(Te){return pe||(re.error=`${Te}`,re.aborted=!0),re.error}finally{delete re.initPromise}}},b=async Y=>{let re=Y.executionProviders||[],pe=re.map(Be=>typeof Be=="string"?Be:Be.name),Te=pe.length===0?T:pe,we,Le=[],Ae=new Set;for(let Be of Te){let rt=await C(Be);typeof rt=="string"?Le.push({name:Be,err:rt}):(we||(we=rt),we===rt&&Ae.add(Be))}if(!we)throw new Error(`no available backend found. ERR: ${Le.map(Be=>`[${Be.name}] ${Be.err}`).join(", ")}`);for(let{name:Be,err:rt}of Le)pe.includes(Be)&&console.warn(`removing requested execution provider "${Be}" from session options because it is not available: ${rt}`);let Ie=re.filter(Be=>Ae.has(typeof Be=="string"?Be:Be.name));return[we,new Proxy(Y,{get:(Be,rt)=>rt==="executionProviders"?Ie:Reflect.get(Be,rt)})]}}),S=c(()=>{x()}),y,D=c(()=>{y="1.26.0"}),R,N,M=c(()=>{D(),R="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:y},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);R=Y}},get logLevel(){return R}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,F=c(()=>{M(),j=N}),V,te,de=c(()=>{V=(Y,re)=>{let pe=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);pe.width=Y.dims[3],pe.height=Y.dims[2];let Te=pe.getContext("2d");if(Te!=null){let we,Le;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(we=Y.dims[2],Le=Y.dims[3]):(we=Y.dims[3],Le=Y.dims[2]);let Ae=(re==null?void 0:re.format)!==void 0?re.format:"RGB",Ie=re==null?void 0:re.norm,Be,rt;Ie===void 0||Ie.mean===void 0?Be=[255,255,255,255]:typeof Ie.mean=="number"?Be=[Ie.mean,Ie.mean,Ie.mean,Ie.mean]:(Be=[Ie.mean[0],Ie.mean[1],Ie.mean[2],0],Ie.mean[3]!==void 0&&(Be[3]=Ie.mean[3])),Ie===void 0||Ie.bias===void 0?rt=[0,0,0,0]:typeof Ie.bias=="number"?rt=[Ie.bias,Ie.bias,Ie.bias,Ie.bias]:(rt=[Ie.bias[0],Ie.bias[1],Ie.bias[2],0],Ie.bias[3]!==void 0&&(rt[3]=Ie.bias[3]));let lt=Le*we,ot=0,Xe=lt,Nt=lt*2,Me=-1;Ae==="RGBA"?(ot=0,Xe=lt,Nt=lt*2,Me=lt*3):Ae==="RGB"?(ot=0,Xe=lt,Nt=lt*2):Ae==="RBG"&&(ot=0,Nt=lt,Xe=lt*2);for(let ft=0;ft<Le;ft++)for(let zi=0;zi<we;zi++){let ii=(Y.data[ot++]-rt[0])*Be[0],ni=(Y.data[Xe++]-rt[1])*Be[1],Bi=(Y.data[Nt++]-rt[2])*Be[2],Gt=Me===-1?255:(Y.data[Me++]-rt[3])*Be[3];Te.fillStyle="rgba("+ii+","+ni+","+Bi+","+Gt+")",Te.fillRect(zi,ft,1,1)}if("toDataURL"in pe)return pe.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},te=(Y,re)=>{let pe=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(pe!=null){let we,Le,Ae;(re==null?void 0:re.tensorLayout)!==void 0&&re.tensorLayout==="NHWC"?(we=Y.dims[2],Le=Y.dims[1],Ae=Y.dims[3]):(we=Y.dims[3],Le=Y.dims[2],Ae=Y.dims[1]);let Ie=re!==void 0&&re.format!==void 0?re.format:"RGB",Be=re==null?void 0:re.norm,rt,lt;Be===void 0||Be.mean===void 0?rt=[255,255,255,255]:typeof Be.mean=="number"?rt=[Be.mean,Be.mean,Be.mean,Be.mean]:(rt=[Be.mean[0],Be.mean[1],Be.mean[2],255],Be.mean[3]!==void 0&&(rt[3]=Be.mean[3])),Be===void 0||Be.bias===void 0?lt=[0,0,0,0]:typeof Be.bias=="number"?lt=[Be.bias,Be.bias,Be.bias,Be.bias]:(lt=[Be.bias[0],Be.bias[1],Be.bias[2],0],Be.bias[3]!==void 0&&(lt[3]=Be.bias[3]));let ot=Le*we;if(re!==void 0&&(re.format!==void 0&&Ae===4&&re.format!=="RGBA"||Ae===3&&re.format!=="RGB"&&re.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,Nt=0,Me=1,ft=2,zi=3,ii=0,ni=ot,Bi=ot*2,Gt=-1;Ie==="RGBA"?(ii=0,ni=ot,Bi=ot*2,Gt=ot*3):Ie==="RGB"?(ii=0,ni=ot,Bi=ot*2):Ie==="RBG"&&(ii=0,Bi=ot,ni=ot*2),Te=pe.createImageData(we,Le);for(let Yi=0;Yi<Le*we;Nt+=Xe,Me+=Xe,ft+=Xe,zi+=Xe,Yi++)Te.data[Nt]=(Y.data[ii++]-lt[0])*rt[0],Te.data[Me]=(Y.data[ni++]-lt[1])*rt[1],Te.data[ft]=(Y.data[Bi++]-lt[2])*rt[2],Te.data[zi]=Gt===-1?255:(Y.data[Gt++]-lt[3])*rt[3]}else throw new Error("Can not access image data");return Te}}),Q,ge,oe,me,$e,he,W=c(()=>{Pe(),Q=(Y,re)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(re.height===void 0||re.width===void 0)throw new Error("Image height and width must be defined");if(re.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:pe,width:Te}=re,we=re.norm??{mean:255,bias:0},Le,Ae;typeof we.mean=="number"?Le=[we.mean,we.mean,we.mean,we.mean]:Le=[we.mean[0],we.mean[1],we.mean[2],we.mean[3]??255],typeof we.bias=="number"?Ae=[we.bias,we.bias,we.bias,we.bias]:Ae=[we.bias[0],we.bias[1],we.bias[2],we.bias[3]??0];let Ie=re.format!==void 0?re.format:"RGBA",Be=re.tensorFormat!==void 0&&re.tensorFormat!==void 0?re.tensorFormat:"RGB",rt=pe*Te,lt=Be==="RGBA"?new Float32Array(rt*4):new Float32Array(rt*3),ot=4,Xe=0,Nt=1,Me=2,ft=3,zi=0,ii=rt,ni=rt*2,Bi=-1;Ie==="RGB"&&(ot=3,Xe=0,Nt=1,Me=2,ft=-1),Be==="RGBA"?Bi=rt*3:Be==="RBG"?(zi=0,ni=rt,ii=rt*2):Be==="BGR"&&(ni=0,ii=rt,zi=rt*2);for(let Gt=0;Gt<rt;Gt++,Xe+=ot,Me+=ot,Nt+=ot,ft+=ot)lt[zi++]=(Y[Xe]+Ae[0])/Le[0],lt[ii++]=(Y[Nt]+Ae[1])/Le[1],lt[ni++]=(Y[Me]+Ae[2])/Le[2],Bi!==-1&&ft!==-1&&(lt[Bi++]=(Y[ft]+Ae[3])/Le[3]);return Be==="RGBA"?new J("float32",lt,[1,4,pe,Te]):new J("float32",lt,[1,3,pe,Te])},ge=async(Y,re)=>{let pe=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,we=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Le=typeof Y=="string",Ae,Ie=re??{},Be=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},rt=lt=>typeof HTMLCanvasElement<"u"&< instanceof HTMLCanvasElement||lt instanceof OffscreenCanvas?lt.getContext("2d"):null;if(pe){let lt=Be();lt.width=Y.width,lt.height=Y.height;let ot=rt(lt);if(ot!=null){let Xe=Y.height,Nt=Y.width;if(re!==void 0&&re.resizedHeight!==void 0&&re.resizedWidth!==void 0&&(Xe=re.resizedHeight,Nt=re.resizedWidth),re!==void 0){if(Ie=re,re.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ie.tensorFormat="RGBA",Ie.height=Xe,Ie.width=Nt}else Ie.tensorFormat="RGBA",Ie.height=Xe,Ie.width=Nt;ot.drawImage(Y,0,0),Ae=ot.getImageData(0,0,Nt,Xe).data}else throw new Error("Can not access image data")}else if(Te){let lt,ot;if(re!==void 0&&re.resizedWidth!==void 0&&re.resizedHeight!==void 0?(lt=re.resizedHeight,ot=re.resizedWidth):(lt=Y.height,ot=Y.width),re!==void 0&&(Ie=re),Ie.format="RGBA",Ie.height=lt,Ie.width=ot,re!==void 0){let Xe=Be();Xe.width=ot,Xe.height=lt;let Nt=rt(Xe);if(Nt!=null)Nt.putImageData(Y,0,0),Ae=Nt.getImageData(0,0,ot,lt).data;else throw new Error("Can not access image data")}else Ae=Y.data}else if(we){if(re===void 0)throw new Error("Please provide image config with format for Imagebitmap");let lt=Be();lt.width=Y.width,lt.height=Y.height;let ot=rt(lt);if(ot!=null){let Xe=Y.height,Nt=Y.width;return ot.drawImage(Y,0,0,Nt,Xe),Ae=ot.getImageData(0,0,Nt,Xe).data,Ie.height=Xe,Ie.width=Nt,Q(Ae,Ie)}else throw new Error("Can not access image data")}else{if(Le)return new Promise((lt,ot)=>{let Xe=Be(),Nt=rt(Xe);if(!Y||!Nt)return ot();let Me=new Image;Me.crossOrigin="Anonymous",Me.src=Y,Me.onload=()=>{Xe.width=Me.width,Xe.height=Me.height,Nt.drawImage(Me,0,0,Xe.width,Xe.height);let ft=Nt.getImageData(0,0,Xe.width,Xe.height);Ie.height=Xe.height,Ie.width=Xe.width,lt(Q(ft.data,Ie))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ae!==void 0)return Q(Ae,Ie);throw new Error("Input data provided is not supported - aborted tensor creation")},oe=(Y,re)=>{let{width:pe,height:Te,download:we,dispose:Le}=re,Ae=[1,Te,pe,4];return new J({location:"texture",type:"float32",texture:Y,dims:Ae,download:we,dispose:Le})},me=(Y,re)=>{let{dataType:pe,dims:Te,download:we,dispose:Le}=re;return new J({location:"gpu-buffer",type:pe??"float32",gpuBuffer:Y,dims:Te,download:we,dispose:Le})},$e=(Y,re)=>{let{dataType:pe,dims:Te,download:we,dispose:Le}=re;return new J({location:"ml-tensor",type:pe??"float32",mlTensor:Y,dims:Te,download:we,dispose:Le})},he=(Y,re,pe)=>new J({location:"cpu-pinned",type:Y,data:re,dims:pe??[re.length]})}),X,U,ee,ue,ye=c(()=>{X=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),U=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ee=!1,ue=()=>{if(!ee){ee=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,re=typeof BigUint64Array<"u"&&BigUint64Array.from,pe=globalThis.Float16Array,Te=typeof pe<"u"&&pe.from;Y&&(X.set("int64",BigInt64Array),U.set(BigInt64Array,"int64")),re&&(X.set("uint64",BigUint64Array),U.set(BigUint64Array,"uint64")),Te?(X.set("float16",pe),U.set(pe,"float16")):X.set("float16",Uint16Array)}}}),ze,it,ve=c(()=>{Pe(),ze=Y=>{let re=1;for(let pe=0;pe<Y.length;pe++){let Te=Y[pe];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${pe}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${pe}] must be a non-negative integer, got: ${Te}`);re*=Te}return re},it=(Y,re)=>{switch(Y.location){case"cpu":return new J(Y.type,Y.data,re);case"cpu-pinned":return new J({location:"cpu-pinned",data:Y.data,type:Y.type,dims:re});case"texture":return new J({location:"texture",texture:Y.texture,type:Y.type,dims:re});case"gpu-buffer":return new J({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:re});case"ml-tensor":return new J({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:re});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),J,Pe=c(()=>{de(),W(),ye(),ve(),J=class{constructor(Y,re,pe){ue();let Te,we;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,we=Y.dims,Y.location){case"cpu-pinned":{let Ae=X.get(Te);if(!Ae)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(Y.data instanceof Ae))throw new TypeError(`buffer should be of type ${Ae.name}`);this.cpuData=Y.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=Y.mlTensor,this.downloader=Y.download,this.disposer=Y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ae,Ie;if(typeof Y=="string")if(Te=Y,Ie=pe,Y==="string"){if(!Array.isArray(re))throw new TypeError("A string tensor's data must be a string array.");Ae=re}else{let Be=X.get(Y);if(Be===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(re)){if(Y==="float16"&&Be===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Be.name} as data.`);Y==="uint64"||Y==="int64"?Ae=Be.from(re,BigInt):Ae=Be.from(re)}else if(re instanceof Be)Ae=re;else if(re instanceof Uint8ClampedArray)if(Y==="uint8")Ae=Uint8Array.from(re);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&re instanceof Uint16Array&&Be!==Uint16Array)Ae=new globalThis.Float16Array(re.buffer,re.byteOffset,re.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Be}`)}else if(Ie=re,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Be=typeof Y[0];if(Be==="string")Te="string",Ae=Y;else if(Be==="boolean")Te="bool",Ae=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Be}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",Ae=Uint8Array.from(Y);else{let Be=U.get(Y.constructor);if(Be===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Be,Ae=Y}if(Ie===void 0)Ie=[Ae.length];else if(!Array.isArray(Ie))throw new TypeError("A tensor's dims must be a number array");we=Ie,this.cpuData=Ae,this.dataLocation="cpu"}let Le=ze(we);if(this.cpuData&&Le!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Le/2)===this.cpuData.length))throw new Error(`Tensor's size(${Le}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=we,this.size=Le}static async fromImage(Y,re){return ge(Y,re)}static fromTexture(Y,re){return oe(Y,re)}static fromGpuBuffer(Y,re){return me(Y,re)}static fromMLTensor(Y,re){return $e(Y,re)}static fromPinnedBuffer(Y,re,pe){return he(Y,re,pe)}toDataURL(Y){return V(this,Y)}toImageData(Y){return te(this,Y)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Y){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let re=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=re,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),re}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(Y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return it(this,Y)}}}),ke,Se=c(()=>{Pe(),ke=J}),Ee,et,gt,Oe,ct,st,Qt=c(()=>{M(),Ee=(Y,re)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${re}`)},et=(Y,re)=>{var we;let pe=((we=new Error().stack)==null?void 0:we.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Le=0;Le<pe.length;Le++){if(Te&&!pe[Le].includes("TRACE_FUNC")){let Ae=`FUNC_${Y}::${pe[Le].trim().split(" ")[1]}`;re&&(Ae+=`::${re}`),Ee("CPU",Ae);return}pe[Le].includes("TRACE_FUNC")&&(Te=!0)}},gt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||et("BEGIN",Y)},Oe=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||et("END",Y)},ct=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},st=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),oi,hi=c(()=>{x(),Se(),Qt(),oi=class VC{constructor(re){this.handler=re}async run(re,pe,Te){gt(),ct("InferenceSession.run");let we={},Le={};if(typeof re!="object"||re===null||re instanceof ke||Array.isArray(re))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ae=!0;if(typeof pe=="object"){if(pe===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(pe instanceof ke)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(pe)){if(pe.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ae=!1;for(let rt of pe){if(typeof rt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(rt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${rt}.`);we[rt]=null}if(typeof Te=="object"&&Te!==null)Le=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let rt=!1,lt=Object.getOwnPropertyNames(pe);for(let ot of this.outputNames)if(lt.indexOf(ot)!==-1){let Xe=pe[ot];(Xe===null||Xe instanceof ke)&&(rt=!0,Ae=!1,we[ot]=Xe)}if(rt){if(typeof Te=="object"&&Te!==null)Le=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Le=pe}}else if(typeof pe<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let rt of this.inputNames)if(typeof re[rt]>"u")throw new Error(`input '${rt}' is missing in 'feeds'.`);if(Ae)for(let rt of this.outputNames)we[rt]=null;let Ie=await this.handler.run(re,we,Le),Be={};for(let rt in Ie)if(Object.hasOwnProperty.call(Ie,rt)){let lt=Ie[rt];lt instanceof ke?Be[rt]=lt:Be[rt]=new ke(lt.type,lt.data,lt.dims)}return st("InferenceSession.run"),Oe(),Be}async release(){return this.handler.dispose()}static async create(re,pe,Te,we){gt(),ct("InferenceSession.create");let Le,Ae={};if(typeof re=="string"){if(Le=re,typeof pe=="object"&&pe!==null)Ae=pe;else if(typeof pe<"u")throw new TypeError("'options' must be an object.")}else if(re instanceof Uint8Array){if(Le=re,typeof pe=="object"&&pe!==null)Ae=pe;else if(typeof pe<"u")throw new TypeError("'options' must be an object.")}else if(re instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&re instanceof SharedArrayBuffer){let lt=re,ot=0,Xe=re.byteLength;if(typeof pe=="object"&&pe!==null)Ae=pe;else if(typeof pe=="number"){if(ot=pe,!Number.isSafeInteger(ot))throw new RangeError("'byteOffset' must be an integer.");if(ot<0||ot>=lt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${lt.byteLength}).`);if(Xe=re.byteLength-ot,typeof Te=="number"){if(Xe=Te,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||ot+Xe>lt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${lt.byteLength-ot}].`);if(typeof we=="object"&&we!==null)Ae=we;else if(typeof we<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof pe<"u")throw new TypeError("'options' must be an object.");Le=new Uint8Array(lt,ot,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ie,Be]=await b(Ae),rt=await Ie.createInferenceSessionHandler(Le,Be);return st("InferenceSession.create"),Oe(),new VC(rt)}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}}}),Ai,Je=c(()=>{hi(),Ai=oi}),bt=c(()=>{}),wt=c(()=>{}),Ke=c(()=>{}),tt=c(()=>{}),Dt={};f(Dt,{InferenceSession:()=>Ai,TRACE:()=>Ee,TRACE_EVENT_BEGIN:()=>ct,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>Oe,Tensor:()=>ke,env:()=>j,registerBackend:()=>k});var Zt=c(()=>{S(),F(),Je(),Se(),bt(),wt(),Qt(),Ke(),tt()}),mi=c(()=>{}),gi={};f(gi,{default:()=>Vn});var Mt,ai,Vn,ss=c(()=>{var Y;fe(),$n(),ln(),Mt="ort-wasm-proxy-worker",ai=((Y=globalThis.self)==null?void 0:Y.name)===Mt,ai&&(self.onmessage=re=>{let{type:pe,in:Te}=re.data;try{switch(pe){case"init-wasm":wi(Te.wasm).then(()=>{Uo(Te).then(()=>{postMessage({type:pe})},we=>{postMessage({type:pe,err:we})})},we=>{postMessage({type:pe,err:we})});break;case"init-ep":{let{epName:we,env:Le}=Te;$r(Le,we).then(()=>{postMessage({type:pe})},Ae=>{postMessage({type:pe,err:Ae})});break}case"copy-from":{let{buffer:we}=Te,Le=ui(we);postMessage({type:pe,out:Le});break}case"create":{let{model:we,options:Le}=Te;$s(we,Le).then(Ae=>{postMessage({type:pe,out:Ae})},Ae=>{postMessage({type:pe,err:Ae})});break}case"release":qr(Te),postMessage({type:pe});break;case"run":{let{sessionId:we,inputIndices:Le,inputs:Ae,outputIndices:Ie,options:Be}=Te;Ye(we,Le,Ae,Ie,new Array(Ie.length).fill(null),Be).then(rt=>{rt.some(lt=>lt[3]!=="cpu")?postMessage({type:pe,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:pe,out:rt},xt([...Ae,...rt]))},rt=>{postMessage({type:pe,err:rt})});break}case"end-profiling":fs(Te),postMessage({type:pe});break;default:}}catch(we){postMessage({type:pe,err:we})}}),Vn=ai?null:re=>new Worker(re??bi,{type:"classic",name:Mt})}),qn,Kn,bi,an,Gi,Yn,vt,yi,Sn,qi,Li,_n,Qi,ln=c(()=>{mi(),qn=typeof location>"u"?void 0:location.origin,Kn=()=>{var Y,re;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(re=self.location)==null?void 0:re.href:void 0},bi=Kn(),an=()=>{if(bi&&!bi.startsWith("blob:"))return bi.substring(0,bi.lastIndexOf("/")+1)},Gi=(Y,re)=>{try{let pe=re??bi;return(pe?new URL(Y,pe):new URL(Y)).origin===qn}catch{return!1}},Yn=(Y,re)=>{let pe=re??bi;try{return(pe?new URL(Y,pe):new URL(Y)).href}catch{return}},vt=(Y,re)=>`${re??"./"}${Y}`,yi=async Y=>{let re=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(re)},Sn=async Y=>(await import(Y)).default,qi=(ss(),g(gi)).default,Li=async()=>{if(!bi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Gi(bi))return[void 0,qi()];let Y=await yi(bi);return[Y,qi(Y)]},_n=void 0,Qi=async(Y,re,pe,Te)=>{let we=_n&&!(Y||re);if(we)if(bi)we=Gi(bi)||Te&&!pe;else if(Te&&!pe)we=!0;else throw new Error("cannot determine the script source URL.");if(we)return[void 0,_n];{let Le="ort-wasm-simd-threaded.mjs",Ae=Y??Yn(Le,re),Ie=pe&&Ae&&!Gi(Ae,re),Be=Ie?await yi(Ae):Ae??vt(Le,re);return[Ie?Be:void 0,await Sn(Be)]}}}),Xn,bn,Fe,pt,ci,vi,Ki,wi,It,$n=c(()=>{ln(),bn=!1,Fe=!1,pt=!1,ci=()=>{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}},vi=()=>{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}},Ki=()=>{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}},wi=async Y=>{if(bn)return Promise.resolve();if(Fe)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(pt)throw new Error("previous call to 'initializeWebAssembly()' failed.");Fe=!0;let re=Y.initTimeout,pe=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!Ki())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!vi())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ci();pe>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+pe+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),Y.numThreads=pe=1);let we=Y.wasmPaths,Le=typeof we=="string"?we:void 0,Ae=we==null?void 0:we.mjs,Ie=(Ae==null?void 0:Ae.href)??Ae,Be=we==null?void 0:we.wasm,rt=(Be==null?void 0:Be.href)??Be,lt=Y.wasmBinary,[ot,Xe]=await Qi(Ie,Le,pe>1,!!lt||!!rt),Nt=!1,Me=[];if(re>0&&Me.push(new Promise(ft=>{setTimeout(()=>{Nt=!0,ft()},re)})),Me.push(new Promise((ft,zi)=>{let ii={numThreads:pe};if(lt)ii.wasmBinary=lt,ii.locateFile=ni=>ni;else if(rt||Le)ii.locateFile=ni=>rt??Le+ni;else if(Ie&&Ie.indexOf("blob:")!==0)ii.locateFile=ni=>new URL(ni,Ie).href;else if(ot){let ni=an();ni&&(ii.locateFile=Bi=>ni+Bi)}Xe(ii).then(ni=>{Fe=!1,bn=!0,Xn=ni,ft(),ot&&URL.revokeObjectURL(ot)},ni=>{Fe=!1,pt=!0,zi(ni)})})),await Promise.race(Me),Nt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${re}ms`)},It=()=>{if(bn&&Xn)return Xn;throw new Error("WebAssembly is not initialized yet.")}}),rn,ji,$t,Ur=c(()=>{$n(),rn=(Y,re)=>{let pe=It(),Te=pe.lengthBytesUTF8(Y)+1,we=pe._malloc(Te);return pe.stringToUTF8(Y,we,Te),re.push(we),we},ji=(Y,re,pe,Te)=>{if(typeof Y=="object"&&Y!==null){if(pe.has(Y))throw new Error("Circular reference in options");pe.add(Y)}Object.entries(Y).forEach(([we,Le])=>{let Ae=re?re+we:we;if(typeof Le=="object")ji(Le,Ae+".",pe,Te);else if(typeof Le=="string"||typeof Le=="number")Te(Ae,Le.toString());else if(typeof Le=="boolean")Te(Ae,Le?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Le}`)})},$t=Y=>{let re=It(),pe=re.stackSave();try{let Te=re.PTR_SIZE,we=re.stackAlloc(2*Te);re._OrtGetLastError(we,we+Te);let Le=Number(re.getValue(we,Te===4?"i32":"i64")),Ae=re.getValue(we+Te,"*"),Ie=Ae?re.UTF8ToString(Ae):"";throw new Error(`${Y} ERROR_CODE: ${Le}, ERROR_MESSAGE: ${Ie}`)}finally{re.stackRestore(pe)}}}),ho,Ea=c(()=>{$n(),Ur(),ho=Y=>{let re=It(),pe=0,Te=[],we=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)we.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)we.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(we.terminate=!1);let Le=0;return(Y==null?void 0:Y.tag)!==void 0&&(Le=rn(Y.tag,Te)),pe=re._OrtCreateRunOptions(we.logSeverityLevel,we.logVerbosityLevel,!!we.terminate,Le),pe===0&&$t("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&ji(Y.extra,"",new WeakSet,(Ae,Ie)=>{let Be=rn(Ae,Te),rt=rn(Ie,Te);re._OrtAddRunConfigEntry(pe,Be,rt)!==0&&$t(`Can't set a run config entry: ${Ae} - ${Ie}.`)}),[pe,Te]}catch(Le){throw pe!==0&&re._OrtReleaseRunOptions(pe),Te.forEach(Ae=>re._free(Ae)),Le}}}),po,fo,Wo,Jn,Ta,Da,Ni=c(()=>{$n(),Ur(),po=Y=>{switch(Y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${Y}`)}},fo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},Wo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let re=Y.extra.session;re.use_ort_model_bytes_directly||(re.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(pe=>(typeof pe=="string"?pe:pe.name)==="webgpu")&&(Y.enableMemPattern=!1)},Jn=(Y,re,pe,Te)=>{let we=rn(re,Te),Le=rn(pe,Te);It()._OrtAddSessionConfigEntry(Y,we,Le)!==0&&$t(`Can't set a session config entry: ${re} - ${pe}.`)},Ta=async(Y,re,pe)=>{let Te=re.executionProviders;for(let we of Te){let Le=typeof we=="string"?we:we.name,Ae=[];switch(Le){case"webnn":if(Le="WEBNN",Jn(Y,"session.disable_quant_qdq","1",pe),Jn(Y,"session.disable_qdq_constant_folding","1",pe),typeof we!="string"){let ot=we==null?void 0:we.deviceType;ot&&Jn(Y,"deviceType",ot,pe)}break;case"webgpu":if(Le="JS",typeof we!="string"){let ot=we;if(ot!=null&&ot.preferredLayout){if(ot.preferredLayout!=="NCHW"&&ot.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${ot.preferredLayout}`);Jn(Y,"preferredLayout",ot.preferredLayout,pe)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Le}`)}let Ie=rn(Le,pe),Be=Ae.length,rt=0,lt=0;if(Be>0){rt=It()._malloc(Be*It().PTR_SIZE),pe.push(rt),lt=It()._malloc(Be*It().PTR_SIZE),pe.push(lt);for(let ot=0;ot<Be;ot++)It().setValue(rt+ot*It().PTR_SIZE,Ae[ot][0],"*"),It().setValue(lt+ot*It().PTR_SIZE,Ae[ot][1],"*")}await It()._OrtAppendExecutionProvider(Y,Ie,rt,lt,Be)!==0&&$t(`Can't append execution provider: ${Le}.`)}},Da=async Y=>{let re=It(),pe=0,Te=[],we=Y||{};Wo(we);try{let Le=po(we.graphOptimizationLevel??"all"),Ae=fo(we.executionMode??"sequential"),Ie=typeof we.logId=="string"?rn(we.logId,Te):0,Be=we.logSeverityLevel??2;if(!Number.isInteger(Be)||Be<0||Be>4)throw new Error(`log severity level is not valid: ${Be}`);let rt=we.logVerbosityLevel??0;if(!Number.isInteger(rt)||rt<0||rt>4)throw new Error(`log verbosity level is not valid: ${rt}`);let lt=typeof we.optimizedModelFilePath=="string"?rn(we.optimizedModelFilePath,Te):0;if(pe=re._OrtCreateSessionOptions(Le,!!we.enableCpuMemArena,!!we.enableMemPattern,Ae,!!we.enableProfiling,0,Ie,Be,rt,lt),pe===0&&$t("Can't create session options."),we.executionProviders&&await Ta(pe,we,Te),we.enableGraphCapture!==void 0){if(typeof we.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${we.enableGraphCapture}`);Jn(pe,"enableGraphCapture",we.enableGraphCapture.toString(),Te)}if(we.freeDimensionOverrides)for(let[ot,Xe]of Object.entries(we.freeDimensionOverrides)){if(typeof ot!="string")throw new Error(`free dimension override name must be a string: ${ot}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let Nt=rn(ot,Te);re._OrtAddFreeDimensionOverride(pe,Nt,Xe)!==0&&$t(`Can't set a free dimension override: ${ot} - ${Xe}.`)}return we.extra!==void 0&&ji(we.extra,"",new WeakSet,(ot,Xe)=>{Jn(pe,ot,Xe,Te)}),[pe,Te]}catch(Le){throw pe!==0&&re._OrtReleaseSessionOptions(pe)!==0&&$t("Can't release session options."),Te.forEach(Ae=>re._free(Ae)),Le}}}),rs,cn,os,hr,Vr,Tr,Ts,Mn,Wt=c(()=>{rs=Y=>{switch(Y){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${Y}`)}},cn=Y=>{switch(Y){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${Y}`)}},os=(Y,re)=>{let pe=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][Y],Te=typeof re=="number"?re:re.reduce((we,Le)=>we*Le,1);return pe>0?Math.ceil(Te*pe):void 0},hr=Y=>{switch(Y){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${Y}`)}},Vr=Y=>{switch(Y){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${Y}`)}},Tr=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",Ts=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",Mn=Y=>{switch(Y){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${Y}`)}}}),dn,Dr=c(()=>{mi(),dn=async Y=>{if(typeof Y=="string"){let re=await fetch(Y);if(!re.ok)throw new Error(`failed to load external data file: ${Y}`);let pe=re.headers.get("Content-Length"),Te=pe?parseInt(pe,10):0;if(Te<1073741824)return new Uint8Array(await re.arrayBuffer());{if(!re.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let we=re.body.getReader(),Le;try{Le=new ArrayBuffer(Te)}catch(Ie){if(Ie instanceof RangeError){let Be=Math.ceil(Te/65536);Le=new WebAssembly.Memory({initial:Be,maximum:Be}).buffer}else throw Ie}let Ae=0;for(;;){let{done:Ie,value:Be}=await we.read();if(Ie)break;let rt=Be.byteLength;new Uint8Array(Le,Ae,rt).set(Be),Ae+=rt}return new Uint8Array(Le,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),Ds,Uo,$r,ps,Qs,Ar,ui,$s,qr,Us,Ye,fs,xt,fe=c(()=>{Zt(),Ea(),Ni(),Wt(),$n(),Ur(),Dr(),Ds=(Y,re)=>{It()._OrtInit(Y,re)!==0&&$t("Can't initialize onnxruntime.")},Uo=async Y=>{Ds(Y.wasm.numThreads,Vr(Y.logLevel))},$r=async(Y,re)=>{var Te,we;(we=(Te=It()).asyncInit)==null||we.call(Te);let pe=Y.webgpu.adapter;if(re==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(pe){if(typeof pe.limits!="object"||typeof pe.features!="object"||typeof pe.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Le=Y.webgpu.powerPreference;if(Le!==void 0&&Le!=="low-power"&&Le!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Le}"`);let Ae=Y.webgpu.forceFallbackAdapter;if(Ae!==void 0&&typeof Ae!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ae}"`);if(pe=await navigator.gpu.requestAdapter({powerPreference:Le,forceFallbackAdapter:Ae}),!pe)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(re==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},ps=new Map,Qs=Y=>{let re=It(),pe=re.stackSave();try{let Te=re.PTR_SIZE,we=re.stackAlloc(2*Te);re._OrtGetInputOutputCount(Y,we,we+Te)!==0&&$t("Can't get session input/output count.");let Le=Te===4?"i32":"i64";return[Number(re.getValue(we,Le)),Number(re.getValue(we+Te,Le))]}finally{re.stackRestore(pe)}},Ar=(Y,re)=>{let pe=It(),Te=pe.stackSave(),we=0;try{let Le=pe.PTR_SIZE,Ae=pe.stackAlloc(2*Le);pe._OrtGetInputOutputMetadata(Y,re,Ae,Ae+Le)!==0&&$t("Can't get session input/output metadata.");let Ie=Number(pe.getValue(Ae,"*"));we=Number(pe.getValue(Ae+Le,"*"));let Be=pe.HEAP32[we/4];if(Be===0)return[Ie,0];let rt=pe.HEAPU32[we/4+1],lt=[];for(let ot=0;ot<rt;ot++){let Xe=Number(pe.getValue(we+8+ot*Le,"*"));lt.push(Xe!==0?pe.UTF8ToString(Xe):Number(pe.getValue(we+8+(ot+rt)*Le,"*")))}return[Ie,Be,lt]}finally{pe.stackRestore(Te),we!==0&&pe._OrtFree(we)}},ui=Y=>{let re=It(),pe=re._malloc(Y.byteLength);if(pe===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return re.HEAPU8.set(Y,pe),[pe,Y.byteLength]},$s=async(Y,re)=>{var lt,ot,Xe;let pe,Te,we=It();Array.isArray(Y)?[pe,Te]=Y:Y.buffer===we.HEAPU8.buffer?[pe,Te]=[Y.byteOffset,Y.byteLength]:[pe,Te]=ui(Y);let Le=0,Ae=0,Ie=[],Be=[],rt=[];try{if([Ae,Ie]=await Da(re),(re==null?void 0:re.externalData)&&we.mountExternalData){let Yi=[];for(let xi of re.externalData){let On=typeof xi=="string"?xi:xi.path;Yi.push(dn(typeof xi=="string"?xi:xi.data).then(as=>{we.mountExternalData(On,as)}))}await Promise.all(Yi)}for(let Yi of(re==null?void 0:re.executionProviders)??[])if((typeof Yi=="string"?Yi:Yi.name)==="webnn"){if(we.shouldTransferToMLTensor=!1,typeof Yi!="string"){let xi=Yi,On=xi==null?void 0:xi.context,as=xi==null?void 0:xi.gpuDevice,ms=xi==null?void 0:xi.deviceType,Aa=xi==null?void 0:xi.powerPreference;On?we.currentContext=On:as?we.currentContext=await we.webnnCreateMLContext(as):we.currentContext=await we.webnnCreateMLContext({deviceType:ms,powerPreference:Aa})}else we.currentContext=await we.webnnCreateMLContext();break}Le=await we._OrtCreateSession(pe,Te,Ae),(lt=we.webgpuOnCreateSession)==null||lt.call(we,Le),Le===0&&$t("Can't create a session."),(ot=we.jsepOnCreateSession)==null||ot.call(we),we.currentContext&&(we.webnnRegisterMLContext(Le,we.currentContext),we.currentContext=void 0,we.shouldTransferToMLTensor=!0);let[Nt,Me]=Qs(Le),ft=!!(re!=null&&re.enableGraphCapture),zi=[],ii=[],ni=[],Bi=[],Gt=[];for(let Yi=0;Yi<Nt;Yi++){let[xi,On,as]=Ar(Le,Yi);xi===0&&$t("Can't get an input name."),Be.push(xi);let ms=we.UTF8ToString(xi);zi.push(ms),ni.push(On===0?{name:ms,isTensor:!1}:{name:ms,isTensor:!0,type:cn(On),shape:as})}for(let Yi=0;Yi<Me;Yi++){let[xi,On,as]=Ar(Le,Yi+Nt);xi===0&&$t("Can't get an output name."),rt.push(xi);let ms=we.UTF8ToString(xi);ii.push(ms),Bi.push(On===0?{name:ms,isTensor:!1}:{name:ms,isTensor:!0,type:cn(On),shape:as})}return ps.set(Le,[Le,Be,rt,null,ft,!1]),[Le,zi,ii,ni,Bi]}catch(Nt){throw Be.forEach(Me=>we._OrtFree(Me)),rt.forEach(Me=>we._OrtFree(Me)),Le!==0&&we._OrtReleaseSession(Le)!==0&&$t("Can't release session."),Nt}finally{we._free(pe),Ae!==0&&we._OrtReleaseSessionOptions(Ae)!==0&&$t("Can't release session options."),Ie.forEach(Nt=>we._free(Nt)),(Xe=we.unmountExternalData)==null||Xe.call(we)}},qr=Y=>{var Be,rt,lt;let re=It(),pe=ps.get(Y);if(!pe)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,we,Le,Ae,Ie]=pe;Ae&&(Ie&&re._OrtClearBoundOutputs(Ae.handle)!==0&&$t("Can't clear bound outputs."),re._OrtReleaseBinding(Ae.handle)!==0&&$t("Can't release IO binding.")),(Be=re.jsepOnReleaseSession)==null||Be.call(re,Y),(rt=re.webnnOnReleaseSession)==null||rt.call(re,Y),(lt=re.webgpuOnReleaseSession)==null||lt.call(re,Y),we.forEach(ot=>re._OrtFree(ot)),Le.forEach(ot=>re._OrtFree(ot)),re._OrtReleaseSession(Te)!==0&&$t("Can't release session."),ps.delete(Y)},Us=async(Y,re,pe,Te,we,Le,Ae=!1)=>{if(!Y){re.push(0);return}let Ie=It(),Be=Ie.PTR_SIZE,rt=Y[0],lt=Y[1],ot=Y[3],Xe=ot,Nt,Me;if(rt==="string"&&(ot==="gpu-buffer"||ot==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ae&&ot!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Le} when enableGraphCapture is true.`);if(ot==="gpu-buffer"){let ii=Y[2].gpuBuffer;Me=os(rs(rt),lt);{let ni=Ie.jsepRegisterBuffer;if(!ni)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Nt=ni(Te,Le,ii,Me)}}else if(ot==="ml-tensor"){let ii=Y[2].mlTensor;Me=os(rs(rt),lt);let ni=Ie.webnnRegisterMLTensor;if(!ni)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Nt=ni(Te,ii,rs(rt),lt)}else{let ii=Y[2];if(Array.isArray(ii)){Me=Be*ii.length,Nt=Ie._malloc(Me),pe.push(Nt);for(let ni=0;ni<ii.length;ni++){if(typeof ii[ni]!="string")throw new TypeError(`tensor data at index ${ni} is not a string`);Ie.setValue(Nt+ni*Be,rn(ii[ni],pe),"*")}}else{let ni=Ie.webnnIsGraphInput,Bi=Ie.webnnIsGraphOutput;if(rt!=="string"&&ni&&Bi){let Gt=Ie.UTF8ToString(we);if(ni(Te,Gt)||Bi(Te,Gt)){let Yi=rs(rt);Me=os(Yi,lt),Xe="ml-tensor";let xi=Ie.webnnCreateTemporaryTensor,On=Ie.webnnUploadTensor;if(!xi||!On)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let as=await xi(Te,Yi,lt);On(as,new Uint8Array(ii.buffer,ii.byteOffset,ii.byteLength)),Nt=as}else Me=ii.byteLength,Nt=Ie._malloc(Me),pe.push(Nt),Ie.HEAPU8.set(new Uint8Array(ii.buffer,ii.byteOffset,Me),Nt)}else Me=ii.byteLength,Nt=Ie._malloc(Me),pe.push(Nt),Ie.HEAPU8.set(new Uint8Array(ii.buffer,ii.byteOffset,Me),Nt)}}let ft=Ie.stackSave(),zi=Ie.stackAlloc(4*lt.length);try{lt.forEach((ni,Bi)=>Ie.setValue(zi+Bi*Be,ni,Be===4?"i32":"i64"));let ii=Ie._OrtCreateTensor(rs(rt),Nt,Me,zi,lt.length,Mn(Xe));ii===0&&$t(`Can't create tensor for input/output. session=${Te}, index=${Le}.`),re.push(ii)}finally{Ie.stackRestore(ft)}},Ye=async(Y,re,pe,Te,we,Le)=>{var gs,fl,gc;let Ae=It(),Ie=Ae.PTR_SIZE,Be=ps.get(Y);if(!Be)throw new Error(`cannot run inference. invalid session id: ${Y}`);let rt=Be[0],lt=Be[1],ot=Be[2],Xe=Be[3],Nt=Be[4];Be[5];let Me=re.length,ft=Te.length,zi=0,ii=[],ni=[],Bi=[],Gt=[],Yi=[],xi=Ae.stackSave(),On=Ae.stackAlloc(Me*Ie),as=Ae.stackAlloc(Me*Ie),ms=Ae.stackAlloc(ft*Ie),Aa=Ae.stackAlloc(ft*Ie);try{[zi,ii]=ho(Le),ct("wasm prepareInputOutputTensor");for(let fi=0;fi<Me;fi++)await Us(pe[fi],ni,Gt,Y,lt[re[fi]],re[fi],Nt);for(let fi=0;fi<ft;fi++)await Us(we[fi],Bi,Gt,Y,ot[Te[fi]],Me+Te[fi],Nt);st("wasm prepareInputOutputTensor");for(let fi=0;fi<Me;fi++)Ae.setValue(On+fi*Ie,ni[fi],"*"),Ae.setValue(as+fi*Ie,lt[re[fi]],"*");for(let fi=0;fi<ft;fi++)Ae.setValue(ms+fi*Ie,Bi[fi],"*"),Ae.setValue(Aa+fi*Ie,ot[Te[fi]],"*");(gs=Ae.jsepOnRunStart)==null||gs.call(Ae,rt),(fl=Ae.webnnOnRunStart)==null||fl.call(Ae,rt);let Ln;Ln=await Ae._OrtRun(rt,as,On,Me,Aa,ft,ms,zi),Ln!==0&&$t("failed to call OrtRun().");let fr=[],vc=[];ct("wasm ProcessOutputTensor");for(let fi=0;fi<ft;fi++){let tr=Number(Ae.getValue(ms+fi*Ie,"*"));if(tr===Bi[fi]||Yi.includes(Bi[fi])){fr.push(we[fi]),tr!==Bi[fi]&&Ae._OrtReleaseTensor(tr)!==0&&$t("Can't release tensor.");continue}let Id=Ae.stackSave(),Rr=Ae.stackAlloc(4*Ie),Vo=!1,kn,vs=0;try{Ae._OrtGetTensorData(tr,Rr,Rr+Ie,Rr+2*Ie,Rr+3*Ie)!==0&&$t(`Can't access output tensor data on index ${fi}.`);let ml=Ie===4?"i32":"i64",_s=Number(Ae.getValue(Rr,ml));vs=Ae.getValue(Rr+Ie,"*");let _c=Ae.getValue(Rr+Ie*2,"*"),Pd=Number(Ae.getValue(Rr+Ie*3,ml)),jr=[];for(let En=0;En<Pd;En++)jr.push(Number(Ae.getValue(_c+En*Ie,ml)));Ae._OrtFree(_c)!==0&&$t("Can't free memory for tensor dims.");let ir=jr.reduce((En,on)=>En*on,1);kn=cn(_s);let mr=Xe==null?void 0:Xe.outputPreferredLocations[Te[fi]];if(kn==="string"){if(mr==="gpu-buffer"||mr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let En=[];for(let on=0;on<ir;on++){let nr=Ae.getValue(vs+on*Ie,"*"),bc=Ae.getValue(vs+(on+1)*Ie,"*"),wc=on===ir-1?void 0:bc-nr;En.push(Ae.UTF8ToString(nr,wc))}fr.push([kn,jr,En,"cpu"])}else if(mr==="gpu-buffer"&&ir>0){let En=Ae.jsepGetBuffer;if(!En)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let on=En(vs),nr=os(_s,ir);if(nr===void 0||!Tr(kn))throw new Error(`Unsupported data type: ${kn}`);Vo=!0,fr.push([kn,jr,{gpuBuffer:on,download:Ae.jsepCreateDownloader(on,nr,kn),dispose:()=>{Ae._OrtReleaseTensor(tr)!==0&&$t("Can't release tensor.")}},"gpu-buffer"])}else if(mr==="ml-tensor"&&ir>0){let En=Ae.webnnEnsureTensor,on=Ae.webnnIsGraphInputOutputTypeSupported;if(!En||!on)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(os(_s,ir)===void 0||!Ts(kn))throw new Error(`Unsupported data type: ${kn}`);if(!on(Y,kn,!1))throw new Error(`preferredLocation "ml-tensor" for ${kn} output is not supported by current WebNN Context.`);let nr=await En(Y,vs,_s,jr,!1);Vo=!0,fr.push([kn,jr,{mlTensor:nr,download:Ae.webnnCreateMLTensorDownloader(vs,kn),dispose:()=>{Ae.webnnReleaseTensorId(vs),Ae._OrtReleaseTensor(tr)}},"ml-tensor"])}else if(mr==="ml-tensor-cpu-output"&&ir>0){let En=Ae.webnnCreateMLTensorDownloader(vs,kn)(),on=fr.length;Vo=!0,vc.push((async()=>{let nr=[on,await En];return Ae.webnnReleaseTensorId(vs),Ae._OrtReleaseTensor(tr),nr})()),fr.push([kn,jr,[],"cpu"])}else{let En=hr(kn),on=new En(ir);new Uint8Array(on.buffer,on.byteOffset,on.byteLength).set(Ae.HEAPU8.subarray(vs,vs+on.byteLength)),fr.push([kn,jr,on,"cpu"])}}finally{Ae.stackRestore(Id),kn==="string"&&vs&&Ae._free(vs),Vo||Ae._OrtReleaseTensor(tr)}}Xe&&!Nt&&(Ae._OrtClearBoundOutputs(Xe.handle)!==0&&$t("Can't clear bound outputs."),ps.set(Y,[rt,lt,ot,Xe,Nt,!1]));for(let[fi,tr]of await Promise.all(vc))fr[fi][2]=tr;return st("wasm ProcessOutputTensor"),fr}finally{(gc=Ae.webnnOnRunEnd)==null||gc.call(Ae,rt),Ae.stackRestore(xi),ni.forEach(Ln=>Ae._OrtReleaseTensor(Ln)),Bi.forEach(Ln=>Ae._OrtReleaseTensor(Ln)),Gt.forEach(Ln=>Ae._free(Ln)),zi!==0&&Ae._OrtReleaseRunOptions(zi),ii.forEach(Ln=>Ae._free(Ln))}},fs=Y=>{let re=It(),pe=ps.get(Y);if(!pe)throw new Error("invalid session id");let Te=pe[0],we=re._OrtEndProfiling(Te);we===0&&$t("Can't get an profile file name."),re._OrtFree(we)},xt=Y=>{let re=[];for(let pe of Y){let Te=pe[2];!Array.isArray(Te)&&"buffer"in Te&&re.push(Te.buffer)}return re}}),je,Qe,Pt,li,pi,Ui,Fi,wn,en,Cn,Hi,er,Kr,mo,pr,Ad,go,vo,pc=c(()=>{Zt(),fe(),$n(),ln(),je=()=>!!j.wasm.proxy&&typeof document<"u",Pt=!1,li=!1,pi=!1,wn=new Map,en=(Y,re)=>{let pe=wn.get(Y);pe?pe.push(re):wn.set(Y,[re])},Cn=()=>{if(Pt||!li||pi||!Qe)throw new Error("worker not ready")},Hi=Y=>{switch(Y.data.type){case"init-wasm":Pt=!1,Y.data.err?(pi=!0,Fi[1](Y.data.err)):(li=!0,Fi[0]()),Ui&&(URL.revokeObjectURL(Ui),Ui=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let re=wn.get(Y.data.type);Y.data.err?re.shift()[1](Y.data.err):re.shift()[0](Y.data.out);break}}},er=async()=>{if(!li){if(Pt)throw new Error("multiple calls to 'initWasm()' detected.");if(pi)throw new Error("previous call to 'initWasm()' failed.");if(Pt=!0,je())return new Promise((Y,re)=>{Qe==null||Qe.terminate(),Li().then(([pe,Te])=>{try{Qe=Te,Qe.onerror=Le=>re(Le),Qe.onmessage=Hi,Fi=[Y,re];let we={type:"init-wasm",in:j};if(!we.in.wasm.wasmPaths&&pe){let Le=an();Le&&(we.in.wasm.wasmPaths=Le)}Qe.postMessage(we),Ui=pe}catch(we){re(we)}},re)});try{await wi(j.wasm),await Uo(j),li=!0}catch(Y){throw pi=!0,Y}finally{Pt=!1}}},Kr=async Y=>{if(je())return Cn(),new Promise((re,pe)=>{en("init-ep",[re,pe]);let Te={type:"init-ep",in:{epName:Y,env:j}};Qe.postMessage(Te)});await $r(j,Y)},mo=async Y=>je()?(Cn(),new Promise((re,pe)=>{en("copy-from",[re,pe]);let Te={type:"copy-from",in:{buffer:Y}};Qe.postMessage(Te,[Y.buffer])})):ui(Y),pr=async(Y,re)=>{if(je()){if(re!=null&&re.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Cn(),new Promise((pe,Te)=>{en("create",[pe,Te]);let we={type:"create",in:{model:Y,options:{...re}}},Le=[];Y instanceof Uint8Array&&Le.push(Y.buffer),Qe.postMessage(we,Le)})}else return $s(Y,re)},Ad=async Y=>{if(je())return Cn(),new Promise((re,pe)=>{en("release",[re,pe]);let Te={type:"release",in:Y};Qe.postMessage(Te)});qr(Y)},go=async(Y,re,pe,Te,we,Le)=>{if(je()){if(pe.some(Ae=>Ae[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(we.some(Ae=>Ae))throw new Error("pre-allocated output tensor is not supported for proxy.");return Cn(),new Promise((Ae,Ie)=>{en("run",[Ae,Ie]);let Be=pe,rt={type:"run",in:{sessionId:Y,inputIndices:re,inputs:Be,outputIndices:Te,options:Le}};Qe.postMessage(rt,xt(Be))})}else return Ye(Y,re,pe,Te,we,Le)},vo=async Y=>{if(je())return Cn(),new Promise((re,pe)=>{en("end-profiling",[re,pe]);let Te={type:"end-profiling",in:Y};Qe.postMessage(Te)});fs(Y)}}),dl,_o,$a,ul=c(()=>{Zt(),pc(),Wt(),mi(),Dr(),dl=(Y,re)=>{switch(Y.location){case"cpu":return[Y.type,Y.dims,Y.data,"cpu"];case"gpu-buffer":return[Y.type,Y.dims,{gpuBuffer:Y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Y.type,Y.dims,{mlTensor:Y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Y.location} for ${re()}`)}},_o=Y=>{switch(Y[3]){case"cpu":return new ke(Y[0],Y[2],Y[1]);case"gpu-buffer":{let re=Y[0];if(!Tr(re))throw new Error(`not supported data type: ${re} for deserializing GPU tensor`);let{gpuBuffer:pe,download:Te,dispose:we}=Y[2];return ke.fromGpuBuffer(pe,{dataType:re,dims:Y[1],download:Te,dispose:we})}case"ml-tensor":{let re=Y[0];if(!Ts(re))throw new Error(`not supported data type: ${re} for deserializing MLTensor tensor`);let{mlTensor:pe,download:Te,dispose:we}=Y[2];return ke.fromMLTensor(pe,{dataType:re,dims:Y[1],download:Te,dispose:we})}default:throw new Error(`invalid data location: ${Y[3]}`)}},$a=class{async fetchModelAndCopyToWasmMemory(Y){return mo(await dn(Y))}async loadModel(Y,re){gt();let pe;typeof Y=="string"?pe=await this.fetchModelAndCopyToWasmMemory(Y):pe=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await pr(pe,re),Oe()}async dispose(){return Ad(this.sessionId)}async run(Y,re,pe){gt();let Te=[],we=[];Object.entries(Y).forEach(ot=>{let Xe=ot[0],Nt=ot[1],Me=this.inputNames.indexOf(Xe);if(Me===-1)throw new Error(`invalid input '${Xe}'`);Te.push(Nt),we.push(Me)});let Le=[],Ae=[];Object.entries(re).forEach(ot=>{let Xe=ot[0],Nt=ot[1],Me=this.outputNames.indexOf(Xe);if(Me===-1)throw new Error(`invalid output '${Xe}'`);Le.push(Nt),Ae.push(Me)});let Ie=Te.map((ot,Xe)=>dl(ot,()=>`input "${this.inputNames[we[Xe]]}"`)),Be=Le.map((ot,Xe)=>ot?dl(ot,()=>`output "${this.outputNames[Ae[Xe]]}"`):null),rt=await go(this.sessionId,we,Ie,Ae,Be,pe),lt={};for(let ot=0;ot<rt.length;ot++)lt[this.outputNames[Ae[ot]]]=Le[ot]??_o(rt[ot]);return Oe(),lt}startProfiling(){}endProfiling(){vo(this.sessionId)}}}),Ir={};f(Ir,{OnnxruntimeWebAssemblyBackend:()=>Pr,initializeFlags:()=>Yr,wasmBackend:()=>bo});var Yr,Pr,bo,fc=c(()=>{Zt(),pc(),ul(),Yr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let Y=j.wasm.simd;if(typeof Y!="boolean"&&Y!==void 0&&Y!=="fixed"&&Y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Y}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let re=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((re||1)/2))}},Pr=class{async init(Y){Yr(),await er(),await Kr(Y)}async createInferenceSessionHandler(Y,re){let pe=new $a;return await pe.loadModel(Y,re),pe}},bo=new Pr}),mc={};f(mc,{InferenceSession:()=>Ai,TRACE:()=>Ee,TRACE_EVENT_BEGIN:()=>ct,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>Oe,Tensor:()=>ke,default:()=>pl,env:()=>j,registerBackend:()=>k}),Zt(),Zt(),Zt();var hl="1.26.0",pl=Dt;{let Y=(fc(),g(Ir)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:hl,enumerable:!0}),g(mc)})();i.exports=t})(R_)),R_.exports}var a0;function XD(){return a0||(a0=1,(function(i){var e=Qa&&Qa.__createBinding||(Object.create?(function(y,D,R,N){N===void 0&&(N=R);var M=Object.getOwnPropertyDescriptor(D,R);(!M||("get"in M?!D.__esModule:M.writable||M.configurable))&&(M={enumerable:!0,get:function(){return D[R]}}),Object.defineProperty(y,N,M)}):(function(y,D,R,N){N===void 0&&(N=R),y[N]=D[R]})),t=Qa&&Qa.__setModuleDefault||(Object.create?(function(y,D){Object.defineProperty(y,"default",{enumerable:!0,value:D})}):function(y,D){y.default=D}),n=Qa&&Qa.__importStar||function(y){if(y&&y.__esModule)return y;var D={};if(y!=null)for(var R in y)R!=="default"&&Object.prototype.hasOwnProperty.call(y,R)&&e(D,y,R);return t(D,y),D};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const s=n(YD()),l=Qw(),p=ex(),a=bm(),c=Jv(),f=WC(),m=UC();i.DEFAULT_MODEL="legacy",i.ort=s;const g="vad.worklet.bundle.min.js",w="silero_vad_v5.onnx",T="silero_vad_legacy.onnx",k=y=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:y,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async D=>{D.getTracks().forEach(R=>{R.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:D=>{D.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const C=y=>"audioWorklet"in y&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(y,D,R,N,M){await R.audioWorklet.addModule(y),D.processorOptions={...D.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(R,"vad-helper-worklet",D);return j.port.onmessage=async F=>{const V=F.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case c.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const te=new Float32Array(V.data);await M(te);break}}},j}async function x(y,D,R){const N=new m.Resampler({nativeSampleRate:y.sampleRate,targetSampleRate:16e3,targetFrameSize:D});a.log.debug("using script processor");const j=y.createScriptProcessor(4096,1,1);let F=!1;return j.onaudioprocess=async V=>{if(!F){F=!0;try{const te=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const Q=N.process(te);for(const ge of Q)await R(ge)}catch(te){console.error("Error processing audio:",te)}finally{F=!1}}},j.connect(y.destination),j}class S{constructor(D,R,N,M,j=!1,F=null,V=null,te=null,de=null,Q=null,ge=null,oe="uninitialized",me=!1){this.options=D,this.frameProcessor=R,this.model=N,this.frameSamples=M,this.listening=j,this.errored=F,this._stream=V,this._audioContext=te,this._vadNode=de,this._mediaStreamAudioSourceNode=Q,this._audioProcessorAdapterType=ge,this.initializationState=oe,this.ownsAudioContext=me,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=$e=>{this.initializationState="errored",this.errored=$e},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch($e){throw $e instanceof Error?this.setErrored($e.message):this.setErrored(String($e)),$e}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?C(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+g,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await x(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),a.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{a.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:$e,audioContext:he,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream($e);const X=new MediaStreamAudioSourceNode(he,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=X,X.connect(W);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:$e,mediaStreamAudioSourceNode:he}=this.getAudioInstances();await this.options.pauseStream($e),he.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var he;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:$e}=this.getAudioInstances();$e instanceof AudioWorkletNode&&$e.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((he=this._audioContext)==null?void 0:he.close())},this.setOptions=$e=>{this.frameProcessor.setOptions($e)},this.processFrame=async $e=>{await this.frameProcessor.process($e,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=$e=>{switch($e.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed($e.probs,$e.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd($e.audio);break}}}static async new(D={}){const R={...(0,i.getDefaultRealTimeVADOptions)(D.model??i.DEFAULT_MODEL),...D};(0,p.validateOptions)(R),i.ort.env.wasm.wasmPaths=R.onnxWASMBasePath,R.ortConfig!==void 0&&R.ortConfig(i.ort);const N=R.model==="v5"?w:T,M=R.baseAssetPath+N,j=R.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let F;try{F=await j(i.ort,()=>(0,l.defaultModelFetcher)(M))}catch(ge){throw console.error(`Encountered an error while loading model file ${M}`),ge}const V=R.model==="v5"?512:1536,te=V/16,de=new p.FrameProcessor(F.process,F.reset_state,{positiveSpeechThreshold:R.positiveSpeechThreshold,negativeSpeechThreshold:R.negativeSpeechThreshold,redemptionMs:R.redemptionMs,preSpeechPadMs:R.preSpeechPadMs,minSpeechMs:R.minSpeechMs,submitUserSpeechOnPause:R.submitUserSpeechOnPause},te),Q=new S(R,de,F,V);if(R.startOnLoad)try{await Q.start()}catch(ge){throw console.error("Error starting micVad",ge),ge}return Q}}i.MicVAD=S})(Qa)),Qa}var l0;function JD(){return l0||(l0=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=GC();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=Qw();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=ex();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var s=Jv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return s.Message}});var l=qD();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=KD();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=XD();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return a.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return a.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return a.getDefaultRealTimeVADOptions}})})(A_)),A_}var ZD=JD();function Ig(i,e,t,n,s){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,s)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const mt={debug:(i,e,t)=>Ig(i,"debug",e,t),info:(i,e,t)=>Ig(i,"info",e,t),warn:(i,e,t)=>Ig(i,"warn",e,t),error:(i,e,t,n)=>Ig(i,"error",e,t,n)},qC=16e3,QD=6,ph=qC*QD,e$=400,t$=qC*e$/1e3,c0=300,d0=2e3,u0=1500,h0=3e3,i$=600,KC=.5,YC=.35,p0=.85,f0=.7;let Gs=null,Bo=!1,Js=!1;const Lb=new Set;function Pg(i){for(const e of Array.from(Lb))try{e(i)}catch(t){mt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let j_=0;const m0=2;let Eh=!1,XC=!1;function JC(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";mt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{mt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),n$(`error:${e.message||"unknown"}`)})}function Pv(){return Gs||(Gs=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),JC(Gs),mt.info("speech","worker spawned"),Gs)}let Rg=!1;function n$(i){if(!Eh){if(Rg){mt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(Rg=!0,j_+=1,XC=!0,mt.warn("speech","respawnWorker: starting",{reason:i,attempt:j_}),Pg({reason:i,respawned:!1,finalOnly:!0}),j_>m0){if(Eh=!0,mt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:m0}),Gs)try{Gs.terminate()}catch{}Gs=null,Bo=!1,Js=!1,Pg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),Rg=!1;return}if(Gs)try{Gs.terminate()}catch{}Gs=null,Bo=!1,Js=!1;try{Gs=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),JC(Gs),Js=!0,Gs.postMessage({type:"load"}),mt.info("speech","respawnWorker: new worker spawned, load posted"),Pg({reason:i,respawned:!0,finalOnly:!0})}catch(e){Eh=!0,mt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),Pg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{Rg=!1}}}function s$(i,e){if(Bo||Js)return;Js=!0;const t=Pv();mt.info("speech","preloadModel: posting load");const n=s=>{s.data.type==="status"?(i==null||i(s.data.status,s.data.message),s.data.status==="ready"&&(Bo=!0,Js=!1,mt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(Js=!1,mt.error("speech","preloadModel: worker reported error",{error:s.data.error}),i==null||i("error",s.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function r$(){mt.info("speech","resetModel: clearing load flags"),Bo=!1,Js=!1}function o$(){if(mt.info("speech","releaseModel: terminating worker"),Gs)try{Gs.terminate()}catch{}Gs=null,Bo=!1,Js=!1}function Zv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function a$(i){const e=Pv();return!Bo&&!Js&&(Js=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const s=l=>{var p,a,c;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",s),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",s),n(new Error(String(l.data.error??"Transcription failed")))):((c=l.data)==null?void 0:c.type)==="status"&&l.data.status==="ready"&&(Bo=!0,Js=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function ZC(i){let e=Pv(),t=!1,n=null,s=null,l=null,p=null,a=null;const c=[],f=new Set;let m=null,g=0,w=!1,T=0,k=!1,C=!1,b=0,x=0,S=0,y=-1,D=c0,R=0,N=null,M="",j="",F=!1,V=0;function te(ue,ye){const ze=Math.min(ue.length,ye.length);let it=0;for(;it<ze&&ue.charCodeAt(it)===ye.charCodeAt(it);)it++;return it}function de(ue){const ye=te(M,ue);return M=ue,ye>j.length&&(j=ue.slice(0,ye)),j.length>ue.length&&(j=ue),j}const Q=()=>(m||(m=new Float32Array(ph)),m),ge=()=>{g=0},oe=ue=>{const ye=Q(),ze=ue.length;if(ze>=ph){ye.set(ue.subarray(ze-ph)),g=ph;return}if(g+ze<=ph){ye.set(ue,g),g+=ze;return}const it=g+ze-ph;ye.copyWithin(0,it,g),g-=it,ye.set(ue,g),g+=ze},me=()=>{N&&(clearTimeout(N),N=null)},$e=()=>{me(),w=!1,k=!1,C=!1,D=c0,M="",j="",F=!1,V=0,ge()},he=()=>{if(t||!w||C||k||N)return;if(g<t$){N=setTimeout(()=>{N=null,he()},D);return}const ue=performance.now()-b;if(ue<D&&b!==0){N=setTimeout(()=>{N=null,he()},D-ue);return}if(XC||Eh||i.partialsEnabled&&!i.partialsEnabled())return;const ye=Q(),ze=new Float32Array(g);ze.set(ye.subarray(0,g)),x+=1,S=x,k=!0,R=performance.now(),b=R,e.postMessage({type:"transcribe-partial",audio:ze,seq:x},[ze.buffer])},W=ue=>ue.length===0?Promise.resolve():Eh?(mt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(ye=>{c.push(ye),x+=1;const ze=x;y=ze,e.postMessage({type:"transcribe",audio:ue,seq:ze},[ue.buffer])}),X=ue=>{const ye=W(ue);return f.add(ye),ye.finally(()=>{f.delete(ye)}),ye},U=ue=>{var ye,ze,it,ve,J;if(ue.data.type==="result"){const Pe=ue.data.text,ke=ue.data.seq??0;ke&&ke<y&&mt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ke,latestFinalSeq:y}),!t&&Pe&&i.onFinal(Pe),(ye=c.shift())==null||ye()}else if(ue.data.type==="partial"){const Pe=ue.data.seq??0,ke=ue.data.text??"",Se=performance.now()-R;k=!1,Se>=h0?(C=!0,mt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Se),seq:Pe})):Se>=u0&&(D=Math.min(D*2,d0),mt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Se),newIntervalMs:D,seq:Pe})),F||(F=!0,Se>i$&&D<500&&(D=500,mt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Se),newIntervalMs:500})));const Ee=Pe!==S||Pe<=y;if(!t&&!Ee&&ke){const et=de(ke);et&&((ze=i.onPartial)==null||ze.call(i,et),V===0&&(V=performance.now(),mt.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-T)})))}he()}else if(ue.data.type==="partial-error"){const Pe=performance.now()-R;k=!1,Pe>=h0?(C=!0,mt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Pe),seq:ue.data.seq})):Pe>=u0&&(D=Math.min(D*2,d0),mt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Pe),newIntervalMs:D,seq:ue.data.seq})),mt.warn("speech","partial encode failed",{error:ue.data.error,seq:ue.data.seq}),he()}else ue.data.type==="error"?(t||i.onError(ue.data.error),(it=c.shift())==null||it()):ue.data.type==="status"?(t||(ve=i.onModelStatus)==null||ve.call(i,ue.data.status,ue.data.message),ue.data.status==="ready"&&(Bo=!0,Js=!1)):ue.data.type==="progress"&&(t||(J=i.onProgress)==null||J.call(i,ue.data.pct))};e.addEventListener("message",U);const ee=ue=>{var ye,ze;if(!t){for(mt.warn("speech","createRecognition: worker death event",ue),(ye=i.onStatusChange)==null||ye.call(i,"restarting");c.length;)(ze=c.shift())==null||ze();if(f.clear(),me(),k=!1,ue.respawned){try{e.removeEventListener("message",U)}catch{}e=Pv(),e.addEventListener("message",U)}}};return Lb.add(ee),{start:async()=>{if(!t){if(Eh){i.onError("Speech recognition disabled — please reload the app.");return}!Bo&&!Js&&(Js=!0,mt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),mt.info("speech","createRecognition.start: initializing VAD",{modelReady:Bo,modelLoading:Js});try{const ue=new URL("vad/",document.baseURI).href;mt.info("speech","vad: asset base resolved",{vadBase:ue}),FD();const ye=i.inputDeviceId||null,ze={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};ye&&(ze.deviceId={exact:ye}),mt.info("speech","getUserMedia",{hasDeviceId:!!ye,deviceIdPrefix:ye?ye.slice(0,8):null});const it=await navigator.mediaDevices.getUserMedia({audio:ze});s=it,l=new AudioContext;for(const ve of it.getAudioTracks())ve.addEventListener("ended",()=>{t||(mt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(s),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ve){mt.warn("speech","analyser init failed",{error:ve instanceof Error?ve.message:String(ve)}),a=null,p=null}n=await ZD.MicVAD.new({audioContext:l,getStream:async()=>it,resumeStream:async()=>it,pauseStream:async()=>{},baseAssetPath:ue,onnxWASMBasePath:ue,model:"v5",positiveSpeechThreshold:KC,negativeSpeechThreshold:YC,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ve,J)=>{var Pe;t||((Pe=i.onFrame)==null||Pe.call(i,ve),w&&(oe(J),he()))},onSpeechStart:()=>{var ve;t||($e(),w=!0,T=performance.now(),(ve=i.onSpeechStart)==null||ve.call(i))},onSpeechEnd:ve=>{var J;t||((J=i.onStatusChange)==null||J.call(i,"transcribing"),$e(),X(ve))},onVADMisfire:()=>{var ve,J;t||((ve=i.onStatusChange)==null||ve.call(i,"idle"),$e(),(J=i.onMisfire)==null||J.call(i))}}),mt.info("speech","vad: ort wasm files loaded",{files:GD()}),n.start()}catch(ue){const ye=ue instanceof Error?ue.message:"Microphone access denied",ze=ue instanceof Error?ue.stack:"";if(mt.error("speech","createRecognition.start: VAD init failed",{error:ye,stack:ze}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(s){try{s.getTracks().forEach(it=>it.stop())}catch{}s=null}if(l){try{await l.close()}catch{}l=null}i.onError(ye)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for($e();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(s){try{s.getTracks().forEach(ue=>ue.stop())}catch{}s=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ue,ye)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ue,negativeSpeechThreshold:ye})}catch(ze){mt.warn("speech","setVadThresholds failed",{error:ze instanceof Error?ze.message:String(ze)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,$e(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(s){try{s.getTracks().forEach(ue=>ue.stop())}catch{}s=null}Lb.delete(ee),e.removeEventListener("message",U)}}}let Kf=null;const zb=new Set,Bb=new Set;function l$(){for(const i of zb)try{i()}catch{}}function Gb(){for(const i of Bb)try{i()}catch{}}function c$(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function d$(i){if(!window.speechSynthesis)return;const e=c$(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Kf=performance.now(),l$()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Kf=null,Gb())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Kf=null,Gb())},window.speechSynthesis.speak(t)}function QC(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Kf=null,Gb())}function ek(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function u$(){return Kf}function h$(i){return zb.add(i),()=>{zb.delete(i)}}function p$(i){return Bb.add(i),()=>{Bb.delete(i)}}function f$(i){ek()&&(i.setVadThresholds(p0,f0),mt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=h$(()=>{i.setVadThresholds(p0,f0),mt.info("voice","tts.duck.on")}),t=p$(()=>{i.setVadThresholds(KC,YC),mt.info("voice","tts.duck.off")});return()=>{e(),t()}}const m$=[{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 g$(i){const e=i.trim();return m$.find(t=>t.match.test(e))??null}const v$=4e4;let xd=null;function Th(){xd&&clearTimeout(xd),xd=setTimeout(()=>{xd=null,Ht.getState().stopRecording()},v$)}function jg(){xd&&(clearTimeout(xd),xd=null)}let ac=null,tc=null;const _$=.04,b$=.3;let Rv=0,Fb=0;function w$(i){tc!==null&&cancelAnimationFrame(tc);const e=()=>{if(ac===null||Ht.getState().submitCountdownStartAt===null){tc=null;return}const t=performance.now();if(t-Fb<200&&Rv>b$){const s=t-i;mt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Rv.toFixed(2),msIntoCountdown:Math.round(s)}),Zl(),Th();return}const n=x$();if(n){const s=new Uint8Array(n.fftSize);n.getByteTimeDomainData(s);let l=0;for(let a=0;a<s.length;a++){const c=(s[a]-128)/128;l+=c*c}const p=Math.sqrt(l/s.length);if(p>_$){const a=t-i;mt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Zl(),Th();return}}tc=requestAnimationFrame(e)};tc=requestAnimationFrame(e)}function g0(i){ac&&clearTimeout(ac);const e=Ht.getState().submitDelayMs,t=performance.now();Ht.setState({submitCountdownStartAt:t}),ac=setTimeout(()=>{var s;ac=null,Ht.setState({submitCountdownStartAt:null});const n=Tt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(s=_i.getState().chats[i])==null?void 0:s.pendingVoiceText;l&&(_i.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),_i.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){mt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}Th()},e),w$(t)}function Zl(){tc!==null&&(cancelAnimationFrame(tc),tc=null),ac&&(clearTimeout(ac),ac=null),Ht.getState().submitCountdownStartAt!==null&&Ht.setState({submitCountdownStartAt:null})}let ts=null,Ys=null,Sf=null;function x$(){var i;return((i=ts==null?void 0:ts.getAnalyser)==null?void 0:i.call(ts))??null}const Ng=1e4;let Yf=null;function Mg(){Yf&&(clearTimeout(Yf),Yf=null)}let fv=null,mv=null;function Og(){fv=null,mv&&(mv(),mv=null)}const y$=1500,S$=9e4;let Cf=0,gv=null,Hb=-1;function kf(){gv&&(clearTimeout(gv),gv=null,Hb=-1)}const C$=1800*1e3;let Xf=null,Lg=!1;function v0(){Xf&&(clearTimeout(Xf),Xf=null)}const k$=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ht=Un((i,e)=>{function t(){v0(),Xf=setTimeout(()=>{if(Xf=null,e().isRecording||ts){t();return}mt.info("voice","model idle timeout: releasing worker"),kf(),Cf++,o$(),i({modelStatus:"idle",loadingProgress:0,error:null,errorKind:null})},C$)}function n(){return e().modelStatus==="error"?e().resetAndRetryModel():e().initModel(),new Promise((s,l)=>{let p=()=>{};const a=c=>c.modelStatus==="ready"?(p(),s(),!0):c.modelStatus==="error"?(p(),l(new Error(c.error??"Model load failed")),!0):!1;a(e())||(p=Ht.subscribe(c=>{a(c)}))})}return{isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;mt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const s=++Cf,l=()=>{s===Cf&&(kf(),Hb=s,gv=setTimeout(()=>{Hb===s&&e().modelStatus==="loading"&&(mt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},S$))};l(),s$((p,a)=>{s===Cf&&(p==="ready"?(kf(),mt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null}),!e().isRecording&&!ts&&t()):p==="error"?(kf(),mt.error("voice","modelStatus -> error",{msg:a}),i({modelStatus:"error",error:a,errorKind:"load"})):(l(),i({modelStatus:"loading"})))},p=>{s===Cf&&(l(),i({loadingProgress:Math.round(p)}))})},resetAndRetryModel:()=>{mt.info("voice","mic.gate.retry"),kf(),r$(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(s,l)=>{if(e().isRecording)return;if(ts){mt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Zv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}if(e().modelStatus!=="ready"){if(Lg)return;Lg=!0,n().then(()=>{Lg=!1,e().startRecording(s,l)}).catch(a=>{Lg=!1;const c=a instanceof Error?a.message:String(a);mt.error("voice","startRecording: model load failed",{error:c}),Ze.error(`Could not load speech model: ${c}`)});return}v0();const p=a=>{try{const c=ZC({inputDeviceId:a,onStatusChange:f=>{i(f==="transcribing"?{statusPill:"transcribing"}:f==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:f=>{e().partialsEnabled&&i({lastPartial:f})},partialsEnabled:()=>e().partialsEnabled,onFrame:f=>{Rv=f.isSpeech,Fb=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),jg(),Zl(),ek()){const m=u$(),g=m!==null?performance.now()-m:null;QC(),i({lastBargeInAt:performance.now()}),mt.info("voice","barge-in",{tabId:s,utteranceOffsetMs:g})}else mt.debug("voice","barge-in.no-op",{tabId:s})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),Th();const f=e().lastBargeInAt;f!==null&&performance.now()-f<600&&mt.warn("voice","barge-in.misfire",{tabId:s,sinceBargeInMs:Math.round(performance.now()-f)})},onFinal:f=>{var k;Th();const m=f.trim();if(!m||k$.has(m)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Sf){Sf(m),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((k=Tt.getState().tabs.find(C=>C.id===s))==null?void 0:k.status)==="dormant"){_i.getState().setPendingVoiceText(s,m),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&g0(s);const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}const w=g$(m);if(w){mt.info("voice","voice-command",{tabId:s,label:w.label,transcript:m}),window.api.pty.write({tabId:s,data:w.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Zl();const C=window;C.__transcripts&&(C.__transcripts.push({tabId:s,text:m}),C.__transcripts.length>500&&C.__transcripts.shift());return}window.api.pty.write({tabId:s,data:m}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&g0(s);const T=window;T.__transcripts&&(T.__transcripts.push({tabId:s,text:m}),T.__transcripts.length>500&&T.__transcripts.shift())},onError:f=>{mt.error("voice","recognition error",{err:f}),Zl(),i({error:f,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Ys==null||Ys(),Ys=null,jg(),ts==null||ts.destroy(),ts=null,Sf=null,Ze.error(`Microphone error: ${f}`)},onModelStatus:f=>{f==="ready"?i({modelStatus:"ready",loadingProgress:100}):f==="loading"&&i({modelStatus:"loading"})},onProgress:f=>i({loadingProgress:Math.round(f)})});ts=c,Sf=(l==null?void 0:l.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Th(),c.start().then(()=>{ts===c&&(Ys==null||Ys(),Ys=f$(c))}).catch(f=>{const m=f instanceof Error?f.message:String(f);mt.error("voice","handle.start() failed",{error:m}),Ze.error(`Could not start mic: ${m}`)})}catch(c){i({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,c,f;return((f=(c=(a=window.api)==null?void 0:a.voice)==null?void 0:c.getDevicePref)==null?void 0:f.call(c))??Promise.resolve(null)}).then(a=>p((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{mt.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),p(null)})},stopRecording:()=>{const s=ts;s&&(jg(),Zl(),Rv=0,Fb=0,Ys==null||Ys(),Ys=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t(),s.stop().finally(()=>{s.destroy(),ts===s&&(ts=null,Sf=null),e().hotkeyState==="stopping"&&(Mg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const s=ts;if(!s)return;jg(),Ys==null||Ys(),Ys=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await s.stop()}catch(a){mt.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}s.destroy(),ts===s&&(ts=null);const{useSessions:l}=await Oi(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>oD);return{useSessions:a}},[],import.meta.url),p=l.getState().activeTabId;p&&e().startRecording(p)},setExternalRecording:s=>i({externalRecording:s}),toggleTTS:()=>{const s=!e().ttsEnabled;i({ttsEnabled:s}),Promise.resolve().then(()=>{var l,p,a;return(a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.setTtsEnabled)==null?void 0:a.call(p,s)}).catch(l=>{mt.warn("voice","setTtsEnabled failed",{error:l instanceof Error?l.message:String(l)})})},setAutoSubmit:s=>i({autoSubmit:s}),setSubmitDelayMs:s=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(s)))}),cancelSubmit:()=>Zl(),setPartialsEnabled:s=>{e().partialsEnabled!==s&&(i({partialsEnabled:s}),s||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:s=>{e().permissionState!==s&&(mt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:s}),i({permissionState:s}))},setLevelMeterEnabled:s=>{e().levelMeterEnabled!==s&&i({levelMeterEnabled:s})},setTurnDetectorRuntimeState:s=>{e().turnDetectorState!==s&&(i({turnDetectorState:s}),s==="load_failed"?mt.warn("voice-turn","voice-turn.load_failed"):s==="runtime_error"?mt.warn("voice-turn","voice-turn.runtime_error"):s==="disabled"&&mt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:s=>{e().wizardArmed!==s&&i({wizardArmed:s})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:s,source:l,mode:p,tabId:a})=>{const c=e(),{canRecord:f,reason:m}=tk(c);if(s==="down"){if(m==="error"||m==="load-timeout"){c.resetAndRetryModel(),mt.info("voice-hotkey","down.retry",{source:l,reason:m});return}if(!f&&m!=="loading"){mt.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:m});return}if(c.hotkeyState==="recording"||c.isRecording){(p==="toggle"||l==="global")&&(i({hotkeyState:"stopping"}),Mg(),Yf=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:Ng}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Ng),c.stopRecording());return}if(m==="loading"){c.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),mt.info("voice-hotkey","armed",{source:l,modelStatus:c.modelStatus})),Og(),fv={tabId:a,source:l,mode:p},mv=Ht.subscribe((g,w)=>{if(fv&&g.modelStatus==="ready"&&w.modelStatus!=="ready"&&g.hotkeyState==="armed"){const T=fv;if(Og(),!T.tabId){mt.warn("voice-hotkey","armed-promote-no-tab",{source:T.source}),i({hotkeyState:"idle"});return}mt.info("voice-hotkey","armed-promote",T),i({hotkeyState:"recording"}),Ht.getState().startRecording(T.tabId)}});return}if(!a){mt.warn("voice-hotkey","no-active-tab",{source:l});return}mt.info("voice-hotkey","start",{source:l,mode:p,tabId:a}),c.startRecording(a),e().isRecording?i({hotkeyState:"recording"}):(mt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(p!=="hold"||l==="global")){if(c.hotkeyState==="armed"){Og(),mt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),Mg(),Yf=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:Ng}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},Ng),c.stopRecording())}},destroyHotkey:()=>{const s=e();if(Og(),Zl(),s.hotkeyState==="recording"){mt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{s.stopRecording()}catch{}}else(s.hotkeyState==="armed"||s.hotkeyState==="stopping")&&(Mg(),i({hotkeyState:"destroyed"}))}}}),E$=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),tk=i=>Zv()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};typeof window<"u"&&Promise.resolve().then(()=>{var i,e,t;return(t=(e=(i=window.api)==null?void 0:i.voice)==null?void 0:e.getTtsEnabled)==null?void 0:t.call(e)}).then(i=>{typeof i=="boolean"&&Ht.setState({ttsEnabled:i})}).catch(i=>{mt.warn("voice","getTtsEnabled failed",{error:i instanceof Error?i.message:String(i)})});if(typeof window<"u"){const i=window;i.__voice=Ht,i.__transcripts=[]}const rm=6e4,T$=3e5,D$=.25,$$=5e3,om=Un(()=>({data:null,refreshing:!1}));let _0=!1,vv=null,N_=rm,zg=!1,nl=null;function A$(i,e){if(i.kind==="ok")return{delayMs:rm,nextBackoffMs:rm};const t=Math.min(e*2,T$),n=t*D$;let s=t+(Math.random()*2-1)*n;const l=i.kind==="meter_rate_limited"?i.retryAfterMs:void 0;return typeof l=="number"&&Number.isFinite(l)&&l>s&&(s=l),{delayMs:s,nextBackoffMs:t}}function b0(){return vC(window.api.billing.fetch(),$$,"billing.fetch")}function w0(i){om.setState({data:i,refreshing:!1})}async function tx(){om.setState({refreshing:!0});let i=rm;try{const e=await b0();nl&&(nl.cancel(),nl=null),w0(e);const{delayMs:t,nextBackoffMs:n}=A$(e,N_);N_=n,i=t}catch(e){N_=rm,om.setState({refreshing:!1});const t=_C({error:e,retry:b0,onRetrySuccess:n=>{nl=null,w0(n)},onStillFailing:n=>{nl=null,zg||(zg=!0,Ze.warn(`Billing usage fetch: ${n}`))}});if(t)nl=t;else if(!zg){zg=!0;const n=e instanceof Error?e.message:String(e);Ze.warn(`Billing usage fetch failed: ${n}`)}}vv=setTimeout(tx,i)}function I$(){_0||(_0=!0,tx())}function ik(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function P$(){vv!==null&&(clearTimeout(vv),vv=null),nl&&(nl.cancel(),nl=null),tx()}function am(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),s=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${s} ${e[1]}`:`${n} ${s}`}function lm(i){const e=/(opus|sonnet|haiku|fable)/i.exec(i);return e?e[1].toLowerCase():null}const Bg=new Map,R$=3e4;function ix(i){const[e,t]=O.useState(()=>{var n;return i?((n=Bg.get(i))==null?void 0:n.value)??null:null});return O.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=Bg.get(i);if(l&&Date.now()-l.ts<R$){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;Bg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;Bg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}const j$="~/.claude/session-manager/ui-chrome-prefs.json",nk=Sa(j$),N$=180,M$=480,Wb=252,ud={sidebarWidth:Wb,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function Ub(i){return Math.min(M$,Math.max(N$,i))}let ic=null,_v={};function O$(i){const e=()=>{const t=i(),n={sidebarWidth:t.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed,collapsedGroups:t.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed,tourCompletedAt:t.tourCompletedAt,density:t.density};nk.patch(n).catch(()=>{})};i().hydrated||!ic?e():ic.then(e)}function fh(i,e,t){i(t),!e().hydrated&&ic&&Object.assign(_v,t),O$(e)}const Wn=Un((i,e)=>({...ud,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():ic||(ic=(async()=>{try{const t=await nk.read();if(Object.keys(t).length>0){i({sidebarWidth:typeof t.sidebarWidth=="number"?Ub(t.sidebarWidth):ud.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed??ud.sidebarCollapsed,collapsedGroups:Array.isArray(t.collapsedGroups)?t.collapsedGroups:ud.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed??ud.learningPanelCollapsed,tourCompletedAt:typeof t.tourCompletedAt=="number"?t.tourCompletedAt:ud.tourCompletedAt,density:t.density==="compact"?"compact":ud.density,..._v,hydrated:!0});return}}catch{}i({..._v,hydrated:!0})})().finally(()=>{ic=null,_v={}}),ic),setSidebarWidth:t=>fh(i,e,{sidebarWidth:Ub(t)}),setSidebarCollapsed:t=>fh(i,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>fh(i,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>fh(i,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>fh(i,e,{tourCompletedAt:t}),setDensity:t=>fh(i,e,{density:t})})),L$=52;function z$(i){return new Set(i.filter(e=>e==="Workspace"||e==="Claude Code"||e==="Session Manager"))}function B$(){const i=Tt(t=>{var n;return((n=t.tabs.find(s=>s.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Hr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(s=>s.status==="running"&&(!i||s.cwd===i))})}}function G$({active:i,onNavigate:e,onNewSession:t}){const n=Wn(Q=>Q.hydrated),s=Wn(Q=>Q.hydrate);O.useEffect(()=>{n||s()},[n,s]);const l=Wn(Q=>Q.collapsedGroups),p=Wn(Q=>Q.setCollapsedGroups),a=O.useMemo(()=>z$(l),[l]),c=O.useCallback(Q=>{const ge=new Set(a);ge.has(Q)?ge.delete(Q):ge.add(Q),p(Array.from(ge))},[a,p]),f=Wn(Q=>Q.sidebarCollapsed),m=Wn(Q=>Q.setSidebarCollapsed),g=O.useCallback(()=>{m(!f)},[f,m]),w=Tt(Q=>Q.tabs),T=Tt(Q=>Q.activeTabId),k=w.find(Q=>Q.id===T)??null,C=B$(),b=ki(Q=>Q.navFace),x=dD(b),S=x.filter(Q=>Q.group==="Workspace"),y=x.filter(Q=>Q.group==="Claude Code"),D=x.filter(Q=>Q.group==="Session Manager"),R=b==="home"&&!f,N=Wn(Q=>Q.sidebarWidth),M=Wn(Q=>Q.setSidebarWidth),[j,F]=O.useState(N),V=O.useRef(j);V.current=j,O.useEffect(()=>{F(N)},[N]);const te=O.useCallback(Q=>{Q.preventDefault();const ge=Q.clientX,oe=V.current;let me=oe;const $e=W=>{me=Ub(oe+(W.clientX-ge)),F(me)},he=()=>{window.removeEventListener("pointermove",$e),window.removeEventListener("pointerup",he),document.body.style.cursor="",document.body.style.userSelect="",M(me)};window.addEventListener("pointermove",$e),window.addEventListener("pointerup",he),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[M]),de=O.useCallback(()=>{F(Wb),M(Wb)},[M]);return d.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:f?L$:j},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[d.jsx(F$,{tab:k,navFace:b,onNewSession:t,rail:f,onToggleRail:g}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:f?"4px":"8px"},children:R?d.jsxs(d.Fragment,{children:[d.jsx(M_,{label:"Workspace",desc:D_.Workspace,collapsed:a.has("Workspace"),count:S.length,onToggle:()=>c("Workspace")}),!a.has("Workspace")&&S.map(Q=>d.jsx(Gg,{item:Q,active:i===Q.key,live:Q.liveKind?C[Q.liveKind]:!1,onClick:()=>e(Q.key),rail:!1},Q.key)),d.jsx(M_,{label:"Claude Code",desc:D_["Claude Code"],collapsed:a.has("Claude Code"),count:y.length,onToggle:()=>c("Claude Code")}),!a.has("Claude Code")&&y.map(Q=>d.jsx(Gg,{item:Q,active:i===Q.key,live:!1,onClick:()=>e(Q.key),rail:!1},Q.key)),d.jsx(M_,{label:"Session Manager",desc:D_["Session Manager"],collapsed:a.has("Session Manager"),count:D.length,onToggle:()=>c("Session Manager")}),!a.has("Session Manager")&&D.map(Q=>d.jsx(Gg,{item:Q,active:i===Q.key,live:!1,onClick:()=>e(Q.key),rail:!1},Q.key))]}):d.jsx("div",{className:"pt-2",children:x.map(Q=>d.jsx(Gg,{item:Q,active:i===Q.key,live:Q.liveKind?C[Q.liveKind]:!1,onClick:()=>e(Q.key),rail:f},Q.key))})}),d.jsx(H$,{rail:f,navFace:b}),!f&&d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:te,onDoubleClick:de,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function F$({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:s}){const l=(i==null?void 0:i.label)??"no session",p=ix((i==null?void 0:i.cwd)??null);return n?d.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[d.jsx("button",{onClick:t,"data-testid":"tour-new-session",title:"Open / Start Project",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:d.jsx(Fr,{name:"plus",size:15,stroke:1.8})}),d.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:d.jsx(Fr,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?d.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),d.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(Fr,{name:"chevron",size:13,stroke:1.8})})})]}),d.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:d.jsxs("button",{onClick:t,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[d.jsx(Fr,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):d.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),d.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:d.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:d.jsx(Fr,{name:"chevron",size:13,stroke:1.8})})})]}),d.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[d.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),d.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),d.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),d.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:d.jsxs("button",{onClick:t,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[d.jsx(Fr,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function M_({label:i,desc:e,collapsed:t,count:n,onToggle:s}){return d.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[d.jsxs("button",{onClick:s,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[d.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),d.jsx("span",{className:"flex-1",children:i}),t&&d.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&d.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:e})]})}function Gg({item:i,active:e,live:t,onClick:n,rail:s}){return d.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&d.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),d.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:d.jsx(Fr,{name:i.icon,size:17,stroke:1.6})}),!s&&d.jsxs("span",{className:"flex-1 min-w-0",children:[d.jsx("span",{className:"block truncate",children:i.label}),i.hint&&d.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!s&&t&&d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&t&&d.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function H$({rail:i,navFace:e}){const t=Ht(c=>c.isRecording),n=Tt(c=>c.tabs),s=Tt(c=>c.activeTabId),l=n.find(c=>c.id===s)??null,[p,a]=O.useState(null);return O.useEffect(()=>{let c=!1;if(!(l!=null&&l.presetId)){a(null);return}return pC(l.presetId).then(f=>{c||a((f==null?void 0:f.model)??null)}).catch(()=>{c||a(null)}),()=>{c=!0}},[l==null?void 0:l.presetId]),i?d.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):d.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"}),(t||e==="project")&&d.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${am(p)}`:"Claude Code"})]})}function W$(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function U$(i,e,t){return{tabId:i,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function V$(i,e,t){const n=Date.now(),s={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,c)=>a.length>c?a.slice(0,c-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];s.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,c=a.input,f={};for(const m of["command","file_path","pattern","url","query","subagent_type","description"])c&&m in c&&(f[m]=c[m]);if(s.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const m=a.input,g=["Edit","Write","NotebookEdit"].includes(a.name),w=typeof(m==null?void 0:m.file_path)=="string"?m.file_path:void 0,T=typeof(m==null?void 0:m.command)=="string"?m.command:void 0,k=w?w.split("/").pop()??w:T?p(T,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:w??T,toolName:a.name}),g&&w&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(w.split("/").pop()??w,34)}`,target:w,toolName:a.name})}break}case"plan":{const a=e.data,c=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);s.plans=[{at:n,content:c??""},...i.plans].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"plan-revision",at:n,label:"Plan revised"});break}case"agent_spawn":{const a=e.data;s.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,c=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,m=a.output_tokens??a.outputTokens??0,g=c+f+m;s.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+m,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(g/1e3)>Math.floor(c/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(g/1e3)}k tokens`});break}case"tool_result":{const a=e.data;s.agents=W$(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:s,newActivity:l}}const bv=Un((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,s)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:U$(t,n,s)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:s}).then(async a=>{const c=e().tabs[t];if(!c)return;if(!a.ok){const{toast:m}=await Oi(async()=>{const{toast:g}=await Promise.resolve().then(()=>mC);return{toast:g}},void 0,import.meta.url);m.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...c,path:null}}});return}i({tabs:{...e().tabs,[t]:{...c,path:a.path}}});const f=await window.api.transcripts.buffer(t);e().ingestBatch(t,f,{replay:!0})}).catch(a=>console.error("[live] transcripts.subscribe failed:",t,a))},unsubscribe:t=>{const n={...e().refs};if(!n[t])return;if(n[t]--,n[t]>0){i({refs:n});return}delete n[t];const s=e().unsubs[t];s==null||s();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,s)=>{e().ingestBatch(t,[n],s)},ingestBatch:(t,n,s)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const c of n){const{next:f,newActivity:m}=V$(p,c,s);p=f,a=a.concat(m)}if(a.length>0){let c=l.activitySeq;const f=a.map(m=>({...m,id:++c}));p={...p,activitySeq:c,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function q$(i){const e=bv(s=>s.subscribe),t=bv(s=>s.unsubscribe),n=bv(s=>i?s.tabs[i.id]:void 0);return O.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>t(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,t]),n}function sk(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),s=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${s}h`:s>0?`${s}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function Vb(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function x0(i,e){const t=Vb(e);if(t==null)return`${i} — usage unavailable`;const n=sk((e==null?void 0:e.resets_at)??null),s=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${s} — click to open Home`}function $B(i,e){return i?i==="session"||i==="five_hour"?"Session · 5h":i==="weekly_all"?"Weekly · all models":i==="weekly_scoped"?"Weekly · scoped":i:null}const rk=O.createContext(null);function K$({panelId:i,children:e}){return d.jsx(rk.Provider,{value:i,children:e})}function Qv(i){const e=O.useContext(rk),t=i??e;return ki(n=>t==null||n.focusedPanelId===t)}function nx(i){const e=Qv(i),t=O.useRef(e);return t.current=e,t}const Y$=5e3;let bd=null;const qb=new Set;let O_=0,Jf=null;function X$(){qb.forEach(i=>i())}async function jv(){try{bd=await window.api.schedule.sessionSlots(),X$()}catch{}}const J$=0,Z$=10;async function AB(i){bd||await jv();const e=bd?bd.min:J$,t=bd?bd.max:Z$,n=Math.min(t,Math.max(e,Math.round(i)));await window.api.schedule.setSessionSlots(n),await jv()}function Q$(){Jf==null&&(jv(),Jf=setInterval(()=>{jv()},Y$))}function eA(){Jf!=null&&(clearInterval(Jf),Jf=null)}function sx(i){const e=Qv(i),[,t]=O.useState(0);return O.useEffect(()=>{const n=()=>t(s=>s+1);return qb.add(n),()=>{qb.delete(n)}},[]),O.useEffect(()=>{if(e)return O_+=1,Q$(),()=>{O_-=1,O_<=0&&eA()}},[e]),bd}let xh=null;const Kb=new Set;let L_=0,wv=null,Yb=!1;const tA=360*60*1e3;let xv=null;function y0(i){xh=i.check||!(xh!=null&&xh.check)?i:{...i,check:xh.check},Kb.forEach(e=>e())}function iA(){if(Yb)return;Yb=!0,wv=window.api.updater.onStatus(y0);const i=()=>{window.api.updater.status().then(y0).catch(()=>{})};i(),xv=setInterval(i,tA)}function nA(){Yb=!1,xv!=null&&(clearInterval(xv),xv=null),wv&&(wv(),wv=null)}function sA(){const[,i]=O.useState(0);return O.useEffect(()=>{const e=()=>i(t=>t+1);return Kb.add(e),L_+=1,iA(),()=>{Kb.delete(e),L_-=1,L_<=0&&nA()}},[]),xh}function rA({total:i,inUse:e,size:t}){const n=Math.min(Math.max(e,0),i),s=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return d.jsx(d.Fragment,{children:Array.from({length:i},(l,p)=>d.jsx("span",{"data-testid":"slot-dot","data-filled":p<n?"true":"false",className:`${s} ${p<n?"bg-accent border-accent":"bg-bg border-line"}`},p))})}function oA({onNavigate:i}){const e=Tt(oe=>oe.tabs),t=Tt(oe=>oe.activeTabId),n=e.find(oe=>oe.id===t)??null,s=q$(n),l=(s==null?void 0:s.lastEventAt)??0,p=om(oe=>oe.data),a=Hr(oe=>{var me;return((me=oe.snapshot)==null?void 0:me.paused)??null}),c=ix((n==null?void 0:n.cwd)??null),f=sx(),m=sA(),g=(m==null?void 0:m.check)??null,w=hs(oe=>oe.show),[,T]=O.useState(0);O.useEffect(()=>{const oe=setInterval(()=>T(me=>me+1),6e4);return()=>clearInterval(oe)},[]);const k=async()=>{const oe=(m==null?void 0:m.latest)??"";try{const me=await window.api.updater.install(!1),$e=(me==null?void 0:me.status)??await window.api.updater.status();($e==null?void 0:$e.state)==="deferred"&&w("info",`Update v${oe} will install when ${$e.busyReason??"running jobs"} finish`)}catch(me){w("error",me instanceof Error?me.message:String(me))}},C=(s==null?void 0:s.todos)??[],[b,x]=O.useState(!1),S=O.useRef(null);O.useEffect(()=>{if(!b)return;const oe=me=>{S.current&&!S.current.contains(me.target)&&x(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[b]),O.useEffect(()=>{C.length===0&&x(!1)},[C.length]);const y=ik(p),D=(y==null?void 0:y.usage.five_hour)??null,R=(y==null?void 0:y.usage.seven_day)??null,N=Vb(D),M=Vb(R),j=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",F=l>0?cA(Date.now()-l):"—",V=(f==null?void 0:f.total)??5,te=f?Math.min(Math.max(f.inUse,0),f.total):0,de=f?`${te} / ${V}`:`— / ${V}`,Q=f&&f.holders.length>0?`
|
|
2931
2931
|
`+f.holders.slice(0,5).map(oe=>oe.owner).join(`
|
|
2932
|
-
`):"",ge=`${de} Claude sessions running${Q}`;return d.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[d.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:j?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${j?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:j?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:x0("Session (5h window)",D),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:N!=null?`${N}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:x0("Weekly window (all models)",R),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:M!=null?`${M}%`:"—"})]}),a&&d.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&d.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,c&&d.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),d.jsxs("span",{className:"text-fg-faint",children:["last activity: ",d.jsx("span",{className:"text-fg-dim",children:F})]}),C.length>0&&d.jsx(aA,{ref:S,todos:C,open:b,onToggle:()=>x(oe=>!oe)}),d.jsx("span",{className:"flex-1"}),d.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:ge,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(rA,{total:V,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),(m==null?void 0:m.state)==="ready"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",m.latest]}):(m==null?void 0:m.state)==="deferred"?d.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"?d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",m.latest,"…"]}):g!=null&&g.behind&&g.latest&&g.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${g.current} → v${g.latest}`,"data-testid":"footer-version",onClick:()=>{const oe=g.downloadUrl;oe&&window.api.shell.open({as:"external",url:oe}).catch(()=>{w("error",`Couldn't open URL: ${oe}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.latest?d.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",g.current," → v",g.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.130.1"]})]})}const aA=O.forwardRef(function({todos:e,open:t,onToggle:n},s){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return d.jsxs("div",{ref:s,className:"relative",children:[d.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[d.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),d.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),d.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),d.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&d.jsx("div",{className:`absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 ${yn.dialog}`,"data-testid":"footer-todos-popover",children:d.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>d.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[d.jsx(lA,{status:p.status}),d.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function lA({status:i}){return i==="completed"?d.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?d.jsx("span",{className:"w-3 shrink-0",children:d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):d.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function cA(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function dA({onClose:i,onSent:e}){const t=Tt(M=>M.tabs),[n,s]=O.useState(""),[l,p]=O.useState(()=>Object.fromEntries(t.map(M=>[M.id,!0]))),[a,c]=O.useState(!1),[f,m]=O.useState({}),g=O.useRef(null),w=O.useRef(e);O.useEffect(()=>{w.current=e},[e]),O.useEffect(()=>{p(M=>{const j={};for(const F of t)j[F.id]=M[F.id]??!0;return j})},[t]),O.useEffect(()=>{var M;(M=g.current)==null||M.focus()},[]),O.useEffect(()=>window.api.pty.onWriteError(j=>{m(F=>j.tabId in F?{...F,[j.tabId]:"skipped"}:F)}),[]),O.useEffect(()=>{if(Object.keys(f).length===0)return;const M=Object.values(f).filter(F=>F==="sent").length,j=window.setTimeout(()=>w.current(M),1500);return()=>window.clearTimeout(j)},[f]);const T=t.filter(M=>l[M.id]).map(M=>M.id),k=T.length,C=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!C,x=()=>{if(!b)return;c(!0);const M=Tt.getState().tabs,j=new Set(M.map(V=>V.id)),F={};for(const V of T)j.has(V)?(window.api.pty.write({tabId:V,data:n+"\r"}),F[V]="sent"):F[V]="skipped";m(F),c(!1)},S=M=>{if(M.key==="Escape"){M.preventDefault(),M.stopPropagation(),i();return}M.key==="Enter"&&(M.metaKey||M.ctrlKey)&&(M.preventDefault(),x())},y=t.length>0&&t.every(M=>l[M.id]),D=()=>{const M=!y;p(Object.fromEntries(t.map(j=>[j.id,M])))},R=Object.values(f).some(M=>M==="skipped"),N=C?R?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return d.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),d.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),d.jsx("textarea",{ref:g,value:n,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"}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:y,onChange:D,className:"accent-accent"}),d.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),d.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(M=>d.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:!!l[M.id],onChange:j=>p(F=>({...F,[M.id]:j.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:M.label}),f[M.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[M.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},M.id))})]}),d.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[d.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),d.jsx("button",{onClick:x,disabled:!b,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:N})]})]})}function uA({tabId:i,cwd:e,onClose:t}){const n=qf(k=>k.watchersForTab(i)),s=qf(k=>k.add),l=qf(k=>k.remove),p=O.useRef(null),[a,c]=O.useState(""),[f,m]=O.useState(""),[g,w]=O.useState(!1);O.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),O.useEffect(()=>{const k=C=>{p.current&&!p.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const T=async()=>{const k=f.trim();if(!k||g)return;w(!0);const C=await s({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),C&&(c(""),m(""))};return d.jsxs("div",{ref:p,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[d.jsxs("div",{className:"flex items-center mb-2",children:[d.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),d.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),d.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[d.jsx("input",{value:a,onChange:k=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("input",{value:f,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&T()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),d.jsx("button",{onClick:T,disabled:!f.trim()||g,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),d.jsxs("span",{className:"text-fg-faint",children:["cwd: ",d.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?d.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):d.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const C=k.lines[k.lines.length-1];return d.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),d.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),d.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),d.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:d.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2932
|
+
`):"",ge=`${de} Claude sessions running${Q}`;return d.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[d.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:j?"Connected to Anthropic":"Disconnected",children:[d.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${j?"bg-sage":"bg-fg-faint"}`}),d.jsx("span",{children:j?"connected":"offline"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:x0("Session (5h window)",D),"data-testid":"footer-usage-session",children:["session ",d.jsx("span",{className:"text-fg",children:N!=null?`${N}%`:"—"})]}),d.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:x0("Weekly window (all models)",R),"data-testid":"footer-usage-weekly",children:["weekly ",d.jsx("span",{className:"text-fg",children:M!=null?`${M}%`:"—"})]}),a&&d.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[d.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&d.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,c&&d.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),d.jsxs("span",{className:"text-fg-faint",children:["last activity: ",d.jsx("span",{className:"text-fg-dim",children:F})]}),C.length>0&&d.jsx(aA,{ref:S,todos:C,open:b,onToggle:()=>x(oe=>!oe)}),d.jsx("span",{className:"flex-1"}),d.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:ge,"data-testid":"footer-active-sessions",children:f&&f.total===0?d.jsx("span",{className:"text-fg-faint",children:"pool paused"}):d.jsx(rA,{total:V,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),(m==null?void 0:m.state)==="ready"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{k()},children:["Update ready — restart to install v",m.latest]}):(m==null?void 0:m.state)==="deferred"?d.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"?d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",m.latest,"…"]}):g!=null&&g.behind&&g.latest&&g.channel==="installer"?d.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${g.current} → v${g.latest}`,"data-testid":"footer-version",onClick:()=>{const oe=g.downloadUrl;oe&&window.api.shell.open({as:"external",url:oe}).catch(()=>{w("error",`Couldn't open URL: ${oe}`)})},children:["Download v",g.latest]}):g!=null&&g.behind&&g.latest?d.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",g.current," → v",g.latest]}):d.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.130.2"]})]})}const aA=O.forwardRef(function({todos:e,open:t,onToggle:n},s){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return d.jsxs("div",{ref:s,className:"relative",children:[d.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[d.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),d.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),d.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),d.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&d.jsx("div",{className:`absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 ${yn.dialog}`,"data-testid":"footer-todos-popover",children:d.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>d.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[d.jsx(lA,{status:p.status}),d.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function lA({status:i}){return i==="completed"?d.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?d.jsx("span",{className:"w-3 shrink-0",children:d.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):d.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function cA(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function dA({onClose:i,onSent:e}){const t=Tt(M=>M.tabs),[n,s]=O.useState(""),[l,p]=O.useState(()=>Object.fromEntries(t.map(M=>[M.id,!0]))),[a,c]=O.useState(!1),[f,m]=O.useState({}),g=O.useRef(null),w=O.useRef(e);O.useEffect(()=>{w.current=e},[e]),O.useEffect(()=>{p(M=>{const j={};for(const F of t)j[F.id]=M[F.id]??!0;return j})},[t]),O.useEffect(()=>{var M;(M=g.current)==null||M.focus()},[]),O.useEffect(()=>window.api.pty.onWriteError(j=>{m(F=>j.tabId in F?{...F,[j.tabId]:"skipped"}:F)}),[]),O.useEffect(()=>{if(Object.keys(f).length===0)return;const M=Object.values(f).filter(F=>F==="sent").length,j=window.setTimeout(()=>w.current(M),1500);return()=>window.clearTimeout(j)},[f]);const T=t.filter(M=>l[M.id]).map(M=>M.id),k=T.length,C=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!C,x=()=>{if(!b)return;c(!0);const M=Tt.getState().tabs,j=new Set(M.map(V=>V.id)),F={};for(const V of T)j.has(V)?(window.api.pty.write({tabId:V,data:n+"\r"}),F[V]="sent"):F[V]="skipped";m(F),c(!1)},S=M=>{if(M.key==="Escape"){M.preventDefault(),M.stopPropagation(),i();return}M.key==="Enter"&&(M.metaKey||M.ctrlKey)&&(M.preventDefault(),x())},y=t.length>0&&t.every(M=>l[M.id]),D=()=>{const M=!y;p(Object.fromEntries(t.map(j=>[j.id,M])))},R=Object.values(f).some(M=>M==="skipped"),N=C?R?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return d.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[d.jsxs("div",{className:"flex items-center justify-between",children:[d.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),d.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),d.jsx("textarea",{ref:g,value:n,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"}),d.jsxs("div",{className:"flex flex-col gap-1",children:[d.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:y,onChange:D,className:"accent-accent"}),d.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),d.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(M=>d.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[d.jsx("input",{type:"checkbox",checked:!!l[M.id],onChange:j=>p(F=>({...F,[M.id]:j.target.checked})),className:"accent-accent"}),d.jsx("span",{className:"truncate max-w-[12rem]",children:M.label}),f[M.id]==="sent"&&d.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[M.id]==="skipped"&&d.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},M.id))})]}),d.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[d.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),d.jsx("button",{onClick:x,disabled:!b,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:N})]})]})}function uA({tabId:i,cwd:e,onClose:t}){const n=qf(k=>k.watchersForTab(i)),s=qf(k=>k.add),l=qf(k=>k.remove),p=O.useRef(null),[a,c]=O.useState(""),[f,m]=O.useState(""),[g,w]=O.useState(!1);O.useEffect(()=>{const k=C=>{C.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),O.useEffect(()=>{const k=C=>{p.current&&!p.current.contains(C.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const T=async()=>{const k=f.trim();if(!k||g)return;w(!0);const C=await s({tabId:i,label:a.trim(),command:k,cwd:e});w(!1),C&&(c(""),m(""))};return d.jsxs("div",{ref:p,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[d.jsxs("div",{className:"flex items-center mb-2",children:[d.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),d.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),d.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[d.jsx("input",{value:a,onChange:k=>c(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("input",{value:f,onChange:k=>m(k.target.value),onKeyDown:k=>{k.key==="Enter"&&T()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),d.jsx("button",{onClick:T,disabled:!f.trim()||g,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),d.jsxs("span",{className:"text-fg-faint",children:["cwd: ",d.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?d.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):d.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const C=k.lines[k.lines.length-1];return d.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[d.jsxs("div",{className:"flex items-center gap-2",children:[d.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),d.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),d.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),d.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(C==null?void 0:C.line)??"",children:C?C.line:d.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2933
2933
|
* dockview-core
|
|
2934
2934
|
* @version 6.6.1
|
|
2935
2935
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3034,7 +3034,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3034
3034
|
|
|
3035
3035
|
${t}`}const Uf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},cO=["popover","review","diff"],qE=["popover","review"];function dO(i,e){switch(e.type){case"SELECT":return{...Uf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Uf,editCount:i.editCount};case"LISTEN":return qE.includes(i.phase)?{...i,phase:"listening",transcript:"",modelStatus:null}:i;case"HEARD":return i.phase!=="listening"?i:{...i,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return cO.includes(i.phase)?{...i,phase:"thinking",instruction:e.recordInstruction?e.instruction:i.instruction}:i;case"RUN_OK":return i.phase!=="thinking"?i:{...i,phase:"diff",diff:e.diff};case"RUN_ERR":return i.phase!=="thinking"?i:{...i,phase:"popover",transcript:"",diff:null};case"ACCEPT":return i.phase!=="diff"?i:{...Uf,editCount:i.editCount+1};case"RESET_FILE":return{...Uf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function uO(i,e){let t=null;for(const n of e){const s=n.cwd;!s||!(i===s||i.startsWith(s.endsWith("/")?s:`${s}/`))||(t===null||s.length>t.length)&&(t=s)}return t}function hO(i,e,t){var l;let n=null,s=-1/0;for(const p of e){if(p.cwd!==i||p.status!=="dormant")continue;const a=((l=t[p.id])==null?void 0:l.lastEventAt)??0;(n===null||a>s)&&(n=p,s=a)}return n}const pO="sonnet";function fO(i,e){const[t,n]=O.useReducer(dO,Uf),s=O.useRef(0),l=O.useRef(null),p=O.useRef(i),a=O.useRef(new Map);O.useEffect(()=>window.api.docEdit.onSessionResult(y=>{const D=a.current.get(y.requestId);D&&(a.current.delete(y.requestId),D(y))}),[]),O.useEffect(()=>{p.current!==i&&(p.current=i,s.current+=1,c(),n({type:"RESET_FILE"}))},[i]);function c(){const y=l.current;y&&(l.current=null,y.stop().catch(()=>{}),y.destroy(),Ht.setState({externalRecording:!1}))}const f=O.useCallback(y=>{s.current+=1,c(),n({type:"SELECT",selection:y})},[]),m=O.useCallback(()=>{s.current+=1,c(),n({type:"CANCEL"})},[]),g=O.useCallback(()=>{if(!qE.includes(t.phase))return;if(Ht.getState().isRecording){Ze.error("Microphone is already in use");return}if(!Zv()){Ze.error("Microphone or Web Worker not available");return}const y=++s.current;n({type:"LISTEN"}),Ht.setState({externalRecording:!0});const D=()=>{l.current===R&&(l.current=null),Ht.setState({externalRecording:!1})},R=ZC({onFinal:N=>{if(s.current!==y)return;R.stop().catch(()=>{}),R.destroy(),D();const M=N.trim();if(!M){n({type:"CANCEL"});return}n({type:"HEARD",transcript:M})},onError:N=>{s.current===y&&(R.destroy(),D(),Ze.error(`Microphone error: ${N}`),n({type:"CANCEL"}))},onModelStatus:(N,M)=>{s.current===y&&n({type:"MODEL_STATUS",status:N,message:M})},onProgress:N=>{s.current===y&&n({type:"MODEL_STATUS",status:"loading",message:`${N}%`})}});l.current=R,R.start().catch(N=>{s.current===y&&(R.destroy(),D(),Ze.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),w=O.useCallback(()=>{const y=uO(i,Tt.getState().tabs);if(!y)return null;const D=hO(y,Tt.getState().tabs,bv.getState().tabs);return!D||_i.getState().get(D.id).running?null:D},[i]),T=O.useCallback((y,D,R,N,M,j)=>{const F=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(V=>{a.current.set(F,V),window.api.docEdit.runInSession({tabId:y,sessionId:D,cwd:R,before:N,instruction:M,documentText:j,requestId:F})})},[]),k=O.useCallback(async(y,D)=>{const R=t.selection;if(!R)return;const N=++s.current;n({type:"RUN",instruction:y,recordInstruction:D});const M=lO(e);try{const j=w(),F=j?await T(j.id,j.sessionId,j.cwd,R.text,y,M):await window.api.docEdit.run({path:i,before:R.text,instruction:y,documentText:M});if(s.current!==N)return;if(!F.ok){Ze.error(F.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:R.text,after:F.after??""}})}catch(j){if(s.current!==N)return;Ze.error(j instanceof Error?j.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,w,T]),C=O.useCallback(y=>{k(y,!0)},[k]),b=O.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),x=O.useCallback(()=>{const y=t.instruction;y&&k(`${y}
|
|
3036
3036
|
|
|
3037
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),S=O.useCallback(y=>{const D=t.diff;if(!D)return{ok:!1,reason:"not-found"};const R=oO(y,D.before,D.after);return R.ok?(s.current+=1,n({type:"ACCEPT"})):Ze.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:m,listen:g,sendHeard:b,run:C,retry:x,accept:S}}async function ya(i){try{const e=await window.api.clipboard.writeText(i);return(e==null?void 0:e.ok)===!0}catch{return!1}}const mO=[{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."}],WS=320,Nf=8;function gO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function vO(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Nf),Math.max(Nf,e-WS-Nf)),n=Math.max(i.top-Nf,Nf);return{position:"fixed",left:t,top:n,width:WS,transform:"translateY(-100%)",zIndex:ED.dialog}}function _O({phase:i,rect:e,selectedText:t,diff:n,transcript:s,modelStatus:l,onQuickAction:p,onRunCustom:a,onListen:c,onSendHeard:f,onCancel:m,onAccept:g,onReject:w,onRetry:T}){const[k,C]=O.useState(""),[b,x]=O.useState(!1),S=hs(N=>N.show),y=O.useRef(null);O.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const D=async()=>{if(!await ya(t)){S("error","Copy failed");return}x(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>x(!1),1500)},R=()=>{const N=k.trim();N&&(a(N),C(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:vO(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&d.jsxs("div",{className:"p-2",children:[d.jsxs("div",{className:"flex items-center justify-between mb-2",children:[d.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.jsx("button",{onClick:D,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:b?"Copied":"Copy"}),d.jsx("button",{onClick:c,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),mO.map(N=>d.jsx("button",{onClick:()=>p(N.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:N.label},N.label))]}),d.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{value:k,onChange:N=>C(N.target.value),onKeyDown:N=>{N.key==="Enter"?R():N.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&d.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[d.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(gO,{}),"Listening…"]}),l&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:l})]}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsxs("div",{className:"p-3 flex items-center justify-between",children:[d.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&d.jsxs("div",{className:"p-3",children:[d.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:T,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function bO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function US({phase:i,transcript:e,diff:t,editCount:n,modelStatus:s,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:m}){return d.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[d.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[d.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),d.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:am(pO)})]}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&d.jsxs("div",{className:"text-fg-faint",children:[d.jsx("p",{children:"Select text in the doc…"}),d.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&d.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&d.jsxs("div",{children:[d.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[d.jsx(bO,{}),"Listening…"]}),s&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),d.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{children:[d.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&d.jsxs("div",{children:[d.jsxs("div",{className:"mb-3 space-y-2",children:[d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function wO(){const i=Tt(t=>t.tabs),e=Tt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function xO({path:i,onRenamed:e,onDeleted:t}){const[n,s]=O.useState(!1),[l,p]=O.useState(!1),[a,c]=O.useState(""),[f,m]=O.useState(!1),g=Ei(V=>V.buffers[i]),w=Ei(V=>V.openFile),T=Ei(V=>V.renameOpenFile),k=Ei(V=>V.closeFile),C=wO(),b=uo(i),x=()=>s(!1),S=()=>{c(b),p(!0),x()},y=async()=>{const V=a.trim();if(!V||V===b){p(!1);return}try{const te=await window.api.files.rename(i,V);if(te.ok){const de=i.slice(0,i.lastIndexOf("/")),Q=te.newPath??`${de}/${V}`;T(i,Q),e==null||e(i,Q),Ze.info(`Renamed to ${V}`)}else Ze.error(te.error??`Couldn't rename ${b}`)}catch(te){Ze.error(te instanceof Error?te.message:`Couldn't rename ${b}`)}p(!1)},D=async()=>{x();try{const V=await window.api.files.duplicate(i);V.ok&&V.path?(w(V.path),Ze.info(`Duplicated as ${uo(V.path)}`)):Ze.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Ze.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const V=await window.api.files.delete(i);V.ok?(k(i),t==null||t(i),Ze.info(`Deleted ${b}`)):Ze.error(V.error??`Couldn't delete ${b}`)}catch(V){Ze.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},N=async()=>{x();const V=g??"";await ya(V)?Ze.info(`Copied ${V.length} chars`):Ze.error(`Couldn't copy ${b}`)},M=()=>{if(x(),!C){Ze.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Ze.info(`Added ${b} to Claude context`)},j=()=>{x(),window.api.shell.open({as:"openPath",path:i}).then(V=>{V.ok||Ze.error(V.error??`Couldn't open ${b}`)}).catch(V=>Ze.error(V instanceof Error?V.message:`Couldn't open ${b}`))},F=()=>{x(),window.api.shell.open({as:"revealPath",path:i}).then(V=>{V.ok||Ze.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Ze.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>s(V=>!V),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuScrim}`,onMouseDown:x}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${yn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(ob,{children:"Edit"}),d.jsx(fd,{label:"Rename",onClick:S}),d.jsx(fd,{label:"Duplicate",onClick:D}),d.jsx(fd,{label:"Delete document",danger:!0,onClick:()=>{x(),m(!0)}}),d.jsx(VS,{}),d.jsx(ob,{children:"Open"}),d.jsx(fd,{label:"Open in default app",onClick:j}),d.jsx(fd,{label:"Reveal in OS",onClick:F}),d.jsx(VS,{}),d.jsx(ob,{children:"Export"}),d.jsx(fd,{label:"Copy as Markdown",onClick:N}),d.jsx(fd,{label:"Add to Claude context",onClick:M,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(yO,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void y()}),f&&d.jsx(SO,{name:b,onCancel:()=>m(!1),onConfirm:()=>void R()})]})}function ob({children:i}){return d.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function fd({label:i,onClick:e,danger:t,disabled:n,title:s}){return d.jsx("button",{onClick:e,disabled:n,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function VS(){return d.jsx("div",{className:"my-1 border-t border-line"})}function yO({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),d.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?n():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function SO({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function CO(){const[i,e]=O.useState(!1),t=yd();return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${yn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(bh,{label:"Text size",children:d.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[d.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),d.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),d.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),d.jsx(bh,{label:"Word wrap",children:d.jsx(sv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(bh,{label:"Minimap",children:d.jsx(sv,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(bh,{label:"Theme",children:d.jsx("button",{onClick:()=>t.setTheme(t.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:t.theme==="dark"?"Dark":"Paper"})}),d.jsx(bh,{label:"Autosave",children:d.jsx(sv,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(bh,{label:"Wide measure",children:d.jsx(sv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function bh({label:i,children:e}){return d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-fg-faint",children:i}),e]})}function sv({on:i,onClick:e}){return d.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const kO=O.lazy(()=>Oi(()=>import("./TiptapBody-BvxcQ_tS.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function rv(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[s,l]of Object.entries(i))t.has(s)||(n[s]=l);return n}function Mf(i){const e=i.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",n=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||n===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||n==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function ov(i){return mE(i)||gE(i)}function EO(){const i=nx(),e=Ei(Je=>Je.openFiles),t=Ei(Je=>Je.activeFilePath),n=Ei(Je=>Je.dirty),s=Ei(Je=>Je.viewMode),l=Ei(Je=>Je.buffers),p=Ei(Je=>Je.setActive),a=Ei(Je=>Je.closeFile),c=Ei(Je=>Je.closeOthers),f=Ei(Je=>Je.closeToTheRight),m=Ei(Je=>Je.closeAll),g=Ei(Je=>Je.loadBuffer),w=Ei(Je=>Je.setBuffer),T=Ei(Je=>Je.markSaved),k=Ei(Je=>Je.setViewMode),C=yd(),[b,x]=O.useState({}),[S,y]=O.useState({}),[D,R]=O.useState(null),[N,M]=O.useState(null),[j,F]=O.useState(!1),[V,te]=O.useState(!1),[de,Q]=O.useState(!0),ge=O.useRef(null),oe=O.useRef(null),me=O.useRef(void 0),$e=O.useRef(null),he=O.useRef(null),W=fO(t??"",l[t??""]??""),X=O.useCallback((Je,bt)=>{w(Je,bt),Mf(Je)&&va.getState().setDraft(Je,bt)},[w]),U=O.useCallback(Je=>{ge.current=Je},[]),ee=O.useCallback(()=>ge.current,[]);O.useEffect(()=>{VR()},[]),O.useEffect(()=>{const Je=t;if(!Je||ov(Je))return;if(Ei.getState().hasBuffer(Je)){x(wt=>wt[Je]==="ready"?wt:{...wt,[Je]:"ready"});return}let bt=!1;return x(wt=>({...wt,[Je]:"loading"})),Mf(Je)?((async()=>{if(await va.getState().loadText(Je,!0),bt)return;const wt=va.getState().files[Je];if(!wt||wt.loadError&&!wt.exists){x(Ke=>({...Ke,[Je]:{error:(wt==null?void 0:wt.loadError)??"failed to read"}}));return}g(Je,wt.diskRaw),wt.dirty&&Ei.getState().setBuffer(Je,wt.draftRaw),x(Ke=>({...Ke,[Je]:"ready"}))})(),()=>{bt=!0}):(window.api.files.read(Je).then(wt=>{bt||(wt.binary?x(Ke=>({...Ke,[Je]:{binary:!0,size:wt.size??0,mime:wt.mime??"application/octet-stream",reason:wt.error??"Binary file"}})):wt.ok?(g(Je,wt.text),x(Ke=>({...Ke,[Je]:"ready"}))):x(Ke=>({...Ke,[Je]:{error:wt.error??"failed to read"}})))}),()=>{bt=!0})},[t,g]),O.useEffect(()=>{M(null)},[t]);const ue=O.useCallback(async(Je,bt=!1)=>{const wt=Ei.getState().buffers[Je];if(wt==null)return;bt&&F(!0);const Ke=Mf(Je);let tt;if(Ke){const Dt=va.getState();if(Dt.setDraft(Je,wt),tt=await Dt.saveText(Je),!tt.ok&&tt.error==="conflict"){bt&&F(!1);return}}else tt=await window.api.files.write(Je,wt);tt.ok?(T(Je),y(Dt=>({...Dt,[Je]:(Dt[Je]??0)+1})),bt||Ze.info(`Saved ${uo(Je)}`)):Ze.error(tt.error??`Couldn't save ${uo(Je)}`),bt&&F(!1)},[T]);O.useEffect(()=>{if(!C.autosave)return;const Je=t;if(!(!Je||ov(Je)||Mf(Je)||!n[Je]))return window.clearTimeout(me.current),me.current=window.setTimeout(()=>{ue(Je,!0)},1200),()=>window.clearTimeout(me.current)},[C.autosave,t,n,l,ue]);const ye=O.useCallback(Je=>{Je.length&&(x(bt=>rv(bt,Je)),y(bt=>rv(bt,Je)))},[]),ze=O.useCallback((Je,bt)=>{x(wt=>Je in wt?{...rv(wt,[Je]),[bt]:wt[Je]}:wt),y(wt=>Je in wt?{...rv(wt,[Je]),[bt]:wt[Je]}:wt)},[]),it=O.useCallback(Je=>{n[Je]?R({kind:"one",path:Je}):(a(Je),ye([Je]))},[n,a,ye]),ve=O.useCallback(Je=>{e.some(wt=>wt.path!==Je&&n[wt.path])?R({kind:"others",path:Je}):(c(Je),ye(e.filter(wt=>wt.path!==Je).map(wt=>wt.path)))},[e,n,c,ye]),J=O.useCallback(Je=>{const bt=e.findIndex(Ke=>Ke.path===Je);bt!==-1&&e.slice(bt+1).some(Ke=>n[Ke.path])?R({kind:"right",path:Je}):(f(Je),ye(bt!==-1?e.slice(bt+1).map(Ke=>Ke.path):[]))},[e,n,f,ye]);O.useEffect(()=>{const Je=bt=>{if(i.current)if((bt.metaKey||bt.ctrlKey)&&(bt.key==="s"||bt.key==="S")){const wt=Ei.getState().activeFilePath;wt&&!ov(wt)&&(bt.preventDefault(),ue(wt))}else if((bt.metaKey||bt.ctrlKey)&&bt.shiftKey&&(bt.key==="f"||bt.key==="F"))bt.preventDefault(),te(wt=>!wt);else if((bt.metaKey||bt.ctrlKey)&&bt.shiftKey&&(bt.key==="w"||bt.key==="W")){const wt=Ei.getState().activeFilePath;wt&&Ei.getState().openFiles.length>1&&(bt.preventDefault(),ve(wt))}else bt.key==="Escape"&&W.state.phase!=="idle"?W.cancel():bt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ue,V,ve,W.state.phase,W.cancel]),O.useEffect(()=>{if(W.state.phase==="idle")return;const Je=bt=>{var Ke,tt;const wt=bt.target;(Ke=he.current)!=null&&Ke.contains(wt)||(tt=$e.current)!=null&&tt.contains(wt)||W.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[W.state.phase,W.cancel]),O.useEffect(()=>{W.cancel()},[t,W.cancel]);const Pe=O.useCallback(()=>{e.some(bt=>n[bt.path])?R({kind:"all",path:""}):(m(),x({}),y({}))},[e,n,m]),ke=()=>{if(D){if(D.kind==="one")a(D.path),ye([D.path]);else if(D.kind==="others"){const Je=e.filter(bt=>bt.path!==D.path).map(bt=>bt.path);c(D.path),ye(Je)}else if(D.kind==="right"){const Je=e.findIndex(wt=>wt.path===D.path),bt=Je!==-1?e.slice(Je+1).map(wt=>wt.path):[];f(D.path),ye(bt)}else m(),x({}),y({});R(null)}};if(e.length===0)return d.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:d.jsxs("div",{className:"text-center",children:[d.jsx("div",{className:"mb-2",children:"no file open"}),d.jsxs("div",{children:["open the ",d.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Se=t,Ee=Se?uo(Se):"",et=Se?b[Se]:void 0,gt=Se?bE(Se):!1,Oe=Se?FR(Se):!1,ct=Se&>?s[Se]??HR(Se):"edit",st=!!Se&&!ov(Se)&&et==="ready",Qt=st,oi=Oe?["edit","wysiwyg","preview","split"]:gt?["edit","preview"]:[],hi=Se&&d.jsx($N,{path:Se,name:Ee,value:l[Se]??"",onChange:Je=>X(Se,Je),onSave:()=>void ue(Se),onReady:U,onCursor:M}),Ai=j?"Saving…":Se&&n[Se]?C.autosave&&!Mf(Se)?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&d.jsx(vj,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:it,onCloseOthers:ve,onCloseToTheRight:J,onCloseAll:Pe}),Se&&!V&&d.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[d.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ee}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Se}),st&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",Ai]}),il(Se)&&(ct==="preview"||ct==="split")&&d.jsx("button",{onClick:()=>Q(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),il(Se)&&(ct==="preview"||ct==="split")&&d.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),oi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:oi.map(Je=>d.jsx("button",{onClick:()=>k(Se,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ct===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),d.jsx("div",{className:"flex-1"}),d.jsx(xO,{path:Se,onRenamed:ze,onDeleted:Je=>ye([Je])}),st&&d.jsx(CO,{}),d.jsx("button",{onClick:()=>te(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&d.jsx("button",{onClick:()=>te(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),d.jsx("div",{className:"flex-1 min-h-0",children:Se?mE(Se)?d.jsx(ZM,{path:Se,name:Ee}):gE(Se)?d.jsx(QM,{path:Se}):et&&typeof et=="object"&&"binary"in et?d.jsx(rO,{path:Se,name:Ee,size:et.size,mime:et.mime,reason:et.reason}):et&&typeof et=="object"&&"error"in et?d.jsx("div",{className:"p-6 text-xs text-red-400",children:et.error}):et!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ct==="wysiwyg"&&il(Se)?d.jsx(O.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(kO,{value:l[Se]??"",onChange:Je=>X(Se,Je)},Se)}):ct==="split"&&il(Se)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(GS,{text:l[Se]??"",scrollRef:oe}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(BS,{getEditor:ee}),d.jsx("div",{className:"flex-1 min-h-0",children:hi})]}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(gw,{ref:oe,text:l[Se]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!V&&C.assistantRail&&d.jsx(US,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):ct==="preview"&&il(Se)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(GS,{text:l[Se]??"",scrollRef:oe}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(gw,{ref:oe,text:l[Se]??"",wideMeasure:C.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!V&&C.assistantRail&&d.jsx(US,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):ct==="preview"&&fE(Se)?d.jsx(XM,{path:Se,dirty:!!n[Se],reloadToken:S[Se]??0}):ct==="preview"&&vE(Se)?d.jsx(tO,{path:Se,text:l[Se]??""}):ct==="preview"&&_E(Se)?d.jsx(sO,{path:Se,text:l[Se]??""}):il(Se)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(BS,{getEditor:ee}),d.jsx("div",{className:"flex-1 min-h-0",children:hi})]}):hi:null}),Qt&&d.jsx(YM,{text:l[Se]??"",cursor:N,language:Wr(Se)||void 0}),Se&&il(Se)&&(ct==="preview"||ct==="split")&&W.state.phase!=="idle"&&W.state.selection&&d.jsx("div",{ref:he,children:d.jsx(_O,{phase:W.state.phase,rect:W.state.selection.rect,selectedText:W.state.selection.text,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)}})}),D&&d.jsx(TO,{message:D.kind==="one"?`Discard unsaved changes to ${uo(D.path)}?`:D.kind==="others"?"Discard unsaved changes in the other open files?":D.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>R(null),onConfirm:ke})]})}const bw=O.memo(EO);function TO({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const DO="~/.claude/session-manager/projects-prefs.json";let qS=Promise.resolve(),av=null;function KS(i){const e=qS.then(i);return qS=e.catch(()=>{}),e}const KE=()=>Sa(DO);async function YS(){const i=(await KE().read()).pinned;return i&&typeof i=="object"?{...i}:{}}const ab=Un(i=>({pinned:{},hydrated:!1,hydrate:()=>av||(av=KS(async()=>{try{i({pinned:await YS(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),i({hydrated:!0})}}),av),togglePin:e=>{KS(async()=>{let t;try{t=await YS()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const n={...t};n[e]?delete n[e]:n[e]=!0;try{await KE().patch({pinned:n}),i({pinned:n})}catch(s){i({pinned:t}),Ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function $O(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function AO(i,e,t){const n=O.useRef(e);n.current=e;const s=Array.from(new Set(i.filter(p=>!!p).map($O))),l=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;O.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const p=window.api.config.onChanged(a=>{s.includes(a.path)&&n.current(a.path)});return()=>{p(),window.api.config.unwatch(s,t)}},[l])}function $x(i){return/^[A-Za-z]:[\\/]/.test(i)&&i.includes("\\")||i.includes("\\")&&!i.includes("/")?"\\":"/"}function YE(i){return i.split(/[\\/]+/).filter(Boolean)}function XE(i){const e=YE(i);return e.length?e[e.length-1]:i}function XS(i){const e=i.length>1?i.replace(/[\\/]+$/,""):i,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 IO(...i){const e=i.filter(s=>s!=="");if(!e.length)return"";const t=$x(e[0]);let n=e[0];for(const s of e.slice(1))n=n.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return n}const JS=i=>i.replace(/\\/g,"/").replace(/\/+$/,"");function pm(i,e){return JS(i).startsWith(JS(e)+"/")}async function PO(i){const e=await Sm(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function RO(i,e){return Ed(i,{fileTreeExpanded:[...e].slice(0,500)})}async function jO(){const i=await o_();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function NO(i){a_({fileTreeShowHidden:i}).catch(()=>{})}function lb(i,e){let t=!1;const n=new Set;for(const s of i){if(s===e||pm(s,e)){t=!0;continue}n.add(s)}return t?n:i}const cb={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:"!"}},MO=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 OO(i){const e=Wr(i);return MO.has(e)||pE.has(e)||e==="pdf"}function LO(i,e){if(e)return"#d97757";switch(Wr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function Of(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}const ZS=64,zO=250,BO={depth:0};function db(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function GO({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const s=nx(),l=Qv(),[p,a]=O.useState([]),[c,f]=O.useState(new Set),m=O.useRef(c);m.current=c;const g=O.useRef(!1),[w,T]=O.useState(""),[k,C]=O.useState(!0),b=O.useRef(!1);O.useEffect(()=>{let Ke=!1;return jO().then(tt=>{!Ke&&!b.current&&C(tt)}),()=>{Ke=!0}},[]);const x=O.useCallback(Ke=>{b.current=!0,C(tt=>{const Dt=typeof Ke=="function"?Ke(tt):Ke;return NO(Dt),Dt})},[]),[S,y]=O.useState(!1),[D,R]=O.useState(null),[N,M]=O.useState({}),[j,F]=O.useState(null),[V,te]=O.useState(null),[de,Q]=O.useState(""),[ge,oe]=O.useState(null),[me,$e]=O.useState(""),[he,W]=O.useState(null),X=O.useRef(null),U=O.useRef(null),ee=O.useRef(0),ue=O.useCallback(async()=>{if(!i)return;const Ke=++ee.current;y(!0),R(null);const tt=await window.api.files.list(i,k);ee.current===Ke&&(tt.ok?a(tt.entries.map(Dt=>({...Dt}))):(R(tt.error??"failed to list"),a([])),y(!1))},[i,k]),ye=O.useCallback(async Ke=>{const tt=ee.current,Dt=new Map;for(const mi of Ke){const gi=YE(mi).length,Mt=Dt.get(gi);Mt?Mt.push(mi):Dt.set(gi,[mi])}const Zt=[];for(const mi of[...Dt.keys()].sort((gi,Mt)=>gi-Mt)){const gi=Dt.get(mi),Mt=await Promise.all(gi.map(async ai=>({p:ai,result:await window.api.files.list(ai,k)})));if(ee.current!==tt)return Zt;for(const{p:ai,result:Vn}of Mt)Vn.ok?a(ss=>Sv(ss,ai,Vn.entries.map(qn=>({...qn})))):Zt.push(ai)}return Zt},[k]),ze=O.useCallback(async Ke=>(await ue(),Ke.length?ye(Ke):[]),[ue,ye]);O.useEffect(()=>{T(""),te(null),F(null),oe(null),W(null),M({});let Ke=!1;return g.current=!1,(async()=>{const[tt]=await Promise.all([PO(i),ue()]);if(Ke)return;if(!g.current){const Zt=new Set(tt);m.current=Zt,f(Zt)}if(!tt.length)return;const Dt=await ye(tt);Ke||!Dt.length||et(Zt=>{const mi=new Set;let gi=!1;for(const Mt of Zt){if(Dt.some(ai=>Mt===ai||pm(Mt,ai))){gi=!0;continue}mi.add(Mt)}return gi?mi:Zt})})(),Of(i).then(tt=>{Ke||M(tt)}),()=>{Ke=!0}},[i]);const it=O.useRef(!0);O.useEffect(()=>{if(it.current){it.current=!1;return}ze([...m.current])},[k]),O.useEffect(()=>{if(!i||!l)return;Of(i).then(M);const Ke=window.setInterval(()=>{Of(i).then(M)},5e3);return()=>window.clearInterval(Ke)},[i,l]);const ve=O.useMemo(()=>{if(!i)return[];const Ke=[...c].filter(tt=>tt!==i);return[i,...Ke.slice(-63)]},[i,c]),J=O.useRef(!1);O.useEffect(()=>{!i||c.size+1<=ZS||J.current||(J.current=!0,console.warn(`FileTree: watching only ${ZS} of ${c.size+1} folders (cap reached)`))},[i,c]);const Pe=O.useRef(new Map),ke=O.useRef(new Set),Se=O.useRef(!1);Se.current=V!==null||ge!==null;const Ee=O.useRef(()=>{});Ee.current=Ke=>{if(!(Ke!==db(i)&&!m.current.has(Ke))){if(Se.current){ke.current.add(Ke);return}Ke===db(i)?ze([...m.current]):Oe(Ke)}},AO(ve,Ke=>{if(Ke!==db(i)&&!m.current.has(Ke))return;const tt=Pe.current,Dt=tt.get(Ke);Dt&&clearTimeout(Dt),tt.set(Ke,setTimeout(()=>{tt.delete(Ke),Ee.current(Ke)},zO))},BO),O.useEffect(()=>{if(V!==null||ge!==null)return;const Ke=[...ke.current];ke.current.clear();for(const tt of Ke)Ee.current(tt)},[V,ge]),O.useEffect(()=>{const Ke=Pe.current,tt=ke.current;return()=>{for(const Dt of Ke.values())clearTimeout(Dt);Ke.clear(),tt.clear()}},[i]),O.useEffect(()=>{if(!j)return;const Ke=()=>F(null),tt=Dt=>{s.current&&Dt.key==="Escape"&&F(null)};return window.addEventListener("mousedown",Ke),window.addEventListener("keydown",tt),()=>{window.removeEventListener("mousedown",Ke),window.removeEventListener("keydown",tt)}},[j]),O.useEffect(()=>{V&&setTimeout(()=>{var Ke;return(Ke=X.current)==null?void 0:Ke.select()},30)},[V]),O.useEffect(()=>{ge&&setTimeout(()=>{var Ke;return(Ke=U.current)==null?void 0:Ke.focus()},30)},[ge]);const et=O.useCallback(Ke=>{const tt=m.current,Dt=Ke(tt);Dt!==tt&&(g.current=!0,m.current=Dt,f(Dt),RO(i,Dt).catch(()=>{m.current===Dt&&(m.current=tt,f(tt),Ze.error("Couldn't save folder expansion — reverted."))}))},[i]),gt=O.useCallback(async Ke=>{if(c.has(Ke.path)){et(Dt=>lb(Dt,Ke.path));return}if(et(Dt=>new Set(Dt).add(Ke.path)),Ke.children)return;const tt=await window.api.files.list(Ke.path,k);tt.ok&&a(Dt=>Sv(Dt,Ke.path,tt.entries.map(Zt=>({...Zt}))))},[c,k,et]),Oe=O.useCallback(async Ke=>{if(Ke===i){await ue();return}const tt=await window.api.files.list(Ke,k);tt.ok&&a(Dt=>Sv(Dt,Ke,tt.entries.map(Zt=>({...Zt}))))},[i,ue,k]),ct=O.useCallback(Ke=>{if(Ke.isDirectory){gt(Ke);return}OO(Ke.name)&&e?e(Ke.path):window.api.shell.open({as:"openPath",path:Ke.path})},[gt,e]),st=O.useCallback(Ke=>{if(t){t(Ke);return}if(n){const tt=pm(Ke,i)?Ke.slice(i.replace(/[\\/]+$/,"").length+1):Ke;window.api.pty.write({tabId:n,data:`@${tt} `})}},[t,n,i]),Qt=O.useCallback((Ke,tt)=>{Ke.preventDefault(),Ke.stopPropagation(),F({x:Ke.clientX,y:Ke.clientY,node:tt})},[]),oi=Ke=>{te(Ke.path),Q(Ke.name)},hi=async()=>{if(!V)return;const Ke=de.trim();if(!Ke){te(null);return}const tt=await window.api.files.rename(V,Ke);if(te(null),tt.ok){const Dt=XS(V);et(Zt=>lb(Zt,V)),await Oe(Dt||i),Of(i).then(M)}else{const Dt=tt.error??"rename failed";R(Dt),Ze.error(Dt)}},Ai=async()=>{if(!ge)return;const Ke=me.trim();if(!Ke){oe(null),$e("");return}const tt=await window.api.files.create(ge.parent,Ke,ge.kind);if(oe(null),$e(""),tt.ok)await Oe(ge.parent),ge.kind==="folder"&&et(Dt=>new Set(Dt).add(ge.parent));else{const Dt=tt.error??"create failed";R(Dt),Ze.error(Dt)}},Je=async()=>{if(!he)return;const Ke=await window.api.files.delete(he.path),tt=XS(he.path);if(W(null),Ke.ok)et(Dt=>lb(Dt,he.path)),await Oe(tt||i),Of(i).then(M);else{const Dt=Ke.error??"delete failed";R(Dt),Ze.error(Dt)}},bt=O.useMemo(()=>{if(!w.trim())return p;const Ke=w.toLowerCase();return p.filter(tt=>tt.name.toLowerCase().includes(Ke))},[p,w]),wt=(i?XE(i):"")||"project";return d.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[d.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[d.jsx(ZE,{size:14,className:"shrink-0 text-accent"}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("p",{className:"text-xs font-medium text-fg truncate",children:wt}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:ue,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:S,children:d.jsx(qO,{size:12,className:S?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:Ke=>T(Ke.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),d.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[d.jsx("button",{onClick:()=>oe({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:d.jsx(KO,{size:12})}),d.jsx("button",{onClick:()=>oe({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:d.jsx(YO,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>x(Ke=>!Ke),className:`p-1.5 rounded transition-colors ${k?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:k?"Hide hidden files":"Show hidden files",children:k?d.jsx(XO,{size:12}):d.jsx(JO,{size:12})})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[D&&d.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:D}),!D&&bt.length===0&&!S&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!D&&d.jsx(JE,{nodes:bt,depth:0,expanded:c,gitStatus:N,renaming:V,renameValue:de,renameInputRef:X,onRenameChange:Q,onRenameCommit:hi,onRenameCancel:()=>te(null),onToggleDir:gt,onFileClick:ct,onSendToChat:st,onContextMenu:Qt})]}),d.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),j&&d.jsx(FO,{x:j.x,y:j.y,node:j.node,onClose:()=>F(null),onRename:()=>{oi(j.node),F(null)},onDelete:()=>{W(j.node),F(null)},onNewFile:()=>{oe({parent:j.node.path,kind:"file"}),F(null)},onNewFolder:()=>{oe({parent:j.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:j.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:j.node.path}),F(null)},onCopyPath:()=>{const Ke=j.node.path;ya(Ke).then(tt=>{tt||Ze.error("Couldn't copy path")}),F(null)},onSendToChat:()=>{st(j.node.path),F(null)}}),ge&&d.jsx(QS,{title:`New ${ge.kind}`,subtitle:`in ${HO(ge.parent)}`,onCancel:()=>{oe(null),$e("")},onConfirm:Ai,confirmLabel:"Create",confirmDisabled:!me.trim(),children:d.jsx("input",{ref:U,value:me,onChange:Ke=>$e(Ke.target.value),onKeyDown:Ke=>{Ke.key==="Enter"&&Ai(),Ke.key==="Escape"&&(oe(null),$e(""))},placeholder:ge.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"})}),he&&d.jsx(QS,{title:`Delete ${he.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>W(null),onConfirm:Je,confirmLabel:"Delete",danger:!0,children:d.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",d.jsxs("span",{className:"text-fg font-medium",children:['"',he.name,'"']})," to the trash?",he.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function JE(i){const{nodes:e,depth:t,expanded:n,gitStatus:s,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,m=s[a.path],g=LO(a.name,a.isDirectory);return d.jsxs("div",{children:[d.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?d.jsx(VO,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):d.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?c?d.jsx(WO,{size:12,color:g}):d.jsx(ZE,{size:12,color:g}):d.jsx(UO,{size:12,color:g}),f?d.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):d.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),m&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:cb[m].color,backgroundColor:`${cb[m].color}20`},title:m,children:cb[m].label}),!a.isDirectory&&d.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:d.jsx(ZO,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(JE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function FO(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${yn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&d.jsx(ql,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(ql,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(ql,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(ub,{}),d.jsx(ql,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(ql,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(ub,{}),d.jsx(ql,{label:"New file",onClick:i.onNewFile}),d.jsx(ql,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(ub,{}),d.jsx(ql,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function ql({label:i,onClick:e,danger:t}){return d.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function ub(){return d.jsx("div",{className:"my-1 border-t border-line"})}function QS(i){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&d.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),d.jsx("div",{className:"mb-4",children:i.children}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),d.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function HO(i){return XE(i)}function Sv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Sv(n.children,e,t)}:n)}function ka({size:i,children:e,className:t,color:n}){return d.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function ZE({size:i,className:e,color:t}){return d.jsx(ka,{size:i,className:e,color:t,children:d.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function WO({size:i,className:e,color:t}){return d.jsx(ka,{size:i,className:e,color:t,children:d.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function UO({size:i,className:e,color:t}){return d.jsxs(ka,{size:i,className:e,color:t,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function VO({size:i,className:e}){return d.jsx(ka,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function qO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("polyline",{points:"1 20 1 14 7 14"}),d.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function KO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"}),d.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),d.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function YO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),d.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),d.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function XO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function JO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),d.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function ZO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),d.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function QE({content:i,children:e,align:t="bottom-right"}){const[n,s]=O.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return d.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${yn.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function im(i,e){if(!e)return i;const t=$x(e),n=e.length>1?e.replace(/[\\/]+$/,""):e;if(i===n)return"~";const s=n.endsWith(t)?n:`${n}${t}`;return i.startsWith(s)?`~${t}${i.slice(s.length)}`:i}function hb(i){a_(i).catch(()=>Ze.error("Couldn't save File Explorer layout."))}const pb=33,QO=20,e3=60,t3=32;function e1(i){return Math.min(e3,Math.max(QO,i))}function i3(){const i=Tt(te=>te.tabs),e=Tt(te=>te.activeTabId),t=i.find(te=>te.id===e)??null,n=ki(te=>te.navFace),s=s_(),l=n==="home"?s:(t==null?void 0:t.cwd)??null,[p,a]=O.useState(pb),[c,f]=O.useState(!1),m=O.useRef(!1),[g,w]=O.useState(!1),T=O.useRef(p);T.current=p;const k=O.useRef(c);k.current=c;const C=O.useRef(null),b=O.useRef(null),{projects:x,openProject:S,archiveProjectByCwd:y}=Dd(),D=ab(te=>te.pinned),R=ab(te=>te.togglePin);O.useEffect(()=>{ab.getState().hydrate()},[]),O.useEffect(()=>{let te=!1;return o_().then(de=>{te||m.current||(typeof de.projectsSplitPct=="number"&&Number.isFinite(de.projectsSplitPct)&&a(e1(de.projectsSplitPct)),typeof de.projectsFileTreeCollapsed=="boolean"&&f(de.projectsFileTreeCollapsed))}),()=>{te=!0}},[]);const N=[...x].sort((te,de)=>(D[de.cwd]?1:0)-(D[te.cwd]?1:0));O.useEffect(()=>{if(!g)return;const te=de=>{b.current&&!b.current.contains(de.target)&&w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[g]);const M=O.useCallback(te=>{Ei.getState().openFile(te)},[]),j=O.useCallback(te=>{te.preventDefault(),m.current=!0;const de=te.clientX,Q=T.current;let ge=Q;const oe=$e=>{const he=C.current;if(!he)return;const W=he.getBoundingClientRect(),X=$e.clientX-de;ge=e1(Q+X/W.width*100),a(ge)},me=()=>{window.removeEventListener("pointermove",oe),window.removeEventListener("pointerup",me),document.body.style.cursor="",document.body.style.userSelect="",hb({projectsSplitPct:ge})};window.addEventListener("pointermove",oe),window.addEventListener("pointerup",me),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),F=O.useCallback(()=>{m.current=!0,a(pb),hb({projectsSplitPct:pb})},[]),V=O.useCallback(()=>{m.current=!0;const te=!k.current;f(te),hb({projectsFileTreeCollapsed:te})},[]);return c?d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:V,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:t3},children:[d.jsx("span",{className:"text-[11px]",children:"▸"}),d.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(bw,{})})]}):d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${p}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:b,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(te=>!te),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[d.jsx("span",{className:"flex-1 truncate text-left",children:l?im(l,s):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),d.jsx("button",{onClick:V,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),g&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${yn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:N.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):N.map(te=>{const de=im(te.cwd,s);return d.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[d.jsx(QE,{content:D[te.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>R(te.cwd),className:`shrink-0 text-sm leading-none transition-colors ${D[te.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:D[te.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{S(te.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:de}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${de}?`)&&await y(te)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},te.cwd)})})]}),l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:l,children:im(l,s)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(GO,{cwd:l,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:M})})]}):d.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:j,onDoubleClick:F,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(bw,{})})]})}const n3=O.memo(i3),s3={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The 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 r3({content:i}){return d.jsxs(d.Fragment,{children:[d.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>d.jsxs("div",{className:"mb-3 last:mb-0",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),d.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>d.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&d.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",d.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&d.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),d.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>d.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function o3({active:i}){const e=Wn(g=>g.learningPanelCollapsed),t=Wn(g=>g.setLearningPanelCollapsed),n=Wn(g=>g.hydrated),s=Wn(g=>g.hydrate);O.useEffect(()=>{n||s()},[n,s]);const[l,p]=O.useState(()=>!e),a=O.useRef(null);O.useEffect(()=>{n&&p(!e)},[n]);const c=O.useCallback(()=>{p(g=>{const w=!g;return t(!w),w})},[t]);O.useEffect(()=>{if(!l)return;const g=w=>{var T;(T=a.current)!=null&&T.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l,t]);const f=O.useRef(!1);O.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const m=s3[i];return m?d.jsxs("span",{ref:a,className:"relative inline-block",children:[d.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":l,title:l?"Close learning panel":"What is this?",children:"Learn"}),l&&d.jsx("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:d.jsx(r3,{content:m})})]}):null}function a3({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:s,children:l}){const p=n&&(i||e||t);return d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&d.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[d.jsxs("div",{className:"max-w-[820px]",children:[i&&d.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&d.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&d.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),s&&d.jsx(o3,{active:s})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const l3=O.lazy(()=>Oi(()=>import("./History-DcnZxMoU.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(i=>({default:i.History}))),c3=O.lazy(()=>Oi(()=>import("./Scheduler-Ca1qo_kp.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),d3=O.lazy(()=>Oi(()=>import("./Settings-BFwlV-as.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(i=>({default:i.Settings}))),u3=O.lazy(()=>Oi(()=>import("./SystemPrompt-B8TXIGXo.js"),__vite__mapDeps([15,4,8,9,10,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),h3=O.lazy(()=>Oi(()=>import("./Memory-smN9-Yoo.js"),__vite__mapDeps([16,17,1,2]),import.meta.url).then(i=>({default:i.Memory}))),p3=O.lazy(()=>Oi(()=>import("./Extensions-Ddb4sQpO.js"),__vite__mapDeps([18,11,10,4,13,8,9,19,14,1,2]),import.meta.url).then(i=>({default:i.Extensions}))),f3=O.lazy(()=>Oi(()=>import("./AppSettings-A3KoPcmL.js"),__vite__mapDeps([20,11,10,19,17,4,1,2]),import.meta.url).then(i=>({default:i.AppSettings}))),m3=O.lazy(()=>Oi(()=>import("./AgentLibrary-Dlhtc8Ty.js"),__vite__mapDeps([21,4,13,11,10,9,12,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),g3=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Kl({children:i}){return d.jsx(O.Suspense,{fallback:g3,children:i})}const v3={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:"Memory",intro:"Claude Code's own memory files for this project and its subagents — a MEMORY.md index plus topic files. Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads."},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},t1=new Map;function _3(i,e){const t=t1.get(i);if(t&&t.ctx===e)return t.node;const n=b3(i,e);return t1.set(i,{ctx:e,node:n}),n}function b3(i,e){switch(i){case"overview":return d.jsx(pR,{onNavigate:e.onNavigate});case"project-home":return d.jsx(pj,{});case"editor":return d.jsx(bw,{});case"projects":return d.jsx(n3,{})}const t=v3[i],n=(()=>{switch(i){case"history":return d.jsx(Kl,{children:d.jsx(l3,{})});case"scheduler":return d.jsx(Kl,{children:d.jsx(c3,{navigate:e.onNavigate})});case"memory":return d.jsx(Kl,{children:d.jsx(h3,{})});case"system-prompt":return d.jsx(Kl,{children:d.jsx(u3,{})});case"settings":return d.jsx(Kl,{children:d.jsx(d3,{scope:"user"})});case"extensions":return d.jsx(Kl,{children:d.jsx(p3,{})});case"app-settings":return d.jsx(Kl,{children:d.jsx(f3,{})});case"agent-library":return d.jsx(Kl,{children:d.jsx(m3,{})});default:return null}})();if(!n)return null;const s=uD[i];return t&&s?d.jsx(a3,{eyebrow:s,title:t.title,intro:t.intro,learnKey:i,children:n}):n}class w3 extends O.Component{constructor(){super(...arguments);Vi(this,"state",{error:null});Vi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):d.jsxs("div",{className:"p-6 text-xs",children:[d.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),d.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),d.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}var fb={exports:{}},i1;function x3(){return i1||(i1=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(S,y,D,R){var N,M=arguments.length,j=M<3?y:R===null?R=Object.getOwnPropertyDescriptor(y,D):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(S,y,D,R);else for(var F=S.length-1;F>=0;F--)(N=S[F])&&(j=(M<3?N(j):M>3?N(y,D,j):N(y,D))||j);return M>3&&j&&Object.defineProperty(y,D,j),j},m=this&&this.__param||function(S,y){return function(D,R){y(D,R,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const g=c(9042),w=c(9924),T=c(844),k=c(4725),C=c(2585),b=c(3656);let x=a.AccessibilityManager=class extends T.Disposable{constructor(S,y,D,R){super(),this._terminal=S,this._coreBrowserService=D,this._renderService=R,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3037
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),S=O.useCallback(y=>{const D=t.diff;if(!D)return{ok:!1,reason:"not-found"};const R=oO(y,D.before,D.after);return R.ok?(s.current+=1,n({type:"ACCEPT"})):Ze.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:m,listen:g,sendHeard:b,run:C,retry:x,accept:S}}async function ya(i){try{const e=await window.api.clipboard.writeText(i);return(e==null?void 0:e.ok)===!0}catch{return!1}}const mO=[{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."}],WS=320,Nf=8;function gO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function vO(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Nf),Math.max(Nf,e-WS-Nf)),n=Math.max(i.top-Nf,Nf);return{position:"fixed",left:t,top:n,width:WS,transform:"translateY(-100%)",zIndex:ED.dialog}}function _O({phase:i,rect:e,selectedText:t,diff:n,transcript:s,modelStatus:l,onQuickAction:p,onRunCustom:a,onListen:c,onSendHeard:f,onCancel:m,onAccept:g,onReject:w,onRetry:T}){const[k,C]=O.useState(""),[b,x]=O.useState(!1),S=hs(N=>N.show),y=O.useRef(null);O.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const D=async()=>{if(!await ya(t)){S("error","Copy failed");return}x(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>x(!1),1500)},R=()=>{const N=k.trim();N&&(a(N),C(""))};return d.jsxs("div",{"data-doc-edit-popover":!0,style:vO(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&d.jsxs("div",{className:"p-2",children:[d.jsxs("div",{className:"flex items-center justify-between mb-2",children:[d.jsxs("div",{className:"flex flex-wrap gap-1",children:[d.jsx("button",{onClick:D,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:b?"Copied":"Copy"}),d.jsx("button",{onClick:c,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),mO.map(N=>d.jsx("button",{onClick:()=>p(N.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:N.label},N.label))]}),d.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),d.jsx("input",{value:k,onChange:N=>C(N.target.value),onKeyDown:N=>{N.key==="Enter"?R():N.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&d.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[d.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[d.jsxs("span",{className:"flex items-center gap-2",children:[d.jsx(gO,{}),"Listening…"]}),l&&d.jsx("span",{className:"text-[10px] text-fg-faint",children:l})]}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[d.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsxs("div",{className:"p-3 flex items-center justify-between",children:[d.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),d.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&n&&d.jsxs("div",{className:"p-3",children:[d.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:n.before}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:n.after})]}),d.jsxs("div",{className:"flex justify-end gap-1.5",children:[d.jsx("button",{onClick:w,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:T,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function bO(){return d.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),d.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function US({phase:i,transcript:e,diff:t,editCount:n,modelStatus:s,onListen:l,onSendHeard:p,onCancel:a,onAccept:c,onReject:f,onRetry:m}){return d.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[d.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[d.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),d.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:am(pO)})]}),d.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&d.jsxs("div",{className:"text-fg-faint",children:[d.jsx("p",{children:"Select text in the doc…"}),d.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&d.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&d.jsxs("div",{children:[d.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[d.jsx(bO,{}),"Listening…"]}),s&&d.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),d.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&d.jsxs("div",{children:[d.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),d.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&d.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&d.jsxs("div",{children:[d.jsxs("div",{className:"mb-3 space-y-2",children:[d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),d.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),d.jsxs("div",{children:[d.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),d.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),d.jsxs("div",{className:"flex gap-1.5",children:[d.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),d.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),d.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function wO(){const i=Tt(t=>t.tabs),e=Tt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function xO({path:i,onRenamed:e,onDeleted:t}){const[n,s]=O.useState(!1),[l,p]=O.useState(!1),[a,c]=O.useState(""),[f,m]=O.useState(!1),g=Ei(V=>V.buffers[i]),w=Ei(V=>V.openFile),T=Ei(V=>V.renameOpenFile),k=Ei(V=>V.closeFile),C=wO(),b=uo(i),x=()=>s(!1),S=()=>{c(b),p(!0),x()},y=async()=>{const V=a.trim();if(!V||V===b){p(!1);return}try{const te=await window.api.files.rename(i,V);if(te.ok){const de=i.slice(0,i.lastIndexOf("/")),Q=te.newPath??`${de}/${V}`;T(i,Q),e==null||e(i,Q),Ze.info(`Renamed to ${V}`)}else Ze.error(te.error??`Couldn't rename ${b}`)}catch(te){Ze.error(te instanceof Error?te.message:`Couldn't rename ${b}`)}p(!1)},D=async()=>{x();try{const V=await window.api.files.duplicate(i);V.ok&&V.path?(w(V.path),Ze.info(`Duplicated as ${uo(V.path)}`)):Ze.error(V.error??`Couldn't duplicate ${b}`)}catch(V){Ze.error(V instanceof Error?V.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const V=await window.api.files.delete(i);V.ok?(k(i),t==null||t(i),Ze.info(`Deleted ${b}`)):Ze.error(V.error??`Couldn't delete ${b}`)}catch(V){Ze.error(V instanceof Error?V.message:`Couldn't delete ${b}`)}m(!1)},N=async()=>{x();const V=g??"";await ya(V)?Ze.info(`Copied ${V.length} chars`):Ze.error(`Couldn't copy ${b}`)},M=()=>{if(x(),!C){Ze.error("No terminal tab is active");return}window.api.pty.write({tabId:C.id,data:`@${i} `}),Ze.info(`Added ${b} to Claude context`)},j=()=>{x(),window.api.shell.open({as:"openPath",path:i}).then(V=>{V.ok||Ze.error(V.error??`Couldn't open ${b}`)}).catch(V=>Ze.error(V instanceof Error?V.message:`Couldn't open ${b}`))},F=()=>{x(),window.api.shell.open({as:"revealPath",path:i}).then(V=>{V.ok||Ze.error(V.error??`Couldn't reveal ${b}`)}).catch(V=>Ze.error(V instanceof Error?V.message:`Couldn't reveal ${b}`))};return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>s(V=>!V),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuScrim}`,onMouseDown:x}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${yn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[d.jsx(ob,{children:"Edit"}),d.jsx(fd,{label:"Rename",onClick:S}),d.jsx(fd,{label:"Duplicate",onClick:D}),d.jsx(fd,{label:"Delete document",danger:!0,onClick:()=>{x(),m(!0)}}),d.jsx(VS,{}),d.jsx(ob,{children:"Open"}),d.jsx(fd,{label:"Open in default app",onClick:j}),d.jsx(fd,{label:"Reveal in OS",onClick:F}),d.jsx(VS,{}),d.jsx(ob,{children:"Export"}),d.jsx(fd,{label:"Copy as Markdown",onClick:N}),d.jsx(fd,{label:"Add to Claude context",onClick:M,disabled:!C,title:C?void 0:"No terminal tab is active"})]})]}),l&&d.jsx(yO,{value:a,onChange:c,onCancel:()=>p(!1),onConfirm:()=>void y()}),f&&d.jsx(SO,{name:b,onCancel:()=>m(!1),onConfirm:()=>void R()})]})}function ob({children:i}){return d.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function fd({label:i,onClick:e,danger:t,disabled:n,title:s}){return d.jsx("button",{onClick:e,disabled:n,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function VS(){return d.jsx("div",{className:"my-1 border-t border-line"})}function yO({value:i,onChange:e,onCancel:t,onConfirm:n}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),d.jsx("input",{autoFocus:!0,value:i,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?n():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function SO({name:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function CO(){const[i,e]=O.useState(!1),t=yd();return d.jsxs("div",{className:"relative inline-block mr-1",children:[d.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&d.jsxs(d.Fragment,{children:[d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),d.jsxs("div",{className:`absolute right-0 top-full mt-1 ${yn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[d.jsx(bh,{label:"Text size",children:d.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[d.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),d.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),d.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),d.jsx(bh,{label:"Word wrap",children:d.jsx(sv,{on:t.wordWrap,onClick:t.toggleWordWrap})}),d.jsx(bh,{label:"Minimap",children:d.jsx(sv,{on:t.minimap,onClick:t.toggleMinimap})}),d.jsx(bh,{label:"Theme",children:d.jsx("button",{onClick:()=>t.setTheme(t.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:t.theme==="dark"?"Dark":"Paper"})}),d.jsx(bh,{label:"Autosave",children:d.jsx(sv,{on:t.autosave,onClick:t.toggleAutosave})}),d.jsx(bh,{label:"Wide measure",children:d.jsx(sv,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function bh({label:i,children:e}){return d.jsxs("div",{className:"flex items-center justify-between gap-2",children:[d.jsx("span",{className:"text-fg-faint",children:i}),e]})}function sv({on:i,onClick:e}){return d.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const kO=O.lazy(()=>Oi(()=>import("./TiptapBody-DiVYC-_O.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function rv(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[s,l]of Object.entries(i))t.has(s)||(n[s]=l);return n}function Mf(i){const e=i.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",n=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||n===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||n==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function ov(i){return mE(i)||gE(i)}function EO(){const i=nx(),e=Ei(Je=>Je.openFiles),t=Ei(Je=>Je.activeFilePath),n=Ei(Je=>Je.dirty),s=Ei(Je=>Je.viewMode),l=Ei(Je=>Je.buffers),p=Ei(Je=>Je.setActive),a=Ei(Je=>Je.closeFile),c=Ei(Je=>Je.closeOthers),f=Ei(Je=>Je.closeToTheRight),m=Ei(Je=>Je.closeAll),g=Ei(Je=>Je.loadBuffer),w=Ei(Je=>Je.setBuffer),T=Ei(Je=>Je.markSaved),k=Ei(Je=>Je.setViewMode),C=yd(),[b,x]=O.useState({}),[S,y]=O.useState({}),[D,R]=O.useState(null),[N,M]=O.useState(null),[j,F]=O.useState(!1),[V,te]=O.useState(!1),[de,Q]=O.useState(!0),ge=O.useRef(null),oe=O.useRef(null),me=O.useRef(void 0),$e=O.useRef(null),he=O.useRef(null),W=fO(t??"",l[t??""]??""),X=O.useCallback((Je,bt)=>{w(Je,bt),Mf(Je)&&va.getState().setDraft(Je,bt)},[w]),U=O.useCallback(Je=>{ge.current=Je},[]),ee=O.useCallback(()=>ge.current,[]);O.useEffect(()=>{VR()},[]),O.useEffect(()=>{const Je=t;if(!Je||ov(Je))return;if(Ei.getState().hasBuffer(Je)){x(wt=>wt[Je]==="ready"?wt:{...wt,[Je]:"ready"});return}let bt=!1;return x(wt=>({...wt,[Je]:"loading"})),Mf(Je)?((async()=>{if(await va.getState().loadText(Je,!0),bt)return;const wt=va.getState().files[Je];if(!wt||wt.loadError&&!wt.exists){x(Ke=>({...Ke,[Je]:{error:(wt==null?void 0:wt.loadError)??"failed to read"}}));return}g(Je,wt.diskRaw),wt.dirty&&Ei.getState().setBuffer(Je,wt.draftRaw),x(Ke=>({...Ke,[Je]:"ready"}))})(),()=>{bt=!0}):(window.api.files.read(Je).then(wt=>{bt||(wt.binary?x(Ke=>({...Ke,[Je]:{binary:!0,size:wt.size??0,mime:wt.mime??"application/octet-stream",reason:wt.error??"Binary file"}})):wt.ok?(g(Je,wt.text),x(Ke=>({...Ke,[Je]:"ready"}))):x(Ke=>({...Ke,[Je]:{error:wt.error??"failed to read"}})))}),()=>{bt=!0})},[t,g]),O.useEffect(()=>{M(null)},[t]);const ue=O.useCallback(async(Je,bt=!1)=>{const wt=Ei.getState().buffers[Je];if(wt==null)return;bt&&F(!0);const Ke=Mf(Je);let tt;if(Ke){const Dt=va.getState();if(Dt.setDraft(Je,wt),tt=await Dt.saveText(Je),!tt.ok&&tt.error==="conflict"){bt&&F(!1);return}}else tt=await window.api.files.write(Je,wt);tt.ok?(T(Je),y(Dt=>({...Dt,[Je]:(Dt[Je]??0)+1})),bt||Ze.info(`Saved ${uo(Je)}`)):Ze.error(tt.error??`Couldn't save ${uo(Je)}`),bt&&F(!1)},[T]);O.useEffect(()=>{if(!C.autosave)return;const Je=t;if(!(!Je||ov(Je)||Mf(Je)||!n[Je]))return window.clearTimeout(me.current),me.current=window.setTimeout(()=>{ue(Je,!0)},1200),()=>window.clearTimeout(me.current)},[C.autosave,t,n,l,ue]);const ye=O.useCallback(Je=>{Je.length&&(x(bt=>rv(bt,Je)),y(bt=>rv(bt,Je)))},[]),ze=O.useCallback((Je,bt)=>{x(wt=>Je in wt?{...rv(wt,[Je]),[bt]:wt[Je]}:wt),y(wt=>Je in wt?{...rv(wt,[Je]),[bt]:wt[Je]}:wt)},[]),it=O.useCallback(Je=>{n[Je]?R({kind:"one",path:Je}):(a(Je),ye([Je]))},[n,a,ye]),ve=O.useCallback(Je=>{e.some(wt=>wt.path!==Je&&n[wt.path])?R({kind:"others",path:Je}):(c(Je),ye(e.filter(wt=>wt.path!==Je).map(wt=>wt.path)))},[e,n,c,ye]),J=O.useCallback(Je=>{const bt=e.findIndex(Ke=>Ke.path===Je);bt!==-1&&e.slice(bt+1).some(Ke=>n[Ke.path])?R({kind:"right",path:Je}):(f(Je),ye(bt!==-1?e.slice(bt+1).map(Ke=>Ke.path):[]))},[e,n,f,ye]);O.useEffect(()=>{const Je=bt=>{if(i.current)if((bt.metaKey||bt.ctrlKey)&&(bt.key==="s"||bt.key==="S")){const wt=Ei.getState().activeFilePath;wt&&!ov(wt)&&(bt.preventDefault(),ue(wt))}else if((bt.metaKey||bt.ctrlKey)&&bt.shiftKey&&(bt.key==="f"||bt.key==="F"))bt.preventDefault(),te(wt=>!wt);else if((bt.metaKey||bt.ctrlKey)&&bt.shiftKey&&(bt.key==="w"||bt.key==="W")){const wt=Ei.getState().activeFilePath;wt&&Ei.getState().openFiles.length>1&&(bt.preventDefault(),ve(wt))}else bt.key==="Escape"&&W.state.phase!=="idle"?W.cancel():bt.key==="Escape"&&V&&te(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ue,V,ve,W.state.phase,W.cancel]),O.useEffect(()=>{if(W.state.phase==="idle")return;const Je=bt=>{var Ke,tt;const wt=bt.target;(Ke=he.current)!=null&&Ke.contains(wt)||(tt=$e.current)!=null&&tt.contains(wt)||W.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[W.state.phase,W.cancel]),O.useEffect(()=>{W.cancel()},[t,W.cancel]);const Pe=O.useCallback(()=>{e.some(bt=>n[bt.path])?R({kind:"all",path:""}):(m(),x({}),y({}))},[e,n,m]),ke=()=>{if(D){if(D.kind==="one")a(D.path),ye([D.path]);else if(D.kind==="others"){const Je=e.filter(bt=>bt.path!==D.path).map(bt=>bt.path);c(D.path),ye(Je)}else if(D.kind==="right"){const Je=e.findIndex(wt=>wt.path===D.path),bt=Je!==-1?e.slice(Je+1).map(wt=>wt.path):[];f(D.path),ye(bt)}else m(),x({}),y({});R(null)}};if(e.length===0)return d.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:d.jsxs("div",{className:"text-center",children:[d.jsx("div",{className:"mb-2",children:"no file open"}),d.jsxs("div",{children:["open the ",d.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Se=t,Ee=Se?uo(Se):"",et=Se?b[Se]:void 0,gt=Se?bE(Se):!1,Oe=Se?FR(Se):!1,ct=Se&>?s[Se]??HR(Se):"edit",st=!!Se&&!ov(Se)&&et==="ready",Qt=st,oi=Oe?["edit","wysiwyg","preview","split"]:gt?["edit","preview"]:[],hi=Se&&d.jsx($N,{path:Se,name:Ee,value:l[Se]??"",onChange:Je=>X(Se,Je),onSave:()=>void ue(Se),onReady:U,onCursor:M}),Ai=j?"Saving…":Se&&n[Se]?C.autosave&&!Mf(Se)?"Editing…":"Unsaved":"All changes saved";return d.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&d.jsx(vj,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:it,onCloseOthers:ve,onCloseToTheRight:J,onCloseAll:Pe}),Se&&!V&&d.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[d.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ee}),d.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Se}),st&&d.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",Ai]}),il(Se)&&(ct==="preview"||ct==="split")&&d.jsx("button",{onClick:()=>Q(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),il(Se)&&(ct==="preview"||ct==="split")&&d.jsx("button",{onClick:C.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${C.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),oi.length>0&&d.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:oi.map(Je=>d.jsx("button",{onClick:()=>k(Se,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ct===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),d.jsx("div",{className:"flex-1"}),d.jsx(xO,{path:Se,onRenamed:ze,onDeleted:Je=>ye([Je])}),st&&d.jsx(CO,{}),d.jsx("button",{onClick:()=>te(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&d.jsx("button",{onClick:()=>te(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),d.jsx("div",{className:"flex-1 min-h-0",children:Se?mE(Se)?d.jsx(ZM,{path:Se,name:Ee}):gE(Se)?d.jsx(QM,{path:Se}):et&&typeof et=="object"&&"binary"in et?d.jsx(rO,{path:Se,name:Ee,size:et.size,mime:et.mime,reason:et.reason}):et&&typeof et=="object"&&"error"in et?d.jsx("div",{className:"p-6 text-xs text-red-400",children:et.error}):et!=="ready"?d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ct==="wysiwyg"&&il(Se)?d.jsx(O.Suspense,{fallback:d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:d.jsx(kO,{value:l[Se]??"",onChange:Je=>X(Se,Je)},Se)}):ct==="split"&&il(Se)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(GS,{text:l[Se]??"",scrollRef:oe}),d.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[d.jsx(BS,{getEditor:ee}),d.jsx("div",{className:"flex-1 min-h-0",children:hi})]}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(gw,{ref:oe,text:l[Se]??"",flush:!0,wideMeasure:C.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!V&&C.assistantRail&&d.jsx(US,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):ct==="preview"&&il(Se)?d.jsxs("div",{className:"flex h-full",children:[de&&d.jsx(GS,{text:l[Se]??"",scrollRef:oe}),d.jsx("div",{ref:$e,className:"flex-1 min-w-0",children:d.jsx(gw,{ref:oe,text:l[Se]??"",wideMeasure:C.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!V&&C.assistantRail&&d.jsx(US,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)},onReject:W.cancel,onRetry:W.retry})]}):ct==="preview"&&fE(Se)?d.jsx(XM,{path:Se,dirty:!!n[Se],reloadToken:S[Se]??0}):ct==="preview"&&vE(Se)?d.jsx(tO,{path:Se,text:l[Se]??""}):ct==="preview"&&_E(Se)?d.jsx(sO,{path:Se,text:l[Se]??""}):il(Se)?d.jsxs("div",{className:"flex flex-col h-full",children:[d.jsx(BS,{getEditor:ee}),d.jsx("div",{className:"flex-1 min-h-0",children:hi})]}):hi:null}),Qt&&d.jsx(YM,{text:l[Se]??"",cursor:N,language:Wr(Se)||void 0}),Se&&il(Se)&&(ct==="preview"||ct==="split")&&W.state.phase!=="idle"&&W.state.selection&&d.jsx("div",{ref:he,children:d.jsx(_O,{phase:W.state.phase,rect:W.state.selection.rect,selectedText:W.state.selection.text,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Je=W.accept(l[Se]??"");Je.ok&&X(Se,Je.next)}})}),D&&d.jsx(TO,{message:D.kind==="one"?`Discard unsaved changes to ${uo(D.path)}?`:D.kind==="others"?"Discard unsaved changes in the other open files?":D.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>R(null),onConfirm:ke})]})}const bw=O.memo(EO);function TO({message:i,onCancel:e,onConfirm:t}){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),d.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const DO="~/.claude/session-manager/projects-prefs.json";let qS=Promise.resolve(),av=null;function KS(i){const e=qS.then(i);return qS=e.catch(()=>{}),e}const KE=()=>Sa(DO);async function YS(){const i=(await KE().read()).pinned;return i&&typeof i=="object"?{...i}:{}}const ab=Un(i=>({pinned:{},hydrated:!1,hydrate:()=>av||(av=KS(async()=>{try{i({pinned:await YS(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),i({hydrated:!0})}}),av),togglePin:e=>{KS(async()=>{let t;try{t=await YS()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),Ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const n={...t};n[e]?delete n[e]:n[e]=!0;try{await KE().patch({pinned:n}),i({pinned:n})}catch(s){i({pinned:t}),Ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function $O(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function AO(i,e,t){const n=O.useRef(e);n.current=e;const s=Array.from(new Set(i.filter(p=>!!p).map($O))),l=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;O.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const p=window.api.config.onChanged(a=>{s.includes(a.path)&&n.current(a.path)});return()=>{p(),window.api.config.unwatch(s,t)}},[l])}function $x(i){return/^[A-Za-z]:[\\/]/.test(i)&&i.includes("\\")||i.includes("\\")&&!i.includes("/")?"\\":"/"}function YE(i){return i.split(/[\\/]+/).filter(Boolean)}function XE(i){const e=YE(i);return e.length?e[e.length-1]:i}function XS(i){const e=i.length>1?i.replace(/[\\/]+$/,""):i,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 IO(...i){const e=i.filter(s=>s!=="");if(!e.length)return"";const t=$x(e[0]);let n=e[0];for(const s of e.slice(1))n=n.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return n}const JS=i=>i.replace(/\\/g,"/").replace(/\/+$/,"");function pm(i,e){return JS(i).startsWith(JS(e)+"/")}async function PO(i){const e=await Sm(i);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function RO(i,e){return Ed(i,{fileTreeExpanded:[...e].slice(0,500)})}async function jO(){const i=await o_();return typeof i.fileTreeShowHidden=="boolean"?i.fileTreeShowHidden:!0}function NO(i){a_({fileTreeShowHidden:i}).catch(()=>{})}function lb(i,e){let t=!1;const n=new Set;for(const s of i){if(s===e||pm(s,e)){t=!0;continue}n.add(s)}return t?n:i}const cb={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:"!"}},MO=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 OO(i){const e=Wr(i);return MO.has(e)||pE.has(e)||e==="pdf"}function LO(i,e){if(e)return"#d97757";switch(Wr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function Of(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}const ZS=64,zO=250,BO={depth:0};function db(i){const e=i.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function GO({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const s=nx(),l=Qv(),[p,a]=O.useState([]),[c,f]=O.useState(new Set),m=O.useRef(c);m.current=c;const g=O.useRef(!1),[w,T]=O.useState(""),[k,C]=O.useState(!0),b=O.useRef(!1);O.useEffect(()=>{let Ke=!1;return jO().then(tt=>{!Ke&&!b.current&&C(tt)}),()=>{Ke=!0}},[]);const x=O.useCallback(Ke=>{b.current=!0,C(tt=>{const Dt=typeof Ke=="function"?Ke(tt):Ke;return NO(Dt),Dt})},[]),[S,y]=O.useState(!1),[D,R]=O.useState(null),[N,M]=O.useState({}),[j,F]=O.useState(null),[V,te]=O.useState(null),[de,Q]=O.useState(""),[ge,oe]=O.useState(null),[me,$e]=O.useState(""),[he,W]=O.useState(null),X=O.useRef(null),U=O.useRef(null),ee=O.useRef(0),ue=O.useCallback(async()=>{if(!i)return;const Ke=++ee.current;y(!0),R(null);const tt=await window.api.files.list(i,k);ee.current===Ke&&(tt.ok?a(tt.entries.map(Dt=>({...Dt}))):(R(tt.error??"failed to list"),a([])),y(!1))},[i,k]),ye=O.useCallback(async Ke=>{const tt=ee.current,Dt=new Map;for(const mi of Ke){const gi=YE(mi).length,Mt=Dt.get(gi);Mt?Mt.push(mi):Dt.set(gi,[mi])}const Zt=[];for(const mi of[...Dt.keys()].sort((gi,Mt)=>gi-Mt)){const gi=Dt.get(mi),Mt=await Promise.all(gi.map(async ai=>({p:ai,result:await window.api.files.list(ai,k)})));if(ee.current!==tt)return Zt;for(const{p:ai,result:Vn}of Mt)Vn.ok?a(ss=>Sv(ss,ai,Vn.entries.map(qn=>({...qn})))):Zt.push(ai)}return Zt},[k]),ze=O.useCallback(async Ke=>(await ue(),Ke.length?ye(Ke):[]),[ue,ye]);O.useEffect(()=>{T(""),te(null),F(null),oe(null),W(null),M({});let Ke=!1;return g.current=!1,(async()=>{const[tt]=await Promise.all([PO(i),ue()]);if(Ke)return;if(!g.current){const Zt=new Set(tt);m.current=Zt,f(Zt)}if(!tt.length)return;const Dt=await ye(tt);Ke||!Dt.length||et(Zt=>{const mi=new Set;let gi=!1;for(const Mt of Zt){if(Dt.some(ai=>Mt===ai||pm(Mt,ai))){gi=!0;continue}mi.add(Mt)}return gi?mi:Zt})})(),Of(i).then(tt=>{Ke||M(tt)}),()=>{Ke=!0}},[i]);const it=O.useRef(!0);O.useEffect(()=>{if(it.current){it.current=!1;return}ze([...m.current])},[k]),O.useEffect(()=>{if(!i||!l)return;Of(i).then(M);const Ke=window.setInterval(()=>{Of(i).then(M)},5e3);return()=>window.clearInterval(Ke)},[i,l]);const ve=O.useMemo(()=>{if(!i)return[];const Ke=[...c].filter(tt=>tt!==i);return[i,...Ke.slice(-63)]},[i,c]),J=O.useRef(!1);O.useEffect(()=>{!i||c.size+1<=ZS||J.current||(J.current=!0,console.warn(`FileTree: watching only ${ZS} of ${c.size+1} folders (cap reached)`))},[i,c]);const Pe=O.useRef(new Map),ke=O.useRef(new Set),Se=O.useRef(!1);Se.current=V!==null||ge!==null;const Ee=O.useRef(()=>{});Ee.current=Ke=>{if(!(Ke!==db(i)&&!m.current.has(Ke))){if(Se.current){ke.current.add(Ke);return}Ke===db(i)?ze([...m.current]):Oe(Ke)}},AO(ve,Ke=>{if(Ke!==db(i)&&!m.current.has(Ke))return;const tt=Pe.current,Dt=tt.get(Ke);Dt&&clearTimeout(Dt),tt.set(Ke,setTimeout(()=>{tt.delete(Ke),Ee.current(Ke)},zO))},BO),O.useEffect(()=>{if(V!==null||ge!==null)return;const Ke=[...ke.current];ke.current.clear();for(const tt of Ke)Ee.current(tt)},[V,ge]),O.useEffect(()=>{const Ke=Pe.current,tt=ke.current;return()=>{for(const Dt of Ke.values())clearTimeout(Dt);Ke.clear(),tt.clear()}},[i]),O.useEffect(()=>{if(!j)return;const Ke=()=>F(null),tt=Dt=>{s.current&&Dt.key==="Escape"&&F(null)};return window.addEventListener("mousedown",Ke),window.addEventListener("keydown",tt),()=>{window.removeEventListener("mousedown",Ke),window.removeEventListener("keydown",tt)}},[j]),O.useEffect(()=>{V&&setTimeout(()=>{var Ke;return(Ke=X.current)==null?void 0:Ke.select()},30)},[V]),O.useEffect(()=>{ge&&setTimeout(()=>{var Ke;return(Ke=U.current)==null?void 0:Ke.focus()},30)},[ge]);const et=O.useCallback(Ke=>{const tt=m.current,Dt=Ke(tt);Dt!==tt&&(g.current=!0,m.current=Dt,f(Dt),RO(i,Dt).catch(()=>{m.current===Dt&&(m.current=tt,f(tt),Ze.error("Couldn't save folder expansion — reverted."))}))},[i]),gt=O.useCallback(async Ke=>{if(c.has(Ke.path)){et(Dt=>lb(Dt,Ke.path));return}if(et(Dt=>new Set(Dt).add(Ke.path)),Ke.children)return;const tt=await window.api.files.list(Ke.path,k);tt.ok&&a(Dt=>Sv(Dt,Ke.path,tt.entries.map(Zt=>({...Zt}))))},[c,k,et]),Oe=O.useCallback(async Ke=>{if(Ke===i){await ue();return}const tt=await window.api.files.list(Ke,k);tt.ok&&a(Dt=>Sv(Dt,Ke,tt.entries.map(Zt=>({...Zt}))))},[i,ue,k]),ct=O.useCallback(Ke=>{if(Ke.isDirectory){gt(Ke);return}OO(Ke.name)&&e?e(Ke.path):window.api.shell.open({as:"openPath",path:Ke.path})},[gt,e]),st=O.useCallback(Ke=>{if(t){t(Ke);return}if(n){const tt=pm(Ke,i)?Ke.slice(i.replace(/[\\/]+$/,"").length+1):Ke;window.api.pty.write({tabId:n,data:`@${tt} `})}},[t,n,i]),Qt=O.useCallback((Ke,tt)=>{Ke.preventDefault(),Ke.stopPropagation(),F({x:Ke.clientX,y:Ke.clientY,node:tt})},[]),oi=Ke=>{te(Ke.path),Q(Ke.name)},hi=async()=>{if(!V)return;const Ke=de.trim();if(!Ke){te(null);return}const tt=await window.api.files.rename(V,Ke);if(te(null),tt.ok){const Dt=XS(V);et(Zt=>lb(Zt,V)),await Oe(Dt||i),Of(i).then(M)}else{const Dt=tt.error??"rename failed";R(Dt),Ze.error(Dt)}},Ai=async()=>{if(!ge)return;const Ke=me.trim();if(!Ke){oe(null),$e("");return}const tt=await window.api.files.create(ge.parent,Ke,ge.kind);if(oe(null),$e(""),tt.ok)await Oe(ge.parent),ge.kind==="folder"&&et(Dt=>new Set(Dt).add(ge.parent));else{const Dt=tt.error??"create failed";R(Dt),Ze.error(Dt)}},Je=async()=>{if(!he)return;const Ke=await window.api.files.delete(he.path),tt=XS(he.path);if(W(null),Ke.ok)et(Dt=>lb(Dt,he.path)),await Oe(tt||i),Of(i).then(M);else{const Dt=Ke.error??"delete failed";R(Dt),Ze.error(Dt)}},bt=O.useMemo(()=>{if(!w.trim())return p;const Ke=w.toLowerCase();return p.filter(tt=>tt.name.toLowerCase().includes(Ke))},[p,w]),wt=(i?XE(i):"")||"project";return d.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[d.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[d.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[d.jsx(ZE,{size:14,className:"shrink-0 text-accent"}),d.jsxs("div",{className:"flex-1 min-w-0",children:[d.jsx("p",{className:"text-xs font-medium text-fg truncate",children:wt}),d.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),d.jsx("button",{onClick:ue,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:S,children:d.jsx(qO,{size:12,className:S?"animate-spin":""})})]}),d.jsx("div",{className:"relative",children:d.jsx("input",{value:w,onChange:Ke=>T(Ke.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),d.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[d.jsx("button",{onClick:()=>oe({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:d.jsx(KO,{size:12})}),d.jsx("button",{onClick:()=>oe({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:d.jsx(YO,{size:12})}),d.jsx("div",{className:"flex-1"}),d.jsx("button",{onClick:()=>x(Ke=>!Ke),className:`p-1.5 rounded transition-colors ${k?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:k?"Hide hidden files":"Show hidden files",children:k?d.jsx(XO,{size:12}):d.jsx(JO,{size:12})})]}),d.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[D&&d.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:D}),!D&&bt.length===0&&!S&&d.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:w?"no matches":"empty folder"}),!D&&d.jsx(JE,{nodes:bt,depth:0,expanded:c,gitStatus:N,renaming:V,renameValue:de,renameInputRef:X,onRenameChange:Q,onRenameCommit:hi,onRenameCancel:()=>te(null),onToggleDir:gt,onFileClick:ct,onSendToChat:st,onContextMenu:Qt})]}),d.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),j&&d.jsx(FO,{x:j.x,y:j.y,node:j.node,onClose:()=>F(null),onRename:()=>{oi(j.node),F(null)},onDelete:()=>{W(j.node),F(null)},onNewFile:()=>{oe({parent:j.node.path,kind:"file"}),F(null)},onNewFolder:()=>{oe({parent:j.node.path,kind:"folder"}),F(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:j.node.path}),F(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:j.node.path}),F(null)},onCopyPath:()=>{const Ke=j.node.path;ya(Ke).then(tt=>{tt||Ze.error("Couldn't copy path")}),F(null)},onSendToChat:()=>{st(j.node.path),F(null)}}),ge&&d.jsx(QS,{title:`New ${ge.kind}`,subtitle:`in ${HO(ge.parent)}`,onCancel:()=>{oe(null),$e("")},onConfirm:Ai,confirmLabel:"Create",confirmDisabled:!me.trim(),children:d.jsx("input",{ref:U,value:me,onChange:Ke=>$e(Ke.target.value),onKeyDown:Ke=>{Ke.key==="Enter"&&Ai(),Ke.key==="Escape"&&(oe(null),$e(""))},placeholder:ge.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"})}),he&&d.jsx(QS,{title:`Delete ${he.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>W(null),onConfirm:Je,confirmLabel:"Delete",danger:!0,children:d.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",d.jsxs("span",{className:"text-fg font-medium",children:['"',he.name,'"']})," to the trash?",he.isDirectory&&d.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function JE(i){const{nodes:e,depth:t,expanded:n,gitStatus:s,renaming:l,onContextMenu:p}=i;return d.jsx(d.Fragment,{children:e.map(a=>{const c=n.has(a.path),f=l===a.path,m=s[a.path],g=LO(a.name,a.isDirectory);return d.jsxs("div",{children:[d.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:w=>p(w,a),children:[a.isDirectory?d.jsx(VO,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):d.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?c?d.jsx(WO,{size:12,color:g}):d.jsx(ZE,{size:12,color:g}):d.jsx(UO,{size:12,color:g}),f?d.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:w=>i.onRenameChange(w.target.value),onClick:w=>w.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:w=>{w.key==="Enter"&&i.onRenameCommit(),w.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):d.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),m&&d.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:cb[m].color,backgroundColor:`${cb[m].color}20`},title:m,children:cb[m].label}),!a.isDirectory&&d.jsx("button",{onClick:w=>{w.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:d.jsx(ZO,{size:10})})]}),a.isDirectory&&c&&a.children&&d.jsx(JE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function FO(i){const{x:e,y:t,node:n}=i;return d.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${yn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&d.jsx(ql,{label:"Send to chat",onClick:i.onSendToChat}),d.jsx(ql,{label:"Open in default app",onClick:i.onOpenExternal}),d.jsx(ql,{label:"Reveal in OS",onClick:i.onShowInFinder}),d.jsx(ub,{}),d.jsx(ql,{label:"Copy path",onClick:i.onCopyPath}),d.jsx(ql,{label:"Rename",onClick:i.onRename}),n.isDirectory&&d.jsxs(d.Fragment,{children:[d.jsx(ub,{}),d.jsx(ql,{label:"New file",onClick:i.onNewFile}),d.jsx(ql,{label:"New folder",onClick:i.onNewFolder})]}),d.jsx(ub,{}),d.jsx(ql,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function ql({label:i,onClick:e,danger:t}){return d.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function ub(){return d.jsx("div",{className:"my-1 border-t border-line"})}function QS(i){return d.jsx("div",{className:`fixed inset-0 ${yn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:d.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[d.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&d.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),d.jsx("div",{className:"mb-4",children:i.children}),d.jsxs("div",{className:"flex justify-end gap-2",children:[d.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),d.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function HO(i){return XE(i)}function Sv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Sv(n.children,e,t)}:n)}function ka({size:i,children:e,className:t,color:n}){return d.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function ZE({size:i,className:e,color:t}){return d.jsx(ka,{size:i,className:e,color:t,children:d.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function WO({size:i,className:e,color:t}){return d.jsx(ka,{size:i,className:e,color:t,children:d.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function UO({size:i,className:e,color:t}){return d.jsxs(ka,{size:i,className:e,color:t,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function VO({size:i,className:e}){return d.jsx(ka,{size:i,className:e,children:d.jsx("polyline",{points:"9 18 15 12 9 6"})})}function qO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("polyline",{points:"23 4 23 10 17 10"}),d.jsx("polyline",{points:"1 20 1 14 7 14"}),d.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function KO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),d.jsx("polyline",{points:"14 2 14 8 20 8"}),d.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),d.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function YO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),d.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),d.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function XO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),d.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function JO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),d.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function ZO({size:i,className:e}){return d.jsxs(ka,{size:i,className:e,children:[d.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),d.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function QE({content:i,children:e,align:t="bottom-right"}){const[n,s]=O.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return d.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,n&&d.jsx("span",{role:"tooltip",className:`absolute ${yn.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function im(i,e){if(!e)return i;const t=$x(e),n=e.length>1?e.replace(/[\\/]+$/,""):e;if(i===n)return"~";const s=n.endsWith(t)?n:`${n}${t}`;return i.startsWith(s)?`~${t}${i.slice(s.length)}`:i}function hb(i){a_(i).catch(()=>Ze.error("Couldn't save File Explorer layout."))}const pb=33,QO=20,e3=60,t3=32;function e1(i){return Math.min(e3,Math.max(QO,i))}function i3(){const i=Tt(te=>te.tabs),e=Tt(te=>te.activeTabId),t=i.find(te=>te.id===e)??null,n=ki(te=>te.navFace),s=s_(),l=n==="home"?s:(t==null?void 0:t.cwd)??null,[p,a]=O.useState(pb),[c,f]=O.useState(!1),m=O.useRef(!1),[g,w]=O.useState(!1),T=O.useRef(p);T.current=p;const k=O.useRef(c);k.current=c;const C=O.useRef(null),b=O.useRef(null),{projects:x,openProject:S,archiveProjectByCwd:y}=Dd(),D=ab(te=>te.pinned),R=ab(te=>te.togglePin);O.useEffect(()=>{ab.getState().hydrate()},[]),O.useEffect(()=>{let te=!1;return o_().then(de=>{te||m.current||(typeof de.projectsSplitPct=="number"&&Number.isFinite(de.projectsSplitPct)&&a(e1(de.projectsSplitPct)),typeof de.projectsFileTreeCollapsed=="boolean"&&f(de.projectsFileTreeCollapsed))}),()=>{te=!0}},[]);const N=[...x].sort((te,de)=>(D[de.cwd]?1:0)-(D[te.cwd]?1:0));O.useEffect(()=>{if(!g)return;const te=de=>{b.current&&!b.current.contains(de.target)&&w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[g]);const M=O.useCallback(te=>{Ei.getState().openFile(te)},[]),j=O.useCallback(te=>{te.preventDefault(),m.current=!0;const de=te.clientX,Q=T.current;let ge=Q;const oe=$e=>{const he=C.current;if(!he)return;const W=he.getBoundingClientRect(),X=$e.clientX-de;ge=e1(Q+X/W.width*100),a(ge)},me=()=>{window.removeEventListener("pointermove",oe),window.removeEventListener("pointerup",me),document.body.style.cursor="",document.body.style.userSelect="",hb({projectsSplitPct:ge})};window.addEventListener("pointermove",oe),window.addEventListener("pointerup",me),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),F=O.useCallback(()=>{m.current=!0,a(pb),hb({projectsSplitPct:pb})},[]),V=O.useCallback(()=>{m.current=!0;const te=!k.current;f(te),hb({projectsFileTreeCollapsed:te})},[]);return c?d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("button",{onClick:V,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:t3},children:[d.jsx("span",{className:"text-[11px]",children:"▸"}),d.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(bw,{})})]}):d.jsxs("div",{ref:C,className:"flex h-full w-full","data-testid":"projects-workspace",children:[d.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${p}%`},"data-testid":"projects-file-tree-pane",children:[d.jsxs("div",{ref:b,className:"relative shrink-0 flex items-stretch border-b border-line",children:[d.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>w(te=>!te),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[d.jsx("span",{className:"flex-1 truncate text-left",children:l?im(l,s):"Projects"}),d.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:g?"▲":"▼"})]}),d.jsx("button",{onClick:V,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),g&&d.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${yn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:N.length===0?d.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):N.map(te=>{const de=im(te.cwd,s);return d.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[d.jsx(QE,{content:D[te.cwd]?"Unpin":"Pin to top",children:d.jsx("button",{onClick:()=>R(te.cwd),className:`shrink-0 text-sm leading-none transition-colors ${D[te.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:D[te.cwd]?"★":"☆"})}),d.jsx("button",{onClick:()=>{S(te.cwd),w(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:de}),d.jsx("button",{onClick:async()=>{window.confirm(`Archive ${de}?`)&&await y(te)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},te.cwd)})})]}),l?d.jsxs(d.Fragment,{children:[d.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:l,children:im(l,s)}),d.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:d.jsx(GO,{cwd:l,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:M})})]}):d.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),d.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:j,onDoubleClick:F,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),d.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:d.jsx(bw,{})})]})}const n3=O.memo(i3),s3={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The 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 r3({content:i}){return d.jsxs(d.Fragment,{children:[d.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>d.jsxs("div",{className:"mb-3 last:mb-0",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),d.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>d.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&d.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",d.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&d.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[d.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),d.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>d.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function o3({active:i}){const e=Wn(g=>g.learningPanelCollapsed),t=Wn(g=>g.setLearningPanelCollapsed),n=Wn(g=>g.hydrated),s=Wn(g=>g.hydrate);O.useEffect(()=>{n||s()},[n,s]);const[l,p]=O.useState(()=>!e),a=O.useRef(null);O.useEffect(()=>{n&&p(!e)},[n]);const c=O.useCallback(()=>{p(g=>{const w=!g;return t(!w),w})},[t]);O.useEffect(()=>{if(!l)return;const g=w=>{var T;(T=a.current)!=null&&T.contains(w.target)||(p(!1),t(!0))};return document.addEventListener("mousedown",g),()=>document.removeEventListener("mousedown",g)},[l,t]);const f=O.useRef(!1);O.useEffect(()=>{if(!f.current){f.current=!0;return}p(!1)},[i]);const m=s3[i];return m?d.jsxs("span",{ref:a,className:"relative inline-block",children:[d.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":l,title:l?"Close learning panel":"What is this?",children:"Learn"}),l&&d.jsx("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:d.jsx(r3,{content:m})})]}):null}function a3({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:s,children:l}){const p=n&&(i||e||t);return d.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&d.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[d.jsxs("div",{className:"max-w-[820px]",children:[i&&d.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&d.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&d.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),s&&d.jsx(o3,{active:s})]}),d.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const l3=O.lazy(()=>Oi(()=>import("./History-DzMo9Otn.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(i=>({default:i.History}))),c3=O.lazy(()=>Oi(()=>import("./Scheduler-CkGHMXvo.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),d3=O.lazy(()=>Oi(()=>import("./Settings-DGxvyajs.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(i=>({default:i.Settings}))),u3=O.lazy(()=>Oi(()=>import("./SystemPrompt-CfozyVQx.js"),__vite__mapDeps([15,4,8,9,10,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),h3=O.lazy(()=>Oi(()=>import("./Memory-Bq5T33d2.js"),__vite__mapDeps([16,17,1,2]),import.meta.url).then(i=>({default:i.Memory}))),p3=O.lazy(()=>Oi(()=>import("./Extensions-BziIutWV.js"),__vite__mapDeps([18,11,10,4,13,8,9,19,14,1,2]),import.meta.url).then(i=>({default:i.Extensions}))),f3=O.lazy(()=>Oi(()=>import("./AppSettings-Bpwynea4.js"),__vite__mapDeps([20,11,10,19,17,4,1,2]),import.meta.url).then(i=>({default:i.AppSettings}))),m3=O.lazy(()=>Oi(()=>import("./AgentLibrary-Bfj862qf.js"),__vite__mapDeps([21,4,13,11,10,9,12,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),g3=d.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Kl({children:i}){return d.jsx(O.Suspense,{fallback:g3,children:i})}const v3={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:"Memory",intro:"Claude Code's own memory files for this project and its subagents — a MEMORY.md index plus topic files. Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads."},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},t1=new Map;function _3(i,e){const t=t1.get(i);if(t&&t.ctx===e)return t.node;const n=b3(i,e);return t1.set(i,{ctx:e,node:n}),n}function b3(i,e){switch(i){case"overview":return d.jsx(pR,{onNavigate:e.onNavigate});case"project-home":return d.jsx(pj,{});case"editor":return d.jsx(bw,{});case"projects":return d.jsx(n3,{})}const t=v3[i],n=(()=>{switch(i){case"history":return d.jsx(Kl,{children:d.jsx(l3,{})});case"scheduler":return d.jsx(Kl,{children:d.jsx(c3,{navigate:e.onNavigate})});case"memory":return d.jsx(Kl,{children:d.jsx(h3,{})});case"system-prompt":return d.jsx(Kl,{children:d.jsx(u3,{})});case"settings":return d.jsx(Kl,{children:d.jsx(d3,{scope:"user"})});case"extensions":return d.jsx(Kl,{children:d.jsx(p3,{})});case"app-settings":return d.jsx(Kl,{children:d.jsx(f3,{})});case"agent-library":return d.jsx(Kl,{children:d.jsx(m3,{})});default:return null}})();if(!n)return null;const s=uD[i];return t&&s?d.jsx(a3,{eyebrow:s,title:t.title,intro:t.intro,learnKey:i,children:n}):n}class w3 extends O.Component{constructor(){super(...arguments);Vi(this,"state",{error:null});Vi(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):d.jsxs("div",{className:"p-6 text-xs",children:[d.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),d.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),d.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}var fb={exports:{}},i1;function x3(){return i1||(i1=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,c){var f=this&&this.__decorate||function(S,y,D,R){var N,M=arguments.length,j=M<3?y:R===null?R=Object.getOwnPropertyDescriptor(y,D):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(S,y,D,R);else for(var F=S.length-1;F>=0;F--)(N=S[F])&&(j=(M<3?N(j):M>3?N(y,D,j):N(y,D))||j);return M>3&&j&&Object.defineProperty(y,D,j),j},m=this&&this.__param||function(S,y){return function(D,R){y(D,R,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const g=c(9042),w=c(9924),T=c(844),k=c(4725),C=c(2585),b=c(3656);let x=a.AccessibilityManager=class extends T.Disposable{constructor(S,y,D,R){super(),this._terminal=S,this._coreBrowserService=D,this._renderService=R,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new w.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3038
3038
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,b.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,T.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(S){for(let y=0;y<S;y++)this._handleChar(" ")}_handleChar(S){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==S&&(this._charsToAnnounce+=S):this._charsToAnnounce+=S,S===`
|
|
3039
3039
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(S){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(S)||this._charsToConsume.push(S)}_refreshRows(S,y){this._liveRegionDebouncer.refresh(S,y,this._terminal.rows)}_renderRows(S,y){const D=this._terminal.buffer,R=D.lines.length.toString();for(let N=S;N<=y;N++){const M=D.lines.get(D.ydisp+N),j=[],F=(M==null?void 0:M.translateToString(!0,void 0,void 0,j))||"",V=(D.ydisp+N+1).toString(),te=this._rowElements[N];te&&(F.length===0?(te.innerText=" ",this._rowColumns.set(te,[0,1])):(te.textContent=F,this._rowColumns.set(te,j)),te.setAttribute("aria-posinset",V),te.setAttribute("aria-setsize",R))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(S,y){const D=S.target,R=this._rowElements[y===0?1:this._rowElements.length-2];if(D.getAttribute("aria-posinset")===(y===0?"1":`${this._terminal.buffer.lines.length}`)||S.relatedTarget!==R)return;let N,M;if(y===0?(N=D,M=this._rowElements.pop(),this._rowContainer.removeChild(M)):(N=this._rowElements.shift(),M=D,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),M.removeEventListener("focus",this._bottomBoundaryFocusListener),y===0){const j=this._createAccessibilityTreeNode();this._rowElements.unshift(j),this._rowContainer.insertAdjacentElement("afterbegin",j)}else{const j=this._createAccessibilityTreeNode();this._rowElements.push(j),this._rowContainer.appendChild(j)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(y===0?-1:1),this._rowElements[y===0?1:this._rowElements.length-2].focus(),S.preventDefault(),S.stopImmediatePropagation()}_handleSelectionChange(){var F;if(this._rowElements.length===0)return;const S=document.getSelection();if(!S)return;if(S.isCollapsed)return void(this._rowContainer.contains(S.anchorNode)&&this._terminal.clearSelection());if(!S.anchorNode||!S.focusNode)return void console.error("anchorNode and/or focusNode are null");let y={node:S.anchorNode,offset:S.anchorOffset},D={node:S.focusNode,offset:S.focusOffset};if((y.node.compareDocumentPosition(D.node)&Node.DOCUMENT_POSITION_PRECEDING||y.node===D.node&&y.offset>D.offset)&&([y,D]=[D,y]),y.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(y={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(y.node))return;const R=this._rowElements.slice(-1)[0];if(D.node.compareDocumentPosition(R)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(D={node:R,offset:((F=R.textContent)==null?void 0:F.length)??0}),!this._rowContainer.contains(D.node))return;const N=({node:V,offset:te})=>{const de=V instanceof Text?V.parentNode:V;let Q=parseInt(de==null?void 0:de.getAttribute("aria-posinset"),10)-1;if(isNaN(Q))return console.warn("row is invalid. Race condition?"),null;const ge=this._rowColumns.get(de);if(!ge)return console.warn("columns is null. Race condition?"),null;let oe=te<ge.length?ge[te]:ge.slice(-1)[0]+1;return oe>=this._terminal.cols&&(++Q,oe=0),{row:Q,column:oe}},M=N(y),j=N(D);if(M&&j){if(M.row>j.row||M.row===j.row&&M.column>=j.column)throw new Error("invalid range");this._terminal.select(M.column,M.row,(j.row-M.row)*this._terminal.cols-M.column+j.column)}}_handleResize(S){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let y=this._rowContainer.children.length;y<this._terminal.rows;y++)this._rowElements[y]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[y]);for(;this._rowElements.length>S;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const S=this._coreBrowserService.mainDocument.createElement("div");return S.setAttribute("role","listitem"),S.tabIndex=-1,this._refreshRowDimensions(S),S}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let S=0;S<this._terminal.rows;S++)this._refreshRowDimensions(this._rowElements[S])}}_refreshRowDimensions(S){S.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=x=f([m(1,C.IInstantiationService),m(2,k.ICoreBrowserService),m(3,k.IRenderService)],x)},3614:(p,a)=>{function c(w){return w.replace(/\r?\n/g,"\r")}function f(w,T){return T?"\x1B[200~"+w+"\x1B[201~":w}function m(w,T,k,C){w=f(w=c(w),k.decPrivateModes.bracketedPasteMode&&C.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(w,!0),T.value=""}function g(w,T,k){const C=k.getBoundingClientRect(),b=w.clientX-C.left-10,x=w.clientY-C.top-10;T.style.width="20px",T.style.height="20px",T.style.left=`${b}px`,T.style.top=`${x}px`,T.style.zIndex="1000",T.focus()}Object.defineProperty(a,"__esModule",{value:!0}),a.rightClickHandler=a.moveTextAreaUnderMouseCursor=a.paste=a.handlePasteEvent=a.copyHandler=a.bracketTextForPaste=a.prepareTextForTerminal=void 0,a.prepareTextForTerminal=c,a.bracketTextForPaste=f,a.copyHandler=function(w,T){w.clipboardData&&w.clipboardData.setData("text/plain",T.selectionText),w.preventDefault()},a.handlePasteEvent=function(w,T,k,C){w.stopPropagation(),w.clipboardData&&m(w.clipboardData.getData("text/plain"),T,k,C)},a.paste=m,a.moveTextAreaUnderMouseCursor=g,a.rightClickHandler=function(w,T,k,C,b){g(w,T,k),b&&C.rightClickSelect(w),T.value=C.selectionText,T.select()}},7239:(p,a,c)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorContrastCache=void 0;const f=c(1505);a.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.TwoKeyMap}setCss(m,g,w){this._css.set(m,g,w)}getCss(m,g){return this._css.get(m,g)}setColor(m,g,w){this._color.set(m,g,w)}getColor(m,g){return this._color.get(m,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(c,f,m,g){c.addEventListener(f,m,g);let w=!1;return{dispose:()=>{w||(w=!0,c.removeEventListener(f,m,g))}}}},3551:function(p,a,c){var f=this&&this.__decorate||function(x,S,y,D){var R,N=arguments.length,M=N<3?S:D===null?D=Object.getOwnPropertyDescriptor(S,y):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(x,S,y,D);else for(var j=x.length-1;j>=0;j--)(R=x[j])&&(M=(N<3?R(M):N>3?R(S,y,M):R(S,y))||M);return N>3&&M&&Object.defineProperty(S,y,M),M},m=this&&this.__param||function(x,S){return function(y,D){S(y,D,x)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const g=c(3656),w=c(8460),T=c(844),k=c(2585),C=c(4725);let b=a.Linkifier=class extends T.Disposable{get currentLink(){return this._currentLink}constructor(x,S,y,D,R){super(),this._element=x,this._mouseService=S,this._renderService=y,this._bufferService=D,this._linkProviderService=R,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new w.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new w.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,T.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,T.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(x){this._lastMouseEvent=x;const S=this._positionFromMouseEvent(x,this._element,this._mouseService);if(!S)return;this._isMouseOut=!1;const y=x.composedPath();for(let D=0;D<y.length;D++){const R=y[D];if(R.classList.contains("xterm"))break;if(R.classList.contains("xterm-hover"))return}this._lastBufferCell&&S.x===this._lastBufferCell.x&&S.y===this._lastBufferCell.y||(this._handleHover(S),this._lastBufferCell=S)}_handleHover(x){if(this._activeLine!==x.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(x,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,x)||(this._clearCurrentLink(),this._askForLink(x,!0))}_askForLink(x,S){var D,R;this._activeProviderReplies&&S||((D=this._activeProviderReplies)==null||D.forEach((N=>{N==null||N.forEach((M=>{M.link.dispose&&M.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=x.y);let y=!1;for(const[N,M]of this._linkProviderService.linkProviders.entries())S?(R=this._activeProviderReplies)!=null&&R.get(N)&&(y=this._checkLinkProviderResult(N,x,y)):M.provideLinks(x.y,(j=>{var V,te;if(this._isMouseOut)return;const F=j==null?void 0:j.map((de=>({link:de})));(V=this._activeProviderReplies)==null||V.set(N,F),y=this._checkLinkProviderResult(N,x,y),((te=this._activeProviderReplies)==null?void 0:te.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(x.y,this._activeProviderReplies)}))}_removeIntersectingLinks(x,S){const y=new Set;for(let D=0;D<S.size;D++){const R=S.get(D);if(R)for(let N=0;N<R.length;N++){const M=R[N],j=M.link.range.start.y<x?0:M.link.range.start.x,F=M.link.range.end.y>x?this._bufferService.cols:M.link.range.end.x;for(let V=j;V<=F;V++){if(y.has(V)){R.splice(N--,1);break}y.add(V)}}}}_checkLinkProviderResult(x,S,y){var N;if(!this._activeProviderReplies)return y;const D=this._activeProviderReplies.get(x);let R=!1;for(let M=0;M<x;M++)this._activeProviderReplies.has(M)&&!this._activeProviderReplies.get(M)||(R=!0);if(!R&&D){const M=D.find((j=>this._linkAtPosition(j.link,S)));M&&(y=!0,this._handleNewLink(M))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!y)for(let M=0;M<this._activeProviderReplies.size;M++){const j=(N=this._activeProviderReplies.get(M))==null?void 0:N.find((F=>this._linkAtPosition(F.link,S)));if(j){y=!0,this._handleNewLink(j);break}}return y}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(x){if(!this._currentLink)return;const S=this._positionFromMouseEvent(x,this._element,this._mouseService);S&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,S)&&this._currentLink.link.activate(x,this._currentLink.link.text)}_clearCurrentLink(x,S){this._currentLink&&this._lastMouseEvent&&(!x||!S||this._currentLink.link.range.start.y>=x&&this._currentLink.link.range.end.y<=S)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,T.disposeArray)(this._linkCacheDisposables))}_handleNewLink(x){if(!this._lastMouseEvent)return;const S=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);S&&this._linkAtPosition(x.link,S)&&(this._currentLink=x,this._currentLink.state={decorations:{underline:x.link.decorations===void 0||x.link.decorations.underline,pointerCursor:x.link.decorations===void 0||x.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,x.link,this._lastMouseEvent),x.link.decorations={},Object.defineProperties(x.link.decorations,{pointerCursor:{get:()=>{var y,D;return(D=(y=this._currentLink)==null?void 0:y.state)==null?void 0:D.decorations.pointerCursor},set:y=>{var D;(D=this._currentLink)!=null&&D.state&&this._currentLink.state.decorations.pointerCursor!==y&&(this._currentLink.state.decorations.pointerCursor=y,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",y))}},underline:{get:()=>{var y,D;return(D=(y=this._currentLink)==null?void 0:y.state)==null?void 0:D.decorations.underline},set:y=>{var D,R,N;(D=this._currentLink)!=null&&D.state&&((N=(R=this._currentLink)==null?void 0:R.state)==null?void 0:N.decorations.underline)!==y&&(this._currentLink.state.decorations.underline=y,this._currentLink.state.isHovered&&this._fireUnderlineEvent(x.link,y))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((y=>{if(!this._currentLink)return;const D=y.start===0?0:y.start+1+this._bufferService.buffer.ydisp,R=this._bufferService.buffer.ydisp+1+y.end;if(this._currentLink.link.range.start.y>=D&&this._currentLink.link.range.end.y<=R&&(this._clearCurrentLink(D,R),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(x,S,y){var D;(D=this._currentLink)!=null&&D.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!0),this._currentLink.state.decorations.pointerCursor&&x.classList.add("xterm-cursor-pointer")),S.hover&&S.hover(y,S.text)}_fireUnderlineEvent(x,S){const y=x.range,D=this._bufferService.buffer.ydisp,R=this._createLinkUnderlineEvent(y.start.x-1,y.start.y-D-1,y.end.x,y.end.y-D-1,void 0);(S?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(R)}_linkLeave(x,S,y){var D;(D=this._currentLink)!=null&&D.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!1),this._currentLink.state.decorations.pointerCursor&&x.classList.remove("xterm-cursor-pointer")),S.leave&&S.leave(y,S.text)}_linkAtPosition(x,S){const y=x.range.start.y*this._bufferService.cols+x.range.start.x,D=x.range.end.y*this._bufferService.cols+x.range.end.x,R=S.y*this._bufferService.cols+S.x;return y<=R&&R<=D}_positionFromMouseEvent(x,S,y){const D=y.getCoords(x,S,this._bufferService.cols,this._bufferService.rows);if(D)return{x:D[0],y:D[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(x,S,y,D,R){return{x1:x,y1:S,x2:y,y2:D,cols:this._bufferService.cols,fg:R}}};a.Linkifier=b=f([m(1,C.IMouseService),m(2,C.IRenderService),m(3,k.IBufferService),m(4,C.ILinkProviderService)],b)},9042:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(p,a,c){var f=this&&this.__decorate||function(C,b,x,S){var y,D=arguments.length,R=D<3?b:S===null?S=Object.getOwnPropertyDescriptor(b,x):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(C,b,x,S);else for(var N=C.length-1;N>=0;N--)(y=C[N])&&(R=(D<3?y(R):D>3?y(b,x,R):y(b,x))||R);return D>3&&R&&Object.defineProperty(b,x,R),R},m=this&&this.__param||function(C,b){return function(x,S){b(x,S,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const g=c(511),w=c(2585);let T=a.OscLinkProvider=class{constructor(C,b,x){this._bufferService=C,this._optionsService=b,this._oscLinkService=x}provideLinks(C,b){var F;const x=this._bufferService.buffer.lines.get(C-1);if(!x)return void b(void 0);const S=[],y=this._optionsService.rawOptions.linkHandler,D=new g.CellData,R=x.getTrimmedLength();let N=-1,M=-1,j=!1;for(let V=0;V<R;V++)if(M!==-1||x.hasContent(V)){if(x.loadCell(V,D),D.hasExtendedAttrs()&&D.extended.urlId){if(M===-1){M=V,N=D.extended.urlId;continue}j=D.extended.urlId!==N}else M!==-1&&(j=!0);if(j||M!==-1&&V===R-1){const te=(F=this._oscLinkService.getLinkData(N))==null?void 0:F.uri;if(te){const de={start:{x:M+1,y:C},end:{x:V+(j||V!==R-1?0:1),y:C}};let Q=!1;if(!(y!=null&&y.allowNonHttpProtocols))try{const ge=new URL(te);["http:","https:"].includes(ge.protocol)||(Q=!0)}catch{Q=!0}Q||S.push({text:te,range:de,activate:(ge,oe)=>y?y.activate(ge,oe,de):k(0,oe),hover:(ge,oe)=>{var me;return(me=y==null?void 0:y.hover)==null?void 0:me.call(y,ge,oe,de)},leave:(ge,oe)=>{var me;return(me=y==null?void 0:y.leave)==null?void 0:me.call(y,ge,oe,de)}})}j=!1,D.hasExtendedAttrs()&&D.extended.urlId?(M=V,N=D.extended.urlId):(M=-1,N=-1)}}b(S)}};function k(C,b){if(confirm(`Do you want to navigate to ${b}?
|
|
3040
3040
|
|