claude-code-session-manager 0.136.0 → 0.136.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-BFztz90B.js → AgentLibrary-CbvVbzm2.js} +1 -1
- package/dist/assets/{AppSettings-6_dqi9Ti.js → AppSettings-Blks3xh_.js} +1 -1
- package/dist/assets/{Button-5wbUTtD5.js → Button-hPwe-y_4.js} +1 -1
- package/dist/assets/{DocumentEditorPane-CRgJFjka.js → DocumentEditorPane-C_fgkNoa.js} +1 -1
- package/dist/assets/{Extensions-ZXSJbnK7.js → Extensions-CcDjNq7W.js} +2 -2
- package/dist/assets/{History-CmSTZeiu.js → History-D4s5ykcm.js} +1 -1
- package/dist/assets/{Library-DcTnW9kq.js → Library-BtJ7gnDM.js} +1 -1
- package/dist/assets/{ListDetail-BGsdNFiK.js → ListDetail-Bbwwd-HR.js} +1 -1
- package/dist/assets/{Panel-BR2PeMf6.js → Panel-8xYPYH7R.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-DJYcUU1G.js → ProjectClaudeConfig-B9PlbaSV.js} +1 -1
- package/dist/assets/{ProvenanceBadge-B_TDAI3k.js → ProvenanceBadge-COnyY49b.js} +1 -1
- package/dist/assets/{Scheduler-DqocyumD.js → Scheduler-CpmSitKx.js} +1 -1
- package/dist/assets/{Settings-BzPe2TH6.js → Settings-Blfjp8Bp.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-DfdO0Q_N.js → SkillReferenceGraph-pYSyx841.js} +1 -1
- package/dist/assets/{Skills-CGPJxKhR.js → Skills-C4fV80-T.js} +1 -1
- package/dist/assets/{SourceChip-CI8xpHRi.js → SourceChip-Bx9marLv.js} +1 -1
- package/dist/assets/{SystemPrompt-BbzGIHoz.js → SystemPrompt-CBvedERn.js} +1 -1
- package/dist/assets/{TiptapBody-CTmjUhAI.js → TiptapBody-BV7WhKYF.js} +1 -1
- package/dist/assets/{Toggle-CWx9Rq6E.js → Toggle-BUPbeHTj.js} +1 -1
- package/dist/assets/{ViewTabs-BnjD0Crp.js → ViewTabs-oXSVRUrm.js} +1 -1
- package/dist/assets/{VoiceButton-C-iQGCL1.js → VoiceButton-Ca6X_WNA.js} +1 -1
- package/dist/assets/{historyTotals-BaxAMu7r.js → historyTotals-BcJ7QH96.js} +1 -1
- package/dist/assets/{index-Cob2iZhR.js → index-h8BmSc_8.js} +3 -3
- package/dist/index.html +1 -1
- package/dist-web/app.js +1 -1
- package/package.json +1 -1
- package/scripts/scheduler-mcp-server.cjs +8 -2
- package/src/main/build-info.json +4 -4
- package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +3 -0
- package/src/main/lib/feedback-remote/crossProjectReply.cjs +23 -2
- package/src/main/lib/mcpToolCatalog.cjs +5 -3
|
@@ -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-BV7WhKYF.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./History-D4s5ykcm.js","./Panel-8xYPYH7R.js","./historyTotals-BcJ7QH96.js","./Scheduler-CpmSitKx.js","./Settings-Blfjp8Bp.js","./Library-BtJ7gnDM.js","./Button-hPwe-y_4.js","./SourceChip-Bx9marLv.js","./ViewTabs-oXSVRUrm.js","./claude-settings-schema-COigsajx.js","./ListDetail-Bbwwd-HR.js","./ProvenanceBadge-COnyY49b.js","./SystemPrompt-CBvedERn.js","./DocumentEditorPane-C_fgkNoa.js","./ProjectClaudeConfig-B9PlbaSV.js","./VoiceButton-Ca6X_WNA.js","./Skills-C4fV80-T.js","./Toggle-BUPbeHTj.js","./Extensions-CcDjNq7W.js","./AppSettings-Blks3xh_.js","./AgentLibrary-CbvVbzm2.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var D$=Object.defineProperty;var j$=(n,e,t)=>e in n?D$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var ai=(n,e,t)=>j$(n,typeof e!="symbol"?e+"":e,t);import{_ as qn}from"./monaco-editor-BsIlgG7c.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const u of a.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&i(u)}).observe(document,{childList:!0,subtree:!0});function t(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function i(s){if(s.ep)return;s.ep=!0;const a=t(s);fetch(s.href,a)}})();function by(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var yb={exports:{}},Af={},Sb={exports:{}},Nn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -2931,7 +2931,7 @@ ${P}`,z=v.createShaderModule({code:M,label:o.name});xn("verbose",()=>`[WebGPU] $
|
|
|
2931
2931
|
* Licensed under the MIT License.
|
|
2932
2932
|
*/var V1;function $A(){return V1||(V1=1,(function(n,e){var t=(()=>{var i=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,u=Object.prototype.hasOwnProperty,l=(J=>typeof go<"u"?go:typeof Proxy<"u"?new Proxy(J,{get:(ae,ve)=>(typeof go<"u"?go:ae)[ve]}):J)(function(J){if(typeof go<"u")return go.apply(this,arguments);throw Error('Dynamic require of "'+J+'" is not supported')}),c=(J,ae)=>()=>(J&&(ae=J(J=0)),ae),h=(J,ae)=>{for(var ve in ae)i(J,ve,{get:ae[ve],enumerable:!0})},g=(J,ae,ve,je)=>{if(ae&&typeof ae=="object"||typeof ae=="function")for(let ye of a(ae))!u.call(J,ye)&&ye!==ve&&i(J,ye,{get:()=>ae[ye],enumerable:!(je=s(ae,ye))||je.enumerable});return J},m=J=>g(i({},"__esModule",{value:!0}),J),b,k,C,E,_,w=c(()=>{b=new Map,k=[],C=(J,ae,ve)=>{if(ae&&typeof ae.init=="function"&&typeof ae.createInferenceSessionHandler=="function"){let je=b.get(J);if(je===void 0)b.set(J,{backend:ae,priority:ve});else{if(je.priority>ve)return;if(je.priority===ve&&je.backend!==ae)throw new Error(`cannot register backend "${J}" using priority ${ve}`)}if(ve>=0){let ye=k.indexOf(J);ye!==-1&&k.splice(ye,1);for(let Be=0;Be<k.length;Be++)if(b.get(k[Be]).priority<=ve){k.splice(Be,0,J);return}k.push(J)}return}throw new TypeError("not a valid backend")},E=async J=>{let ae=b.get(J);if(!ae)return"backend not found.";if(ae.initialized)return ae.backend;if(ae.aborted)return ae.error;{let ve=!!ae.initPromise;try{return ve||(ae.initPromise=ae.backend.init(J)),await ae.initPromise,ae.initialized=!0,ae.backend}catch(je){return ve||(ae.error=`${je}`,ae.aborted=!0),ae.error}finally{delete ae.initPromise}}},_=async J=>{let ae=J.executionProviders||[],ve=ae.map(Fe=>typeof Fe=="string"?Fe:Fe.name),je=ve.length===0?k:ve,ye,Be=[],Ae=new Set;for(let Fe of je){let nt=await E(Fe);typeof nt=="string"?Be.push({name:Fe,err:nt}):(ye||(ye=nt),ye===nt&&Ae.add(Fe))}if(!ye)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:nt}of Be)ve.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${nt}`);let Ie=ae.filter(Fe=>Ae.has(typeof Fe=="string"?Fe:Fe.name));return[ye,new Proxy(J,{get:(Fe,nt)=>nt==="executionProviders"?Ie:Reflect.get(Fe,nt)})]}}),x=c(()=>{w()}),S,T=c(()=>{S="1.26.0"}),N,R,O=c(()=>{T(),N="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:S},set logLevel(J){if(J!==void 0){if(typeof J!="string"||["verbose","info","warning","error","fatal"].indexOf(J)===-1)throw new Error(`Unsupported logging level: ${J}`);N=J}},get logLevel(){return N}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),A,L=c(()=>{O(),A=R}),V,Q,ie=c(()=>{V=(J,ae)=>{let ve=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ve.width=J.dims[3],ve.height=J.dims[2];let je=ve.getContext("2d");if(je!=null){let ye,Be;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(ye=J.dims[2],Be=J.dims[3]):(ye=J.dims[3],Be=J.dims[2]);let Ae=(ae==null?void 0:ae.format)!==void 0?ae.format:"RGB",Ie=ae==null?void 0:ae.norm,Fe,nt;Ie===void 0||Ie.mean===void 0?Fe=[255,255,255,255]:typeof Ie.mean=="number"?Fe=[Ie.mean,Ie.mean,Ie.mean,Ie.mean]:(Fe=[Ie.mean[0],Ie.mean[1],Ie.mean[2],0],Ie.mean[3]!==void 0&&(Fe[3]=Ie.mean[3])),Ie===void 0||Ie.bias===void 0?nt=[0,0,0,0]:typeof Ie.bias=="number"?nt=[Ie.bias,Ie.bias,Ie.bias,Ie.bias]:(nt=[Ie.bias[0],Ie.bias[1],Ie.bias[2],0],Ie.bias[3]!==void 0&&(nt[3]=Ie.bias[3]));let dt=Be*ye,st=0,Ze=dt,Lt=dt*2,Le=-1;Ae==="RGBA"?(st=0,Ze=dt,Lt=dt*2,Le=dt*3):Ae==="RGB"?(st=0,Ze=dt,Lt=dt*2):Ae==="RBG"&&(st=0,Lt=dt,Ze=dt*2);for(let ft=0;ft<Be;ft++)for(let Zn=0;Zn<ye;Zn++){let dn=(J.data[st++]-nt[0])*Fe[0],un=(J.data[Ze++]-nt[1])*Fe[1],Qn=(J.data[Lt++]-nt[2])*Fe[2],Ut=Le===-1?255:(J.data[Le++]-nt[3])*Fe[3];je.fillStyle="rgba("+dn+","+un+","+Qn+","+Ut+")",je.fillRect(Zn,ft,1,1)}if("toDataURL"in ve)return ve.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},Q=(J,ae)=>{let ve=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),je;if(ve!=null){let ye,Be,Ae;(ae==null?void 0:ae.tensorLayout)!==void 0&&ae.tensorLayout==="NHWC"?(ye=J.dims[2],Be=J.dims[1],Ae=J.dims[3]):(ye=J.dims[3],Be=J.dims[2],Ae=J.dims[1]);let Ie=ae!==void 0&&ae.format!==void 0?ae.format:"RGB",Fe=ae==null?void 0:ae.norm,nt,dt;Fe===void 0||Fe.mean===void 0?nt=[255,255,255,255]:typeof Fe.mean=="number"?nt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(nt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(nt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?dt=[0,0,0,0]:typeof Fe.bias=="number"?dt=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(dt=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(dt[3]=Fe.bias[3]));let st=Be*ye;if(ae!==void 0&&(ae.format!==void 0&&Ae===4&&ae.format!=="RGBA"||Ae===3&&ae.format!=="RGB"&&ae.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Ze=4,Lt=0,Le=1,ft=2,Zn=3,dn=0,un=st,Qn=st*2,Ut=-1;Ie==="RGBA"?(dn=0,un=st,Qn=st*2,Ut=st*3):Ie==="RGB"?(dn=0,un=st,Qn=st*2):Ie==="RBG"&&(dn=0,Qn=st,un=st*2),je=ve.createImageData(ye,Be);for(let ci=0;ci<Be*ye;Lt+=Ze,Le+=Ze,ft+=Ze,Zn+=Ze,ci++)je.data[Lt]=(J.data[dn++]-dt[0])*nt[0],je.data[Le]=(J.data[un++]-dt[1])*nt[1],je.data[ft]=(J.data[Qn++]-dt[2])*nt[2],je.data[Zn]=Ut===-1?255:(J.data[Ut++]-dt[3])*nt[3]}else throw new Error("Can not access image data");return je}}),K,ue,te,ce,Ce,fe,F=c(()=>{Ne(),K=(J,ae)=>{if(J===void 0)throw new Error("Image buffer must be defined");if(ae.height===void 0||ae.width===void 0)throw new Error("Image height and width must be defined");if(ae.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ve,width:je}=ae,ye=ae.norm??{mean:255,bias:0},Be,Ae;typeof ye.mean=="number"?Be=[ye.mean,ye.mean,ye.mean,ye.mean]:Be=[ye.mean[0],ye.mean[1],ye.mean[2],ye.mean[3]??255],typeof ye.bias=="number"?Ae=[ye.bias,ye.bias,ye.bias,ye.bias]:Ae=[ye.bias[0],ye.bias[1],ye.bias[2],ye.bias[3]??0];let Ie=ae.format!==void 0?ae.format:"RGBA",Fe=ae.tensorFormat!==void 0&&ae.tensorFormat!==void 0?ae.tensorFormat:"RGB",nt=ve*je,dt=Fe==="RGBA"?new Float32Array(nt*4):new Float32Array(nt*3),st=4,Ze=0,Lt=1,Le=2,ft=3,Zn=0,dn=nt,un=nt*2,Qn=-1;Ie==="RGB"&&(st=3,Ze=0,Lt=1,Le=2,ft=-1),Fe==="RGBA"?Qn=nt*3:Fe==="RBG"?(Zn=0,un=nt,dn=nt*2):Fe==="BGR"&&(un=0,dn=nt,Zn=nt*2);for(let Ut=0;Ut<nt;Ut++,Ze+=st,Le+=st,Lt+=st,ft+=st)dt[Zn++]=(J[Ze]+Ae[0])/Be[0],dt[dn++]=(J[Lt]+Ae[1])/Be[1],dt[un++]=(J[Le]+Ae[2])/Be[2],Qn!==-1&&ft!==-1&&(dt[Qn++]=(J[ft]+Ae[3])/Be[3]);return Fe==="RGBA"?new ee("float32",dt,[1,4,ve,je]):new ee("float32",dt,[1,3,ve,je])},ue=async(J,ae)=>{let ve=typeof HTMLImageElement<"u"&&J instanceof HTMLImageElement,je=typeof ImageData<"u"&&J instanceof ImageData,ye=typeof ImageBitmap<"u"&&J instanceof ImageBitmap,Be=typeof J=="string",Ae,Ie=ae??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},nt=dt=>typeof HTMLCanvasElement<"u"&&dt instanceof HTMLCanvasElement||dt instanceof OffscreenCanvas?dt.getContext("2d"):null;if(ve){let dt=Fe();dt.width=J.width,dt.height=J.height;let st=nt(dt);if(st!=null){let Ze=J.height,Lt=J.width;if(ae!==void 0&&ae.resizedHeight!==void 0&&ae.resizedWidth!==void 0&&(Ze=ae.resizedHeight,Lt=ae.resizedWidth),ae!==void 0){if(Ie=ae,ae.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ie.tensorFormat="RGBA",Ie.height=Ze,Ie.width=Lt}else Ie.tensorFormat="RGBA",Ie.height=Ze,Ie.width=Lt;st.drawImage(J,0,0),Ae=st.getImageData(0,0,Lt,Ze).data}else throw new Error("Can not access image data")}else if(je){let dt,st;if(ae!==void 0&&ae.resizedWidth!==void 0&&ae.resizedHeight!==void 0?(dt=ae.resizedHeight,st=ae.resizedWidth):(dt=J.height,st=J.width),ae!==void 0&&(Ie=ae),Ie.format="RGBA",Ie.height=dt,Ie.width=st,ae!==void 0){let Ze=Fe();Ze.width=st,Ze.height=dt;let Lt=nt(Ze);if(Lt!=null)Lt.putImageData(J,0,0),Ae=Lt.getImageData(0,0,st,dt).data;else throw new Error("Can not access image data")}else Ae=J.data}else if(ye){if(ae===void 0)throw new Error("Please provide image config with format for Imagebitmap");let dt=Fe();dt.width=J.width,dt.height=J.height;let st=nt(dt);if(st!=null){let Ze=J.height,Lt=J.width;return st.drawImage(J,0,0,Lt,Ze),Ae=st.getImageData(0,0,Lt,Ze).data,Ie.height=Ze,Ie.width=Lt,K(Ae,Ie)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((dt,st)=>{let Ze=Fe(),Lt=nt(Ze);if(!J||!Lt)return st();let Le=new Image;Le.crossOrigin="Anonymous",Le.src=J,Le.onload=()=>{Ze.width=Le.width,Ze.height=Le.height,Lt.drawImage(Le,0,0,Ze.width,Ze.height);let ft=Lt.getImageData(0,0,Ze.width,Ze.height);Ie.height=Ze.height,Ie.width=Ze.width,dt(K(ft.data,Ie))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ae!==void 0)return K(Ae,Ie);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(J,ae)=>{let{width:ve,height:je,download:ye,dispose:Be}=ae,Ae=[1,je,ve,4];return new ee({location:"texture",type:"float32",texture:J,dims:Ae,download:ye,dispose:Be})},ce=(J,ae)=>{let{dataType:ve,dims:je,download:ye,dispose:Be}=ae;return new ee({location:"gpu-buffer",type:ve??"float32",gpuBuffer:J,dims:je,download:ye,dispose:Be})},Ce=(J,ae)=>{let{dataType:ve,dims:je,download:ye,dispose:Be}=ae;return new ee({location:"ml-tensor",type:ve??"float32",mlTensor:J,dims:je,download:ye,dispose:Be})},fe=(J,ae,ve)=>new ee({location:"cpu-pinned",type:J,data:ae,dims:ve??[ae.length]})}),q,H,Z,le,me=c(()=>{q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),H=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),Z=!1,le=()=>{if(!Z){Z=!0;let J=typeof BigInt64Array<"u"&&BigInt64Array.from,ae=typeof BigUint64Array<"u"&&BigUint64Array.from,ve=globalThis.Float16Array,je=typeof ve<"u"&&ve.from;J&&(q.set("int64",BigInt64Array),H.set(BigInt64Array,"int64")),ae&&(q.set("uint64",BigUint64Array),H.set(BigUint64Array,"uint64")),je?(q.set("float16",ve),H.set(ve,"float16")):q.set("float16",Uint16Array)}}}),Re,He,ge=c(()=>{Ne(),Re=J=>{let ae=1;for(let ve=0;ve<J.length;ve++){let je=J[ve];if(typeof je!="number"||!Number.isSafeInteger(je))throw new TypeError(`dims[${ve}] must be an integer, got: ${je}`);if(je<0)throw new RangeError(`dims[${ve}] must be a non-negative integer, got: ${je}`);ae*=je}return ae},He=(J,ae)=>{switch(J.location){case"cpu":return new ee(J.type,J.data,ae);case"cpu-pinned":return new ee({location:"cpu-pinned",data:J.data,type:J.type,dims:ae});case"texture":return new ee({location:"texture",texture:J.texture,type:J.type,dims:ae});case"gpu-buffer":return new ee({location:"gpu-buffer",gpuBuffer:J.gpuBuffer,type:J.type,dims:ae});case"ml-tensor":return new ee({location:"ml-tensor",mlTensor:J.mlTensor,type:J.type,dims:ae});default:throw new Error(`tensorReshape: tensor location ${J.location} is not supported`)}}}),ee,Ne=c(()=>{ie(),F(),me(),ge(),ee=class{constructor(J,ae,ve){le();let je,ye;if(typeof J=="object"&&"location"in J)switch(this.dataLocation=J.location,je=J.type,ye=J.dims,J.location){case"cpu-pinned":{let Ae=q.get(je);if(!Ae)throw new TypeError(`unsupported type "${je}" to create tensor from pinned buffer`);if(!(J.data instanceof Ae))throw new TypeError(`buffer should be of type ${Ae.name}`);this.cpuData=J.data;break}case"texture":{if(je!=="float32")throw new TypeError(`unsupported type "${je}" to create tensor from texture`);this.gpuTextureData=J.texture,this.downloader=J.download,this.disposer=J.dispose;break}case"gpu-buffer":{if(je!=="float32"&&je!=="float16"&&je!=="int32"&&je!=="int64"&&je!=="uint32"&&je!=="uint8"&&je!=="bool"&&je!=="uint4"&&je!=="int4")throw new TypeError(`unsupported type "${je}" to create tensor from gpu buffer`);this.gpuBufferData=J.gpuBuffer,this.downloader=J.download,this.disposer=J.dispose;break}case"ml-tensor":{if(je!=="float32"&&je!=="float16"&&je!=="int32"&&je!=="int64"&&je!=="uint32"&&je!=="uint64"&&je!=="int8"&&je!=="uint8"&&je!=="bool"&&je!=="uint4"&&je!=="int4")throw new TypeError(`unsupported type "${je}" to create tensor from MLTensor`);this.mlTensorData=J.mlTensor,this.downloader=J.download,this.disposer=J.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ae,Ie;if(typeof J=="string")if(je=J,Ie=ve,J==="string"){if(!Array.isArray(ae))throw new TypeError("A string tensor's data must be a string array.");Ae=ae}else{let Fe=q.get(J);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${J}.`);if(Array.isArray(ae)){if(J==="float16"&&Fe===Uint16Array||J==="uint4"||J==="int4")throw new TypeError(`Creating a ${J} tensor from number array is not supported. Please use ${Fe.name} as data.`);J==="uint64"||J==="int64"?Ae=Fe.from(ae,BigInt):Ae=Fe.from(ae)}else if(ae instanceof Fe)Ae=ae;else if(ae instanceof Uint8ClampedArray)if(J==="uint8")Ae=Uint8Array.from(ae);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(J==="float16"&&ae instanceof Uint16Array&&Fe!==Uint16Array)Ae=new globalThis.Float16Array(ae.buffer,ae.byteOffset,ae.length);else throw new TypeError(`A ${je} tensor's data must be type of ${Fe}`)}else if(Ie=ae,Array.isArray(J)){if(J.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof J[0];if(Fe==="string")je="string",Ae=J;else if(Fe==="boolean")je="bool",Ae=Uint8Array.from(J);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(J instanceof Uint8ClampedArray)je="uint8",Ae=Uint8Array.from(J);else{let Fe=H.get(J.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${J.constructor}.`);je=Fe,Ae=J}if(Ie===void 0)Ie=[Ae.length];else if(!Array.isArray(Ie))throw new TypeError("A tensor's dims must be a number array");ye=Ie,this.cpuData=Ae,this.dataLocation="cpu"}let Be=Re(ye);if(this.cpuData&&Be!==this.cpuData.length&&!((je==="uint4"||je==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=je,this.dims=ye,this.size=Be}static async fromImage(J,ae){return ue(J,ae)}static fromTexture(J,ae){return te(J,ae)}static fromGpuBuffer(J,ae){return ce(J,ae)}static fromMLTensor(J,ae){return Ce(J,ae)}static fromPinnedBuffer(J,ae,ve){return fe(J,ae,ve)}toDataURL(J){return V(this,J)}toImageData(J){return Q(this,J)}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(J){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let ae=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=ae,J&&this.disposer&&(this.disposer(),this.disposer=void 0),ae}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(J){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return He(this,J)}}}),Ee,Te=c(()=>{Ne(),Ee=ee}),be,Qe,gt,lt,$t,We,Wt=c(()=>{O(),be=(J,ae)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${J}::ORT::${ae}`)},Qe=(J,ae)=>{var ye;let ve=((ye=new Error().stack)==null?void 0:ye.split(/\r\n|\r|\n/g))||[],je=!1;for(let Be=0;Be<ve.length;Be++){if(je&&!ve[Be].includes("TRACE_FUNC")){let Ae=`FUNC_${J}::${ve[Be].trim().split(" ")[1]}`;ae&&(Ae+=`::${ae}`),be("CPU",Ae);return}ve[Be].includes("TRACE_FUNC")&&(je=!0)}},gt=J=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||Qe("BEGIN",J)},lt=J=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||Qe("END",J)},$t=J=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${J}`)},We=J=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${J}`)}}),kt,rn=c(()=>{w(),Te(),Wt(),kt=class L2{constructor(ae){this.handler=ae}async run(ae,ve,je){gt(),$t("InferenceSession.run");let ye={},Be={};if(typeof ae!="object"||ae===null||ae instanceof Ee||Array.isArray(ae))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ae=!0;if(typeof ve=="object"){if(ve===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ve instanceof Ee)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ve)){if(ve.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ae=!1;for(let nt of ve){if(typeof nt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(nt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${nt}.`);ye[nt]=null}if(typeof je=="object"&&je!==null)Be=je;else if(typeof je<"u")throw new TypeError("'options' must be an object.")}else{let nt=!1,dt=Object.getOwnPropertyNames(ve);for(let st of this.outputNames)if(dt.indexOf(st)!==-1){let Ze=ve[st];(Ze===null||Ze instanceof Ee)&&(nt=!0,Ae=!1,ye[st]=Ze)}if(nt){if(typeof je=="object"&&je!==null)Be=je;else if(typeof je<"u")throw new TypeError("'options' must be an object.")}else Be=ve}}else if(typeof ve<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let nt of this.inputNames)if(typeof ae[nt]>"u")throw new Error(`input '${nt}' is missing in 'feeds'.`);if(Ae)for(let nt of this.outputNames)ye[nt]=null;let Ie=await this.handler.run(ae,ye,Be),Fe={};for(let nt in Ie)if(Object.hasOwnProperty.call(Ie,nt)){let dt=Ie[nt];dt instanceof Ee?Fe[nt]=dt:Fe[nt]=new Ee(dt.type,dt.data,dt.dims)}return We("InferenceSession.run"),lt(),Fe}async release(){return this.handler.dispose()}static async create(ae,ve,je,ye){gt(),$t("InferenceSession.create");let Be,Ae={};if(typeof ae=="string"){if(Be=ae,typeof ve=="object"&&ve!==null)Ae=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof Uint8Array){if(Be=ae,typeof ve=="object"&&ve!==null)Ae=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(ae instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&ae instanceof SharedArrayBuffer){let dt=ae,st=0,Ze=ae.byteLength;if(typeof ve=="object"&&ve!==null)Ae=ve;else if(typeof ve=="number"){if(st=ve,!Number.isSafeInteger(st))throw new RangeError("'byteOffset' must be an integer.");if(st<0||st>=dt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${dt.byteLength}).`);if(Ze=ae.byteLength-st,typeof je=="number"){if(Ze=je,!Number.isSafeInteger(Ze))throw new RangeError("'byteLength' must be an integer.");if(Ze<=0||st+Ze>dt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${dt.byteLength-st}].`);if(typeof ye=="object"&&ye!==null)Ae=ye;else if(typeof ye<"u")throw new TypeError("'options' must be an object.")}else if(typeof je<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ve<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(dt,st,Ze)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ie,Fe]=await _(Ae),nt=await Ie.createInferenceSessionHandler(Be,Fe);return We("InferenceSession.create"),lt(),new L2(nt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),pn,Ue=c(()=>{rn(),pn=kt}),xt=c(()=>{}),St=c(()=>{}),en=c(()=>{}),En=c(()=>{}),In={};h(In,{InferenceSession:()=>pn,TRACE:()=>be,TRACE_EVENT_BEGIN:()=>$t,TRACE_EVENT_END:()=>We,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>lt,Tensor:()=>Ee,env:()=>A,registerBackend:()=>C});var vn=c(()=>{x(),L(),Ue(),Te(),xt(),St(),Wt(),en(),En()}),ii=c(()=>{}),Cn={};h(Cn,{default:()=>Ri});var jn,fn,Ri,Ci=c(()=>{var J;xe(),si(),On(),jn="ort-wasm-proxy-worker",fn=((J=globalThis.self)==null?void 0:J.name)===jn,fn&&(self.onmessage=ae=>{let{type:ve,in:je}=ae.data;try{switch(ve){case"init-wasm":xi(je.wasm).then(()=>{_n(je).then(()=>{postMessage({type:ve})},ye=>{postMessage({type:ve,err:ye})})},ye=>{postMessage({type:ve,err:ye})});break;case"init-ep":{let{epName:ye,env:Be}=je;ri(Be,ye).then(()=>{postMessage({type:ve})},Ae=>{postMessage({type:ve,err:Ae})});break}case"copy-from":{let{buffer:ye}=je,Be=xn(ye);postMessage({type:ve,out:Be});break}case"create":{let{model:ye,options:Be}=je;zs(ye,Be).then(Ae=>{postMessage({type:ve,out:Ae})},Ae=>{postMessage({type:ve,err:Ae})});break}case"release":to(je),postMessage({type:ve});break;case"run":{let{sessionId:ye,inputIndices:Be,inputs:Ae,outputIndices:Ie,options:Fe}=je;Je(ye,Be,Ae,Ie,new Array(Ie.length).fill(null),Fe).then(nt=>{nt.some(dt=>dt[3]!=="cpu")?postMessage({type:ve,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ve,out:nt},wt([...Ae,...nt]))},nt=>{postMessage({type:ve,err:nt})});break}case"end-profiling":ys(je),postMessage({type:ve});break;default:}}catch(ye){postMessage({type:ve,err:ye})}}),Ri=fn?null:ae=>new Worker(ae??at,{type:"classic",name:jn})}),Fi,ls,at,Wn,Kn,Pi,vi,ki,it,vt,Rt,ln,Mn,On=c(()=>{ii(),Fi=typeof location>"u"?void 0:location.origin,ls=()=>{var J,ae;return typeof document<"u"?(J=document.currentScript)==null?void 0:J.src:typeof self<"u"?(ae=self.location)==null?void 0:ae.href:void 0},at=ls(),Wn=()=>{if(at&&!at.startsWith("blob:"))return at.substring(0,at.lastIndexOf("/")+1)},Kn=(J,ae)=>{try{let ve=ae??at;return(ve?new URL(J,ve):new URL(J)).origin===Fi}catch{return!1}},Pi=(J,ae)=>{let ve=ae??at;try{return(ve?new URL(J,ve):new URL(J)).href}catch{return}},vi=(J,ae)=>`${ae??"./"}${J}`,ki=async J=>{let ae=await(await fetch(J,{credentials:"same-origin"})).blob();return URL.createObjectURL(ae)},it=async J=>(await import(J)).default,vt=(Ci(),m(Cn)).default,Rt=async()=>{if(!at)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Kn(at))return[void 0,vt()];let J=await ki(at);return[J,vt(J)]},ln=void 0,Mn=async(J,ae,ve,je)=>{let ye=ln&&!(J||ae);if(ye)if(at)ye=Kn(at)||je&&!ve;else if(je&&!ve)ye=!0;else throw new Error("cannot determine the script source URL.");if(ye)return[void 0,ln];{let Be="ort-wasm-simd-threaded.mjs",Ae=J??Pi(Be,ae),Ie=ve&&Ae&&!Kn(Ae,ae),Fe=Ie?await ki(Ae):Ae??vi(Be,ae);return[Ie?Fe:void 0,await it(Fe)]}}}),kn,rt,cn,Yn,Xn,bt,Un,xi,At,si=c(()=>{On(),rt=!1,cn=!1,Yn=!1,Xn=()=>{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}},bt=()=>{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}},Un=()=>{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}},xi=async J=>{if(rt)return Promise.resolve();if(cn)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Yn)throw new Error("previous call to 'initializeWebAssembly()' failed.");cn=!0;let ae=J.initTimeout,ve=J.numThreads;if(J.simd!==!1){if(J.simd==="relaxed"){if(!Un())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!bt())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let je=Xn();ve>1&&!je&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ve+", 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."),J.numThreads=ve=1);let ye=J.wasmPaths,Be=typeof ye=="string"?ye:void 0,Ae=ye==null?void 0:ye.mjs,Ie=(Ae==null?void 0:Ae.href)??Ae,Fe=ye==null?void 0:ye.wasm,nt=(Fe==null?void 0:Fe.href)??Fe,dt=J.wasmBinary,[st,Ze]=await Mn(Ie,Be,ve>1,!!dt||!!nt),Lt=!1,Le=[];if(ae>0&&Le.push(new Promise(ft=>{setTimeout(()=>{Lt=!0,ft()},ae)})),Le.push(new Promise((ft,Zn)=>{let dn={numThreads:ve};if(dt)dn.wasmBinary=dt,dn.locateFile=un=>un;else if(nt||Be)dn.locateFile=un=>nt??Be+un;else if(Ie&&Ie.indexOf("blob:")!==0)dn.locateFile=un=>new URL(un,Ie).href;else if(st){let un=Wn();un&&(dn.locateFile=Qn=>un+Qn)}Ze(dn).then(un=>{cn=!1,rt=!0,kn=un,ft(),st&&URL.revokeObjectURL(st)},un=>{cn=!1,Yn=!0,Zn(un)})})),await Promise.race(Le),Lt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${ae}ms`)},At=()=>{if(rt&&kn)return kn;throw new Error("WebAssembly is not initialized yet.")}}),Jn,Rn,Nt,yr=c(()=>{si(),Jn=(J,ae)=>{let ve=At(),je=ve.lengthBytesUTF8(J)+1,ye=ve._malloc(je);return ve.stringToUTF8(J,ye,je),ae.push(ye),ye},Rn=(J,ae,ve,je)=>{if(typeof J=="object"&&J!==null){if(ve.has(J))throw new Error("Circular reference in options");ve.add(J)}Object.entries(J).forEach(([ye,Be])=>{let Ae=ae?ae+ye:ye;if(typeof Be=="object")Rn(Be,Ae+".",ve,je);else if(typeof Be=="string"||typeof Be=="number")je(Ae,Be.toString());else if(typeof Be=="boolean")je(Ae,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Nt=J=>{let ae=At(),ve=ae.stackSave();try{let je=ae.PTR_SIZE,ye=ae.stackAlloc(2*je);ae._OrtGetLastError(ye,ye+je);let Be=Number(ae.getValue(ye,je===4?"i32":"i64")),Ae=ae.getValue(ye+je,"*"),Ie=Ae?ae.UTF8ToString(Ae):"";throw new Error(`${J} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Ie}`)}finally{ae.stackRestore(ve)}}}),tr,Qr=c(()=>{si(),yr(),tr=J=>{let ae=At(),ve=0,je=[],ye=J||{};try{if((J==null?void 0:J.logSeverityLevel)===void 0)ye.logSeverityLevel=2;else if(typeof J.logSeverityLevel!="number"||!Number.isInteger(J.logSeverityLevel)||J.logSeverityLevel<0||J.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${J.logSeverityLevel}`);if((J==null?void 0:J.logVerbosityLevel)===void 0)ye.logVerbosityLevel=0;else if(typeof J.logVerbosityLevel!="number"||!Number.isInteger(J.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${J.logVerbosityLevel}`);(J==null?void 0:J.terminate)===void 0&&(ye.terminate=!1);let Be=0;return(J==null?void 0:J.tag)!==void 0&&(Be=Jn(J.tag,je)),ve=ae._OrtCreateRunOptions(ye.logSeverityLevel,ye.logVerbosityLevel,!!ye.terminate,Be),ve===0&&Nt("Can't create run options."),(J==null?void 0:J.extra)!==void 0&&Rn(J.extra,"",new WeakSet,(Ae,Ie)=>{let Fe=Jn(Ae,je),nt=Jn(Ie,je);ae._OrtAddRunConfigEntry(ve,Fe,nt)!==0&&Nt(`Can't set a run config entry: ${Ae} - ${Ie}.`)}),[ve,je]}catch(Be){throw ve!==0&&ae._OrtReleaseRunOptions(ve),je.forEach(Ae=>ae._free(Ae)),Be}}}),Lr,cs,zr,Mi,Br,eo,Pn=c(()=>{si(),yr(),Lr=J=>{switch(J){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: ${J}`)}},cs=J=>{switch(J){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${J}`)}},zr=J=>{J.extra||(J.extra={}),J.extra.session||(J.extra.session={});let ae=J.extra.session;ae.use_ort_model_bytes_directly||(ae.use_ort_model_bytes_directly="1"),J.executionProviders&&J.executionProviders.some(ve=>(typeof ve=="string"?ve:ve.name)==="webgpu")&&(J.enableMemPattern=!1)},Mi=(J,ae,ve,je)=>{let ye=Jn(ae,je),Be=Jn(ve,je);At()._OrtAddSessionConfigEntry(J,ye,Be)!==0&&Nt(`Can't set a session config entry: ${ae} - ${ve}.`)},Br=async(J,ae,ve)=>{let je=ae.executionProviders;for(let ye of je){let Be=typeof ye=="string"?ye:ye.name,Ae=[];switch(Be){case"webnn":if(Be="WEBNN",Mi(J,"session.disable_quant_qdq","1",ve),Mi(J,"session.disable_qdq_constant_folding","1",ve),typeof ye!="string"){let st=ye==null?void 0:ye.deviceType;st&&Mi(J,"deviceType",st,ve)}break;case"webgpu":if(Be="JS",typeof ye!="string"){let st=ye;if(st!=null&&st.preferredLayout){if(st.preferredLayout!=="NCHW"&&st.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${st.preferredLayout}`);Mi(J,"preferredLayout",st.preferredLayout,ve)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Ie=Jn(Be,ve),Fe=Ae.length,nt=0,dt=0;if(Fe>0){nt=At()._malloc(Fe*At().PTR_SIZE),ve.push(nt),dt=At()._malloc(Fe*At().PTR_SIZE),ve.push(dt);for(let st=0;st<Fe;st++)At().setValue(nt+st*At().PTR_SIZE,Ae[st][0],"*"),At().setValue(dt+st*At().PTR_SIZE,Ae[st][1],"*")}await At()._OrtAppendExecutionProvider(J,Ie,nt,dt,Fe)!==0&&Nt(`Can't append execution provider: ${Be}.`)}},eo=async J=>{let ae=At(),ve=0,je=[],ye=J||{};zr(ye);try{let Be=Lr(ye.graphOptimizationLevel??"all"),Ae=cs(ye.executionMode??"sequential"),Ie=typeof ye.logId=="string"?Jn(ye.logId,je):0,Fe=ye.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let nt=ye.logVerbosityLevel??0;if(!Number.isInteger(nt)||nt<0||nt>4)throw new Error(`log verbosity level is not valid: ${nt}`);let dt=typeof ye.optimizedModelFilePath=="string"?Jn(ye.optimizedModelFilePath,je):0;if(ve=ae._OrtCreateSessionOptions(Be,!!ye.enableCpuMemArena,!!ye.enableMemPattern,Ae,!!ye.enableProfiling,0,Ie,Fe,nt,dt),ve===0&&Nt("Can't create session options."),ye.executionProviders&&await Br(ve,ye,je),ye.enableGraphCapture!==void 0){if(typeof ye.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${ye.enableGraphCapture}`);Mi(ve,"enableGraphCapture",ye.enableGraphCapture.toString(),je)}if(ye.freeDimensionOverrides)for(let[st,Ze]of Object.entries(ye.freeDimensionOverrides)){if(typeof st!="string")throw new Error(`free dimension override name must be a string: ${st}`);if(typeof Ze!="number"||!Number.isInteger(Ze)||Ze<0)throw new Error(`free dimension override value must be a non-negative integer: ${Ze}`);let Lt=Jn(st,je);ae._OrtAddFreeDimensionOverride(ve,Lt,Ze)!==0&&Nt(`Can't set a free dimension override: ${st} - ${Ze}.`)}return ye.extra!==void 0&&Rn(ye.extra,"",new WeakSet,(st,Ze)=>{Mi(ve,st,Ze,je)}),[ve,je]}catch(Be){throw ve!==0&&ae._OrtReleaseSessionOptions(ve)!==0&&Nt("Can't release session options."),je.forEach(Ae=>ae._free(Ae)),Be}}}),qi,li,Ei,Ms,Os,nr,ds,Oi,Gt=c(()=>{qi=J=>{switch(J){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: ${J}`)}},li=J=>{switch(J){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: ${J}`)}},Ei=(J,ae)=>{let ve=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][J],je=typeof ae=="number"?ae:ae.reduce((ye,Be)=>ye*Be,1);return ve>0?Math.ceil(je*ve):void 0},Ms=J=>{switch(J){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: ${J}`)}},Os=J=>{switch(J){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: ${J}`)}},nr=J=>J==="float32"||J==="float16"||J==="int32"||J==="int64"||J==="uint32"||J==="uint8"||J==="bool"||J==="uint4"||J==="int4",ds=J=>J==="float32"||J==="float16"||J==="int32"||J==="int64"||J==="uint32"||J==="uint64"||J==="int8"||J==="uint8"||J==="bool"||J==="uint4"||J==="int4",Oi=J=>{switch(J){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: ${J}`)}}}),De,ct=c(()=>{ii(),De=async J=>{if(typeof J=="string"){let ae=await fetch(J);if(!ae.ok)throw new Error(`failed to load external data file: ${J}`);let ve=ae.headers.get("Content-Length"),je=ve?parseInt(ve,10):0;if(je<1073741824)return new Uint8Array(await ae.arrayBuffer());{if(!ae.body)throw new Error(`failed to load external data file: ${J}, no response body.`);let ye=ae.body.getReader(),Be;try{Be=new ArrayBuffer(je)}catch(Ie){if(Ie instanceof RangeError){let Fe=Math.ceil(je/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Ie}let Ae=0;for(;;){let{done:Ie,value:Fe}=await ye.read();if(Ie)break;let nt=Fe.byteLength;new Uint8Array(Be,Ae,nt).set(Fe),Ae+=nt}return new Uint8Array(Be,0,je)}}else return J instanceof Blob?new Uint8Array(await J.arrayBuffer()):J instanceof Uint8Array?J:new Uint8Array(J)}}),Yt,_n,ri,wn,Ti,Ls,xn,zs,to,ir,Je,ys,wt,xe=c(()=>{vn(),Qr(),Pn(),Gt(),si(),yr(),ct(),Yt=(J,ae)=>{At()._OrtInit(J,ae)!==0&&Nt("Can't initialize onnxruntime.")},_n=async J=>{Yt(J.wasm.numThreads,Os(J.logLevel))},ri=async(J,ae)=>{var je,ye;(ye=(je=At()).asyncInit)==null||ye.call(je);let ve=J.webgpu.adapter;if(ae==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ve){if(typeof ve.limits!="object"||typeof ve.features!="object"||typeof ve.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=J.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Ae=J.webgpu.forceFallbackAdapter;if(Ae!==void 0&&typeof Ae!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ae}"`);if(ve=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Ae}),!ve)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(ae==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},wn=new Map,Ti=J=>{let ae=At(),ve=ae.stackSave();try{let je=ae.PTR_SIZE,ye=ae.stackAlloc(2*je);ae._OrtGetInputOutputCount(J,ye,ye+je)!==0&&Nt("Can't get session input/output count.");let Be=je===4?"i32":"i64";return[Number(ae.getValue(ye,Be)),Number(ae.getValue(ye+je,Be))]}finally{ae.stackRestore(ve)}},Ls=(J,ae)=>{let ve=At(),je=ve.stackSave(),ye=0;try{let Be=ve.PTR_SIZE,Ae=ve.stackAlloc(2*Be);ve._OrtGetInputOutputMetadata(J,ae,Ae,Ae+Be)!==0&&Nt("Can't get session input/output metadata.");let Ie=Number(ve.getValue(Ae,"*"));ye=Number(ve.getValue(Ae+Be,"*"));let Fe=ve.HEAP32[ye/4];if(Fe===0)return[Ie,0];let nt=ve.HEAPU32[ye/4+1],dt=[];for(let st=0;st<nt;st++){let Ze=Number(ve.getValue(ye+8+st*Be,"*"));dt.push(Ze!==0?ve.UTF8ToString(Ze):Number(ve.getValue(ye+8+(st+nt)*Be,"*")))}return[Ie,Fe,dt]}finally{ve.stackRestore(je),ye!==0&&ve._OrtFree(ye)}},xn=J=>{let ae=At(),ve=ae._malloc(J.byteLength);if(ve===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${J.byteLength}.`);return ae.HEAPU8.set(J,ve),[ve,J.byteLength]},zs=async(J,ae)=>{var dt,st,Ze;let ve,je,ye=At();Array.isArray(J)?[ve,je]=J:J.buffer===ye.HEAPU8.buffer?[ve,je]=[J.byteOffset,J.byteLength]:[ve,je]=xn(J);let Be=0,Ae=0,Ie=[],Fe=[],nt=[];try{if([Ae,Ie]=await eo(ae),(ae==null?void 0:ae.externalData)&&ye.mountExternalData){let ci=[];for(let Tn of ae.externalData){let es=typeof Tn=="string"?Tn:Tn.path;ci.push(De(typeof Tn=="string"?Tn:Tn.data).then(vs=>{ye.mountExternalData(es,vs)}))}await Promise.all(ci)}for(let ci of(ae==null?void 0:ae.executionProviders)??[])if((typeof ci=="string"?ci:ci.name)==="webnn"){if(ye.shouldTransferToMLTensor=!1,typeof ci!="string"){let Tn=ci,es=Tn==null?void 0:Tn.context,vs=Tn==null?void 0:Tn.gpuDevice,Ss=Tn==null?void 0:Tn.deviceType,Ra=Tn==null?void 0:Tn.powerPreference;es?ye.currentContext=es:vs?ye.currentContext=await ye.webnnCreateMLContext(vs):ye.currentContext=await ye.webnnCreateMLContext({deviceType:Ss,powerPreference:Ra})}else ye.currentContext=await ye.webnnCreateMLContext();break}Be=await ye._OrtCreateSession(ve,je,Ae),(dt=ye.webgpuOnCreateSession)==null||dt.call(ye,Be),Be===0&&Nt("Can't create a session."),(st=ye.jsepOnCreateSession)==null||st.call(ye),ye.currentContext&&(ye.webnnRegisterMLContext(Be,ye.currentContext),ye.currentContext=void 0,ye.shouldTransferToMLTensor=!0);let[Lt,Le]=Ti(Be),ft=!!(ae!=null&&ae.enableGraphCapture),Zn=[],dn=[],un=[],Qn=[],Ut=[];for(let ci=0;ci<Lt;ci++){let[Tn,es,vs]=Ls(Be,ci);Tn===0&&Nt("Can't get an input name."),Fe.push(Tn);let Ss=ye.UTF8ToString(Tn);Zn.push(Ss),un.push(es===0?{name:Ss,isTensor:!1}:{name:Ss,isTensor:!0,type:li(es),shape:vs})}for(let ci=0;ci<Le;ci++){let[Tn,es,vs]=Ls(Be,ci+Lt);Tn===0&&Nt("Can't get an output name."),nt.push(Tn);let Ss=ye.UTF8ToString(Tn);dn.push(Ss),Qn.push(es===0?{name:Ss,isTensor:!1}:{name:Ss,isTensor:!0,type:li(es),shape:vs})}return wn.set(Be,[Be,Fe,nt,null,ft,!1]),[Be,Zn,dn,un,Qn]}catch(Lt){throw Fe.forEach(Le=>ye._OrtFree(Le)),nt.forEach(Le=>ye._OrtFree(Le)),Be!==0&&ye._OrtReleaseSession(Be)!==0&&Nt("Can't release session."),Lt}finally{ye._free(ve),Ae!==0&&ye._OrtReleaseSessionOptions(Ae)!==0&&Nt("Can't release session options."),Ie.forEach(Lt=>ye._free(Lt)),(Ze=ye.unmountExternalData)==null||Ze.call(ye)}},to=J=>{var Fe,nt,dt;let ae=At(),ve=wn.get(J);if(!ve)throw new Error(`cannot release session. invalid session id: ${J}`);let[je,ye,Be,Ae,Ie]=ve;Ae&&(Ie&&ae._OrtClearBoundOutputs(Ae.handle)!==0&&Nt("Can't clear bound outputs."),ae._OrtReleaseBinding(Ae.handle)!==0&&Nt("Can't release IO binding.")),(Fe=ae.jsepOnReleaseSession)==null||Fe.call(ae,J),(nt=ae.webnnOnReleaseSession)==null||nt.call(ae,J),(dt=ae.webgpuOnReleaseSession)==null||dt.call(ae,J),ye.forEach(st=>ae._OrtFree(st)),Be.forEach(st=>ae._OrtFree(st)),ae._OrtReleaseSession(je)!==0&&Nt("Can't release session."),wn.delete(J)},ir=async(J,ae,ve,je,ye,Be,Ae=!1)=>{if(!J){ae.push(0);return}let Ie=At(),Fe=Ie.PTR_SIZE,nt=J[0],dt=J[1],st=J[3],Ze=st,Lt,Le;if(nt==="string"&&(st==="gpu-buffer"||st==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ae&&st!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(st==="gpu-buffer"){let dn=J[2].gpuBuffer;Le=Ei(qi(nt),dt);{let un=Ie.jsepRegisterBuffer;if(!un)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Lt=un(je,Be,dn,Le)}}else if(st==="ml-tensor"){let dn=J[2].mlTensor;Le=Ei(qi(nt),dt);let un=Ie.webnnRegisterMLTensor;if(!un)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Lt=un(je,dn,qi(nt),dt)}else{let dn=J[2];if(Array.isArray(dn)){Le=Fe*dn.length,Lt=Ie._malloc(Le),ve.push(Lt);for(let un=0;un<dn.length;un++){if(typeof dn[un]!="string")throw new TypeError(`tensor data at index ${un} is not a string`);Ie.setValue(Lt+un*Fe,Jn(dn[un],ve),"*")}}else{let un=Ie.webnnIsGraphInput,Qn=Ie.webnnIsGraphOutput;if(nt!=="string"&&un&&Qn){let Ut=Ie.UTF8ToString(ye);if(un(je,Ut)||Qn(je,Ut)){let ci=qi(nt);Le=Ei(ci,dt),Ze="ml-tensor";let Tn=Ie.webnnCreateTemporaryTensor,es=Ie.webnnUploadTensor;if(!Tn||!es)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let vs=await Tn(je,ci,dt);es(vs,new Uint8Array(dn.buffer,dn.byteOffset,dn.byteLength)),Lt=vs}else Le=dn.byteLength,Lt=Ie._malloc(Le),ve.push(Lt),Ie.HEAPU8.set(new Uint8Array(dn.buffer,dn.byteOffset,Le),Lt)}else Le=dn.byteLength,Lt=Ie._malloc(Le),ve.push(Lt),Ie.HEAPU8.set(new Uint8Array(dn.buffer,dn.byteOffset,Le),Lt)}}let ft=Ie.stackSave(),Zn=Ie.stackAlloc(4*dt.length);try{dt.forEach((un,Qn)=>Ie.setValue(Zn+Qn*Fe,un,Fe===4?"i32":"i64"));let dn=Ie._OrtCreateTensor(qi(nt),Lt,Le,Zn,dt.length,Oi(Ze));dn===0&&Nt(`Can't create tensor for input/output. session=${je}, index=${Be}.`),ae.push(dn)}finally{Ie.stackRestore(ft)}},Je=async(J,ae,ve,je,ye,Be)=>{var Cs,xl,Sc;let Ae=At(),Ie=Ae.PTR_SIZE,Fe=wn.get(J);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${J}`);let nt=Fe[0],dt=Fe[1],st=Fe[2],Ze=Fe[3],Lt=Fe[4];Fe[5];let Le=ae.length,ft=je.length,Zn=0,dn=[],un=[],Qn=[],Ut=[],ci=[],Tn=Ae.stackSave(),es=Ae.stackAlloc(Le*Ie),vs=Ae.stackAlloc(Le*Ie),Ss=Ae.stackAlloc(ft*Ie),Ra=Ae.stackAlloc(ft*Ie);try{[Zn,dn]=tr(Be),$t("wasm prepareInputOutputTensor");for(let yn=0;yn<Le;yn++)await ir(ve[yn],un,Ut,J,dt[ae[yn]],ae[yn],Lt);for(let yn=0;yn<ft;yn++)await ir(ye[yn],Qn,Ut,J,st[je[yn]],Le+je[yn],Lt);We("wasm prepareInputOutputTensor");for(let yn=0;yn<Le;yn++)Ae.setValue(es+yn*Ie,un[yn],"*"),Ae.setValue(vs+yn*Ie,dt[ae[yn]],"*");for(let yn=0;yn<ft;yn++)Ae.setValue(Ss+yn*Ie,Qn[yn],"*"),Ae.setValue(Ra+yn*Ie,st[je[yn]],"*");(Cs=Ae.jsepOnRunStart)==null||Cs.call(Ae,nt),(xl=Ae.webnnOnRunStart)==null||xl.call(Ae,nt);let ts;ts=await Ae._OrtRun(nt,vs,es,Le,Ra,ft,Ss,Zn),ts!==0&&Nt("failed to call OrtRun().");let Cr=[],Cc=[];$t("wasm ProcessOutputTensor");for(let yn=0;yn<ft;yn++){let hr=Number(Ae.getValue(Ss+yn*Ie,"*"));if(hr===Qn[yn]||ci.includes(Qn[yn])){Cr.push(ye[yn]),hr!==Qn[yn]&&Ae._OrtReleaseTensor(hr)!==0&&Nt("Can't release tensor.");continue}let Bd=Ae.stackSave(),Hr=Ae.stackAlloc(4*Ie),Jo=!1,Hi,ks=0;try{Ae._OrtGetTensorData(hr,Hr,Hr+Ie,Hr+2*Ie,Hr+3*Ie)!==0&&Nt(`Can't access output tensor data on index ${yn}.`);let bl=Ie===4?"i32":"i64",Es=Number(Ae.getValue(Hr,bl));ks=Ae.getValue(Hr+Ie,"*");let kc=Ae.getValue(Hr+Ie*2,"*"),Fd=Number(Ae.getValue(Hr+Ie*3,bl)),Wr=[];for(let Wi=0;Wi<Fd;Wi++)Wr.push(Number(Ae.getValue(kc+Wi*Ie,bl)));Ae._OrtFree(kc)!==0&&Nt("Can't free memory for tensor dims.");let pr=Wr.reduce((Wi,bi)=>Wi*bi,1);Hi=li(Es);let kr=Ze==null?void 0:Ze.outputPreferredLocations[je[yn]];if(Hi==="string"){if(kr==="gpu-buffer"||kr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Wi=[];for(let bi=0;bi<pr;bi++){let fr=Ae.getValue(ks+bi*Ie,"*"),Ec=Ae.getValue(ks+(bi+1)*Ie,"*"),Tc=bi===pr-1?void 0:Ec-fr;Wi.push(Ae.UTF8ToString(fr,Tc))}Cr.push([Hi,Wr,Wi,"cpu"])}else if(kr==="gpu-buffer"&&pr>0){let Wi=Ae.jsepGetBuffer;if(!Wi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let bi=Wi(ks),fr=Ei(Es,pr);if(fr===void 0||!nr(Hi))throw new Error(`Unsupported data type: ${Hi}`);Jo=!0,Cr.push([Hi,Wr,{gpuBuffer:bi,download:Ae.jsepCreateDownloader(bi,fr,Hi),dispose:()=>{Ae._OrtReleaseTensor(hr)!==0&&Nt("Can't release tensor.")}},"gpu-buffer"])}else if(kr==="ml-tensor"&&pr>0){let Wi=Ae.webnnEnsureTensor,bi=Ae.webnnIsGraphInputOutputTypeSupported;if(!Wi||!bi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ei(Es,pr)===void 0||!ds(Hi))throw new Error(`Unsupported data type: ${Hi}`);if(!bi(J,Hi,!1))throw new Error(`preferredLocation "ml-tensor" for ${Hi} output is not supported by current WebNN Context.`);let fr=await Wi(J,ks,Es,Wr,!1);Jo=!0,Cr.push([Hi,Wr,{mlTensor:fr,download:Ae.webnnCreateMLTensorDownloader(ks,Hi),dispose:()=>{Ae.webnnReleaseTensorId(ks),Ae._OrtReleaseTensor(hr)}},"ml-tensor"])}else if(kr==="ml-tensor-cpu-output"&&pr>0){let Wi=Ae.webnnCreateMLTensorDownloader(ks,Hi)(),bi=Cr.length;Jo=!0,Cc.push((async()=>{let fr=[bi,await Wi];return Ae.webnnReleaseTensorId(ks),Ae._OrtReleaseTensor(hr),fr})()),Cr.push([Hi,Wr,[],"cpu"])}else{let Wi=Ms(Hi),bi=new Wi(pr);new Uint8Array(bi.buffer,bi.byteOffset,bi.byteLength).set(Ae.HEAPU8.subarray(ks,ks+bi.byteLength)),Cr.push([Hi,Wr,bi,"cpu"])}}finally{Ae.stackRestore(Bd),Hi==="string"&&ks&&Ae._free(ks),Jo||Ae._OrtReleaseTensor(hr)}}Ze&&!Lt&&(Ae._OrtClearBoundOutputs(Ze.handle)!==0&&Nt("Can't clear bound outputs."),wn.set(J,[nt,dt,st,Ze,Lt,!1]));for(let[yn,hr]of await Promise.all(Cc))Cr[yn][2]=hr;return We("wasm ProcessOutputTensor"),Cr}finally{(Sc=Ae.webnnOnRunEnd)==null||Sc.call(Ae,nt),Ae.stackRestore(Tn),un.forEach(ts=>Ae._OrtReleaseTensor(ts)),Qn.forEach(ts=>Ae._OrtReleaseTensor(ts)),Ut.forEach(ts=>Ae._free(ts)),Zn!==0&&Ae._OrtReleaseRunOptions(Zn),dn.forEach(ts=>Ae._free(ts))}},ys=J=>{let ae=At(),ve=wn.get(J);if(!ve)throw new Error("invalid session id");let je=ve[0],ye=ae._OrtEndProfiling(je);ye===0&&Nt("Can't get an profile file name."),ae._OrtFree(ye)},wt=J=>{let ae=[];for(let ve of J){let je=ve[2];!Array.isArray(je)&&"buffer"in je&&ae.push(je.buffer)}return ae}}),Me,et,Pt,mn,bn,oi,ei,Li,pi,Gi,ti,ur,no,_o,Sr,zd,wo,yo,_c=c(()=>{vn(),xe(),si(),On(),Me=()=>!!A.wasm.proxy&&typeof document<"u",Pt=!1,mn=!1,bn=!1,Li=new Map,pi=(J,ae)=>{let ve=Li.get(J);ve?ve.push(ae):Li.set(J,[ae])},Gi=()=>{if(Pt||!mn||bn||!et)throw new Error("worker not ready")},ti=J=>{switch(J.data.type){case"init-wasm":Pt=!1,J.data.err?(bn=!0,ei[1](J.data.err)):(mn=!0,ei[0]()),oi&&(URL.revokeObjectURL(oi),oi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let ae=Li.get(J.data.type);J.data.err?ae.shift()[1](J.data.err):ae.shift()[0](J.data.out);break}}},ur=async()=>{if(!mn){if(Pt)throw new Error("multiple calls to 'initWasm()' detected.");if(bn)throw new Error("previous call to 'initWasm()' failed.");if(Pt=!0,Me())return new Promise((J,ae)=>{et==null||et.terminate(),Rt().then(([ve,je])=>{try{et=je,et.onerror=Be=>ae(Be),et.onmessage=ti,ei=[J,ae];let ye={type:"init-wasm",in:A};if(!ye.in.wasm.wasmPaths&&ve){let Be=Wn();Be&&(ye.in.wasm.wasmPaths=Be)}et.postMessage(ye),oi=ve}catch(ye){ae(ye)}},ae)});try{await xi(A.wasm),await _n(A),mn=!0}catch(J){throw bn=!0,J}finally{Pt=!1}}},no=async J=>{if(Me())return Gi(),new Promise((ae,ve)=>{pi("init-ep",[ae,ve]);let je={type:"init-ep",in:{epName:J,env:A}};et.postMessage(je)});await ri(A,J)},_o=async J=>Me()?(Gi(),new Promise((ae,ve)=>{pi("copy-from",[ae,ve]);let je={type:"copy-from",in:{buffer:J}};et.postMessage(je,[J.buffer])})):xn(J),Sr=async(J,ae)=>{if(Me()){if(ae!=null&&ae.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Gi(),new Promise((ve,je)=>{pi("create",[ve,je]);let ye={type:"create",in:{model:J,options:{...ae}}},Be=[];J instanceof Uint8Array&&Be.push(J.buffer),et.postMessage(ye,Be)})}else return zs(J,ae)},zd=async J=>{if(Me())return Gi(),new Promise((ae,ve)=>{pi("release",[ae,ve]);let je={type:"release",in:J};et.postMessage(je)});to(J)},wo=async(J,ae,ve,je,ye,Be)=>{if(Me()){if(ve.some(Ae=>Ae[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(ye.some(Ae=>Ae))throw new Error("pre-allocated output tensor is not supported for proxy.");return Gi(),new Promise((Ae,Ie)=>{pi("run",[Ae,Ie]);let Fe=ve,nt={type:"run",in:{sessionId:J,inputIndices:ae,inputs:Fe,outputIndices:je,options:Be}};et.postMessage(nt,wt(Fe))})}else return Je(J,ae,ve,je,ye,Be)},yo=async J=>{if(Me())return Gi(),new Promise((ae,ve)=>{pi("end-profiling",[ae,ve]);let je={type:"end-profiling",in:J};et.postMessage(je)});ys(J)}}),fl,So,Ia,ml=c(()=>{vn(),_c(),Gt(),ii(),ct(),fl=(J,ae)=>{switch(J.location){case"cpu":return[J.type,J.dims,J.data,"cpu"];case"gpu-buffer":return[J.type,J.dims,{gpuBuffer:J.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[J.type,J.dims,{mlTensor:J.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${J.location} for ${ae()}`)}},So=J=>{switch(J[3]){case"cpu":return new Ee(J[0],J[2],J[1]);case"gpu-buffer":{let ae=J[0];if(!nr(ae))throw new Error(`not supported data type: ${ae} for deserializing GPU tensor`);let{gpuBuffer:ve,download:je,dispose:ye}=J[2];return Ee.fromGpuBuffer(ve,{dataType:ae,dims:J[1],download:je,dispose:ye})}case"ml-tensor":{let ae=J[0];if(!ds(ae))throw new Error(`not supported data type: ${ae} for deserializing MLTensor tensor`);let{mlTensor:ve,download:je,dispose:ye}=J[2];return Ee.fromMLTensor(ve,{dataType:ae,dims:J[1],download:je,dispose:ye})}default:throw new Error(`invalid data location: ${J[3]}`)}},Ia=class{async fetchModelAndCopyToWasmMemory(J){return _o(await De(J))}async loadModel(J,ae){gt();let ve;typeof J=="string"?ve=await this.fetchModelAndCopyToWasmMemory(J):ve=J,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Sr(ve,ae),lt()}async dispose(){return zd(this.sessionId)}async run(J,ae,ve){gt();let je=[],ye=[];Object.entries(J).forEach(st=>{let Ze=st[0],Lt=st[1],Le=this.inputNames.indexOf(Ze);if(Le===-1)throw new Error(`invalid input '${Ze}'`);je.push(Lt),ye.push(Le)});let Be=[],Ae=[];Object.entries(ae).forEach(st=>{let Ze=st[0],Lt=st[1],Le=this.outputNames.indexOf(Ze);if(Le===-1)throw new Error(`invalid output '${Ze}'`);Be.push(Lt),Ae.push(Le)});let Ie=je.map((st,Ze)=>fl(st,()=>`input "${this.inputNames[ye[Ze]]}"`)),Fe=Be.map((st,Ze)=>st?fl(st,()=>`output "${this.outputNames[Ae[Ze]]}"`):null),nt=await wo(this.sessionId,ye,Ie,Ae,Fe,ve),dt={};for(let st=0;st<nt.length;st++)dt[this.outputNames[Ae[st]]]=Be[st]??So(nt[st]);return lt(),dt}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Fr={};h(Fr,{OnnxruntimeWebAssemblyBackend:()=>Gr,initializeFlags:()=>io,wasmBackend:()=>Co});var io,Gr,Co,wc=c(()=>{vn(),_c(),ml(),io=()=>{(typeof A.wasm.initTimeout!="number"||A.wasm.initTimeout<0)&&(A.wasm.initTimeout=0);let J=A.wasm.simd;if(typeof J!="boolean"&&J!==void 0&&J!=="fixed"&&J!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${J}". Reset it to \`false\` and ignore SIMD feature checking.`),A.wasm.simd=!1),typeof A.wasm.proxy!="boolean"&&(A.wasm.proxy=!1),typeof A.wasm.trace!="boolean"&&(A.wasm.trace=!1),typeof A.wasm.numThreads!="number"||!Number.isInteger(A.wasm.numThreads)||A.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)A.wasm.numThreads=1;else{let ae=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;A.wasm.numThreads=Math.min(4,Math.ceil((ae||1)/2))}},Gr=class{async init(J){io(),await ur(),await no(J)}async createInferenceSessionHandler(J,ae){let ve=new Ia;return await ve.loadModel(J,ae),ve}},Co=new Gr}),yc={};h(yc,{InferenceSession:()=>pn,TRACE:()=>be,TRACE_EVENT_BEGIN:()=>$t,TRACE_EVENT_END:()=>We,TRACE_FUNC_BEGIN:()=>gt,TRACE_FUNC_END:()=>lt,Tensor:()=>Ee,default:()=>vl,env:()=>A,registerBackend:()=>C}),vn(),vn(),vn();var gl="1.26.0",vl=In;{let J=(wc(),m(Fr)).wasmBackend;C("cpu",J,10),C("wasm",J,10)}return Object.defineProperty(A.versions,"web",{value:gl,enumerable:!0}),m(yc)})();n.exports=t})(Rb)),Rb.exports}var q1;function NA(){return q1||(q1=1,(function(n){var e=il&&il.__createBinding||(Object.create?(function(S,T,N,R){R===void 0&&(R=N);var O=Object.getOwnPropertyDescriptor(T,N);(!O||("get"in O?!T.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return T[N]}}),Object.defineProperty(S,R,O)}):(function(S,T,N,R){R===void 0&&(R=N),S[R]=T[N]})),t=il&&il.__setModuleDefault||(Object.create?(function(S,T){Object.defineProperty(S,"default",{enumerable:!0,value:T})}):function(S,T){S.default=T}),i=il&&il.__importStar||function(S){if(S&&S.__esModule)return S;var T={};if(S!=null)for(var N in S)N!=="default"&&Object.prototype.hasOwnProperty.call(S,N)&&e(T,S,N);return t(T,S),T};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=i($A()),a=$y(),u=Ny(),l=Vm(),c=Xx(),h=M2(),g=O2();n.DEFAULT_MODEL="legacy",n.ort=s;const m="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",k="silero_vad_legacy.onnx",C=S=>({...u.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:S,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async T=>{T.getTracks().forEach(N=>{N.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:T=>{T.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});n.getDefaultRealTimeVADOptions=C;const E=S=>"audioWorklet"in S&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function _(S,T,N,R,O){await N.audioWorklet.addModule(S),T.processorOptions={...T.processorOptions??{},frameSamples:R};const A=new AudioWorkletNode(N,"vad-helper-worklet",T);return A.port.onmessage=async L=>{const V=L.data;if(!(typeof V=="object"&&V&&"message"in V)){console.error("Invalid message event",V);return}switch(V.message){case c.Message.AudioFrame:{if(!("data"in V&&V.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const Q=new Float32Array(V.data);await O(Q);break}}},A}async function w(S,T,N){const R=new g.Resampler({nativeSampleRate:S.sampleRate,targetSampleRate:16e3,targetFrameSize:T});l.log.debug("using script processor");const A=S.createScriptProcessor(4096,1,1);let L=!1;return A.onaudioprocess=async V=>{if(!L){L=!0;try{const Q=V.inputBuffer.getChannelData(0);V.outputBuffer.getChannelData(0).fill(0);const K=R.process(Q);for(const ue of K)await N(ue)}catch(Q){console.error("Error processing audio:",Q)}finally{L=!1}}},A.connect(S.destination),A}class x{constructor(T,N,R,O,A=!1,L=null,V=null,Q=null,ie=null,K=null,ue=null,te="uninitialized",ce=!1){this.options=T,this.frameProcessor=N,this.model=R,this.frameSamples=O,this.listening=A,this.errored=L,this._stream=V,this._audioContext=Q,this._vadNode=ie,this._mediaStreamAudioSourceNode=K,this._audioProcessorAdapterType=ue,this.initializationState=te,this.ownsAudioContext=ce,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ce=>{this.initializationState="errored",this.errored=Ce},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?E(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await _(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await w(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:Ce,audioContext:fe,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const q=new MediaStreamAudioSourceNode(fe,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=q,q.connect(F);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ce,mediaStreamAudioSourceNode:fe}=this.getAudioInstances();await this.options.pauseStream(Ce),fe.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var fe;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((fe=this._audioContext)==null?void 0:fe.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.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(Ce.audio);break}}}static async new(T={}){const N={...(0,n.getDefaultRealTimeVADOptions)(T.model??n.DEFAULT_MODEL),...T};(0,u.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const R=N.model==="v5"?b:k,O=N.baseAssetPath+R,A=N.model==="v5"?h.SileroV5.new:h.SileroLegacy.new;let L;try{L=await A(n.ort,()=>(0,a.defaultModelFetcher)(O))}catch(ue){throw console.error(`Encountered an error while loading model file ${O}`),ue}const V=N.model==="v5"?512:1536,Q=V/16,ie=new u.FrameProcessor(L.process,L.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},Q),K=new x(N,ie,L,V);if(N.startOnLoad)try{await K.start()}catch(ue){throw console.error("Error starting micVad",ue),ue}return K}}n.MicVAD=x})(il)),il}var K1;function AA(){return K1||(K1=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=I2();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=$y();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var i=Ny();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var s=Xx();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=DA();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const u=jA();n.utils={audioFileToArray:u.audioFileToArray,minFramesForTargetMS:u.minFramesForTargetMS,arrayBufferToBase64:u.arrayBufferToBase64,encodeWAV:u.encodeWAV};var l=NA();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(Nb)),Nb}var IA=AA();function rv(n,e,t,i,s){var u,l;try{(l=(u=window.api)==null?void 0:u.logs)==null||l.write(n,e,t,i,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;i!==void 0?a(`[${n}]`,t,i):a(`[${n}]`,t)}const mt={debug:(n,e,t)=>rv(n,"debug",e,t),info:(n,e,t)=>rv(n,"info",e,t),warn:(n,e,t)=>rv(n,"warn",e,t),error:(n,e,t,i)=>rv(n,"error",e,t,i)},z2=16e3,RA=6,yh=z2*RA,PA=400,MA=z2*PA/1e3,Y1=300,X1=2e3,J1=1500,Z1=3e3,OA=600,B2=.5,F2=.35,Q1=.85,eS=.7;let Js=null,Vo=!1,dr=!1;const nw=new Set;function ov(n){for(const e of Array.from(nw))try{e(n)}catch(t){mt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Pb=0;const tS=2;let Lh=!1,G2=!1;function H2(n){n.addEventListener("message",e=>{var i;if(((i=e.data)==null?void 0:i.type)!=="log")return;const t=e.data.level||"info";mt[t]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{mt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),LA(`error:${e.message||"unknown"}`)})}function wx(){return Js||(Js=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),H2(Js),mt.info("speech","worker spawned"),Js)}let av=!1;function LA(n){if(!Lh){if(av){mt.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(av=!0,Pb+=1,G2=!0,mt.warn("speech","respawnWorker: starting",{reason:n,attempt:Pb}),ov({reason:n,respawned:!1,finalOnly:!0}),Pb>tS){if(Lh=!0,mt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:tS}),Js)try{Js.terminate()}catch{}Js=null,Vo=!1,dr=!1,ov({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),av=!1;return}if(Js)try{Js.terminate()}catch{}Js=null,Vo=!1,dr=!1;try{Js=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),H2(Js),dr=!0,Js.postMessage({type:"load"}),mt.info("speech","respawnWorker: new worker spawned, load posted"),ov({reason:n,respawned:!0,finalOnly:!0})}catch(e){Lh=!0,mt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),ov({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{av=!1}}}function zA(n,e){if(Vo||dr)return;dr=!0;const t=wx();mt.info("speech","preloadModel: posting load");const i=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(Vo=!0,dr=!1,mt.info("speech","preloadModel: ready"),t.removeEventListener("message",i))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(dr=!1,mt.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),t.removeEventListener("message",i))};t.addEventListener("message",i),t.postMessage({type:"load"})}function BA(){mt.info("speech","resetModel: clearing load flags"),Vo=!1,dr=!1}function FA(){if(mt.info("speech","releaseModel: terminating worker"),Js)try{Js.terminate()}catch{}Js=null,Vo=!1,dr=!1}function Jx(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function GA(n){const e=wx();return!Vo&&!dr&&(dr=!0,e.postMessage({type:"load"})),new Promise((t,i)=>{const s=a=>{var u,l,c;((u=a.data)==null?void 0:u.type)==="result"?(e.removeEventListener("message",s),t((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),i(new Error(String(a.data.error??"Transcription failed")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(Vo=!0,dr=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function W2(n){let e=wx(),t=!1,i=null,s=null,a=null,u=null,l=null;const c=[],h=new Set;let g=null,m=0,b=!1,k=0,C=!1,E=!1,_=0,w=0,x=0,S=-1,T=Y1,N=0,R=null,O="",A="",L=!1,V=0;function Q(le,me){const Re=Math.min(le.length,me.length);let He=0;for(;He<Re&&le.charCodeAt(He)===me.charCodeAt(He);)He++;return He}function ie(le){const me=Q(O,le);return O=le,me>A.length&&(A=le.slice(0,me)),A.length>le.length&&(A=le),A}const K=()=>(g||(g=new Float32Array(yh)),g),ue=()=>{m=0},te=le=>{const me=K(),Re=le.length;if(Re>=yh){me.set(le.subarray(Re-yh)),m=yh;return}if(m+Re<=yh){me.set(le,m),m+=Re;return}const He=m+Re-yh;me.copyWithin(0,He,m),m-=He,me.set(le,m),m+=Re},ce=()=>{R&&(clearTimeout(R),R=null)},Ce=()=>{ce(),b=!1,C=!1,E=!1,T=Y1,O="",A="",L=!1,V=0,ue()},fe=()=>{if(t||!b||E||C||R)return;if(m<MA){R=setTimeout(()=>{R=null,fe()},T);return}const le=performance.now()-_;if(le<T&&_!==0){R=setTimeout(()=>{R=null,fe()},T-le);return}if(G2||Lh||n.partialsEnabled&&!n.partialsEnabled())return;const me=K(),Re=new Float32Array(m);Re.set(me.subarray(0,m)),w+=1,x=w,C=!0,N=performance.now(),_=N,e.postMessage({type:"transcribe-partial",audio:Re,seq:w},[Re.buffer])},F=le=>le.length===0?Promise.resolve():Lh?(mt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(me=>{c.push(me),w+=1;const Re=w;S=Re,e.postMessage({type:"transcribe",audio:le,seq:Re},[le.buffer])}),q=le=>{const me=F(le);return h.add(me),me.finally(()=>{h.delete(me)}),me},H=le=>{var me,Re,He,ge,ee;if(le.data.type==="result"){const Ne=le.data.text,Ee=le.data.seq??0;Ee&&Ee<S&&mt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ee,latestFinalSeq:S}),!t&&Ne&&n.onFinal(Ne),(me=c.shift())==null||me()}else if(le.data.type==="partial"){const Ne=le.data.seq??0,Ee=le.data.text??"",Te=performance.now()-N;C=!1,Te>=Z1?(E=!0,mt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Te),seq:Ne})):Te>=J1&&(T=Math.min(T*2,X1),mt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Te),newIntervalMs:T,seq:Ne})),L||(L=!0,Te>OA&&T<500&&(T=500,mt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Te),newIntervalMs:500})));const be=Ne!==x||Ne<=S;if(!t&&!be&&Ee){const Qe=ie(Ee);Qe&&((Re=n.onPartial)==null||Re.call(n,Qe),V===0&&(V=performance.now(),mt.info("speech","partial.first",{msSinceSpeechStart:Math.round(V-k)})))}fe()}else if(le.data.type==="partial-error"){const Ne=performance.now()-N;C=!1,Ne>=Z1?(E=!0,mt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ne),seq:le.data.seq})):Ne>=J1&&(T=Math.min(T*2,X1),mt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ne),newIntervalMs:T,seq:le.data.seq})),mt.warn("speech","partial encode failed",{error:le.data.error,seq:le.data.seq}),fe()}else le.data.type==="error"?(t||n.onError(le.data.error),(He=c.shift())==null||He()):le.data.type==="status"?(t||(ge=n.onModelStatus)==null||ge.call(n,le.data.status,le.data.message),le.data.status==="ready"&&(Vo=!0,dr=!1)):le.data.type==="progress"&&(t||(ee=n.onProgress)==null||ee.call(n,le.data.pct))};e.addEventListener("message",H);const Z=le=>{var me,Re;if(!t){for(mt.warn("speech","createRecognition: worker death event",le),(me=n.onStatusChange)==null||me.call(n,"restarting");c.length;)(Re=c.shift())==null||Re();if(h.clear(),ce(),C=!1,le.respawned){try{e.removeEventListener("message",H)}catch{}e=wx(),e.addEventListener("message",H)}}};return nw.add(Z),{start:async()=>{if(!t){if(Lh){n.onError("Speech recognition disabled — please reload the app.");return}!Vo&&!dr&&(dr=!0,mt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),mt.info("speech","createRecognition.start: initializing VAD",{modelReady:Vo,modelLoading:dr});try{const le=new URL("vad/",document.baseURI).href;mt.info("speech","vad: asset base resolved",{vadBase:le}),SA();const me=n.inputDeviceId||null,Re={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};me&&(Re.deviceId={exact:me}),mt.info("speech","getUserMedia",{hasDeviceId:!!me,deviceIdPrefix:me?me.slice(0,8):null});const He=await navigator.mediaDevices.getUserMedia({audio:Re});s=He,a=new AudioContext;for(const ge of He.getAudioTracks())ge.addEventListener("ended",()=>{t||(mt.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),u=a.createAnalyser(),u.fftSize=2048,u.smoothingTimeConstant=.3,l.connect(u)}catch(ge){mt.warn("speech","analyser init failed",{error:ge instanceof Error?ge.message:String(ge)}),l=null,u=null}i=await IA.MicVAD.new({audioContext:a,getStream:async()=>He,resumeStream:async()=>He,pauseStream:async()=>{},baseAssetPath:le,onnxWASMBasePath:le,model:"v5",positiveSpeechThreshold:B2,negativeSpeechThreshold:F2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ge,ee)=>{var Ne;t||((Ne=n.onFrame)==null||Ne.call(n,ge),b&&(te(ee),fe()))},onSpeechStart:()=>{var ge;t||(Ce(),b=!0,k=performance.now(),(ge=n.onSpeechStart)==null||ge.call(n))},onSpeechEnd:ge=>{var ee;t||((ee=n.onStatusChange)==null||ee.call(n,"transcribing"),Ce(),q(ge))},onVADMisfire:()=>{var ge,ee;t||((ge=n.onStatusChange)==null||ge.call(n,"idle"),Ce(),(ee=n.onMisfire)==null||ee.call(n))}}),mt.info("speech","vad: ort wasm files loaded",{files:yA()}),i.start()}catch(le){const me=le instanceof Error?le.message:"Microphone access denied",Re=le instanceof Error?le.stack:"";if(mt.error("speech","createRecognition.start: VAD init failed",{error:me,stack:Re}),u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(He=>He.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(me)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(Ce();h.size>0;)await Promise.all(Array.from(h));if(i){try{await i.destroy()}catch{}i=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(le=>le.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(le,me)=>{if(i)try{i.setOptions({positiveSpeechThreshold:le,negativeSpeechThreshold:me})}catch(Re){mt.warn("speech","setVadThresholds failed",{error:Re instanceof Error?Re.message:String(Re)})}},getAnalyser:()=>u,destroy:()=>{if(t=!0,Ce(),i){try{i.destroy()}catch{}i=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(le=>le.stop())}catch{}s=null}nw.delete(Z),e.removeEventListener("message",H)}}}let vm=null;const iw=new Set,sw=new Set;function HA(){for(const n of iw)try{n()}catch{}}function rw(){for(const n of sw)try{n()}catch{}}function WA(n){return n.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function UA(n){if(!window.speechSynthesis)return;const e=WA(n);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{vm=performance.now(),HA()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vm=null,rw())},t.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(vm=null,rw())},window.speechSynthesis.speak(t)}function U2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),vm=null,rw())}function V2(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function VA(){return vm}function qA(n){return iw.add(n),()=>{iw.delete(n)}}function KA(n){return sw.add(n),()=>{sw.delete(n)}}function YA(n){V2()&&(n.setVadThresholds(Q1,eS),mt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=qA(()=>{n.setVadThresholds(Q1,eS),mt.info("voice","tts.duck.on")}),t=KA(()=>{n.setVadThresholds(B2,F2),mt.info("voice","tts.duck.off")});return()=>{e(),t()}}const XA=[{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 JA(n){const e=n.trim();return XA.find(t=>t.match.test(e))??null}const ZA=4e4;let $d=null;function zh(){$d&&clearTimeout($d),$d=setTimeout(()=>{$d=null,qt.getState().stopRecording()},ZA)}function lv(){$d&&(clearTimeout($d),$d=null)}let hc=null,oc=null;const QA=.04,eI=.3;let yx=0,ow=0;function tI(n){oc!==null&&cancelAnimationFrame(oc);const e=()=>{if(hc===null||qt.getState().submitCountdownStartAt===null){oc=null;return}const t=performance.now();if(t-ow<200&&yx>eI){const s=t-n;mt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:yx.toFixed(2),msIntoCountdown:Math.round(s)}),ic(),zh();return}const i=nI();if(i){const s=new Uint8Array(i.fftSize);i.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const u=Math.sqrt(a/s.length);if(u>QA){const l=t-n;mt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:u.toFixed(3),msIntoCountdown:Math.round(l)}),ic(),zh();return}}oc=requestAnimationFrame(e)};oc=requestAnimationFrame(e)}function nS(n){hc&&clearTimeout(hc);const e=qt.getState().submitDelayMs,t=performance.now();qt.setState({submitCountdownStartAt:t}),hc=setTimeout(()=>{var s;hc=null,qt.setState({submitCountdownStartAt:null});const i=jt.getState().tabs.find(a=>a.id===n);if((i==null?void 0:i.status)==="dormant"){const a=(s=Sn.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(Sn.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:a}),Sn.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){mt.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}zh()},e),tI(t)}function ic(){oc!==null&&(cancelAnimationFrame(oc),oc=null),hc&&(clearTimeout(hc),hc=null),qt.getState().submitCountdownStartAt!==null&&qt.setState({submitCountdownStartAt:null})}let fs=null,ar=null,Ff=null;function nI(){var n;return((n=fs==null?void 0:fs.getAnalyser)==null?void 0:n.call(fs))??null}const cv=1e4;let xm=null;function dv(){xm&&(clearTimeout(xm),xm=null)}let Xv=null,Jv=null;function uv(){Xv=null,Jv&&(Jv(),Jv=null)}const iI=1500,sI=9e4;let Gf=0,Zv=null,aw=-1;function Hf(){Zv&&(clearTimeout(Zv),Zv=null,aw=-1)}const rI=1800*1e3;let bm=null,hv=!1;function iS(){bm&&(clearTimeout(bm),bm=null)}const oI=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),qt=Si((n,e)=>{function t(){iS(),bm=setTimeout(()=>{if(bm=null,e().isRecording||fs){t();return}mt.info("voice","model idle timeout: releasing worker"),Hf(),Gf++,FA(),n({modelStatus:"idle",loadingProgress:0,error:null,errorKind:null})},rI)}function i(){return e().modelStatus==="error"?e().resetAndRetryModel():e().initModel(),new Promise((s,a)=>{let u=()=>{};const l=c=>c.modelStatus==="ready"?(u(),s(),!0):c.modelStatus==="error"?(u(),a(new Error(c.error??"Model load failed")),!0):!1;l(e())||(u=qt.subscribe(c=>{l(c)}))})}return{isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;mt.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const s=++Gf,a=()=>{s===Gf&&(Hf(),aw=s,Zv=setTimeout(()=>{aw===s&&e().modelStatus==="loading"&&(mt.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},sI))};a(),zA((u,l)=>{s===Gf&&(u==="ready"?(Hf(),mt.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null}),!e().isRecording&&!fs&&t()):u==="error"?(Hf(),mt.error("voice","modelStatus -> error",{msg:l}),n({modelStatus:"error",error:l,errorKind:"load"})):(a(),n({modelStatus:"loading"})))},u=>{s===Gf&&(a(),n({loadingProgress:Math.round(u)}))})},resetAndRetryModel:()=>{mt.info("voice","mic.gate.retry"),Hf(),BA(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(s,a)=>{if(e().isRecording)return;if(fs){mt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Jx()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}if(e().modelStatus!=="ready"){if(hv)return;hv=!0,i().then(()=>{hv=!1,e().startRecording(s,a)}).catch(l=>{hv=!1;const c=l instanceof Error?l.message:String(l);mt.error("voice","startRecording: model load failed",{error:c}),ze.error(`Could not load speech model: ${c}`)});return}iS();const u=l=>{try{const c=W2({inputDeviceId:l,onStatusChange:h=>{n(h==="transcribing"?{statusPill:"transcribing"}:h==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:h=>{e().partialsEnabled&&n({lastPartial:h})},partialsEnabled:()=>e().partialsEnabled,onFrame:h=>{yx=h.isSpeech,ow=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),lv(),ic(),V2()){const g=VA(),m=g!==null?performance.now()-g:null;U2(),n({lastBargeInAt:performance.now()}),mt.info("voice","barge-in",{tabId:s,utteranceOffsetMs:m})}else mt.debug("voice","barge-in.no-op",{tabId:s})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),zh();const h=e().lastBargeInAt;h!==null&&performance.now()-h<600&&mt.warn("voice","barge-in.misfire",{tabId:s,sinceBargeInMs:Math.round(performance.now()-h)})},onFinal:h=>{var C;zh();const g=h.trim();if(!g||oI.has(g)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Ff){Ff(g),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((C=jt.getState().tabs.find(E=>E.id===s))==null?void 0:C.status)==="dormant"){Sn.getState().setPendingVoiceText(s,g),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&nS(s);const E=window;E.__transcripts&&(E.__transcripts.push({tabId:s,text:g}),E.__transcripts.length>500&&E.__transcripts.shift());return}const b=JA(g);if(b){mt.info("voice","voice-command",{tabId:s,label:b.label,transcript:g}),window.api.pty.write({tabId:s,data:b.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),ic();const E=window;E.__transcripts&&(E.__transcripts.push({tabId:s,text:g}),E.__transcripts.length>500&&E.__transcripts.shift());return}window.api.pty.write({tabId:s,data:g}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&nS(s);const k=window;k.__transcripts&&(k.__transcripts.push({tabId:s,text:g}),k.__transcripts.length>500&&k.__transcripts.shift())},onError:h=>{mt.error("voice","recognition error",{err:h}),ic(),n({error:h,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),ar==null||ar(),ar=null,lv(),fs==null||fs.destroy(),fs=null,Ff=null,ze.error(`Microphone error: ${h}`)},onModelStatus:h=>{h==="ready"?n({modelStatus:"ready",loadingProgress:100}):h==="loading"&&n({modelStatus:"loading"})},onProgress:h=>n({loadingProgress:Math.round(h)})});fs=c,Ff=(a==null?void 0:a.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),zh(),c.start().then(()=>{fs===c&&(ar==null||ar(),ar=YA(c))}).catch(h=>{const g=h instanceof Error?h.message:String(h);mt.error("voice","handle.start() failed",{error:g}),ze.error(`Could not start mic: ${g}`)})}catch(c){n({error:c instanceof Error?c.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,c,h;return((h=(c=(l=window.api)==null?void 0:l.voice)==null?void 0:c.getDevicePref)==null?void 0:h.call(c))??Promise.resolve(null)}).then(l=>u((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{mt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),u(null)})},stopRecording:()=>{const s=fs;s&&(lv(),ic(),yx=0,ow=0,ar==null||ar(),ar=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t(),s.stop().finally(()=>{s.destroy(),fs===s&&(fs=null,Ff=null),e().hotkeyState==="stopping"&&(dv(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const s=fs;if(!s)return;lv(),ar==null||ar(),ar=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await s.stop()}catch(l){mt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}s.destroy(),fs===s&&(fs=null);const{useSessions:a}=await qn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>BN);return{useSessions:l}},[],import.meta.url),u=a.getState().activeTabId;u&&e().startRecording(u)},setExternalRecording:s=>n({externalRecording:s}),toggleTTS:()=>{const s=!e().ttsEnabled;n({ttsEnabled:s}),Promise.resolve().then(()=>{var a,u,l;return(l=(u=(a=window.api)==null?void 0:a.voice)==null?void 0:u.setTtsEnabled)==null?void 0:l.call(u,s)}).catch(a=>{mt.warn("voice","setTtsEnabled failed",{error:a instanceof Error?a.message:String(a)})})},setAutoSubmit:s=>n({autoSubmit:s}),setSubmitDelayMs:s=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(s)))}),cancelSubmit:()=>ic(),setPartialsEnabled:s=>{e().partialsEnabled!==s&&(n({partialsEnabled:s}),s||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:s=>{e().permissionState!==s&&(mt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:s}),n({permissionState:s}))},setLevelMeterEnabled:s=>{e().levelMeterEnabled!==s&&n({levelMeterEnabled:s})},setTurnDetectorRuntimeState:s=>{e().turnDetectorState!==s&&(n({turnDetectorState:s}),s==="load_failed"?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&&n({wizardArmed:s})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:s,source:a,mode:u,tabId:l})=>{const c=e(),{canRecord:h,reason:g}=q2(c);if(s==="down"){if(g==="error"||g==="load-timeout"){c.resetAndRetryModel(),mt.info("voice-hotkey","down.retry",{source:a,reason:g});return}if(!h&&g!=="loading"){mt.warn("voice-hotkey","miss-model-loading",{modelStatus:c.modelStatus,reason:g});return}if(c.hotkeyState==="recording"||c.isRecording){(u==="toggle"||a==="global")&&(n({hotkeyState:"stopping"}),dv(),xm=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:cv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},cv),c.stopRecording());return}if(g==="loading"){c.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),mt.info("voice-hotkey","armed",{source:a,modelStatus:c.modelStatus})),uv(),Xv={tabId:l,source:a,mode:u},Jv=qt.subscribe((m,b)=>{if(Xv&&m.modelStatus==="ready"&&b.modelStatus!=="ready"&&m.hotkeyState==="armed"){const k=Xv;if(uv(),!k.tabId){mt.warn("voice-hotkey","armed-promote-no-tab",{source:k.source}),n({hotkeyState:"idle"});return}mt.info("voice-hotkey","armed-promote",k),n({hotkeyState:"recording"}),qt.getState().startRecording(k.tabId)}});return}if(!l){mt.warn("voice-hotkey","no-active-tab",{source:a});return}mt.info("voice-hotkey","start",{source:a,mode:u,tabId:l}),c.startRecording(l),e().isRecording?n({hotkeyState:"recording"}):(mt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(u!=="hold"||a==="global")){if(c.hotkeyState==="armed"){uv(),mt.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}c.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),dv(),xm=setTimeout(()=>{e().hotkeyState==="stopping"&&(mt.warn("voice-hotkey","drain-timeout",{durationMs:cv}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},cv),c.stopRecording())}},destroyHotkey:()=>{const s=e();if(uv(),ic(),s.hotkeyState==="recording"){mt.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{s.stopRecording()}catch{}}else(s.hotkeyState==="armed"||s.hotkeyState==="stopping")&&(dv(),n({hotkeyState:"destroyed"}))}}}),aI=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),q2=n=>Jx()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};typeof window<"u"&&Promise.resolve().then(()=>{var n,e,t;return(t=(e=(n=window.api)==null?void 0:n.voice)==null?void 0:e.getTtsEnabled)==null?void 0:t.call(e)}).then(n=>{typeof n=="boolean"&&qt.setState({ttsEnabled:n})}).catch(n=>{mt.warn("voice","getTtsEnabled failed",{error:n instanceof Error?n.message:String(n)})});if(typeof window<"u"){const n=window;n.__voice=qt,n.__transcripts=[]}const Nm=6e4,lI=3e5,cI=.25,dI=5e3,Am=Si(()=>({data:null,refreshing:!1}));let sS=!1,Qv=null,Mb=Nm,pv=!1,al=null;function uI(n,e){if(n.kind==="ok")return{delayMs:Nm,nextBackoffMs:Nm};const t=Math.min(e*2,lI),i=t*cI;let s=t+(Math.random()*2-1)*i;const a=n.kind==="meter_rate_limited"?n.retryAfterMs:void 0;return typeof a=="number"&&Number.isFinite(a)&&a>s&&(s=a),{delayMs:s,nextBackoffMs:t}}function rS(){return c2(window.api.billing.fetch(),dI,"billing.fetch")}function oS(n){Am.setState({data:n,refreshing:!1})}async function Ay(){Am.setState({refreshing:!0});let n=Nm;try{const e=await rS();al&&(al.cancel(),al=null),oS(e);const{delayMs:t,nextBackoffMs:i}=uI(e,Mb);Mb=i,n=t}catch(e){Mb=Nm,Am.setState({refreshing:!1});const t=d2({error:e,retry:rS,onRetrySuccess:i=>{al=null,oS(i)},onStillFailing:i=>{al=null,pv||(pv=!0,ze.warn(`Billing usage fetch: ${i}`))}});if(t)al=t;else if(!pv){pv=!0;const i=e instanceof Error?e.message:String(e);ze.warn(`Billing usage fetch failed: ${i}`)}}Qv=setTimeout(Ay,n)}function hI(){sS||(sS=!0,Ay())}function K2(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function pI(){Qv!==null&&(clearTimeout(Qv),Qv=null),al&&(al.cancel(),al=null),Ay()}function Im(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!t)return n;const i=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),s=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${i} ${s} ${e[1]}`:`${i} ${s}`}function Rm(n){const e=/(opus|sonnet|haiku|fable)/i.exec(n);return e?e[1].toLowerCase():null}const fv=new Map,fI=3e4;function Iy(n){const[e,t]=I.useState(()=>{var i;return n?((i=fv.get(n))==null?void 0:i.value)??null:null});return I.useEffect(()=>{if(!n){t(null);return}let i=!1;return(async()=>{const a=fv.get(n);if(a&&Date.now()-a.ts<fI){i||t(a.value);return}try{const u=await window.api.app.gitBranch(n);if(i)return;fv.set(n,{value:u,ts:Date.now()}),t(u)}catch{if(i)return;fv.set(n,{value:null,ts:Date.now()}),t(null)}})(),()=>{i=!0}},[n]),e}const mI="~/.claude/session-manager/ui-chrome-prefs.json",Y2=$a(mI),gI=180,vI=480,lw=252,xd={sidebarWidth:lw,sidebarCollapsed:!1,collapsedGroups:[],learningPanelCollapsed:!1,tourCompletedAt:null,density:"roomy"};function cw(n){return Math.min(vI,Math.max(gI,n))}let ac=null,ex={};function xI(n){const e=()=>{const t=n(),i={sidebarWidth:t.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed,collapsedGroups:t.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed,tourCompletedAt:t.tourCompletedAt,density:t.density};Y2.patch(i).catch(()=>{})};n().hydrated||!ac?e():ac.then(e)}function Sh(n,e,t){n(t),!e().hydrated&&ac&&Object.assign(ex,t),xI(e)}const as=Si((n,e)=>({...xd,hydrated:!1,hydrate:()=>e().hydrated?Promise.resolve():ac||(ac=(async()=>{try{const t=await Y2.read();if(Object.keys(t).length>0){n({sidebarWidth:typeof t.sidebarWidth=="number"?cw(t.sidebarWidth):xd.sidebarWidth,sidebarCollapsed:t.sidebarCollapsed??xd.sidebarCollapsed,collapsedGroups:Array.isArray(t.collapsedGroups)?t.collapsedGroups:xd.collapsedGroups,learningPanelCollapsed:t.learningPanelCollapsed??xd.learningPanelCollapsed,tourCompletedAt:typeof t.tourCompletedAt=="number"?t.tourCompletedAt:xd.tourCompletedAt,density:t.density==="compact"?"compact":xd.density,...ex,hydrated:!0});return}}catch{}n({...ex,hydrated:!0})})().finally(()=>{ac=null,ex={}}),ac),setSidebarWidth:t=>Sh(n,e,{sidebarWidth:cw(t)}),setSidebarCollapsed:t=>Sh(n,e,{sidebarCollapsed:t}),setCollapsedGroups:t=>Sh(n,e,{collapsedGroups:t}),setLearningPanelCollapsed:t=>Sh(n,e,{learningPanelCollapsed:t}),setTourCompletedAt:t=>Sh(n,e,{tourCompletedAt:t}),setDensity:t=>Sh(n,e,{density:t})})),bI=52;function _I(n){return new Set(n.filter(e=>e==="Workspace"||e==="Claude Code"||e==="Session Manager"))}function wI(){const n=jt(t=>{var i;return((i=t.tabs.find(s=>s.id===t.activeTabId))==null?void 0:i.cwd)??null});return{scheduler:Mr(t=>{var i;return(((i=t.snapshot)==null?void 0:i.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function yI({active:n,onNavigate:e,onNewSession:t}){const i=as(K=>K.hydrated),s=as(K=>K.hydrate);I.useEffect(()=>{i||s()},[i,s]);const a=as(K=>K.collapsedGroups),u=as(K=>K.setCollapsedGroups),l=I.useMemo(()=>_I(a),[a]),c=I.useCallback(K=>{const ue=new Set(l);ue.has(K)?ue.delete(K):ue.add(K),u(Array.from(ue))},[l,u]),h=as(K=>K.sidebarCollapsed),g=as(K=>K.setSidebarCollapsed),m=I.useCallback(()=>{g(!h)},[h,g]),b=jt(K=>K.tabs),k=jt(K=>K.activeTabId),C=b.find(K=>K.id===k)??null,E=wI(),_=Dn(K=>K.navFace),w=WN(_),x=w.filter(K=>K.group==="Workspace"),S=w.filter(K=>K.group==="Claude Code"),T=w.filter(K=>K.group==="Session Manager"),N=_==="home"&&!h,R=as(K=>K.sidebarWidth),O=as(K=>K.setSidebarWidth),[A,L]=I.useState(R),V=I.useRef(A);V.current=A,I.useEffect(()=>{L(R)},[R]);const Q=I.useCallback(K=>{K.preventDefault();const ue=K.clientX,te=V.current;let ce=te;const Ce=F=>{ce=cw(te+(F.clientX-ue)),L(ce)},fe=()=>{window.removeEventListener("pointermove",Ce),window.removeEventListener("pointerup",fe),document.body.style.cursor="",document.body.style.userSelect="",O(ce)};window.addEventListener("pointermove",Ce),window.addEventListener("pointerup",fe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[O]),ie=I.useCallback(()=>{L(lw),O(lw)},[O]);return r.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:h?bI:A},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[r.jsx(SI,{tab:C,navFace:_,onNewSession:t,rail:h,onToggleRail:m}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:h?"4px":"8px"},children:N?r.jsxs(r.Fragment,{children:[r.jsx(Ob,{label:"Workspace",desc:jb.Workspace,collapsed:l.has("Workspace"),count:x.length,onToggle:()=>c("Workspace")}),!l.has("Workspace")&&x.map(K=>r.jsx(mv,{item:K,active:n===K.key,live:K.liveKind?E[K.liveKind]:!1,onClick:()=>e(K.key),rail:!1},K.key)),r.jsx(Ob,{label:"Claude Code",desc:jb["Claude Code"],collapsed:l.has("Claude Code"),count:S.length,onToggle:()=>c("Claude Code")}),!l.has("Claude Code")&&S.map(K=>r.jsx(mv,{item:K,active:n===K.key,live:!1,onClick:()=>e(K.key),rail:!1},K.key)),r.jsx(Ob,{label:"Session Manager",desc:jb["Session Manager"],collapsed:l.has("Session Manager"),count:T.length,onToggle:()=>c("Session Manager")}),!l.has("Session Manager")&&T.map(K=>r.jsx(mv,{item:K,active:n===K.key,live:!1,onClick:()=>e(K.key),rail:!1},K.key))]}):r.jsx("div",{className:"pt-2",children:w.map(K=>r.jsx(mv,{item:K,active:n===K.key,live:K.liveKind?E[K.liveKind]:!1,onClick:()=>e(K.key),rail:h},K.key))})}),r.jsx(CI,{rail:h,navFace:_}),!h&&r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:Q,onDoubleClick:ie,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 SI({tab:n,navFace:e,onNewSession:t,rail:i,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",u=Iy((n==null?void 0:n.cwd)??null);return i?r.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[r.jsx("button",{onClick:t,"data-testid":"tour-new-session",title:"Open / Start Project",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:r.jsx(_i,{name:"plus",size:15,stroke:1.8})}),r.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:r.jsx(_i,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?r.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),r.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:r.jsx(_i,{name:"chevron",size:13,stroke:1.8})})})]}),r.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:r.jsxs("button",{onClick:t,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[r.jsx(_i,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):r.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),r.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:r.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:r.jsx(_i,{name:"chevron",size:13,stroke:1.8})})})]}),r.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[r.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),r.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),r.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:u?`⌥${u}`:n?n.cwd:"—"}),r.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:r.jsxs("button",{onClick:t,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[r.jsx(_i,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Ob({label:n,desc:e,collapsed:t,count:i,onToggle:s}){return r.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[r.jsxs("button",{onClick:s,"aria-expanded":!t,title:t?`Expand ${n}`:`Collapse ${n}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[r.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),r.jsx("span",{className:"flex-1",children:n}),t&&r.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!t&&r.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:e})]})}function mv({item:n,active:e,live:t,onClick:i,rail:s}){return r.jsxs("button",{onClick:i,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":n.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&r.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),r.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:r.jsx(_i,{name:n.icon,size:17,stroke:1.6})}),!s&&r.jsxs("span",{className:"flex-1 min-w-0",children:[r.jsx("span",{className:"block truncate",children:n.label}),n.hint&&r.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&t&&r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&t&&r.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function CI({rail:n,navFace:e}){const t=qt(c=>c.isRecording),i=jt(c=>c.tabs),s=jt(c=>c.activeTabId),a=i.find(c=>c.id===s)??null,[u,l]=I.useState(null);return I.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return r2(a.presetId).then(h=>{c||l((h==null?void 0:h.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?r.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):r.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"}),(t||e==="project")&&r.jsx("span",{className:"truncate",title:u??"",children:t?"recording…":u?`Claude · ${Im(u)}`:"Claude Code"})]})}function kI(n,e,t){return e?n.map(i=>i.id===e?{...i,lastActivityAt:t}:i):n}function EI(n,e,t){return{tabId:n,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function TI(n,e,t){const i=Date.now(),s={...n,lastEventAt:t!=null&&t.replay?n.lastEventAt:i},a=[],u=(l,c)=>l.length>c?l.slice(0,c-1)+"…":l;switch(e.kind){case"todo_write":{const l=Array.isArray(e.data)?e.data:[];s.todos=l,t!=null&&t.replay||a.push({id:0,kind:"todo-update",at:i,label:`Todos · ${l.length} item${l.length!==1?"s":""}`});break}case"tool_use":{const l=e.data,c=l.input,h={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])c&&g in c&&(h[g]=c[g]);if(s.lastToolUses=[{id:l.id,name:l.name,input:h,at:i},...n.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=l.input,m=["Edit","Write","NotebookEdit"].includes(l.name),b=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,k=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,C=b?b.split("/").pop()??b:k?u(k,28):"";a.push({id:0,kind:"tool-use",at:i,label:C?`${l.name} · ${C}`:l.name,target:b??k,toolName:l.name}),m&&b&&a.push({id:0,kind:"file-edit",at:i,label:`${l.name} · ${u(b.split("/").pop()??b,34)}`,target:b,toolName:l.name})}break}case"plan":{const l=e.data,c=typeof l=="string"?l:(l==null?void 0:l.plan)??JSON.stringify(l);s.plans=[{at:i,content:c??""},...n.plans].slice(0,50),t!=null&&t.replay||a.push({id:0,kind:"plan-revision",at:i,label:"Plan revised"});break}case"agent_spawn":{const l=e.data;s.agents=[{id:l==null?void 0:l.toolUseId,at:i,subagentType:l==null?void 0:l.subagent_type,description:l==null?void 0:l.description,lastActivityAt:i},...n.agents].slice(0,50),t!=null&&t.replay||a.push({id:0,kind:"agent-spawn",at:i,label:l!=null&&l.subagent_type?`Agent: ${u(l.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const l=e.data,c=(n.usage.inputTokens||0)+(n.usage.outputTokens||0),h=l.input_tokens??l.inputTokens??0,g=l.output_tokens??l.outputTokens??0,m=c+h+g;s.usage={inputTokens:(n.usage.inputTokens||0)+h,outputTokens:(n.usage.outputTokens||0)+g,cacheCreationInputTokens:(n.usage.cacheCreationInputTokens||0)+(l.cache_creation_input_tokens??l.cacheCreationInputTokens??0),cacheReadInputTokens:(n.usage.cacheReadInputTokens||0)+(l.cache_read_input_tokens??l.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(c/1e3)&&a.push({id:0,kind:"usage-tick",at:i,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const l=e.data;s.agents=kI(n.agents,l==null?void 0:l.toolUseId,i);break}}return{next:s,newActivity:a}}const tx=Si((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,i,s)=>{const a={...e().refs};if(a[t]=(a[t]??0)+1,n({refs:a}),a[t]>1)return;n({tabs:{...e().tabs,[t]:EI(t,i,s)}});const u=window.api.transcripts.onEvent(t,l=>e().ingestBatch(t,l));n({unsubs:{...e().unsubs,[t]:u}}),window.api.transcripts.subscribe({tabId:t,cwd:i,sessionUuid:s}).then(async l=>{const c=e().tabs[t];if(!c)return;if(!l.ok){const{toast:g}=await qn(async()=>{const{toast:m}=await Promise.resolve().then(()=>a2);return{toast:m}},void 0,import.meta.url);g.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[t]:{...c,path:null}}});return}n({tabs:{...e().tabs,[t]:{...c,path:l.path}}});const h=await window.api.transcripts.buffer(t);e().ingestBatch(t,h,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",t,l))},unsubscribe:t=>{const i={...e().refs};if(!i[t])return;if(i[t]--,i[t]>0){n({refs:i});return}delete i[t];const s=e().unsubs[t];s==null||s();const a={...e().unsubs};delete a[t];const u={...e().tabs};delete u[t],window.api.transcripts.unsubscribe(t),n({refs:i,unsubs:a,tabs:u})},ingest:(t,i,s)=>{e().ingestBatch(t,[i],s)},ingestBatch:(t,i,s)=>{const a=e().tabs[t];if(!a||i.length===0)return;let u=a,l=[];for(const c of i){const{next:h,newActivity:g}=TI(u,c,s);u=h,l=l.concat(g)}if(l.length>0){let c=a.activitySeq;const h=l.map(g=>({...g,id:++c}));u={...u,activitySeq:c,activityRing:[...a.activityRing,...h].slice(-32)}}n({tabs:{...e().tabs,[t]:u}})}}));function DI(n){const e=tx(s=>s.subscribe),t=tx(s=>s.unsubscribe),i=tx(s=>n?s.tabs[n.id]:void 0);return I.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>t(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,t]),i}function X2(n){if(!n)return null;const e=new Date(n);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const i=Math.floor(t/864e5),s=Math.floor(t%864e5/36e5),a=Math.floor(t%36e5/6e4),u=i>0?`${i}d ${s}h`:s>0?`${s}h ${a}m`:`${a}m`,l=i>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:u,abs:`${l} PT`}}function dw(n){return!n||typeof n.utilization!="number"||Number.isNaN(n.utilization)?null:Math.round(n.utilization)}function aS(n,e){const t=dw(e);if(t==null)return`${n} — usage unavailable`;const i=X2((e==null?void 0:e.resets_at)??null),s=i?` · resets in ${i.rel}${i.abs?` (${i.abs})`:""}`:"";return`${n} · ${t}% used${s} — click to open Home`}function e8(n,e){return n?n==="session"||n==="five_hour"?"Session · 5h":n==="weekly_all"?"Weekly · all models":n==="weekly_scoped"?"Weekly · scoped":n:null}const J2=I.createContext(null);function jI({panelId:n,children:e}){return r.jsx(J2.Provider,{value:n,children:e})}function Zx(n){const e=I.useContext(J2),t=n??e;return Dn(i=>t==null||i.focusedPanelId===t)}function Ry(n){const e=Zx(n),t=I.useRef(e);return t.current=e,t}const $I=5e3;let Dd=null;const uw=new Set;let Lb=0,_m=null;function NI(){uw.forEach(n=>n())}async function Sx(){try{Dd=await window.api.schedule.sessionSlots(),NI()}catch{}}const AI=0,II=10;async function t8(n){Dd||await Sx();const e=Dd?Dd.min:AI,t=Dd?Dd.max:II,i=Math.min(t,Math.max(e,Math.round(n)));await window.api.schedule.setSessionSlots(i),await Sx()}function RI(){_m==null&&(Sx(),_m=setInterval(()=>{Sx()},$I))}function PI(){_m!=null&&(clearInterval(_m),_m=null)}function Py(n){const e=Zx(n),[,t]=I.useState(0);return I.useEffect(()=>{const i=()=>t(s=>s+1);return uw.add(i),()=>{uw.delete(i)}},[]),I.useEffect(()=>{if(e)return Lb+=1,RI(),()=>{Lb-=1,Lb<=0&&PI()}},[e]),Dd}let Ah=null;const hw=new Set;let zb=0,nx=null,pw=!1;const MI=360*60*1e3;let ix=null;function lS(n){Ah=n.check||!(Ah!=null&&Ah.check)?n:{...n,check:Ah.check},hw.forEach(e=>e())}function OI(){if(pw)return;pw=!0,nx=window.api.updater.onStatus(lS);const n=()=>{window.api.updater.status().then(lS).catch(()=>{})};n(),ix=setInterval(n,MI)}function LI(){pw=!1,ix!=null&&(clearInterval(ix),ix=null),nx&&(nx(),nx=null)}function zI(){const[,n]=I.useState(0);return I.useEffect(()=>{const e=()=>n(t=>t+1);return hw.add(e),zb+=1,OI(),()=>{hw.delete(e),zb-=1,zb<=0&&LI()}},[]),Ah}function BI({total:n,inUse:e,size:t}){const i=Math.min(Math.max(e,0),n),s=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return r.jsx(r.Fragment,{children:Array.from({length:n},(a,u)=>r.jsx("span",{"data-testid":"slot-dot","data-filled":u<i?"true":"false",className:`${s} ${u<i?"bg-accent border-accent":"bg-bg border-line"}`},u))})}function FI({onNavigate:n}){const e=jt(te=>te.tabs),t=jt(te=>te.activeTabId),i=e.find(te=>te.id===t)??null,s=DI(i),a=(s==null?void 0:s.lastEventAt)??0,u=Am(te=>te.data),l=Mr(te=>{var ce;return((ce=te.snapshot)==null?void 0:ce.paused)??null}),c=Iy((i==null?void 0:i.cwd)??null),h=Py(),g=zI(),m=(g==null?void 0:g.check)??null,b=Bi(te=>te.show),[,k]=I.useState(0);I.useEffect(()=>{const te=setInterval(()=>k(ce=>ce+1),6e4);return()=>clearInterval(te)},[]);const C=async()=>{const te=(g==null?void 0:g.latest)??"";try{const ce=await window.api.updater.install(!1),Ce=(ce==null?void 0:ce.status)??await window.api.updater.status();(Ce==null?void 0:Ce.state)==="deferred"&&b("info",`Update v${te} will install when ${Ce.busyReason??"running jobs"} finish`)}catch(ce){b("error",ce instanceof Error?ce.message:String(ce))}},E=(s==null?void 0:s.todos)??[],[_,w]=I.useState(!1),x=I.useRef(null);I.useEffect(()=>{if(!_)return;const te=ce=>{x.current&&!x.current.contains(ce.target)&&w(!1)};return document.addEventListener("mousedown",te),()=>document.removeEventListener("mousedown",te)},[_]),I.useEffect(()=>{E.length===0&&w(!1)},[E.length]);const S=K2(u),T=(S==null?void 0:S.usage.five_hour)??null,N=(S==null?void 0:S.usage.seven_day)??null,R=dw(T),O=dw(N),A=(u==null?void 0:u.kind)==="ok"||(u==null?void 0:u.kind)==="ok-stale",L=a>0?WI(Date.now()-a):"—",V=(h==null?void 0:h.total)??5,Q=h?Math.min(Math.max(h.inUse,0),h.total):0,ie=h?`${Q} / ${V}`:`— / ${V}`,K=h&&h.holders.length>0?`
|
|
2933
2933
|
`+h.holders.slice(0,5).map(te=>te.owner).join(`
|
|
2934
|
-
`):"",ue=`${ie} Claude sessions running${K}`;return r.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[r.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:A?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:A?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:aS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:R!=null?`${R}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:aS("Weekly window (all models)",N),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:O!=null?`${O}%`:"—"})]}),l&&r.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),i&&r.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,c&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),E.length>0&&r.jsx(GI,{ref:x,todos:E,open:_,onToggle:()=>w(te=>!te)}),r.jsx("span",{className:"flex-1"}),r.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:ue,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(BI,{total:V,inUse:(h==null?void 0:h.inUse)??0,size:"sm"})}),(g==null?void 0:g.state)==="ready"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{C()},children:["Update ready — restart to install v",g.latest]}):(g==null?void 0:g.state)==="deferred"?r.jsxs("span",{className:"text-amber-300",title:`Waiting for ${g.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",g.latest," installs when idle"]}):(g==null?void 0:g.state)==="downloading"?r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",g.latest,"…"]}):m!=null&&m.behind&&m.latest&&m.channel==="installer"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${m.current} → v${m.latest}`,"data-testid":"footer-version",onClick:()=>{const te=m.downloadUrl;te&&window.api.shell.open({as:"external",url:te}).catch(()=>{b("error",`Couldn't open URL: ${te}`)})},children:["Download v",m.latest]}):m!=null&&m.behind&&m.latest?r.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",m.current," → v",m.latest]}):r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(m==null?void 0:m.current)??"0.136.0"]})]})}const GI=I.forwardRef(function({todos:e,open:t,onToggle:i},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return r.jsxs("div",{ref:s,className:"relative",children:[r.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[r.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),r.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),r.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),r.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&r.jsx("div",{className:`absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 ${Ii.dialog}`,"data-testid":"footer-todos-popover",children:r.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>r.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[r.jsx(HI,{status:u.status}),r.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function HI({status:n}){return n==="completed"?r.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?r.jsx("span",{className:"w-3 shrink-0",children:r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):r.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function WI(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function UI({onClose:n,onSent:e}){const t=jt(O=>O.tabs),[i,s]=I.useState(""),[a,u]=I.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[l,c]=I.useState(!1),[h,g]=I.useState({}),m=I.useRef(null),b=I.useRef(e);I.useEffect(()=>{b.current=e},[e]),I.useEffect(()=>{u(O=>{const A={};for(const L of t)A[L.id]=O[L.id]??!0;return A})},[t]),I.useEffect(()=>{var O;(O=m.current)==null||O.focus()},[]),I.useEffect(()=>window.api.pty.onWriteError(A=>{g(L=>A.tabId in L?{...L,[A.tabId]:"skipped"}:L)}),[]),I.useEffect(()=>{if(Object.keys(h).length===0)return;const O=Object.values(h).filter(L=>L==="sent").length,A=window.setTimeout(()=>b.current(O),1500);return()=>window.clearTimeout(A)},[h]);const k=t.filter(O=>a[O.id]).map(O=>O.id),C=k.length,E=Object.keys(h).length>0,_=i.length>0&&C>0&&!l&&!E,w=()=>{if(!_)return;c(!0);const O=jt.getState().tabs,A=new Set(O.map(V=>V.id)),L={};for(const V of k)A.has(V)?(window.api.pty.write({tabId:V,data:i+"\r"}),L[V]="sent"):L[V]="skipped";g(L),c(!1)},x=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),n();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),w())},S=t.length>0&&t.every(O=>a[O.id]),T=()=>{const O=!S;u(Object.fromEntries(t.map(A=>[A.id,O])))},N=Object.values(h).some(O=>O==="skipped"),R=E?N?"Sent (some skipped)":"Sent":`Send to ${C} tab${C===1?"":"s"}`;return r.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),r.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),r.jsx("textarea",{ref:m,value:i,onChange:O=>s(O.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:S,onChange:T,className:"accent-accent"}),r.jsxs("span",{children:["All tabs (",C,"/",t.length,")"]})]}),r.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(O=>r.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:!!a[O.id],onChange:A=>u(L=>({...L,[O.id]:A.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),h[O.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[O.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.id))})]}),r.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[r.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:w,disabled:!_,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:R})]})]})}function VI({tabId:n,cwd:e,onClose:t}){const i=gm(C=>C.watchersForTab(n)),s=gm(C=>C.add),a=gm(C=>C.remove),u=I.useRef(null),[l,c]=I.useState(""),[h,g]=I.useState(""),[m,b]=I.useState(!1);I.useEffect(()=>{const C=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[t]),I.useEffect(()=>{const C=E=>{u.current&&!u.current.contains(E.target)&&t()};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const k=async()=>{const C=h.trim();if(!C||m)return;b(!0);const E=await s({tabId:n,label:l.trim(),command:C,cwd:e});b(!1),E&&(c(""),g(""))};return r.jsxs("div",{ref:u,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[r.jsxs("div",{className:"flex items-center mb-2",children:[r.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),r.jsxs("span",{className:"text-fg-faint ml-2",children:[i.length," active"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[r.jsx("input",{value:l,onChange:C=>c(C.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("input",{value:h,onChange:C=>g(C.target.value),onKeyDown:C=>{C.key==="Enter"&&k()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),r.jsx("button",{onClick:k,disabled:!h.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),r.jsxs("span",{className:"text-fg-faint",children:["cwd: ",r.jsx("span",{className:"font-mono",children:e})]})]}),i.length===0?r.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):r.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:i.map(C=>{const E=C.lines[C.lines.length-1];return r.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-medium text-fg truncate",children:C.label}),r.jsxs("span",{className:"text-fg-faint",children:[C.lineCount," line",C.lineCount===1?"":"s"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>a(C.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${C.watcherId}`,children:"stop"})]}),r.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:C.command,children:C.command}),r.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},C.watcherId)})})]})}/**
|
|
2934
|
+
`):"",ue=`${ie} Claude sessions running${K}`;return r.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[r.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:A?"Connected to Anthropic":"Disconnected",children:[r.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${A?"bg-sage":"bg-fg-faint"}`}),r.jsx("span",{children:A?"connected":"offline"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:aS("Session (5h window)",T),"data-testid":"footer-usage-session",children:["session ",r.jsx("span",{className:"text-fg",children:R!=null?`${R}%`:"—"})]}),r.jsxs("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:aS("Weekly window (all models)",N),"data-testid":"footer-usage-weekly",children:["weekly ",r.jsx("span",{className:"text-fg",children:O!=null?`${O}%`:"—"})]}),l&&r.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[r.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),i&&r.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,c&&r.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),r.jsxs("span",{className:"text-fg-faint",children:["last activity: ",r.jsx("span",{className:"text-fg-dim",children:L})]}),E.length>0&&r.jsx(GI,{ref:x,todos:E,open:_,onToggle:()=>w(te=>!te)}),r.jsx("span",{className:"flex-1"}),r.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:ue,"data-testid":"footer-active-sessions",children:h&&h.total===0?r.jsx("span",{className:"text-fg-faint",children:"pool paused"}):r.jsx(BI,{total:V,inUse:(h==null?void 0:h.inUse)??0,size:"sm"})}),(g==null?void 0:g.state)==="ready"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:"A new version is downloaded. Click to restart and install — running jobs are waited for first.","data-testid":"footer-version",onClick:()=>{C()},children:["Update ready — restart to install v",g.latest]}):(g==null?void 0:g.state)==="deferred"?r.jsxs("span",{className:"text-amber-300",title:`Waiting for ${g.busyReason??"running jobs"} to finish before restarting`,"data-testid":"footer-version",children:["v",g.latest," installs when idle"]}):(g==null?void 0:g.state)==="downloading"?r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["Downloading v",g.latest,"…"]}):m!=null&&m.behind&&m.latest&&m.channel==="installer"?r.jsxs("button",{type:"button",className:"text-amber-300 hover:underline",title:`v${m.current} → v${m.latest}`,"data-testid":"footer-version",onClick:()=>{const te=m.downloadUrl;te&&window.api.shell.open({as:"external",url:te}).catch(()=>{b("error",`Couldn't open URL: ${te}`)})},children:["Download v",m.latest]}):m!=null&&m.behind&&m.latest?r.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",m.current," → v",m.latest]}):r.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(m==null?void 0:m.current)??"0.136.2"]})]})}const GI=I.forwardRef(function({todos:e,open:t,onToggle:i},s){const a={completed:e.filter(u=>u.status==="completed").length,in_progress:e.filter(u=>u.status==="in_progress").length,pending:e.filter(u=>u.status==="pending").length};return r.jsxs("div",{ref:s,className:"relative",children:[r.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[r.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),r.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),r.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),r.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&r.jsx("div",{className:`absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 ${Ii.dialog}`,"data-testid":"footer-todos-popover",children:r.jsx("ul",{className:"space-y-0.5",children:e.map((u,l)=>r.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${u.status==="in_progress"?"bg-bg-hi":""}`,children:[r.jsx(HI,{status:u.status}),r.jsx("span",{className:u.status==="completed"?"text-fg-faint line-through":u.status==="in_progress"?"text-fg":"text-fg-dim",children:u.status==="in_progress"&&u.activeForm?u.activeForm:u.content})]},l))})})]})});function HI({status:n}){return n==="completed"?r.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?r.jsx("span",{className:"w-3 shrink-0",children:r.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):r.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function WI(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function UI({onClose:n,onSent:e}){const t=jt(O=>O.tabs),[i,s]=I.useState(""),[a,u]=I.useState(()=>Object.fromEntries(t.map(O=>[O.id,!0]))),[l,c]=I.useState(!1),[h,g]=I.useState({}),m=I.useRef(null),b=I.useRef(e);I.useEffect(()=>{b.current=e},[e]),I.useEffect(()=>{u(O=>{const A={};for(const L of t)A[L.id]=O[L.id]??!0;return A})},[t]),I.useEffect(()=>{var O;(O=m.current)==null||O.focus()},[]),I.useEffect(()=>window.api.pty.onWriteError(A=>{g(L=>A.tabId in L?{...L,[A.tabId]:"skipped"}:L)}),[]),I.useEffect(()=>{if(Object.keys(h).length===0)return;const O=Object.values(h).filter(L=>L==="sent").length,A=window.setTimeout(()=>b.current(O),1500);return()=>window.clearTimeout(A)},[h]);const k=t.filter(O=>a[O.id]).map(O=>O.id),C=k.length,E=Object.keys(h).length>0,_=i.length>0&&C>0&&!l&&!E,w=()=>{if(!_)return;c(!0);const O=jt.getState().tabs,A=new Set(O.map(V=>V.id)),L={};for(const V of k)A.has(V)?(window.api.pty.write({tabId:V,data:i+"\r"}),L[V]="sent"):L[V]="skipped";g(L),c(!1)},x=O=>{if(O.key==="Escape"){O.preventDefault(),O.stopPropagation(),n();return}O.key==="Enter"&&(O.metaKey||O.ctrlKey)&&(O.preventDefault(),w())},S=t.length>0&&t.every(O=>a[O.id]),T=()=>{const O=!S;u(Object.fromEntries(t.map(A=>[A.id,O])))},N=Object.values(h).some(O=>O==="skipped"),R=E?N?"Sent (some skipped)":"Sent":`Send to ${C} tab${C===1?"":"s"}`;return r.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:x,"data-testid":"broadcast-bar",children:[r.jsxs("div",{className:"flex items-center justify-between",children:[r.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),r.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),r.jsx("textarea",{ref:m,value:i,onChange:O=>s(O.target.value),rows:3,placeholder:"Prompt to broadcast…",className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono resize-y focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex flex-col gap-1",children:[r.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:S,onChange:T,className:"accent-accent"}),r.jsxs("span",{children:["All tabs (",C,"/",t.length,")"]})]}),r.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(O=>r.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[r.jsx("input",{type:"checkbox",checked:!!a[O.id],onChange:A=>u(L=>({...L,[O.id]:A.target.checked})),className:"accent-accent"}),r.jsx("span",{className:"truncate max-w-[12rem]",children:O.label}),h[O.id]==="sent"&&r.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),h[O.id]==="skipped"&&r.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},O.id))})]}),r.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[r.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:w,disabled:!_,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:R})]})]})}function VI({tabId:n,cwd:e,onClose:t}){const i=gm(C=>C.watchersForTab(n)),s=gm(C=>C.add),a=gm(C=>C.remove),u=I.useRef(null),[l,c]=I.useState(""),[h,g]=I.useState(""),[m,b]=I.useState(!1);I.useEffect(()=>{const C=E=>{E.key==="Escape"&&t()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[t]),I.useEffect(()=>{const C=E=>{u.current&&!u.current.contains(E.target)&&t()};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[t]);const k=async()=>{const C=h.trim();if(!C||m)return;b(!0);const E=await s({tabId:n,label:l.trim(),command:C,cwd:e});b(!1),E&&(c(""),g(""))};return r.jsxs("div",{ref:u,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[r.jsxs("div",{className:"flex items-center mb-2",children:[r.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),r.jsxs("span",{className:"text-fg-faint ml-2",children:[i.length," active"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),r.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[r.jsx("input",{value:l,onChange:C=>c(C.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("input",{value:h,onChange:C=>g(C.target.value),onKeyDown:C=>{C.key==="Enter"&&k()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),r.jsx("button",{onClick:k,disabled:!h.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),r.jsxs("span",{className:"text-fg-faint",children:["cwd: ",r.jsx("span",{className:"font-mono",children:e})]})]}),i.length===0?r.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):r.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:i.map(C=>{const E=C.lines[C.lines.length-1];return r.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[r.jsxs("div",{className:"flex items-center gap-2",children:[r.jsx("span",{className:"font-medium text-fg truncate",children:C.label}),r.jsxs("span",{className:"text-fg-faint",children:[C.lineCount," line",C.lineCount===1?"":"s"]}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>a(C.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${C.watcherId}`,children:"stop"})]}),r.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:C.command,children:C.command}),r.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(E==null?void 0:E.line)??"",children:E?E.line:r.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},C.watcherId)})})]})}/**
|
|
2935
2935
|
* dockview-core
|
|
2936
2936
|
* @version 6.6.1
|
|
2937
2937
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3051,7 +3051,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3051
3051
|
|
|
3052
3052
|
${t}`}const pm={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},yB=["popover","review","diff"],yj=["popover","review"];function SB(n,e){switch(e.type){case"SELECT":return{...pm,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...pm,editCount:n.editCount};case"LISTEN":return yj.includes(n.phase)?{...n,phase:"listening",transcript:"",modelStatus:null}:n;case"HEARD":return n.phase!=="listening"?n:{...n,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return yB.includes(n.phase)?{...n,phase:"thinking",instruction:e.recordInstruction?e.instruction:n.instruction}:n;case"RUN_OK":return n.phase!=="thinking"?n:{...n,phase:"diff",diff:e.diff};case"RUN_ERR":return n.phase!=="thinking"?n:{...n,phase:"popover",transcript:"",diff:null};case"ACCEPT":return n.phase!=="diff"?n:{...pm,editCount:n.editCount+1};case"RESET_FILE":return{...pm,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function CB(n,e){let t=null;for(const i of e){const s=i.cwd;!s||!(n===s||n.startsWith(s.endsWith("/")?s:`${s}/`))||(t===null||s.length>t.length)&&(t=s)}return t}function kB(n,e,t){var a;let i=null,s=-1/0;for(const u of e){if(u.cwd!==n||u.status!=="dormant")continue;const l=((a=t[u.id])==null?void 0:a.lastEventAt)??0;(i===null||l>s)&&(i=u,s=l)}return i}const EB="sonnet";function TB(n,e){const[t,i]=I.useReducer(SB,pm),s=I.useRef(0),a=I.useRef(null),u=I.useRef(n),l=I.useRef(new Map);I.useEffect(()=>window.api.docEdit.onSessionResult(S=>{const T=l.current.get(S.requestId);T&&(l.current.delete(S.requestId),T(S))}),[]),I.useEffect(()=>{u.current!==n&&(u.current=n,s.current+=1,c(),i({type:"RESET_FILE"}))},[n]);function c(){const S=a.current;S&&(a.current=null,S.stop().catch(()=>{}),S.destroy(),qt.setState({externalRecording:!1}))}const h=I.useCallback(S=>{s.current+=1,c(),i({type:"SELECT",selection:S})},[]),g=I.useCallback(()=>{s.current+=1,c(),i({type:"CANCEL"})},[]),m=I.useCallback(()=>{if(!yj.includes(t.phase))return;if(qt.getState().isRecording){ze.error("Microphone is already in use");return}if(!Jx()){ze.error("Microphone or Web Worker not available");return}const S=++s.current;i({type:"LISTEN"}),qt.setState({externalRecording:!0});const T=()=>{a.current===N&&(a.current=null),qt.setState({externalRecording:!1})},N=W2({onFinal:R=>{if(s.current!==S)return;N.stop().catch(()=>{}),N.destroy(),T();const O=R.trim();if(!O){i({type:"CANCEL"});return}i({type:"HEARD",transcript:O})},onError:R=>{s.current===S&&(N.destroy(),T(),ze.error(`Microphone error: ${R}`),i({type:"CANCEL"}))},onModelStatus:(R,O)=>{s.current===S&&i({type:"MODEL_STATUS",status:R,message:O})},onProgress:R=>{s.current===S&&i({type:"MODEL_STATUS",status:"loading",message:`${R}%`})}});a.current=N,N.start().catch(R=>{s.current===S&&(N.destroy(),T(),ze.error(`Could not start mic: ${R instanceof Error?R.message:String(R)}`),i({type:"CANCEL"}))})},[t.phase]),b=I.useCallback(()=>{const S=CB(n,jt.getState().tabs);if(!S)return null;const T=kB(S,jt.getState().tabs,tx.getState().tabs);return!T||Sn.getState().get(T.id).running?null:T},[n]),k=I.useCallback((S,T,N,R,O,A)=>{const L=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(V=>{l.current.set(L,V),window.api.docEdit.runInSession({tabId:S,sessionId:T,cwd:N,before:R,instruction:O,documentText:A,requestId:L})})},[]),C=I.useCallback(async(S,T)=>{const N=t.selection;if(!N)return;const R=++s.current;i({type:"RUN",instruction:S,recordInstruction:T});const O=wB(e);try{const A=b(),L=A?await k(A.id,A.sessionId,A.cwd,N.text,S,O):await window.api.docEdit.run({path:n,before:N.text,instruction:S,documentText:O});if(s.current!==R)return;if(!L.ok){ze.error(L.error||"Edit failed"),i({type:"RUN_ERR"});return}i({type:"RUN_OK",diff:{before:N.text,after:L.after??""}})}catch(A){if(s.current!==R)return;ze.error(A instanceof Error?A.message:"Edit failed"),i({type:"RUN_ERR"})}},[n,t.selection,e,b,k]),E=I.useCallback(S=>{C(S,!0)},[C]),_=I.useCallback(()=>{t.phase==="review"&&C(t.transcript,!0)},[C,t.phase,t.transcript]),w=I.useCallback(()=>{const S=t.instruction;S&&C(`${S}
|
|
3053
3053
|
|
|
3054
|
-
(Give a different rewrite than the last one.)`,!1)},[C,t.instruction]),x=I.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const N=bB(S,T.before,T.after);return N.ok?(s.current+=1,i({type:"ACCEPT"})):ze.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[t.diff]);return{state:t,select:h,cancel:g,listen:m,sendHeard:_,run:E,retry:w,accept:x}}const DB=[{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."}],Ck=320,em=8;function jB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function $B(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,em),Math.max(em,e-Ck-em)),i=Math.max(n.top-em,em);return{position:"fixed",left:t,top:i,width:Ck,transform:"translateY(-100%)",zIndex:aA.dialog}}function NB({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:c,onSendHeard:h,onCancel:g,onAccept:m,onReject:b,onRetry:k}){const[C,E]=I.useState(""),[_,w]=I.useState(!1),x=Bi(R=>R.show),S=I.useRef(null);I.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await qo(t)){x("error","Copy failed");return}w(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>w(!1),1500)},N=()=>{const R=C.trim();R&&(l(R),E(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:$B(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&r.jsxs("div",{className:"p-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:_?"Copied":"Copy"}),r.jsx("button",{onClick: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"}),DB.map(R=>r.jsx("button",{onClick:()=>u(R.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:R.label},R.label))]}),r.jsx("button",{onClick:g,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),r.jsx("input",{value:C,onChange:R=>E(R.target.value),onKeyDown:R=>{R.key==="Enter"?N():R.key==="Escape"&&g()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&r.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[r.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(jB,{}),"Listening…"]}),a&&r.jsx("span",{className:"text-[10px] text-fg-faint",children:a})]}),r.jsx("button",{onClick:g,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[r.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsxs("div",{className:"p-3 flex items-center justify-between",children:[r.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),r.jsx("button",{onClick:g,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&r.jsxs("div",{className:"p-3",children:[r.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:k,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function AB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function kk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:c,onReject:h,onRetry:g}){return r.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[r.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),r.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Im(EB)})]}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&r.jsxs("div",{className:"text-fg-faint",children:[r.jsx("p",{children:"Select text in the doc…"}),r.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),n==="popover"&&r.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&r.jsxs("div",{children:[r.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[r.jsx(AB,{}),"Listening…"]}),s&&r.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),r.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{children:[r.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&t&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-3 space-y-2",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function IB(){const n=jt(t=>t.tabs),e=jt(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function RB({path:n,onRenamed:e,onDeleted:t}){const[i,s]=I.useState(!1),[a,u]=I.useState(!1),[l,c]=I.useState(""),[h,g]=I.useState(!1),m=An(V=>V.buffers[n]),b=An(V=>V.openFile),k=An(V=>V.renameOpenFile),C=An(V=>V.closeFile),E=IB(),_=bo(n),w=()=>s(!1),x=()=>{c(_),u(!0),w()},S=async()=>{const V=l.trim();if(!V||V===_){u(!1);return}try{const Q=await window.api.files.rename(n,V);if(Q.ok){const ie=n.slice(0,n.lastIndexOf("/")),K=Q.newPath??`${ie}/${V}`;k(n,K),e==null||e(n,K),ze.info(`Renamed to ${V}`)}else ze.error(Q.error??`Couldn't rename ${_}`)}catch(Q){ze.error(Q instanceof Error?Q.message:`Couldn't rename ${_}`)}u(!1)},T=async()=>{w();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(b(V.path),ze.info(`Duplicated as ${bo(V.path)}`)):ze.error(V.error??`Couldn't duplicate ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't duplicate ${_}`)}},N=async()=>{try{const V=await window.api.files.delete(n);V.ok?(C(n),t==null||t(n),ze.info(`Deleted ${_}`)):ze.error(V.error??`Couldn't delete ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't delete ${_}`)}g(!1)},R=async()=>{w();const V=m??"";await qo(V)?ze.info(`Copied ${V.length} chars`):ze.error(`Couldn't copy ${_}`)},O=()=>{if(w(),!E){ze.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${n} `}),ze.info(`Added ${_} to Claude context`)},A=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't open ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't open ${_}`))},L=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't reveal ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't reveal ${_}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(V=>!V),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:w}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[r.jsx(y_,{children:"Edit"}),r.jsx(Sd,{label:"Rename",onClick:x}),r.jsx(Sd,{label:"Duplicate",onClick:T}),r.jsx(Sd,{label:"Delete document",danger:!0,onClick:()=>{w(),g(!0)}}),r.jsx(Ek,{}),r.jsx(y_,{children:"Open"}),r.jsx(Sd,{label:"Open in default app",onClick:A}),r.jsx(Sd,{label:"Reveal in OS",onClick:L}),r.jsx(Ek,{}),r.jsx(y_,{children:"Export"}),r.jsx(Sd,{label:"Copy as Markdown",onClick:R}),r.jsx(Sd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(PB,{value:l,onChange:c,onCancel:()=>u(!1),onConfirm:()=>void S()}),h&&r.jsx(MB,{name:_,onCancel:()=>g(!1),onConfirm:()=>void N()})]})}function y_({children:n}){return r.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function Sd({label:n,onClick:e,danger:t,disabled:i,title:s}){return r.jsx("button",{onClick:e,disabled:i,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function Ek(){return r.jsx("div",{className:"my-1 border-t border-line"})}function PB({value:n,onChange:e,onCancel:t,onConfirm:i}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),r.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?i():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function MB({name:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function OB(){const[n,e]=I.useState(!1),t=Ad();return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>e(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:()=>e(!1)}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[r.jsx(Dh,{label:"Text size",children:r.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[r.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),r.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),r.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),r.jsx(Dh,{label:"Word wrap",children:r.jsx(Ov,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx(Dh,{label:"Minimap",children:r.jsx(Ov,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx(Dh,{label:"Theme",children:r.jsx("button",{onClick:()=>t.setTheme(t.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:t.theme==="dark"?"Dark":"Paper"})}),r.jsx(Dh,{label:"Autosave",children:r.jsx(Ov,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx(Dh,{label:"Wide measure",children:r.jsx(Ov,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Dh({label:n,children:e}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Ov({on:n,onClick:e}){return r.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const LB=I.lazy(()=>qn(()=>import("./TiptapBody-CTmjUhAI.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Lv(n,e){if(!e.length)return n;const t=new Set(e),i={};for(const[s,a]of Object.entries(n))t.has(s)||(i[s]=a);return i}function tm(n){const e=n.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",i=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||i===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||i==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function zv(n){return wD(n)||yD(n)}function zB(){const n=Ry(),e=An(Ue=>Ue.openFiles),t=An(Ue=>Ue.activeFilePath),i=An(Ue=>Ue.dirty),s=An(Ue=>Ue.viewMode),a=An(Ue=>Ue.buffers),u=An(Ue=>Ue.setActive),l=An(Ue=>Ue.closeFile),c=An(Ue=>Ue.closeOthers),h=An(Ue=>Ue.closeToTheRight),g=An(Ue=>Ue.closeAll),m=An(Ue=>Ue.loadBuffer),b=An(Ue=>Ue.setBuffer),k=An(Ue=>Ue.markSaved),C=An(Ue=>Ue.setViewMode),E=Ad(),[_,w]=I.useState({}),[x,S]=I.useState({}),[T,N]=I.useState(null),[R,O]=I.useState(null),[A,L]=I.useState(!1),[V,Q]=I.useState(!1),[ie,K]=I.useState(!0),ue=I.useRef(null),te=I.useRef(null),ce=I.useRef(void 0),Ce=I.useRef(null),fe=I.useRef(null),F=TB(t??"",a[t??""]??""),q=I.useCallback((Ue,xt)=>{b(Ue,xt),tm(Ue)&&Ca.getState().setDraft(Ue,xt)},[b]),H=I.useCallback(Ue=>{ue.current=Ue},[]),Z=I.useCallback(()=>ue.current,[]);I.useEffect(()=>{d3()},[]),I.useEffect(()=>{const Ue=t;if(!Ue||zv(Ue))return;if(An.getState().hasBuffer(Ue)){w(St=>St[Ue]==="ready"?St:{...St,[Ue]:"ready"});return}let xt=!1;return w(St=>({...St,[Ue]:"loading"})),tm(Ue)?((async()=>{if(await Ca.getState().loadText(Ue,!0),xt)return;const St=Ca.getState().files[Ue];if(!St||St.loadError&&!St.exists){w(en=>({...en,[Ue]:{error:(St==null?void 0:St.loadError)??"failed to read"}}));return}m(Ue,St.diskRaw),St.dirty&&An.getState().setBuffer(Ue,St.draftRaw),w(en=>({...en,[Ue]:"ready"}))})(),()=>{xt=!0}):(window.api.files.read(Ue).then(St=>{xt||(St.binary?w(en=>({...en,[Ue]:{binary:!0,size:St.size??0,mime:St.mime??"application/octet-stream",reason:St.error??"Binary file"}})):St.ok?(m(Ue,St.text),w(en=>({...en,[Ue]:"ready"}))):w(en=>({...en,[Ue]:{error:St.error??"failed to read"}})))}),()=>{xt=!0})},[t,m]),I.useEffect(()=>{O(null)},[t]);const le=I.useCallback(async(Ue,xt=!1)=>{const St=An.getState().buffers[Ue];if(St==null)return;xt&&L(!0);const en=tm(Ue);let En;if(en){const In=Ca.getState();if(In.setDraft(Ue,St),En=await In.saveText(Ue),!En.ok&&En.error==="conflict"){xt&&L(!1);return}}else En=await window.api.files.write(Ue,St);En.ok?(k(Ue),S(In=>({...In,[Ue]:(In[Ue]??0)+1})),xt||ze.info(`Saved ${bo(Ue)}`)):ze.error(En.error??`Couldn't save ${bo(Ue)}`),xt&&L(!1)},[k]);I.useEffect(()=>{if(!E.autosave)return;const Ue=t;if(!(!Ue||zv(Ue)||tm(Ue)||!i[Ue]))return window.clearTimeout(ce.current),ce.current=window.setTimeout(()=>{le(Ue,!0)},1200),()=>window.clearTimeout(ce.current)},[E.autosave,t,i,a,le]);const me=I.useCallback(Ue=>{Ue.length&&(w(xt=>Lv(xt,Ue)),S(xt=>Lv(xt,Ue)))},[]),Re=I.useCallback((Ue,xt)=>{w(St=>Ue in St?{...Lv(St,[Ue]),[xt]:St[Ue]}:St),S(St=>Ue in St?{...Lv(St,[Ue]),[xt]:St[Ue]}:St)},[]),He=I.useCallback(Ue=>{i[Ue]?N({kind:"one",path:Ue}):(l(Ue),me([Ue]))},[i,l,me]),ge=I.useCallback(Ue=>{e.some(St=>St.path!==Ue&&i[St.path])?N({kind:"others",path:Ue}):(c(Ue),me(e.filter(St=>St.path!==Ue).map(St=>St.path)))},[e,i,c,me]),ee=I.useCallback(Ue=>{const xt=e.findIndex(en=>en.path===Ue);xt!==-1&&e.slice(xt+1).some(en=>i[en.path])?N({kind:"right",path:Ue}):(h(Ue),me(xt!==-1?e.slice(xt+1).map(en=>en.path):[]))},[e,i,h,me]);I.useEffect(()=>{const Ue=xt=>{if(n.current)if((xt.metaKey||xt.ctrlKey)&&(xt.key==="s"||xt.key==="S")){const St=An.getState().activeFilePath;St&&!zv(St)&&(xt.preventDefault(),le(St))}else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="f"||xt.key==="F"))xt.preventDefault(),Q(St=>!St);else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="w"||xt.key==="W")){const St=An.getState().activeFilePath;St&&An.getState().openFiles.length>1&&(xt.preventDefault(),ge(St))}else xt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():xt.key==="Escape"&&V&&Q(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[le,V,ge,F.state.phase,F.cancel]),I.useEffect(()=>{if(F.state.phase==="idle")return;const Ue=xt=>{var en,En;const St=xt.target;(en=fe.current)!=null&&en.contains(St)||(En=Ce.current)!=null&&En.contains(St)||F.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[F.state.phase,F.cancel]),I.useEffect(()=>{F.cancel()},[t,F.cancel]);const Ne=I.useCallback(()=>{e.some(xt=>i[xt.path])?N({kind:"all",path:""}):(g(),w({}),S({}))},[e,i,g]),Ee=()=>{if(T){if(T.kind==="one")l(T.path),me([T.path]);else if(T.kind==="others"){const Ue=e.filter(xt=>xt.path!==T.path).map(xt=>xt.path);c(T.path),me(Ue)}else if(T.kind==="right"){const Ue=e.findIndex(St=>St.path===T.path),xt=Ue!==-1?e.slice(Ue+1).map(St=>St.path):[];h(T.path),me(xt)}else g(),w({}),S({});N(null)}};if(e.length===0)return r.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"mb-2",children:"no file open"}),r.jsxs("div",{children:["open the ",r.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Te=t,be=Te?bo(Te):"",Qe=Te?_[Te]:void 0,gt=Te?kD(Te):!1,lt=Te?o3(Te):!1,$t=Te&>?s[Te]??a3(Te):"edit",We=!!Te&&!zv(Te)&&Qe==="ready",Wt=We,kt=lt?["edit","wysiwyg","preview","split"]:gt?["edit","preview"]:[],rn=Te&&r.jsx(sB,{path:Te,name:be,value:a[Te]??"",onChange:Ue=>q(Te,Ue),onSave:()=>void le(Te),onReady:H,onCursor:O}),pn=A?"Saving…":Te&&i[Te]?E.autosave&&!tm(Te)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&r.jsx(Wz,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:He,onCloseOthers:ge,onCloseToTheRight:ee,onCloseAll:Ne}),Te&&!V&&r.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[r.jsx("span",{className:"text-xs font-medium text-fg truncate",children:be}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Te}),We&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",pn]}),ol(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:()=>K(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${ie?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),ol(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),kt.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:kt.map(Ue=>r.jsx("button",{onClick:()=>C(Te,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${$t===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),r.jsx("div",{className:"flex-1"}),r.jsx(RB,{path:Te,onRenamed:Re,onDeleted:Ue=>me([Ue])}),We&&r.jsx(OB,{}),r.jsx("button",{onClick:()=>Q(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&r.jsx("button",{onClick:()=>Q(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),r.jsx("div",{className:"flex-1 min-h-0",children:Te?wD(Te)?r.jsx(uB,{path:Te,name:be}):yD(Te)?r.jsx(hB,{path:Te}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(xB,{path:Te,name:be,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?r.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):$t==="wysiwyg"&&ol(Te)?r.jsx(I.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(LB,{value:a[Te]??"",onChange:Ue=>q(Te,Ue)},Te)}):$t==="split"&&ol(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[ie&&r.jsx(wk,{text:a[Te]??"",scrollRef:te}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(_k,{getEditor:Z}),r.jsx("div",{className:"flex-1 min-h-0",children:rn})]}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx(Rx,{ref:te,text:a[Te]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(kk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&ol(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[ie&&r.jsx(wk,{text:a[Te]??"",scrollRef:te}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx(Rx,{ref:te,text:a[Te]??"",wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(kk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&_D(Te)?r.jsx(cB,{path:Te,dirty:!!i[Te],reloadToken:x[Te]??0}):$t==="preview"&&SD(Te)?r.jsx(fB,{path:Te,text:a[Te]??""}):$t==="preview"&&CD(Te)?r.jsx(vB,{path:Te,text:a[Te]??""}):ol(Te)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(_k,{getEditor:Z}),r.jsx("div",{className:"flex-1 min-h-0",children:rn})]}):rn:null}),Wt&&r.jsx(lB,{text:a[Te]??"",cursor:R,language:Zr(Te)||void 0}),Te&&ol(Te)&&($t==="preview"||$t==="split")&&F.state.phase!=="idle"&&F.state.selection&&r.jsx("div",{ref:fe,children:r.jsx(NB,{phase:F.state.phase,rect:F.state.selection.rect,selectedText:F.state.selection.text,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)}})}),T&&r.jsx(BB,{message:T.kind==="one"?`Discard unsaved changes to ${bo(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:Ee})]})}const Kw=I.memo(zB);function BB({message:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const FB="~/.claude/session-manager/projects-prefs.json";let Tk=Promise.resolve(),Bv=null;function Dk(n){const e=Tk.then(n);return Tk=e.catch(()=>{}),e}const Sj=()=>$a(FB);async function jk(){const n=(await Sj().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const S_=Si(n=>({pinned:{},hydrated:!1,hydrate:()=>Bv||(Bv=Dk(async()=>{try{n({pinned:await jk(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Bv),togglePin:e=>{Dk(async()=>{let t;try{t=await jk()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const i={...t};i[e]?delete i[e]:i[e]=!0;try{await Sj().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function GB(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function HB(n,e,t){const i=I.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(GB))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;I.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const u=window.api.config.onChanged(l=>{s.includes(l.path)&&i.current(l.path)});return()=>{u(),window.api.config.unwatch(s,t)}},[a])}function g0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function Cj(n){return n.split(/[\\/]+/).filter(Boolean)}function kj(n){const e=Cj(n);return e.length?e[e.length-1]:n}function $k(n){const e=n.length>1?n.replace(/[\\/]+$/,""):n,t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t<0?"":t===0?e.slice(0,1):/^[A-Za-z]:$/.test(e.slice(0,t))?e.slice(0,t+1):e.slice(0,t)}function Ej(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=g0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const Nk=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Bm(n,e){return Nk(n).startsWith(Nk(e)+"/")}const Yw="reveal:";function o8(n){Dn.getState().openPanel("projects",Yw+n)}function WB(n){return n.startsWith(Yw)&&n.slice(Yw.length)||null}const UB=/^[A-Za-z]:$/;function Ak(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(UB.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function Tj(n,e){const t=Ak(n),i=Ak(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function VB(n){const e=await Jh(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function qB(n,e){return bc(n,{fileTreeExpanded:[...e].slice(0,500)})}async function KB(){const n=await lb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function YB(n){cb({fileTreeShowHidden:n}).catch(()=>{})}function C_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Bm(s,e)){t=!0;continue}i.add(s)}return t?i:n}const Ik=(n,e)=>`${e?1:0}:${n}`,k_={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:"!"}},XB=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 JB(n){const e=Zr(n);return XB.has(e)||bD.has(e)||e==="pdf"}function ZB(n,e){if(e)return"#d97757";switch(Zr(n)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function nm(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const Rk=64,QB=250,eF={depth:0};function E_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function tF({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=Ry(),l=Zx(),[c,h]=I.useState([]),g=I.useRef(c);g.current=c;const[m,b]=I.useState(null),k=I.useRef(null),C=I.useRef(null),[E,_]=I.useState(0),[w,x]=I.useState(null),[S,T]=I.useState(null),N=I.useRef(null),[R,O]=I.useState(0),A=I.useRef(a);A.current=a;const[L,V]=I.useState(new Set),Q=I.useRef(L);Q.current=L;const ie=I.useRef(!1),[K,ue]=I.useState(""),[te,ce]=I.useState(!0),Ce=I.useRef(!1);I.useEffect(()=>{let it=!1;return KB().then(vt=>{!it&&!Ce.current&&ce(vt)}),()=>{it=!0}},[]);const fe=I.useCallback(it=>{Ce.current=!0,ce(vt=>{const Rt=typeof it=="function"?it(vt):it;return YB(Rt),Rt})},[]),[F,q]=I.useState(!1),[H,Z]=I.useState(null),[le,me]=I.useState({}),[Re,He]=I.useState(null),[ge,ee]=I.useState(null),[Ne,Ee]=I.useState(""),[Te,be]=I.useState(null),[Qe,gt]=I.useState(""),[lt,$t]=I.useState(null),We=I.useRef(null),Wt=I.useRef(null),kt=I.useRef(0),rn=I.useCallback(async()=>{if(!n)return;const it=++kt.current;q(!0),Z(null);const vt=await window.api.files.list(n,te);kt.current===it&&(vt.ok?h(vt.entries.map(Rt=>({...Rt}))):(Z(vt.error??"failed to list"),h([])),T(Ik(n,te)),q(!1))},[n,te]),pn=I.useCallback(async it=>{const vt=kt.current,Rt=new Map;for(const Mn of it){const On=Cj(Mn).length,kn=Rt.get(On);kn?kn.push(Mn):Rt.set(On,[Mn])}const ln=[];for(const Mn of[...Rt.keys()].sort((On,kn)=>On-kn)){const On=Rt.get(Mn),kn=await Promise.all(On.map(async rt=>({p:rt,result:await window.api.files.list(rt,te)})));if(kt.current!==vt)return ln;for(const{p:rt,result:cn}of kn)cn.ok?h(Yn=>fm(Yn,rt,cn.entries.map(Xn=>({...Xn})),Q.current)):ln.push(rt)}return ln},[te]),Ue=I.useCallback(async it=>(await rn(),it.length?pn(it):[]),[rn,pn]);I.useEffect(()=>{ue(""),ee(null),He(null),be(null),$t(null),me({}),b(null);let it=!1;return ie.current=!1,(async()=>{const[vt]=await Promise.all([VB(n),rn()]);if(it)return;if(!ie.current){const ln=new Set(vt);Q.current=ln,V(ln)}if(x(n),!vt.length)return;const Rt=await pn(vt);it||!Rt.length||Cn(ln=>{const Mn=new Set;let On=!1;for(const kn of ln){if(Rt.some(rt=>kn===rt||Bm(kn,rt))){On=!0;continue}Mn.add(kn)}return On?Mn:ln})})(),nm(n).then(vt=>{it||me(vt)}),()=>{it=!0}},[n]);const xt=I.useRef(!0);I.useEffect(()=>{if(xt.current){xt.current=!1;return}Ue([...Q.current])},[te]),I.useEffect(()=>{if(!n||!l)return;nm(n).then(me);const it=window.setInterval(()=>{nm(n).then(me)},5e3);return()=>window.clearInterval(it)},[n,l]);const St=I.useMemo(()=>{if(!n)return[];const it=[...L].filter(vt=>vt!==n);return[n,...it.slice(-63)]},[n,L]),en=I.useRef(!1);I.useEffect(()=>{!n||L.size+1<=Rk||en.current||(en.current=!0,console.warn(`FileTree: watching only ${Rk} of ${L.size+1} folders (cap reached)`))},[n,L]);const En=I.useRef(new Map),In=I.useRef(new Set),vn=I.useRef(!1);vn.current=ge!==null||Te!==null;const ii=I.useRef(()=>{});ii.current=it=>{if(!(it!==E_(n)&&!Q.current.has(it))){if(vn.current){In.current.add(it);return}it===E_(n)?Ue([...Q.current]):fn(it)}},HB(St,it=>{if(it!==E_(n)&&!Q.current.has(it))return;const vt=En.current,Rt=vt.get(it);Rt&&clearTimeout(Rt),vt.set(it,setTimeout(()=>{vt.delete(it),ii.current(it)},QB))},eF),I.useEffect(()=>{if(ge!==null||Te!==null)return;const it=[...In.current];In.current.clear();for(const vt of it)ii.current(vt)},[ge,Te]),I.useEffect(()=>{const it=En.current,vt=In.current;return()=>{for(const Rt of it.values())clearTimeout(Rt);it.clear(),vt.clear()}},[n]),I.useEffect(()=>{if(!Re)return;const it=()=>He(null),vt=Rt=>{u.current&&Rt.key==="Escape"&&He(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",vt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",vt)}},[Re]),I.useEffect(()=>{ge&&setTimeout(()=>{var it;return(it=We.current)==null?void 0:it.select()},30)},[ge]),I.useEffect(()=>{Te&&setTimeout(()=>{var it;return(it=Wt.current)==null?void 0:it.focus()},30)},[Te]);const Cn=I.useCallback(it=>{const vt=Q.current,Rt=it(vt);Rt!==vt&&(ie.current=!0,Q.current=Rt,V(Rt),qB(n,Rt).catch(()=>{Q.current===Rt&&(Q.current=vt,V(vt),ze.error("Couldn't save folder expansion — reverted."))}))},[n]),jn=I.useCallback(async it=>{if(L.has(it.path)){Cn(Rt=>C_(Rt,it.path));return}if(Cn(Rt=>new Set(Rt).add(it.path)),it.children)return;const vt=await window.api.files.list(it.path,te);vt.ok&&h(Rt=>fm(Rt,it.path,vt.entries.map(ln=>({...ln})),Q.current))},[L,te,Cn]),fn=I.useCallback(async it=>{if(it===n){await rn();return}const vt=await window.api.files.list(it,te);vt.ok&&h(Rt=>fm(Rt,it,vt.entries.map(ln=>({...ln})),Q.current))},[n,rn,te]),Ri=I.useCallback(async(it,vt)=>{const Rt=()=>{var bt;return(bt=A.current)==null?void 0:bt.call(A,it.token)};if(!vt.length){b(null),Rt();return}const ln=kt.current,Mn=vt.slice(0,-1).map((bt,Un)=>Ej(n,...vt.slice(0,Un+1))),On=await Promise.all(Mn.map(bt=>window.api.files.list(bt,te)));if(kt.current!==ln){N.current=null,O(bt=>bt+1);return}let kn=g.current;const rt=[];let cn=null,Yn="not found";for(let bt=0;bt<vt.length;bt++){const Un=kn.find(si=>si.name===vt[bt]);if(!Un)break;if(bt===vt.length-1){cn=Un;break}const xi=On[bt];if(!Un.isDirectory)break;if(!xi.ok){Yn=xi.error??"could not list its folder";break}const At=xi.entries.map(si=>({...si}));rt.push({path:Un.path,children:At}),kn=At}if(!cn){ze.error(`Couldn't reveal ${it.path}: ${Yn}`),Rt();return}const Xn=rt.map(bt=>bt.path);Cn(bt=>Xn.every(Un=>bt.has(Un))?bt:new Set([...bt,...Xn])),h(bt=>rt.reduce((Un,xi)=>fm(Un,xi.path,xi.children,Q.current),bt)),ue(""),Z(null),b(cn.path),_(bt=>bt+1),Rt()},[n,te,Cn]);I.useEffect(()=>{var vt;if(!s||N.current===s.token||w!==n||S!==Ik(n,te)||F)return;const it=Tj(s.path,n);if(!it){N.current=s.token,ze.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(vt=A.current)==null||vt.call(A,s.token);return}if(it.some(Rt=>Rt.startsWith("."))&&(Ce.current=!0,!te)){ce(!0);return}N.current=s.token,Ri(s,it)},[s,w,S,F,n,te,R,Ri]),I.useEffect(()=>{if(!E)return;const it=C.current,vt=k.current;it&&vt&&Xm(it,vt,{block:"nearest"})},[E]);const Ci=I.useCallback(it=>{if(it.isDirectory){jn(it);return}JB(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[jn,e]),Fi=I.useCallback(it=>{if(t){t(it);return}if(i){const vt=Bm(it,n)?it.slice(n.replace(/[\\/]+$/,"").length+1):it;window.api.pty.write({tabId:i,data:`@${vt} `})}},[t,i,n]),ls=I.useCallback((it,vt)=>{it.preventDefault(),it.stopPropagation(),He({x:it.clientX,y:it.clientY,node:vt})},[]),at=it=>{ee(it.path),Ee(it.name)},Wn=async()=>{if(!ge)return;const it=Ne.trim();if(!it){ee(null);return}const vt=await window.api.files.rename(ge,it);if(ee(null),vt.ok){const Rt=$k(ge);Cn(ln=>C_(ln,ge)),await fn(Rt||n),nm(n).then(me)}else{const Rt=vt.error??"rename failed";Z(Rt),ze.error(Rt)}},Kn=async()=>{if(!Te)return;const it=Qe.trim();if(!it){be(null),gt("");return}const vt=await window.api.files.create(Te.parent,it,Te.kind);if(be(null),gt(""),vt.ok)await fn(Te.parent),Te.kind==="folder"&&Cn(Rt=>new Set(Rt).add(Te.parent));else{const Rt=vt.error??"create failed";Z(Rt),ze.error(Rt)}},Pi=async()=>{if(!lt)return;const it=await window.api.files.delete(lt.path),vt=$k(lt.path);if($t(null),it.ok)Cn(Rt=>C_(Rt,lt.path)),await fn(vt||n),nm(n).then(me);else{const Rt=it.error??"delete failed";Z(Rt),ze.error(Rt)}},vi=I.useMemo(()=>{if(!K.trim())return c;const it=K.toLowerCase();return c.filter(vt=>vt.name.toLowerCase().includes(it))},[c,K]),ki=(n?kj(n):"")||"project";return r.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[r.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[r.jsx(jj,{size:14,className:"shrink-0 text-accent"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs font-medium text-fg truncate",children:ki}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:rn,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:F,children:r.jsx(lF,{size:12,className:F?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:K,onChange:it=>ue(it.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),r.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[r.jsx("button",{onClick:()=>be({parent:n,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:r.jsx(cF,{size:12})}),r.jsx("button",{onClick:()=>be({parent:n,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:r.jsx(dF,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>fe(it=>!it),className:`p-1.5 rounded transition-colors ${te?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:te?"Hide hidden files":"Show hidden files",children:te?r.jsx(uF,{size:12}):r.jsx(hF,{size:12})})]}),r.jsxs("div",{ref:C,className:"flex-1 overflow-y-auto py-1",children:[H&&r.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:H}),!H&&vi.length===0&&!F&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:K?"no matches":"empty folder"}),!H&&r.jsx(Dj,{nodes:vi,depth:0,expanded:L,gitStatus:le,renaming:ge,selected:m,selectedRowRef:k,onSelect:b,renameValue:Ne,renameInputRef:We,onRenameChange:Ee,onRenameCommit:Wn,onRenameCancel:()=>ee(null),onToggleDir:jn,onFileClick:Ci,onSendToChat:Fi,onContextMenu:ls})]}),r.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),Re&&r.jsx(nF,{x:Re.x,y:Re.y,node:Re.node,onClose:()=>He(null),onRename:()=>{at(Re.node),He(null)},onDelete:()=>{$t(Re.node),He(null)},onNewFile:()=>{be({parent:Re.node.path,kind:"file"}),He(null)},onNewFolder:()=>{be({parent:Re.node.path,kind:"folder"}),He(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Re.node.path}),He(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Re.node.path}),He(null)},onCopyPath:()=>{const it=Re.node.path;qo(it).then(vt=>{vt||ze.error("Couldn't copy path")}),He(null)},onSendToChat:()=>{Fi(Re.node.path),He(null)}}),Te&&r.jsx(Pk,{title:`New ${Te.kind}`,subtitle:`in ${iF(Te.parent)}`,onCancel:()=>{be(null),gt("")},onConfirm:Kn,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:Wt,value:Qe,onChange:it=>gt(it.target.value),onKeyDown:it=>{it.key==="Enter"&&Kn(),it.key==="Escape"&&(be(null),gt(""))},placeholder:Te.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),lt&&r.jsx(Pk,{title:`Delete ${lt.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>$t(null),onConfirm:Pi,confirmLabel:"Delete",danger:!0,children:r.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",r.jsxs("span",{className:"text-fg font-medium",children:['"',lt.name,'"']})," to the trash?",lt.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function Dj(n){const{nodes:e,depth:t,expanded:i,gitStatus:s,renaming:a,selected:u,onContextMenu:l}=n;return r.jsx(r.Fragment,{children:e.map(c=>{const h=i.has(c.path),g=a===c.path,m=u===c.path,b=s[c.path],k=ZB(c.name,c.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:m?n.selectedRowRef:void 0,"data-path":c.path,"data-selected":m?"true":void 0,className:`group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi ${m?"bg-accent/15":""}`,style:{paddingLeft:`${8+t*14}px`},onClick:()=>{g||(n.onSelect(c.path),c.isDirectory?n.onToggleDir(c):n.onFileClick(c))},onDoubleClick:()=>{c.isDirectory||window.api.shell.open({as:"openPath",path:c.path})},onContextMenu:C=>l(C,c),children:[c.isDirectory?r.jsx(aF,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),c.isDirectory?h?r.jsx(rF,{size:12,color:k}):r.jsx(jj,{size:12,color:k}):r.jsx(oF,{size:12,color:k}),g?r.jsx("input",{ref:n.renameInputRef,value:n.renameValue,onChange:C=>n.onRenameChange(C.target.value),onClick:C=>C.stopPropagation(),onBlur:n.onRenameCommit,onKeyDown:C=>{C.key==="Enter"&&n.onRenameCommit(),C.key==="Escape"&&n.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):r.jsx("span",{className:`flex-1 truncate text-xs ${c.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:c.name}),b&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:k_[b].color,backgroundColor:`${k_[b].color}20`},title:b,children:k_[b].label}),!c.isDirectory&&r.jsx("button",{onClick:C=>{C.stopPropagation(),n.onSendToChat(c.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:r.jsx(pF,{size:10})})]}),c.isDirectory&&h&&c.children&&r.jsx(Dj,{...n,nodes:c.children,depth:t+1})]},c.path)})})}function nF(n){const{x:e,y:t,node:i}=n;return r.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!i.isDirectory&&r.jsx(Zl,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(Zl,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(Zl,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(T_,{}),r.jsx(Zl,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(Zl,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(T_,{}),r.jsx(Zl,{label:"New file",onClick:n.onNewFile}),r.jsx(Zl,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(T_,{}),r.jsx(Zl,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function Zl({label:n,onClick:e,danger:t}){return r.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:n})}function T_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function Pk(n){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&n.onCancel()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:n.title}),n.subtitle&&r.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:n.subtitle}),r.jsx("div",{className:"mb-4",children:n.children}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:n.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:n.onConfirm,disabled:!!n.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:n.confirmLabel??"OK"})]})]})})}function iF(n){return kj(n)}function fm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:sF(s.children,t,i)}:s.children?{...s,children:fm(s.children,e,t,i)}:s)}function sF(n,e,t){const i=new Map;for(const s of n??[])s.children&&t.has(s.path)&&i.set(s.path,s.children);return i.size?e.map(s=>{const a=s.isDirectory?i.get(s.path):void 0;return a?{...s,children:a}:s}):e}function Aa({size:n,children:e,className:t,color:i}){return r.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:i||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function jj({size:n,className:e,color:t}){return r.jsx(Aa,{size:n,className:e,color:t,children:r.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function rF({size:n,className:e,color:t}){return r.jsx(Aa,{size:n,className:e,color:t,children:r.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function oF({size:n,className:e,color:t}){return r.jsxs(Aa,{size:n,className:e,color:t,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function aF({size:n,className:e}){return r.jsx(Aa,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function lF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("polyline",{points:"1 20 1 14 7 14"}),r.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function cF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),r.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function dF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),r.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),r.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function uF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function hF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function pF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function $j({content:n,children:e,align:t="bottom-right"}){const[i,s]=I.useState(!1),a=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return r.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,i&&r.jsx("span",{role:"tooltip",className:`absolute ${Ii.dialog} ${a} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:n})]})}function Em(n,e){if(!e)return n;const t=g0(e),i=e.length>1?e.replace(/[\\/]+$/,""):e;if(n===i)return"~";const s=i.endsWith(t)?i:`${i}${t}`;return n.startsWith(s)?`~${t}${n.slice(s.length)}`:n}function D_(n){cb(n).catch(()=>ze.error("Couldn't save File Explorer layout."))}const j_=33,fF=20,mF=60,gF=32;function Mk(n){return Math.min(mF,Math.max(fF,n))}function vF(){const n=jt(F=>F.tabs),e=jt(F=>F.activeTabId),t=n.find(F=>F.id===e)??null,i=Dn(F=>F.navFace),s=ib(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=I.useState(j_),[c,h]=I.useState(!1),g=I.useRef(!1),[m,b]=I.useState(!1),k=I.useRef(u);k.current=u;const C=I.useRef(c);C.current=c;const E=I.useRef(null),_=I.useRef(null),w=I.useRef(!1),{projects:x,openProject:S,archiveProjectByCwd:T}=Od(),N=S_(F=>F.pinned),R=S_(F=>F.togglePin);I.useEffect(()=>{S_.getState().hydrate()},[]),I.useEffect(()=>{let F=!1;return lb().then(q=>{F||g.current||(typeof q.projectsSplitPct=="number"&&Number.isFinite(q.projectsSplitPct)&&l(Mk(q.projectsSplitPct)),typeof q.projectsFileTreeCollapsed=="boolean"&&!w.current&&h(q.projectsFileTreeCollapsed))}),()=>{F=!0}},[]);const O=I.useRef(0),[A,L]=I.useState(null),[V,Q]=I.useState(null);nA("projects",F=>{const q=WB(F);q&&L({path:q,token:++O.current})});const ie=(t==null?void 0:t.cwd)??null;I.useEffect(()=>{if(!A)return;const{path:F}=A,q=me=>!!me&&Tj(F,me)!==null,H=i==="home"?s:ie,Z=i==="home"?{face:"project",root:ie}:{face:"home",root:s};let le=null;if(q(H))le={face:i,root:H};else{if(s===null)return;q(Z.root)&&(le={face:Z.face,root:Z.root})}if(L(null),!le){window.api.shell.open({as:"revealPath",path:F}).then(me=>{me.ok||ze.error(`Couldn't reveal ${F}: ${me.error??"unknown error"}`)},me=>ze.error(`Couldn't reveal ${F}: ${me instanceof Error?me.message:String(me)}`));return}le.face!==i&&Dn.getState().setNavFace(le.face),w.current=!0,h(!1),Q({...A,root:le.root})},[A,i,s,ie]),I.useEffect(()=>{Q(F=>F&&a!==null&&F.root!==a?null:F)},[a]);const K=I.useCallback(F=>{Q(q=>q&&q.token===F?null:q)},[]),ue=[...x].sort((F,q)=>(N[q.cwd]?1:0)-(N[F.cwd]?1:0));I.useEffect(()=>{if(!m)return;const F=q=>{_.current&&!_.current.contains(q.target)&&b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[m]);const te=I.useCallback(F=>{An.getState().openFile(F)},[]),ce=I.useCallback(F=>{F.preventDefault(),g.current=!0;const q=F.clientX,H=k.current;let Z=H;const le=Re=>{const He=E.current;if(!He)return;const ge=He.getBoundingClientRect(),ee=Re.clientX-q;Z=Mk(H+ee/ge.width*100),l(Z)},me=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",me),document.body.style.cursor="",document.body.style.userSelect="",D_({projectsSplitPct:Z})};window.addEventListener("pointermove",le),window.addEventListener("pointerup",me),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),Ce=I.useCallback(()=>{g.current=!0,l(j_),D_({projectsSplitPct:j_})},[]),fe=I.useCallback(()=>{g.current=!0;const F=!C.current;h(F),D_({projectsFileTreeCollapsed:F})},[]);return c?r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:fe,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:gF},children:[r.jsx("span",{className:"text-[11px]",children:"▸"}),r.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Kw,{})})]}):r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${u}%`},"data-testid":"projects-file-tree-pane",children:[r.jsxs("div",{ref:_,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(F=>!F),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[r.jsx("span",{className:"flex-1 truncate text-left",children:a?Em(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),r.jsx("button",{onClick:fe,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&r.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Ii.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:ue.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):ue.map(F=>{const q=Em(F.cwd,s);return r.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[r.jsx($j,{content:N[F.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>R(F.cwd),className:`shrink-0 text-sm leading-none transition-colors ${N[F.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:N[F.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{S(F.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:q}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${q}?`)&&await T(F)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},F.cwd)})})]}),a?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:a,children:Em(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(tF,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:te,reveal:V&&V.root===a?V:null,onRevealDone:K})})]}):r.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:i==="home"?"Loading home folder…":"No session selected."})]}),r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:ce,onDoubleClick:Ce,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Kw,{})})]})}const xF=I.memo(vF),bF={"project-home":{headline:"Pages, Videos and Tools — this project's generated library and its tools",intro:"Project Home is this project's own library, written by builder agents from what they read in the repository. Three key buttons at the top switch the area below them: Pages holds Knowledge Pages (static HTML pages that explain a topic), Videos holds short self-contained HTML/JS videos that show the project, and Tools holds one-press tools for the project, led by Review MD network.",sections:[{title:"The key buttons",items:[{term:"Pages",body:"Opens the knowledge-page library. The badge counts ready pages plus any page being built; the line under the name reads “Nothing generated yet”, “<n> building · <m> ready” while a build runs, or the page count and how long ago the newest page was made."},{term:"Videos",body:"The same, for the video library."},{term:"Tools",body:"Opens the tool list. Once you have opened Tools for this project, an accent badge shows how many findings Review MD network's link map found. Its Expand button (or a click on any doc in the map) opens a full-screen explorer with a doc preview and a Docs table."}]},{title:"Pages and Videos",items:[{term:"The list",body:"One row per page or video; a video row adds a thumbnail, its length, its loudness (LUFS) and its reading grade. Select a row to open it — a page shows in a sandboxed frame where no script runs, a video plays in its player above its SOURCES and QUALITY REPORT cards. Rename and Delete sit under the selected row."},{term:"Generate page / Generate video",body:"Opens the Generate composer. Start from a template — Overview, How it works, FAQ, Getting started, What’s new or Custom topic (you name the topic) for a page; Project demo, Feature spotlight, Blog post, Whiteboard explainer or Custom for a video — then adjust it. A page takes Written for (Newcomers, Users or Contributors), Length (Brief, Standard or In-depth) and Read from (README & docs, Source tree, Git log); a video takes Kind, a Feature or Post target, Style, Length (30 or 60 seconds) and Character on or off. Both take an optional Focus note. Your choices reach the builder as plain lines such as “Audience: Users” or “Video length: 60”."},{term:"Regenerate…",body:"In the selected page's or video's title bar. Opens the composer pre-filled from that entry and rebuilds it in place: the builder also gets a “Replace entry: <id>” line, so you end up with one updated entry, not a second copy."},{term:"While it builds",body:"A build runs in the background as a scheduler job in the builder's Session, so Project Home stays put. A building row sits at the top of the list (or the regenerated entry's own row turns building); select it to see its progress and, for a build started in this window, what was sent to the builder. Open session jumps to that Session. When the build finishes, a toast says “<title>” is ready; a failed build shows its reason in that row's place."},{term:"Empty library",body:"With nothing generated yet, the tab shows a starter gallery with one card per template. A card's Generate builds that template's defaults straight away; Customize opens the composer on it (the Custom topic card asks you to name a topic first)."}]},{title:"Tools",items:[{term:"Review MD network",body:"Always listed first. Its LINK MAP draws CLAUDE.md and the docs its links lead to; FINDINGS lists broken links and docs no link path from CLAUDE.md reaches; records (machine-written docs in a record collection, such as validation records) are left out of orphan findings. The strip above the cards says what the tracked docs are: how many are in the network, how many are records and how many are unlinked. Expand on the LINK MAP, or a click on a doc in it, opens the full-screen explorer: zoom and pan the whole map, search paths, and click a doc to read it in the doc preview (its role, usage, recency and contents, with links you can follow). Its Docs view is a table of every tracked doc you can filter and sort by recency, size, links and code mentions. Pick a Scope and a Mode (Full review or Drift check), then Run review opens an architect Session that reports first and changes no files until you approve. The map is scanned when you first open it and again on Refresh — never on a timer."},{term:"Your tools",body:"Every macro saved with Shown on: Project Home for this project is listed after it. A tool with inputs shows its form; otherwise press Run. Each press starts a new Session and opens it, the same as pressing a hot key."},{term:"Add a tool",body:"Opens the macro editor with Shown on already set to Project Home."}]},{title:"Behaviors this affects",items:[{body:"Pages and videos are folders under session-manager-operations/project-pages/ (knowledge/<id>/ and videos/<id>/). Rename changes only the title in the entry's meta.json; Delete removes the entry's folder."},{body:"A build needs delegation to be ready; if it is not, the press shows why in a toast and nothing is queued. Each library builds one entry at a time — Generate and Regenerate stay disabled while a build is queued or running."}]}],tips:["To refresh an out-of-date page or video, use Regenerate… on it — it replaces that entry instead of adding another.","Videos play only for projects inside your home folder.","The Tools badge stays hidden until you open Tools for this project — Project Home never scans on its own."]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The Permissions tab of this page is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab of this page."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via Extensions › MCP Servers for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Merging is per key: Local beats Project beats User. Objects merge key by key, so a Project-scoped { permissions: { allow: [...] } } adds to the user-scoped permissions object instead of replacing it. Lists merge too (allow + allow), and for a plain value the more specific scope wins."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},memory:{headline:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},extensions:{headline:"Extensions — skills, MCP servers and plugins in one place",intro:"Three tabs, one page. Each tab edits the real file Claude Code reads (shown as a chip at the top): ~/.claude/skills for skills, ~/.claude.json mcpServers for MCP servers, installed_plugins.json plus settings.json enabledPlugins for plugins. The Add button opens that tab's catalog.",sections:[{title:"Tabs",items:[{term:"Skills",body:"Markdown files Claude loads on demand, at User or Project scope. Each skill has frontmatter saying when to trigger it."},{term:"MCP Servers",body:"External tools Claude can call. User scope lives in ~/.claude.json; project scope in <repo>/.mcp.json."},{term:"Plugins",body:"Bundles of skills, subagents, hooks and MCP servers installed together and enabled per scope."}]}],tips:["Home face only — User-scope config is machine-wide."]},"app-settings":{headline:"App Settings — Session Manager's own preferences",intro:"Everything here configures this app, not Claude Code: voice input, appearance, telemetry, phone remote, updates and retention, startup behavior, and a map of where the app stores its data. Claude Code's own settings.json lives on the Settings page.",sections:[{title:"Tabs",items:[{term:"Voice",body:"On-device transcription, push-to-talk hotkey, microphone and text-to-speech."},{term:"Storage map",body:"A hand-maintained ERD of what Session Manager persists, its paths and single-writer owners."}]}],tips:["Home face only — these preferences are machine-wide."]}};function _F({content:n}){return r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:n.intro}),n.sections.map(e=>r.jsxs("div",{className:"mb-3 last:mb-0",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),r.jsx("ul",{className:"space-y-1",children:e.items.map((t,i)=>r.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&r.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",r.jsx("span",{children:t.body})]},i))})]},e.title)),n.tips&&n.tips.length>0&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),r.jsx("ul",{className:"space-y-1",children:n.tips.map((e,t)=>r.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function wF({active:n}){const e=as(m=>m.learningPanelCollapsed),t=as(m=>m.setLearningPanelCollapsed),i=as(m=>m.hydrated),s=as(m=>m.hydrate);I.useEffect(()=>{i||s()},[i,s]);const[a,u]=I.useState(()=>!e),l=I.useRef(null);I.useEffect(()=>{i&&u(!e)},[i]);const c=I.useCallback(()=>{u(m=>{const b=!m;return t(!b),b})},[t]);I.useEffect(()=>{if(!a)return;const m=b=>{var k;(k=l.current)!=null&&k.contains(b.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a,t]);const h=I.useRef(!1);I.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const g=bF[n];return g?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":a,title:a?"Close learning panel":"What is this?",children:"Learn"}),a&&r.jsx("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:r.jsx(_F,{content:g})})]}):null}function yF({eyebrow:n,title:e,intro:t,frame:i=!0,learnKey:s,hideTitle:a=!1,children:u}){const l=i&&(n||e||t);return r.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[l&&r.jsxs("header",{className:`shrink-0 px-8 pt-7 flex items-start justify-between gap-4 ${a?"pb-0":"pb-5"}`,children:[r.jsxs("div",{className:"max-w-[820px]",children:[n&&r.jsx("div",{className:`text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint${a?"":" mb-2"}`,children:n}),a?r.jsx("div",{"aria-hidden":"true",className:"h-2","data-testid":"section-frame-title-spacer"}):e&&r.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&r.jsx("p",{className:`text-[14px] text-fg-dim leading-[1.55]${a?"":" mt-3"}`,children:t})]}),s&&r.jsx(wF,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const SF=I.lazy(()=>qn(()=>import("./History-CmSTZeiu.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(n=>({default:n.History}))),CF=I.lazy(()=>qn(()=>import("./Scheduler-DqocyumD.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(n=>({default:n.Scheduler}))),kF=I.lazy(()=>qn(()=>import("./Settings-BzPe2TH6.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(n=>({default:n.Settings}))),EF=I.lazy(()=>qn(()=>import("./SystemPrompt-BbzGIHoz.js"),__vite__mapDeps([15,4,8,9,16,10,1,2]),import.meta.url).then(n=>({default:n.SystemPrompt}))),TF=I.lazy(()=>qn(()=>import("./ProjectClaudeConfig-DJYcUU1G.js"),__vite__mapDeps([17,11,10,8,9,16,18,7,4,12,13,14,1,2,19,20]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),DF=I.lazy(()=>qn(()=>import("./Extensions-ZXSJbnK7.js"),__vite__mapDeps([21,10,19,4,13,8,9,14,20,1,2]),import.meta.url).then(n=>({default:n.Extensions}))),jF=I.lazy(()=>qn(()=>import("./AppSettings-6_dqi9Ti.js"),__vite__mapDeps([22,11,10,20,18,4,1,2]),import.meta.url).then(n=>({default:n.AppSettings}))),$F=I.lazy(()=>qn(()=>import("./AgentLibrary-BFztz90B.js"),__vite__mapDeps([23,4,13,11,10,9,12,1,2]),import.meta.url).then(n=>({default:n.AgentLibrary}))),NF=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ql({children:n}){return r.jsx(I.Suspense,{fallback:NF,children:n})}const AF={history:{title:"Spend, tokens and time",intro:"Estimated spend, tokens, prompts and active time across every project — by project, model and day. Export any range to CSV."},memory:{title:"Claude config",intro:"This project's own Claude Code files — its memory folder, CLAUDE.md and CLAUDE.local.md, .claude/settings.json and settings.local.json, .mcp.json and .claude/skills/. Each tab edits the real file the claude CLI reads when a session starts here; ~/.claude is edited from Home."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads.",hideTitle:!0},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Global personas live in ~/.claude/agents, and any open project, picked in a persona’s project override, can get its own model or effort. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},Ok=new Map;function IF(n,e){const t=Ok.get(n);if(t&&t.ctx===e)return t.node;const i=RF(n,e);return Ok.set(n,{ctx:e,node:i}),i}function RF(n,e){switch(n){case"overview":return r.jsx(KM,{onNavigate:e.onNavigate});case"project-home":return r.jsx(Bz,{});case"editor":return r.jsx(Kw,{});case"projects":return r.jsx(xF,{})}const t=AF[n],i=(()=>{switch(n){case"history":return r.jsx(Ql,{children:r.jsx(SF,{})});case"scheduler":return r.jsx(Ql,{children:r.jsx(CF,{navigate:e.onNavigate})});case"memory":return r.jsx(Ql,{children:r.jsx(TF,{})});case"system-prompt":return r.jsx(Ql,{children:r.jsx(EF,{})});case"settings":return r.jsx(Ql,{children:r.jsx(kF,{scope:"user"})});case"extensions":return r.jsx(Ql,{children:r.jsx(DF,{})});case"app-settings":return r.jsx(Ql,{children:r.jsx(jF,{})});case"agent-library":return r.jsx(Ql,{children:r.jsx($F,{})});default:return null}})();if(!i)return null;const s=UN[n];return t&&s?r.jsx(yF,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class PF extends I.Component{constructor(){super(...arguments);ai(this,"state",{error:null});ai(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,i){console.error("[ErrorBoundary]",t,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):r.jsxs("div",{className:"p-6 text-xs",children:[r.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),r.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),r.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}var $_={exports:{}},Lk;function MF(){return Lk||(Lk=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,c){var h=this&&this.__decorate||function(x,S,T,N){var R,O=arguments.length,A=O<3?S:N===null?N=Object.getOwnPropertyDescriptor(S,T):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,S,T,N);else for(var L=x.length-1;L>=0;L--)(R=x[L])&&(A=(O<3?R(A):O>3?R(S,T,A):R(S,T))||A);return O>3&&A&&Object.defineProperty(S,T,A),A},g=this&&this.__param||function(x,S){return function(T,N){S(T,N,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=c(9042),b=c(9924),k=c(844),C=c(4725),E=c(2585),_=c(3656);let w=l.AccessibilityManager=class extends k.Disposable{constructor(x,S,T,N){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=N,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 R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3054
|
+
(Give a different rewrite than the last one.)`,!1)},[C,t.instruction]),x=I.useCallback(S=>{const T=t.diff;if(!T)return{ok:!1,reason:"not-found"};const N=bB(S,T.before,T.after);return N.ok?(s.current+=1,i({type:"ACCEPT"})):ze.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[t.diff]);return{state:t,select:h,cancel:g,listen:m,sendHeard:_,run:E,retry:w,accept:x}}const DB=[{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."}],Ck=320,em=8;function jB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function $B(n){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(n.left,em),Math.max(em,e-Ck-em)),i=Math.max(n.top-em,em);return{position:"fixed",left:t,top:i,width:Ck,transform:"translateY(-100%)",zIndex:aA.dialog}}function NB({phase:n,rect:e,selectedText:t,diff:i,transcript:s,modelStatus:a,onQuickAction:u,onRunCustom:l,onListen:c,onSendHeard:h,onCancel:g,onAccept:m,onReject:b,onRetry:k}){const[C,E]=I.useState(""),[_,w]=I.useState(!1),x=Bi(R=>R.show),S=I.useRef(null);I.useEffect(()=>()=>{S.current&&clearTimeout(S.current)},[]);const T=async()=>{if(!await qo(t)){x("error","Copy failed");return}w(!0),S.current&&clearTimeout(S.current),S.current=setTimeout(()=>w(!1),1500)},N=()=>{const R=C.trim();R&&(l(R),E(""))};return r.jsxs("div",{"data-doc-edit-popover":!0,style:$B(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&r.jsxs("div",{className:"p-2",children:[r.jsxs("div",{className:"flex items-center justify-between mb-2",children:[r.jsxs("div",{className:"flex flex-wrap gap-1",children:[r.jsx("button",{onClick:T,"data-testid":"doc-edit-copy",className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",title:"Copy the selected text",children:_?"Copied":"Copy"}),r.jsx("button",{onClick: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"}),DB.map(R=>r.jsx("button",{onClick:()=>u(R.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:R.label},R.label))]}),r.jsx("button",{onClick:g,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),r.jsx("input",{value:C,onChange:R=>E(R.target.value),onKeyDown:R=>{R.key==="Enter"?N():R.key==="Escape"&&g()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&r.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[r.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[r.jsxs("span",{className:"flex items-center gap-2",children:[r.jsx(jB,{}),"Listening…"]}),a&&r.jsx("span",{className:"text-[10px] text-fg-faint",children:a})]}),r.jsx("button",{onClick:g,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[r.jsxs("p",{className:"italic text-fg mb-2",children:["«",s,"»"]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsxs("div",{className:"p-3 flex items-center justify-between",children:[r.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),r.jsx("button",{onClick:g,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&r.jsxs("div",{className:"p-3",children:[r.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),r.jsxs("div",{className:"flex justify-end gap-1.5",children:[r.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:k,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function AB(){return r.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),r.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function kk({phase:n,transcript:e,diff:t,editCount:i,modelStatus:s,onListen:a,onSendHeard:u,onCancel:l,onAccept:c,onReject:h,onRetry:g}){return r.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[r.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[r.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),r.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Im(EB)})]}),r.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&r.jsxs("div",{className:"text-fg-faint",children:[r.jsx("p",{children:"Select text in the doc…"}),r.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),n==="popover"&&r.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&r.jsxs("div",{children:[r.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[r.jsx(AB,{}),"Listening…"]}),s&&r.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),r.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&r.jsxs("div",{children:[r.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),r.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&r.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&t&&r.jsxs("div",{children:[r.jsxs("div",{className:"mb-3 space-y-2",children:[r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),r.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),r.jsxs("div",{children:[r.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),r.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),r.jsxs("div",{className:"flex gap-1.5",children:[r.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),r.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),r.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function IB(){const n=jt(t=>t.tabs),e=jt(t=>t.activeTabId);return n.find(t=>t.id===e)??null}function RB({path:n,onRenamed:e,onDeleted:t}){const[i,s]=I.useState(!1),[a,u]=I.useState(!1),[l,c]=I.useState(""),[h,g]=I.useState(!1),m=An(V=>V.buffers[n]),b=An(V=>V.openFile),k=An(V=>V.renameOpenFile),C=An(V=>V.closeFile),E=IB(),_=bo(n),w=()=>s(!1),x=()=>{c(_),u(!0),w()},S=async()=>{const V=l.trim();if(!V||V===_){u(!1);return}try{const Q=await window.api.files.rename(n,V);if(Q.ok){const ie=n.slice(0,n.lastIndexOf("/")),K=Q.newPath??`${ie}/${V}`;k(n,K),e==null||e(n,K),ze.info(`Renamed to ${V}`)}else ze.error(Q.error??`Couldn't rename ${_}`)}catch(Q){ze.error(Q instanceof Error?Q.message:`Couldn't rename ${_}`)}u(!1)},T=async()=>{w();try{const V=await window.api.files.duplicate(n);V.ok&&V.path?(b(V.path),ze.info(`Duplicated as ${bo(V.path)}`)):ze.error(V.error??`Couldn't duplicate ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't duplicate ${_}`)}},N=async()=>{try{const V=await window.api.files.delete(n);V.ok?(C(n),t==null||t(n),ze.info(`Deleted ${_}`)):ze.error(V.error??`Couldn't delete ${_}`)}catch(V){ze.error(V instanceof Error?V.message:`Couldn't delete ${_}`)}g(!1)},R=async()=>{w();const V=m??"";await qo(V)?ze.info(`Copied ${V.length} chars`):ze.error(`Couldn't copy ${_}`)},O=()=>{if(w(),!E){ze.error("No terminal tab is active");return}window.api.pty.write({tabId:E.id,data:`@${n} `}),ze.info(`Added ${_} to Claude context`)},A=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't open ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't open ${_}`))},L=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(V=>{V.ok||ze.error(V.error??`Couldn't reveal ${_}`)}).catch(V=>ze.error(V instanceof Error?V.message:`Couldn't reveal ${_}`))};return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>s(V=>!V),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:w}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[r.jsx(y_,{children:"Edit"}),r.jsx(Sd,{label:"Rename",onClick:x}),r.jsx(Sd,{label:"Duplicate",onClick:T}),r.jsx(Sd,{label:"Delete document",danger:!0,onClick:()=>{w(),g(!0)}}),r.jsx(Ek,{}),r.jsx(y_,{children:"Open"}),r.jsx(Sd,{label:"Open in default app",onClick:A}),r.jsx(Sd,{label:"Reveal in OS",onClick:L}),r.jsx(Ek,{}),r.jsx(y_,{children:"Export"}),r.jsx(Sd,{label:"Copy as Markdown",onClick:R}),r.jsx(Sd,{label:"Add to Claude context",onClick:O,disabled:!E,title:E?void 0:"No terminal tab is active"})]})]}),a&&r.jsx(PB,{value:l,onChange:c,onCancel:()=>u(!1),onConfirm:()=>void S()}),h&&r.jsx(MB,{name:_,onCancel:()=>g(!1),onConfirm:()=>void N()})]})}function y_({children:n}){return r.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function Sd({label:n,onClick:e,danger:t,disabled:i,title:s}){return r.jsx("button",{onClick:e,disabled:i,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function Ek(){return r.jsx("div",{className:"my-1 border-t border-line"})}function PB({value:n,onChange:e,onCancel:t,onConfirm:i}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:s=>{s.target===s.currentTarget&&t()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),r.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?i():s.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function MB({name:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function OB(){const[n,e]=I.useState(!1),t=Ad();return r.jsxs("div",{className:"relative inline-block mr-1",children:[r.jsx("button",{onClick:()=>e(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuScrim}`,onMouseDown:()=>e(!1)}),r.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Ii.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[r.jsx(Dh,{label:"Text size",children:r.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[r.jsx("button",{onClick:()=>t.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),r.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),r.jsx("button",{onClick:()=>t.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),r.jsx(Dh,{label:"Word wrap",children:r.jsx(Ov,{on:t.wordWrap,onClick:t.toggleWordWrap})}),r.jsx(Dh,{label:"Minimap",children:r.jsx(Ov,{on:t.minimap,onClick:t.toggleMinimap})}),r.jsx(Dh,{label:"Theme",children:r.jsx("button",{onClick:()=>t.setTheme(t.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:t.theme==="dark"?"Dark":"Paper"})}),r.jsx(Dh,{label:"Autosave",children:r.jsx(Ov,{on:t.autosave,onClick:t.toggleAutosave})}),r.jsx(Dh,{label:"Wide measure",children:r.jsx(Ov,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Dh({label:n,children:e}){return r.jsxs("div",{className:"flex items-center justify-between gap-2",children:[r.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Ov({on:n,onClick:e}){return r.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const LB=I.lazy(()=>qn(()=>import("./TiptapBody-BV7WhKYF.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Lv(n,e){if(!e.length)return n;const t=new Set(e),i={};for(const[s,a]of Object.entries(n))t.has(s)||(i[s]=a);return i}function tm(n){const e=n.replace(/\\/g,"/").split("/"),t=e[e.length-1]??"",i=e[e.length-2]??"";return!!(t==="CLAUDE.md"||t==="CLAUDE.local.md"||t==="SKILL.md"||t===".claude.json"||t===".mcp.json"||i===".claude"&&/^settings(\.[^/]+)?\.json$/.test(t)||i==="agents"&&e[e.length-3]===".claude"&&t.endsWith(".md"))}function zv(n){return wD(n)||yD(n)}function zB(){const n=Ry(),e=An(Ue=>Ue.openFiles),t=An(Ue=>Ue.activeFilePath),i=An(Ue=>Ue.dirty),s=An(Ue=>Ue.viewMode),a=An(Ue=>Ue.buffers),u=An(Ue=>Ue.setActive),l=An(Ue=>Ue.closeFile),c=An(Ue=>Ue.closeOthers),h=An(Ue=>Ue.closeToTheRight),g=An(Ue=>Ue.closeAll),m=An(Ue=>Ue.loadBuffer),b=An(Ue=>Ue.setBuffer),k=An(Ue=>Ue.markSaved),C=An(Ue=>Ue.setViewMode),E=Ad(),[_,w]=I.useState({}),[x,S]=I.useState({}),[T,N]=I.useState(null),[R,O]=I.useState(null),[A,L]=I.useState(!1),[V,Q]=I.useState(!1),[ie,K]=I.useState(!0),ue=I.useRef(null),te=I.useRef(null),ce=I.useRef(void 0),Ce=I.useRef(null),fe=I.useRef(null),F=TB(t??"",a[t??""]??""),q=I.useCallback((Ue,xt)=>{b(Ue,xt),tm(Ue)&&Ca.getState().setDraft(Ue,xt)},[b]),H=I.useCallback(Ue=>{ue.current=Ue},[]),Z=I.useCallback(()=>ue.current,[]);I.useEffect(()=>{d3()},[]),I.useEffect(()=>{const Ue=t;if(!Ue||zv(Ue))return;if(An.getState().hasBuffer(Ue)){w(St=>St[Ue]==="ready"?St:{...St,[Ue]:"ready"});return}let xt=!1;return w(St=>({...St,[Ue]:"loading"})),tm(Ue)?((async()=>{if(await Ca.getState().loadText(Ue,!0),xt)return;const St=Ca.getState().files[Ue];if(!St||St.loadError&&!St.exists){w(en=>({...en,[Ue]:{error:(St==null?void 0:St.loadError)??"failed to read"}}));return}m(Ue,St.diskRaw),St.dirty&&An.getState().setBuffer(Ue,St.draftRaw),w(en=>({...en,[Ue]:"ready"}))})(),()=>{xt=!0}):(window.api.files.read(Ue).then(St=>{xt||(St.binary?w(en=>({...en,[Ue]:{binary:!0,size:St.size??0,mime:St.mime??"application/octet-stream",reason:St.error??"Binary file"}})):St.ok?(m(Ue,St.text),w(en=>({...en,[Ue]:"ready"}))):w(en=>({...en,[Ue]:{error:St.error??"failed to read"}})))}),()=>{xt=!0})},[t,m]),I.useEffect(()=>{O(null)},[t]);const le=I.useCallback(async(Ue,xt=!1)=>{const St=An.getState().buffers[Ue];if(St==null)return;xt&&L(!0);const en=tm(Ue);let En;if(en){const In=Ca.getState();if(In.setDraft(Ue,St),En=await In.saveText(Ue),!En.ok&&En.error==="conflict"){xt&&L(!1);return}}else En=await window.api.files.write(Ue,St);En.ok?(k(Ue),S(In=>({...In,[Ue]:(In[Ue]??0)+1})),xt||ze.info(`Saved ${bo(Ue)}`)):ze.error(En.error??`Couldn't save ${bo(Ue)}`),xt&&L(!1)},[k]);I.useEffect(()=>{if(!E.autosave)return;const Ue=t;if(!(!Ue||zv(Ue)||tm(Ue)||!i[Ue]))return window.clearTimeout(ce.current),ce.current=window.setTimeout(()=>{le(Ue,!0)},1200),()=>window.clearTimeout(ce.current)},[E.autosave,t,i,a,le]);const me=I.useCallback(Ue=>{Ue.length&&(w(xt=>Lv(xt,Ue)),S(xt=>Lv(xt,Ue)))},[]),Re=I.useCallback((Ue,xt)=>{w(St=>Ue in St?{...Lv(St,[Ue]),[xt]:St[Ue]}:St),S(St=>Ue in St?{...Lv(St,[Ue]),[xt]:St[Ue]}:St)},[]),He=I.useCallback(Ue=>{i[Ue]?N({kind:"one",path:Ue}):(l(Ue),me([Ue]))},[i,l,me]),ge=I.useCallback(Ue=>{e.some(St=>St.path!==Ue&&i[St.path])?N({kind:"others",path:Ue}):(c(Ue),me(e.filter(St=>St.path!==Ue).map(St=>St.path)))},[e,i,c,me]),ee=I.useCallback(Ue=>{const xt=e.findIndex(en=>en.path===Ue);xt!==-1&&e.slice(xt+1).some(en=>i[en.path])?N({kind:"right",path:Ue}):(h(Ue),me(xt!==-1?e.slice(xt+1).map(en=>en.path):[]))},[e,i,h,me]);I.useEffect(()=>{const Ue=xt=>{if(n.current)if((xt.metaKey||xt.ctrlKey)&&(xt.key==="s"||xt.key==="S")){const St=An.getState().activeFilePath;St&&!zv(St)&&(xt.preventDefault(),le(St))}else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="f"||xt.key==="F"))xt.preventDefault(),Q(St=>!St);else if((xt.metaKey||xt.ctrlKey)&&xt.shiftKey&&(xt.key==="w"||xt.key==="W")){const St=An.getState().activeFilePath;St&&An.getState().openFiles.length>1&&(xt.preventDefault(),ge(St))}else xt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():xt.key==="Escape"&&V&&Q(!1)};return window.addEventListener("keydown",Ue),()=>window.removeEventListener("keydown",Ue)},[le,V,ge,F.state.phase,F.cancel]),I.useEffect(()=>{if(F.state.phase==="idle")return;const Ue=xt=>{var en,En;const St=xt.target;(en=fe.current)!=null&&en.contains(St)||(En=Ce.current)!=null&&En.contains(St)||F.cancel()};return window.addEventListener("mousedown",Ue),()=>window.removeEventListener("mousedown",Ue)},[F.state.phase,F.cancel]),I.useEffect(()=>{F.cancel()},[t,F.cancel]);const Ne=I.useCallback(()=>{e.some(xt=>i[xt.path])?N({kind:"all",path:""}):(g(),w({}),S({}))},[e,i,g]),Ee=()=>{if(T){if(T.kind==="one")l(T.path),me([T.path]);else if(T.kind==="others"){const Ue=e.filter(xt=>xt.path!==T.path).map(xt=>xt.path);c(T.path),me(Ue)}else if(T.kind==="right"){const Ue=e.findIndex(St=>St.path===T.path),xt=Ue!==-1?e.slice(Ue+1).map(St=>St.path):[];h(T.path),me(xt)}else g(),w({}),S({});N(null)}};if(e.length===0)return r.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:r.jsxs("div",{className:"text-center",children:[r.jsx("div",{className:"mb-2",children:"no file open"}),r.jsxs("div",{children:["open the ",r.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const Te=t,be=Te?bo(Te):"",Qe=Te?_[Te]:void 0,gt=Te?kD(Te):!1,lt=Te?o3(Te):!1,$t=Te&>?s[Te]??a3(Te):"edit",We=!!Te&&!zv(Te)&&Qe==="ready",Wt=We,kt=lt?["edit","wysiwyg","preview","split"]:gt?["edit","preview"]:[],rn=Te&&r.jsx(sB,{path:Te,name:be,value:a[Te]??"",onChange:Ue=>q(Te,Ue),onSave:()=>void le(Te),onReady:H,onCursor:O}),pn=A?"Saving…":Te&&i[Te]?E.autosave&&!tm(Te)?"Editing…":"Unsaved":"All changes saved";return r.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!V&&r.jsx(Wz,{openFiles:e,activeFilePath:t,dirty:i,onSelectFile:u,onCloseFile:He,onCloseOthers:ge,onCloseToTheRight:ee,onCloseAll:Ne}),Te&&!V&&r.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[r.jsx("span",{className:"text-xs font-medium text-fg truncate",children:be}),r.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:Te}),We&&r.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",pn]}),ol(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:()=>K(Ue=>!Ue),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${ie?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),ol(Te)&&($t==="preview"||$t==="split")&&r.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),kt.length>0&&r.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-clip",children:kt.map(Ue=>r.jsx("button",{onClick:()=>C(Te,Ue),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${$t===Ue?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ue},Ue))}),r.jsx("div",{className:"flex-1"}),r.jsx(RB,{path:Te,onRenamed:Re,onDeleted:Ue=>me([Ue])}),We&&r.jsx(OB,{}),r.jsx("button",{onClick:()=>Q(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),V&&r.jsx("button",{onClick:()=>Q(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),r.jsx("div",{className:"flex-1 min-h-0",children:Te?wD(Te)?r.jsx(uB,{path:Te,name:be}):yD(Te)?r.jsx(hB,{path:Te}):Qe&&typeof Qe=="object"&&"binary"in Qe?r.jsx(xB,{path:Te,name:be,size:Qe.size,mime:Qe.mime,reason:Qe.reason}):Qe&&typeof Qe=="object"&&"error"in Qe?r.jsx("div",{className:"p-6 text-xs text-red-400",children:Qe.error}):Qe!=="ready"?r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):$t==="wysiwyg"&&ol(Te)?r.jsx(I.Suspense,{fallback:r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:r.jsx(LB,{value:a[Te]??"",onChange:Ue=>q(Te,Ue)},Te)}):$t==="split"&&ol(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[ie&&r.jsx(wk,{text:a[Te]??"",scrollRef:te}),r.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[r.jsx(_k,{getEditor:Z}),r.jsx("div",{className:"flex-1 min-h-0",children:rn})]}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx(Rx,{ref:te,text:a[Te]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(kk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&ol(Te)?r.jsxs("div",{className:"flex h-full overflow-clip",children:[ie&&r.jsx(wk,{text:a[Te]??"",scrollRef:te}),r.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:r.jsx(Rx,{ref:te,text:a[Te]??"",wideMeasure:E.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!V&&E.assistantRail&&r.jsx(kk,{phase:F.state.phase,transcript:F.state.transcript,diff:F.state.diff,editCount:F.state.editCount,modelStatus:F.state.modelStatus,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)},onReject:F.cancel,onRetry:F.retry})]}):$t==="preview"&&_D(Te)?r.jsx(cB,{path:Te,dirty:!!i[Te],reloadToken:x[Te]??0}):$t==="preview"&&SD(Te)?r.jsx(fB,{path:Te,text:a[Te]??""}):$t==="preview"&&CD(Te)?r.jsx(vB,{path:Te,text:a[Te]??""}):ol(Te)?r.jsxs("div",{className:"flex flex-col h-full",children:[r.jsx(_k,{getEditor:Z}),r.jsx("div",{className:"flex-1 min-h-0",children:rn})]}):rn:null}),Wt&&r.jsx(lB,{text:a[Te]??"",cursor:R,language:Zr(Te)||void 0}),Te&&ol(Te)&&($t==="preview"||$t==="split")&&F.state.phase!=="idle"&&F.state.selection&&r.jsx("div",{ref:fe,children:r.jsx(NB,{phase:F.state.phase,rect:F.state.selection.rect,selectedText:F.state.selection.text,diff:F.state.diff,transcript:F.state.transcript,modelStatus:F.state.modelStatus,onQuickAction:F.run,onRunCustom:F.run,onListen:F.listen,onSendHeard:F.sendHeard,onCancel:F.cancel,onReject:F.cancel,onRetry:F.retry,onAccept:()=>{const Ue=F.accept(a[Te]??"");Ue.ok&&q(Te,Ue.next)}})}),T&&r.jsx(BB,{message:T.kind==="one"?`Discard unsaved changes to ${bo(T.path)}?`:T.kind==="others"?"Discard unsaved changes in the other open files?":T.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:Ee})]})}const Kw=I.memo(zB);function BB({message:n,onCancel:e,onConfirm:t}){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:i=>{i.target===i.currentTarget&&e()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),r.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const FB="~/.claude/session-manager/projects-prefs.json";let Tk=Promise.resolve(),Bv=null;function Dk(n){const e=Tk.then(n);return Tk=e.catch(()=>{}),e}const Sj=()=>$a(FB);async function jk(){const n=(await Sj().read()).pinned;return n&&typeof n=="object"?{...n}:{}}const S_=Si(n=>({pinned:{},hydrated:!1,hydrate:()=>Bv||(Bv=Dk(async()=>{try{n({pinned:await jk(),hydrated:!0})}catch(e){console.warn("projectsPrefs: could not read launcher pins",e),n({hydrated:!0})}}),Bv),togglePin:e=>{Dk(async()=>{let t;try{t=await jk()}catch(s){console.warn("projectsPrefs: could not read launcher pins",s),ze.error("Could not update pinned projects: the preferences file is unreadable.");return}const i={...t};i[e]?delete i[e]:i[e]=!0;try{await Sj().patch({pinned:i}),n({pinned:i})}catch(s){n({pinned:t}),ze.error(`Could not save pinned projects: ${s instanceof Error?s.message:String(s)}`)}})}}));function GB(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function HB(n,e,t){const i=I.useRef(e);i.current=e;const s=Array.from(new Set(n.filter(u=>!!u).map(GB))),a=s.slice().sort().join("\0")+`${(t==null?void 0:t.depth)??""}`;I.useEffect(()=>{if(s.length===0)return;window.api.config.watch(s,t);const u=window.api.config.onChanged(l=>{s.includes(l.path)&&i.current(l.path)});return()=>{u(),window.api.config.unwatch(s,t)}},[a])}function g0(n){return/^[A-Za-z]:[\\/]/.test(n)&&n.includes("\\")||n.includes("\\")&&!n.includes("/")?"\\":"/"}function Cj(n){return n.split(/[\\/]+/).filter(Boolean)}function kj(n){const e=Cj(n);return e.length?e[e.length-1]:n}function $k(n){const e=n.length>1?n.replace(/[\\/]+$/,""):n,t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t<0?"":t===0?e.slice(0,1):/^[A-Za-z]:$/.test(e.slice(0,t))?e.slice(0,t+1):e.slice(0,t)}function Ej(...n){const e=n.filter(s=>s!=="");if(!e.length)return"";const t=g0(e[0]);let i=e[0];for(const s of e.slice(1))i=i.replace(/[\\/]+$/,"")+t+s.replace(/^[\\/]+/,"");return i}const Nk=n=>n.replace(/\\/g,"/").replace(/\/+$/,"");function Bm(n,e){return Nk(n).startsWith(Nk(e)+"/")}const Yw="reveal:";function o8(n){Dn.getState().openPanel("projects",Yw+n)}function WB(n){return n.startsWith(Yw)&&n.slice(Yw.length)||null}const UB=/^[A-Za-z]:$/;function Ak(n){const e=n.replace(/\\/g,"/"),t=[];for(const i of e.split("/"))if(!(!i||i===".")){if(i===".."){t.length>(UB.test(t[0]??"")?1:0)&&t.pop();continue}t.push(i)}return(e.startsWith("/")?"/":"")+t.join("/")}function Tj(n,e){const t=Ak(n),i=Ak(e);if(t===i)return[];const s=i.endsWith("/")?i:`${i}/`;return t.startsWith(s)?t.slice(s.length).split("/"):null}async function VB(n){const e=await Jh(n);return Array.isArray(e.fileTreeExpanded)?e.fileTreeExpanded.filter(t=>typeof t=="string"):[]}function qB(n,e){return bc(n,{fileTreeExpanded:[...e].slice(0,500)})}async function KB(){const n=await lb();return typeof n.fileTreeShowHidden=="boolean"?n.fileTreeShowHidden:!0}function YB(n){cb({fileTreeShowHidden:n}).catch(()=>{})}function C_(n,e){let t=!1;const i=new Set;for(const s of n){if(s===e||Bm(s,e)){t=!0;continue}i.add(s)}return t?i:n}const Ik=(n,e)=>`${e?1:0}:${n}`,k_={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:"!"}},XB=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 JB(n){const e=Zr(n);return XB.has(e)||bD.has(e)||e==="pdf"}function ZB(n,e){if(e)return"#d97757";switch(Zr(n)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function nm(n){try{return await window.api.git.fileStatus(n)}catch{return{}}}const Rk=64,QB=250,eF={depth:0};function E_(n){const e=n.replace(/\/{2,}/g,"/");return e.length>1?e.replace(/\/+$/,""):e}function tF({cwd:n,onPreviewFile:e,onSendToChat:t,activeTabId:i,reveal:s,onRevealDone:a}){const u=Ry(),l=Zx(),[c,h]=I.useState([]),g=I.useRef(c);g.current=c;const[m,b]=I.useState(null),k=I.useRef(null),C=I.useRef(null),[E,_]=I.useState(0),[w,x]=I.useState(null),[S,T]=I.useState(null),N=I.useRef(null),[R,O]=I.useState(0),A=I.useRef(a);A.current=a;const[L,V]=I.useState(new Set),Q=I.useRef(L);Q.current=L;const ie=I.useRef(!1),[K,ue]=I.useState(""),[te,ce]=I.useState(!0),Ce=I.useRef(!1);I.useEffect(()=>{let it=!1;return KB().then(vt=>{!it&&!Ce.current&&ce(vt)}),()=>{it=!0}},[]);const fe=I.useCallback(it=>{Ce.current=!0,ce(vt=>{const Rt=typeof it=="function"?it(vt):it;return YB(Rt),Rt})},[]),[F,q]=I.useState(!1),[H,Z]=I.useState(null),[le,me]=I.useState({}),[Re,He]=I.useState(null),[ge,ee]=I.useState(null),[Ne,Ee]=I.useState(""),[Te,be]=I.useState(null),[Qe,gt]=I.useState(""),[lt,$t]=I.useState(null),We=I.useRef(null),Wt=I.useRef(null),kt=I.useRef(0),rn=I.useCallback(async()=>{if(!n)return;const it=++kt.current;q(!0),Z(null);const vt=await window.api.files.list(n,te);kt.current===it&&(vt.ok?h(vt.entries.map(Rt=>({...Rt}))):(Z(vt.error??"failed to list"),h([])),T(Ik(n,te)),q(!1))},[n,te]),pn=I.useCallback(async it=>{const vt=kt.current,Rt=new Map;for(const Mn of it){const On=Cj(Mn).length,kn=Rt.get(On);kn?kn.push(Mn):Rt.set(On,[Mn])}const ln=[];for(const Mn of[...Rt.keys()].sort((On,kn)=>On-kn)){const On=Rt.get(Mn),kn=await Promise.all(On.map(async rt=>({p:rt,result:await window.api.files.list(rt,te)})));if(kt.current!==vt)return ln;for(const{p:rt,result:cn}of kn)cn.ok?h(Yn=>fm(Yn,rt,cn.entries.map(Xn=>({...Xn})),Q.current)):ln.push(rt)}return ln},[te]),Ue=I.useCallback(async it=>(await rn(),it.length?pn(it):[]),[rn,pn]);I.useEffect(()=>{ue(""),ee(null),He(null),be(null),$t(null),me({}),b(null);let it=!1;return ie.current=!1,(async()=>{const[vt]=await Promise.all([VB(n),rn()]);if(it)return;if(!ie.current){const ln=new Set(vt);Q.current=ln,V(ln)}if(x(n),!vt.length)return;const Rt=await pn(vt);it||!Rt.length||Cn(ln=>{const Mn=new Set;let On=!1;for(const kn of ln){if(Rt.some(rt=>kn===rt||Bm(kn,rt))){On=!0;continue}Mn.add(kn)}return On?Mn:ln})})(),nm(n).then(vt=>{it||me(vt)}),()=>{it=!0}},[n]);const xt=I.useRef(!0);I.useEffect(()=>{if(xt.current){xt.current=!1;return}Ue([...Q.current])},[te]),I.useEffect(()=>{if(!n||!l)return;nm(n).then(me);const it=window.setInterval(()=>{nm(n).then(me)},5e3);return()=>window.clearInterval(it)},[n,l]);const St=I.useMemo(()=>{if(!n)return[];const it=[...L].filter(vt=>vt!==n);return[n,...it.slice(-63)]},[n,L]),en=I.useRef(!1);I.useEffect(()=>{!n||L.size+1<=Rk||en.current||(en.current=!0,console.warn(`FileTree: watching only ${Rk} of ${L.size+1} folders (cap reached)`))},[n,L]);const En=I.useRef(new Map),In=I.useRef(new Set),vn=I.useRef(!1);vn.current=ge!==null||Te!==null;const ii=I.useRef(()=>{});ii.current=it=>{if(!(it!==E_(n)&&!Q.current.has(it))){if(vn.current){In.current.add(it);return}it===E_(n)?Ue([...Q.current]):fn(it)}},HB(St,it=>{if(it!==E_(n)&&!Q.current.has(it))return;const vt=En.current,Rt=vt.get(it);Rt&&clearTimeout(Rt),vt.set(it,setTimeout(()=>{vt.delete(it),ii.current(it)},QB))},eF),I.useEffect(()=>{if(ge!==null||Te!==null)return;const it=[...In.current];In.current.clear();for(const vt of it)ii.current(vt)},[ge,Te]),I.useEffect(()=>{const it=En.current,vt=In.current;return()=>{for(const Rt of it.values())clearTimeout(Rt);it.clear(),vt.clear()}},[n]),I.useEffect(()=>{if(!Re)return;const it=()=>He(null),vt=Rt=>{u.current&&Rt.key==="Escape"&&He(null)};return window.addEventListener("mousedown",it),window.addEventListener("keydown",vt),()=>{window.removeEventListener("mousedown",it),window.removeEventListener("keydown",vt)}},[Re]),I.useEffect(()=>{ge&&setTimeout(()=>{var it;return(it=We.current)==null?void 0:it.select()},30)},[ge]),I.useEffect(()=>{Te&&setTimeout(()=>{var it;return(it=Wt.current)==null?void 0:it.focus()},30)},[Te]);const Cn=I.useCallback(it=>{const vt=Q.current,Rt=it(vt);Rt!==vt&&(ie.current=!0,Q.current=Rt,V(Rt),qB(n,Rt).catch(()=>{Q.current===Rt&&(Q.current=vt,V(vt),ze.error("Couldn't save folder expansion — reverted."))}))},[n]),jn=I.useCallback(async it=>{if(L.has(it.path)){Cn(Rt=>C_(Rt,it.path));return}if(Cn(Rt=>new Set(Rt).add(it.path)),it.children)return;const vt=await window.api.files.list(it.path,te);vt.ok&&h(Rt=>fm(Rt,it.path,vt.entries.map(ln=>({...ln})),Q.current))},[L,te,Cn]),fn=I.useCallback(async it=>{if(it===n){await rn();return}const vt=await window.api.files.list(it,te);vt.ok&&h(Rt=>fm(Rt,it,vt.entries.map(ln=>({...ln})),Q.current))},[n,rn,te]),Ri=I.useCallback(async(it,vt)=>{const Rt=()=>{var bt;return(bt=A.current)==null?void 0:bt.call(A,it.token)};if(!vt.length){b(null),Rt();return}const ln=kt.current,Mn=vt.slice(0,-1).map((bt,Un)=>Ej(n,...vt.slice(0,Un+1))),On=await Promise.all(Mn.map(bt=>window.api.files.list(bt,te)));if(kt.current!==ln){N.current=null,O(bt=>bt+1);return}let kn=g.current;const rt=[];let cn=null,Yn="not found";for(let bt=0;bt<vt.length;bt++){const Un=kn.find(si=>si.name===vt[bt]);if(!Un)break;if(bt===vt.length-1){cn=Un;break}const xi=On[bt];if(!Un.isDirectory)break;if(!xi.ok){Yn=xi.error??"could not list its folder";break}const At=xi.entries.map(si=>({...si}));rt.push({path:Un.path,children:At}),kn=At}if(!cn){ze.error(`Couldn't reveal ${it.path}: ${Yn}`),Rt();return}const Xn=rt.map(bt=>bt.path);Cn(bt=>Xn.every(Un=>bt.has(Un))?bt:new Set([...bt,...Xn])),h(bt=>rt.reduce((Un,xi)=>fm(Un,xi.path,xi.children,Q.current),bt)),ue(""),Z(null),b(cn.path),_(bt=>bt+1),Rt()},[n,te,Cn]);I.useEffect(()=>{var vt;if(!s||N.current===s.token||w!==n||S!==Ik(n,te)||F)return;const it=Tj(s.path,n);if(!it){N.current=s.token,ze.error(`Couldn't reveal ${s.path}: it is outside ${n}`),(vt=A.current)==null||vt.call(A,s.token);return}if(it.some(Rt=>Rt.startsWith("."))&&(Ce.current=!0,!te)){ce(!0);return}N.current=s.token,Ri(s,it)},[s,w,S,F,n,te,R,Ri]),I.useEffect(()=>{if(!E)return;const it=C.current,vt=k.current;it&&vt&&Xm(it,vt,{block:"nearest"})},[E]);const Ci=I.useCallback(it=>{if(it.isDirectory){jn(it);return}JB(it.name)&&e?e(it.path):window.api.shell.open({as:"openPath",path:it.path})},[jn,e]),Fi=I.useCallback(it=>{if(t){t(it);return}if(i){const vt=Bm(it,n)?it.slice(n.replace(/[\\/]+$/,"").length+1):it;window.api.pty.write({tabId:i,data:`@${vt} `})}},[t,i,n]),ls=I.useCallback((it,vt)=>{it.preventDefault(),it.stopPropagation(),He({x:it.clientX,y:it.clientY,node:vt})},[]),at=it=>{ee(it.path),Ee(it.name)},Wn=async()=>{if(!ge)return;const it=Ne.trim();if(!it){ee(null);return}const vt=await window.api.files.rename(ge,it);if(ee(null),vt.ok){const Rt=$k(ge);Cn(ln=>C_(ln,ge)),await fn(Rt||n),nm(n).then(me)}else{const Rt=vt.error??"rename failed";Z(Rt),ze.error(Rt)}},Kn=async()=>{if(!Te)return;const it=Qe.trim();if(!it){be(null),gt("");return}const vt=await window.api.files.create(Te.parent,it,Te.kind);if(be(null),gt(""),vt.ok)await fn(Te.parent),Te.kind==="folder"&&Cn(Rt=>new Set(Rt).add(Te.parent));else{const Rt=vt.error??"create failed";Z(Rt),ze.error(Rt)}},Pi=async()=>{if(!lt)return;const it=await window.api.files.delete(lt.path),vt=$k(lt.path);if($t(null),it.ok)Cn(Rt=>C_(Rt,lt.path)),await fn(vt||n),nm(n).then(me);else{const Rt=it.error??"delete failed";Z(Rt),ze.error(Rt)}},vi=I.useMemo(()=>{if(!K.trim())return c;const it=K.toLowerCase();return c.filter(vt=>vt.name.toLowerCase().includes(it))},[c,K]),ki=(n?kj(n):"")||"project";return r.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[r.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[r.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[r.jsx(jj,{size:14,className:"shrink-0 text-accent"}),r.jsxs("div",{className:"flex-1 min-w-0",children:[r.jsx("p",{className:"text-xs font-medium text-fg truncate",children:ki}),r.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:n,children:n})]}),r.jsx("button",{onClick:rn,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:F,children:r.jsx(lF,{size:12,className:F?"animate-spin":""})})]}),r.jsx("div",{className:"relative",children:r.jsx("input",{value:K,onChange:it=>ue(it.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),r.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[r.jsx("button",{onClick:()=>be({parent:n,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:r.jsx(cF,{size:12})}),r.jsx("button",{onClick:()=>be({parent:n,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:r.jsx(dF,{size:12})}),r.jsx("div",{className:"flex-1"}),r.jsx("button",{onClick:()=>fe(it=>!it),className:`p-1.5 rounded transition-colors ${te?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:te?"Hide hidden files":"Show hidden files",children:te?r.jsx(uF,{size:12}):r.jsx(hF,{size:12})})]}),r.jsxs("div",{ref:C,className:"flex-1 overflow-y-auto py-1",children:[H&&r.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:H}),!H&&vi.length===0&&!F&&r.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:K?"no matches":"empty folder"}),!H&&r.jsx(Dj,{nodes:vi,depth:0,expanded:L,gitStatus:le,renaming:ge,selected:m,selectedRowRef:k,onSelect:b,renameValue:Ne,renameInputRef:We,onRenameChange:Ee,onRenameCommit:Wn,onRenameCancel:()=>ee(null),onToggleDir:jn,onFileClick:Ci,onSendToChat:Fi,onContextMenu:ls})]}),r.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),Re&&r.jsx(nF,{x:Re.x,y:Re.y,node:Re.node,onClose:()=>He(null),onRename:()=>{at(Re.node),He(null)},onDelete:()=>{$t(Re.node),He(null)},onNewFile:()=>{be({parent:Re.node.path,kind:"file"}),He(null)},onNewFolder:()=>{be({parent:Re.node.path,kind:"folder"}),He(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:Re.node.path}),He(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:Re.node.path}),He(null)},onCopyPath:()=>{const it=Re.node.path;qo(it).then(vt=>{vt||ze.error("Couldn't copy path")}),He(null)},onSendToChat:()=>{Fi(Re.node.path),He(null)}}),Te&&r.jsx(Pk,{title:`New ${Te.kind}`,subtitle:`in ${iF(Te.parent)}`,onCancel:()=>{be(null),gt("")},onConfirm:Kn,confirmLabel:"Create",confirmDisabled:!Qe.trim(),children:r.jsx("input",{ref:Wt,value:Qe,onChange:it=>gt(it.target.value),onKeyDown:it=>{it.key==="Enter"&&Kn(),it.key==="Escape"&&(be(null),gt(""))},placeholder:Te.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),lt&&r.jsx(Pk,{title:`Delete ${lt.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>$t(null),onConfirm:Pi,confirmLabel:"Delete",danger:!0,children:r.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",r.jsxs("span",{className:"text-fg font-medium",children:['"',lt.name,'"']})," to the trash?",lt.isDirectory&&r.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function Dj(n){const{nodes:e,depth:t,expanded:i,gitStatus:s,renaming:a,selected:u,onContextMenu:l}=n;return r.jsx(r.Fragment,{children:e.map(c=>{const h=i.has(c.path),g=a===c.path,m=u===c.path,b=s[c.path],k=ZB(c.name,c.isDirectory);return r.jsxs("div",{children:[r.jsxs("div",{ref:m?n.selectedRowRef:void 0,"data-path":c.path,"data-selected":m?"true":void 0,className:`group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi ${m?"bg-accent/15":""}`,style:{paddingLeft:`${8+t*14}px`},onClick:()=>{g||(n.onSelect(c.path),c.isDirectory?n.onToggleDir(c):n.onFileClick(c))},onDoubleClick:()=>{c.isDirectory||window.api.shell.open({as:"openPath",path:c.path})},onContextMenu:C=>l(C,c),children:[c.isDirectory?r.jsx(aF,{size:10,className:`shrink-0 text-fg-faint transition-transform ${h?"rotate-90":""}`}):r.jsx("span",{className:"w-[10px] shrink-0"}),c.isDirectory?h?r.jsx(rF,{size:12,color:k}):r.jsx(jj,{size:12,color:k}):r.jsx(oF,{size:12,color:k}),g?r.jsx("input",{ref:n.renameInputRef,value:n.renameValue,onChange:C=>n.onRenameChange(C.target.value),onClick:C=>C.stopPropagation(),onBlur:n.onRenameCommit,onKeyDown:C=>{C.key==="Enter"&&n.onRenameCommit(),C.key==="Escape"&&n.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):r.jsx("span",{className:`flex-1 truncate text-xs ${c.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:c.name}),b&&r.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:k_[b].color,backgroundColor:`${k_[b].color}20`},title:b,children:k_[b].label}),!c.isDirectory&&r.jsx("button",{onClick:C=>{C.stopPropagation(),n.onSendToChat(c.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:r.jsx(pF,{size:10})})]}),c.isDirectory&&h&&c.children&&r.jsx(Dj,{...n,nodes:c.children,depth:t+1})]},c.path)})})}function nF(n){const{x:e,y:t,node:i}=n;return r.jsxs("div",{onMouseDown:s=>s.stopPropagation(),className:`fixed ${Ii.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!i.isDirectory&&r.jsx(Zl,{label:"Send to chat",onClick:n.onSendToChat}),r.jsx(Zl,{label:"Open in default app",onClick:n.onOpenExternal}),r.jsx(Zl,{label:"Reveal in OS",onClick:n.onShowInFinder}),r.jsx(T_,{}),r.jsx(Zl,{label:"Copy path",onClick:n.onCopyPath}),r.jsx(Zl,{label:"Rename",onClick:n.onRename}),i.isDirectory&&r.jsxs(r.Fragment,{children:[r.jsx(T_,{}),r.jsx(Zl,{label:"New file",onClick:n.onNewFile}),r.jsx(Zl,{label:"New folder",onClick:n.onNewFolder})]}),r.jsx(T_,{}),r.jsx(Zl,{label:"Delete",onClick:n.onDelete,danger:!0})]})}function Zl({label:n,onClick:e,danger:t}){return r.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:n})}function T_(){return r.jsx("div",{className:"my-1 border-t border-line"})}function Pk(n){return r.jsx("div",{className:`fixed inset-0 ${Ii.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&n.onCancel()},children:r.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[r.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:n.title}),n.subtitle&&r.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:n.subtitle}),r.jsx("div",{className:"mb-4",children:n.children}),r.jsxs("div",{className:"flex justify-end gap-2",children:[r.jsx("button",{onClick:n.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),r.jsx("button",{onClick:n.onConfirm,disabled:!!n.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${n.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:n.confirmLabel??"OK"})]})]})})}function iF(n){return kj(n)}function fm(n,e,t,i){return n.map(s=>s.path===e?{...s,children:sF(s.children,t,i)}:s.children?{...s,children:fm(s.children,e,t,i)}:s)}function sF(n,e,t){const i=new Map;for(const s of n??[])s.children&&t.has(s.path)&&i.set(s.path,s.children);return i.size?e.map(s=>{const a=s.isDirectory?i.get(s.path):void 0;return a?{...s,children:a}:s}):e}function Aa({size:n,children:e,className:t,color:i}){return r.jsx("svg",{width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:i||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function jj({size:n,className:e,color:t}){return r.jsx(Aa,{size:n,className:e,color:t,children:r.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function rF({size:n,className:e,color:t}){return r.jsx(Aa,{size:n,className:e,color:t,children:r.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function oF({size:n,className:e,color:t}){return r.jsxs(Aa,{size:n,className:e,color:t,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function aF({size:n,className:e}){return r.jsx(Aa,{size:n,className:e,children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}function lF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("polyline",{points:"23 4 23 10 17 10"}),r.jsx("polyline",{points:"1 20 1 14 7 14"}),r.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function cF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("polyline",{points:"14 2 14 8 20 8"}),r.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),r.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function dF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),r.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),r.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function uF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function hF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),r.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function pF({size:n,className:e}){return r.jsxs(Aa,{size:n,className:e,children:[r.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),r.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function $j({content:n,children:e,align:t="bottom-right"}){const[i,s]=I.useState(!1),a=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return r.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>s(!0),onMouseLeave:()=>s(!1),onFocus:()=>s(!0),onBlur:()=>s(!1),children:[e,i&&r.jsx("span",{role:"tooltip",className:`absolute ${Ii.dialog} ${a} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:n})]})}function Em(n,e){if(!e)return n;const t=g0(e),i=e.length>1?e.replace(/[\\/]+$/,""):e;if(n===i)return"~";const s=i.endsWith(t)?i:`${i}${t}`;return n.startsWith(s)?`~${t}${n.slice(s.length)}`:n}function D_(n){cb(n).catch(()=>ze.error("Couldn't save File Explorer layout."))}const j_=33,fF=20,mF=60,gF=32;function Mk(n){return Math.min(mF,Math.max(fF,n))}function vF(){const n=jt(F=>F.tabs),e=jt(F=>F.activeTabId),t=n.find(F=>F.id===e)??null,i=Dn(F=>F.navFace),s=ib(),a=i==="home"?s:(t==null?void 0:t.cwd)??null,[u,l]=I.useState(j_),[c,h]=I.useState(!1),g=I.useRef(!1),[m,b]=I.useState(!1),k=I.useRef(u);k.current=u;const C=I.useRef(c);C.current=c;const E=I.useRef(null),_=I.useRef(null),w=I.useRef(!1),{projects:x,openProject:S,archiveProjectByCwd:T}=Od(),N=S_(F=>F.pinned),R=S_(F=>F.togglePin);I.useEffect(()=>{S_.getState().hydrate()},[]),I.useEffect(()=>{let F=!1;return lb().then(q=>{F||g.current||(typeof q.projectsSplitPct=="number"&&Number.isFinite(q.projectsSplitPct)&&l(Mk(q.projectsSplitPct)),typeof q.projectsFileTreeCollapsed=="boolean"&&!w.current&&h(q.projectsFileTreeCollapsed))}),()=>{F=!0}},[]);const O=I.useRef(0),[A,L]=I.useState(null),[V,Q]=I.useState(null);nA("projects",F=>{const q=WB(F);q&&L({path:q,token:++O.current})});const ie=(t==null?void 0:t.cwd)??null;I.useEffect(()=>{if(!A)return;const{path:F}=A,q=me=>!!me&&Tj(F,me)!==null,H=i==="home"?s:ie,Z=i==="home"?{face:"project",root:ie}:{face:"home",root:s};let le=null;if(q(H))le={face:i,root:H};else{if(s===null)return;q(Z.root)&&(le={face:Z.face,root:Z.root})}if(L(null),!le){window.api.shell.open({as:"revealPath",path:F}).then(me=>{me.ok||ze.error(`Couldn't reveal ${F}: ${me.error??"unknown error"}`)},me=>ze.error(`Couldn't reveal ${F}: ${me instanceof Error?me.message:String(me)}`));return}le.face!==i&&Dn.getState().setNavFace(le.face),w.current=!0,h(!1),Q({...A,root:le.root})},[A,i,s,ie]),I.useEffect(()=>{Q(F=>F&&a!==null&&F.root!==a?null:F)},[a]);const K=I.useCallback(F=>{Q(q=>q&&q.token===F?null:q)},[]),ue=[...x].sort((F,q)=>(N[q.cwd]?1:0)-(N[F.cwd]?1:0));I.useEffect(()=>{if(!m)return;const F=q=>{_.current&&!_.current.contains(q.target)&&b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[m]);const te=I.useCallback(F=>{An.getState().openFile(F)},[]),ce=I.useCallback(F=>{F.preventDefault(),g.current=!0;const q=F.clientX,H=k.current;let Z=H;const le=Re=>{const He=E.current;if(!He)return;const ge=He.getBoundingClientRect(),ee=Re.clientX-q;Z=Mk(H+ee/ge.width*100),l(Z)},me=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",me),document.body.style.cursor="",document.body.style.userSelect="",D_({projectsSplitPct:Z})};window.addEventListener("pointermove",le),window.addEventListener("pointerup",me),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),Ce=I.useCallback(()=>{g.current=!0,l(j_),D_({projectsSplitPct:j_})},[]),fe=I.useCallback(()=>{g.current=!0;const F=!C.current;h(F),D_({projectsFileTreeCollapsed:F})},[]);return c?r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("button",{onClick:fe,"data-testid":"projects-file-tree-rail-toggle",title:"Show file explorer",className:"shrink-0 flex flex-col items-center gap-2 py-2 border-r border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",style:{width:gF},children:[r.jsx("span",{className:"text-[11px]",children:"▸"}),r.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Kw,{})})]}):r.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[r.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${u}%`},"data-testid":"projects-file-tree-pane",children:[r.jsxs("div",{ref:_,className:"relative shrink-0 flex items-stretch border-b border-line",children:[r.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(F=>!F),className:"flex-1 min-w-0 px-3 py-1.5 text-[11.5px] text-fg-dim font-mono flex items-center gap-1 hover:bg-bg-hi transition-colors",children:[r.jsx("span",{className:"flex-1 truncate text-left",children:a?Em(a,s):"Projects"}),r.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),r.jsx("button",{onClick:fe,"data-testid":"projects-file-tree-collapse",title:"Hide file explorer",className:"shrink-0 px-2 border-l border-line text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors text-[11px]",children:"◂"}),m&&r.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Ii.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:ue.length===0?r.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):ue.map(F=>{const q=Em(F.cwd,s);return r.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[r.jsx($j,{content:N[F.cwd]?"Unpin":"Pin to top",children:r.jsx("button",{onClick:()=>R(F.cwd),className:`shrink-0 text-sm leading-none transition-colors ${N[F.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:N[F.cwd]?"★":"☆"})}),r.jsx("button",{onClick:()=>{S(F.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:q}),r.jsx("button",{onClick:async()=>{window.confirm(`Archive ${q}?`)&&await T(F)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},F.cwd)})})]}),a?r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:a,children:Em(a,s)}),r.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r.jsx(tF,{cwd:a,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:te,reveal:V&&V.root===a?V:null,onRevealDone:K})})]}):r.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:i==="home"?"Loading home folder…":"No session selected."})]}),r.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:ce,onDoubleClick:Ce,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),r.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:r.jsx(Kw,{})})]})}const xF=I.memo(vF),bF={"project-home":{headline:"Pages, Videos and Tools — this project's generated library and its tools",intro:"Project Home is this project's own library, written by builder agents from what they read in the repository. Three key buttons at the top switch the area below them: Pages holds Knowledge Pages (static HTML pages that explain a topic), Videos holds short self-contained HTML/JS videos that show the project, and Tools holds one-press tools for the project, led by Review MD network.",sections:[{title:"The key buttons",items:[{term:"Pages",body:"Opens the knowledge-page library. The badge counts ready pages plus any page being built; the line under the name reads “Nothing generated yet”, “<n> building · <m> ready” while a build runs, or the page count and how long ago the newest page was made."},{term:"Videos",body:"The same, for the video library."},{term:"Tools",body:"Opens the tool list. Once you have opened Tools for this project, an accent badge shows how many findings Review MD network's link map found. Its Expand button (or a click on any doc in the map) opens a full-screen explorer with a doc preview and a Docs table."}]},{title:"Pages and Videos",items:[{term:"The list",body:"One row per page or video; a video row adds a thumbnail, its length, its loudness (LUFS) and its reading grade. Select a row to open it — a page shows in a sandboxed frame where no script runs, a video plays in its player above its SOURCES and QUALITY REPORT cards. Rename and Delete sit under the selected row."},{term:"Generate page / Generate video",body:"Opens the Generate composer. Start from a template — Overview, How it works, FAQ, Getting started, What’s new or Custom topic (you name the topic) for a page; Project demo, Feature spotlight, Blog post, Whiteboard explainer or Custom for a video — then adjust it. A page takes Written for (Newcomers, Users or Contributors), Length (Brief, Standard or In-depth) and Read from (README & docs, Source tree, Git log); a video takes Kind, a Feature or Post target, Style, Length (30 or 60 seconds) and Character on or off. Both take an optional Focus note. Your choices reach the builder as plain lines such as “Audience: Users” or “Video length: 60”."},{term:"Regenerate…",body:"In the selected page's or video's title bar. Opens the composer pre-filled from that entry and rebuilds it in place: the builder also gets a “Replace entry: <id>” line, so you end up with one updated entry, not a second copy."},{term:"While it builds",body:"A build runs in the background as a scheduler job in the builder's Session, so Project Home stays put. A building row sits at the top of the list (or the regenerated entry's own row turns building); select it to see its progress and, for a build started in this window, what was sent to the builder. Open session jumps to that Session. When the build finishes, a toast says “<title>” is ready; a failed build shows its reason in that row's place."},{term:"Empty library",body:"With nothing generated yet, the tab shows a starter gallery with one card per template. A card's Generate builds that template's defaults straight away; Customize opens the composer on it (the Custom topic card asks you to name a topic first)."}]},{title:"Tools",items:[{term:"Review MD network",body:"Always listed first. Its LINK MAP draws CLAUDE.md and the docs its links lead to; FINDINGS lists broken links and docs no link path from CLAUDE.md reaches; records (machine-written docs in a record collection, such as validation records) are left out of orphan findings. The strip above the cards says what the tracked docs are: how many are in the network, how many are records and how many are unlinked. Expand on the LINK MAP, or a click on a doc in it, opens the full-screen explorer: zoom and pan the whole map, search paths, and click a doc to read it in the doc preview (its role, usage, recency and contents, with links you can follow). Its Docs view is a table of every tracked doc you can filter and sort by recency, size, links and code mentions. Pick a Scope and a Mode (Full review or Drift check), then Run review opens an architect Session that reports first and changes no files until you approve. The map is scanned when you first open it and again on Refresh — never on a timer."},{term:"Your tools",body:"Every macro saved with Shown on: Project Home for this project is listed after it. A tool with inputs shows its form; otherwise press Run. Each press starts a new Session and opens it, the same as pressing a hot key."},{term:"Add a tool",body:"Opens the macro editor with Shown on already set to Project Home."}]},{title:"Behaviors this affects",items:[{body:"Pages and videos are folders under session-manager-operations/project-pages/ (knowledge/<id>/ and videos/<id>/). Rename changes only the title in the entry's meta.json; Delete removes the entry's folder."},{body:"A build needs delegation to be ready; if it is not, the press shows why in a toast and nothing is queued. Each library builds one entry at a time — Generate and Regenerate stay disabled while a build is queued or running."}]}],tips:["To refresh an out-of-date page or video, use Regenerate… on it — it replaces that entry instead of adding another.","Videos play only for projects inside your home folder.","The Tools badge stays hidden until you open Tools for this project — Project Home never scans on its own."]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The Permissions tab of this page is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab of this page."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via Extensions › MCP Servers for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Merging is per key: Local beats Project beats User. Objects merge key by key, so a Project-scoped { permissions: { allow: [...] } } adds to the user-scoped permissions object instead of replacing it. Lists merge too (allow + allow), and for a plain value the more specific scope wins."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},memory:{headline:"A window onto Claude Code's own memory files for this project and its subagents",intro:"Claude Code can keep notes between conversations. These are plain markdown files, stored on your machine. For a project they live in ~/.claude/projects/<project>/memory/. MEMORY.md is the index. Topic files hold the details. At the start of each session Claude loads only the first 200 lines or 25KB of MEMORY.md, whichever comes first, so keep the index short. This tab shows those files and lets you read, edit and delete them. Nothing leaves your machine.",sections:[{title:"What memory is",items:[{term:"Index + topics",body:"MEMORY.md is a short list of one-line pointers. Each pointer names a topic file that holds the full note. Claude reads the index every session and opens a topic file when it needs it."},{term:"Load limit",body:"Only the first 200 lines / 25KB of MEMORY.md are loaded per session. Lines past that are never seen, so a long index quietly loses its tail."},{term:"Who writes",body:"Claude writes memories when you ask it to remember something, or when it decides a fact is worth keeping. You can also edit the files here by hand."}]},{title:"Workspace memories",items:[{term:"Where",body:"The project's auto memory, at ~/.claude/projects/<project>/memory/. It is picked from the active tab's folder, so a different folder shows a different set."},{term:"Worktrees",body:"All git worktrees of the same repository share one workspace memory. A note saved in one worktree is visible in the others."},{term:"Editing",body:"Open a file to read or edit it, add a new one, or delete one. The list refreshes when Claude writes to these files mid-session."}]},{title:"Subagent memories",items:[{term:"Opt-in",body:"A subagent keeps memory only if its definition has `memory: user`, `memory: project` or `memory: local` in its frontmatter. Without that line it has none."},{term:"Where",body:"user: ~/.claude/agent-memory/<agent>/. project: <project>/.claude/agent-memory/<agent>/ (can be committed and shared). local: <project>/.claude/agent-memory-local/<agent>/ (kept out of version control)."},{term:"Agent picker",body:"Pick an agent to see its memory directory. Its files look the same as workspace memory: a MEMORY.md index plus topic files."}]},{title:"What this tab adds",items:[{term:"Stale badge",body:"Marks a memory that has not been touched for a long time, so you can check whether it is still true."},{term:"Not in index",body:"Marks a topic file that MEMORY.md does not point to. Claude will not find it on its own until you add a line to the index."},{term:"Index budget",body:"A strip showing how many lines and KB of MEMORY.md you have used against the 200-line / 25KB limit. It warns when you are close or over."},{term:"Clusters",body:"Groups related memories so you can spot duplicates and merge them. It asks a model to do the grouping, so it costs tokens and only runs when you press the button."},{term:"Natural console",body:"A chat-style box for the workspace. Type list, show <name>, search <text>, remember <text>, forget <name> or help. Free-form text never writes by itself: you choose to send it to Claude in the terminal or add it as a new memory."}]}],tips:["Auto memory off means nothing here is read. Turn it back on if the files seem to have no effect.","Keep MEMORY.md lines short and move detail into topic files so the index stays under the limit.",'Check the "not in index" count after Claude has been writing for a while.']},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (0–32, default 5) overrides the pool size for one launch; chat runs and scheduler jobs share the same pool."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},extensions:{headline:"Extensions — skills, MCP servers and plugins in one place",intro:"Three tabs, one page. Each tab edits the real file Claude Code reads (shown as a chip at the top): ~/.claude/skills for skills, ~/.claude.json mcpServers for MCP servers, installed_plugins.json plus settings.json enabledPlugins for plugins. The Add button opens that tab's catalog.",sections:[{title:"Tabs",items:[{term:"Skills",body:"Markdown files Claude loads on demand, at User or Project scope. Each skill has frontmatter saying when to trigger it."},{term:"MCP Servers",body:"External tools Claude can call. User scope lives in ~/.claude.json; project scope in <repo>/.mcp.json."},{term:"Plugins",body:"Bundles of skills, subagents, hooks and MCP servers installed together and enabled per scope."}]}],tips:["Home face only — User-scope config is machine-wide."]},"app-settings":{headline:"App Settings — Session Manager's own preferences",intro:"Everything here configures this app, not Claude Code: voice input, appearance, telemetry, phone remote, updates and retention, startup behavior, and a map of where the app stores its data. Claude Code's own settings.json lives on the Settings page.",sections:[{title:"Tabs",items:[{term:"Voice",body:"On-device transcription, push-to-talk hotkey, microphone and text-to-speech."},{term:"Storage map",body:"A hand-maintained ERD of what Session Manager persists, its paths and single-writer owners."}]}],tips:["Home face only — these preferences are machine-wide."]}};function _F({content:n}){return r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:n.intro}),n.sections.map(e=>r.jsxs("div",{className:"mb-3 last:mb-0",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),r.jsx("ul",{className:"space-y-1",children:e.items.map((t,i)=>r.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&r.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",r.jsx("span",{children:t.body})]},i))})]},e.title)),n.tips&&n.tips.length>0&&r.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[r.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),r.jsx("ul",{className:"space-y-1",children:n.tips.map((e,t)=>r.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function wF({active:n}){const e=as(m=>m.learningPanelCollapsed),t=as(m=>m.setLearningPanelCollapsed),i=as(m=>m.hydrated),s=as(m=>m.hydrate);I.useEffect(()=>{i||s()},[i,s]);const[a,u]=I.useState(()=>!e),l=I.useRef(null);I.useEffect(()=>{i&&u(!e)},[i]);const c=I.useCallback(()=>{u(m=>{const b=!m;return t(!b),b})},[t]);I.useEffect(()=>{if(!a)return;const m=b=>{var k;(k=l.current)!=null&&k.contains(b.target)||(u(!1),t(!0))};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[a,t]);const h=I.useRef(!1);I.useEffect(()=>{if(!h.current){h.current=!0;return}u(!1)},[n]);const g=bF[n];return g?r.jsxs("span",{ref:l,className:"relative inline-block",children:[r.jsx("button",{type:"button",onClick:c,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":a,title:a?"Close learning panel":"What is this?",children:"Learn"}),a&&r.jsx("div",{className:"absolute right-0 top-full z-30 mt-1 w-96 max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-4 pb-4 pt-3 text-left",children:r.jsx(_F,{content:g})})]}):null}function yF({eyebrow:n,title:e,intro:t,frame:i=!0,learnKey:s,hideTitle:a=!1,children:u}){const l=i&&(n||e||t);return r.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[l&&r.jsxs("header",{className:`shrink-0 px-8 pt-7 flex items-start justify-between gap-4 ${a?"pb-0":"pb-5"}`,children:[r.jsxs("div",{className:"max-w-[820px]",children:[n&&r.jsx("div",{className:`text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint${a?"":" mb-2"}`,children:n}),a?r.jsx("div",{"aria-hidden":"true",className:"h-2","data-testid":"section-frame-title-spacer"}):e&&r.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&r.jsx("p",{className:`text-[14px] text-fg-dim leading-[1.55]${a?"":" mt-3"}`,children:t})]}),s&&r.jsx(wF,{active:s})]}),r.jsx("div",{className:`flex-1 min-h-0 ${l?"px-8 pb-7":"p-8"}`,children:u})]})}const SF=I.lazy(()=>qn(()=>import("./History-D4s5ykcm.js"),__vite__mapDeps([3,4,5,1,2]),import.meta.url).then(n=>({default:n.History}))),CF=I.lazy(()=>qn(()=>import("./Scheduler-CpmSitKx.js"),__vite__mapDeps([6,5,1,2]),import.meta.url).then(n=>({default:n.Scheduler}))),kF=I.lazy(()=>qn(()=>import("./Settings-Blfjp8Bp.js"),__vite__mapDeps([7,4,8,9,10,11,12,13,14,1,2]),import.meta.url).then(n=>({default:n.Settings}))),EF=I.lazy(()=>qn(()=>import("./SystemPrompt-CBvedERn.js"),__vite__mapDeps([15,4,8,9,16,10,1,2]),import.meta.url).then(n=>({default:n.SystemPrompt}))),TF=I.lazy(()=>qn(()=>import("./ProjectClaudeConfig-B9PlbaSV.js"),__vite__mapDeps([17,11,10,8,9,16,18,7,4,12,13,14,1,2,19,20]),import.meta.url).then(n=>({default:n.ProjectClaudeConfig}))),DF=I.lazy(()=>qn(()=>import("./Extensions-CcDjNq7W.js"),__vite__mapDeps([21,10,19,4,13,8,9,14,20,1,2]),import.meta.url).then(n=>({default:n.Extensions}))),jF=I.lazy(()=>qn(()=>import("./AppSettings-Blks3xh_.js"),__vite__mapDeps([22,11,10,20,18,4,1,2]),import.meta.url).then(n=>({default:n.AppSettings}))),$F=I.lazy(()=>qn(()=>import("./AgentLibrary-CbvVbzm2.js"),__vite__mapDeps([23,4,13,11,10,9,12,1,2]),import.meta.url).then(n=>({default:n.AgentLibrary}))),NF=r.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ql({children:n}){return r.jsx(I.Suspense,{fallback:NF,children:n})}const AF={history:{title:"Spend, tokens and time",intro:"Estimated spend, tokens, prompts and active time across every project — by project, model and day. Export any range to CSV."},memory:{title:"Claude config",intro:"This project's own Claude Code files — its memory folder, CLAUDE.md and CLAUDE.local.md, .claude/settings.json and settings.local.json, .mcp.json and .claude/skills/. Each tab edits the real file the claude CLI reads when a session starts here; ~/.claude is edited from Home."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},settings:{title:"Settings",intro:"Claude Code's settings.json — permissions, hooks, env and every other key, per scope, with schema validation."},extensions:{title:"Extensions",intro:"Skills, MCP servers and plugins — each tab edits the real file Claude Code reads.",hideTitle:!0},"app-settings":{title:"App Settings",intro:"Session Manager's own preferences — voice, appearance, telemetry, phone remote, updates and the storage map."},"agent-library":{title:"Agents",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Global personas live in ~/.claude/agents, and any open project, picked in a persona’s project override, can get its own model or effort. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'}},Ok=new Map;function IF(n,e){const t=Ok.get(n);if(t&&t.ctx===e)return t.node;const i=RF(n,e);return Ok.set(n,{ctx:e,node:i}),i}function RF(n,e){switch(n){case"overview":return r.jsx(KM,{onNavigate:e.onNavigate});case"project-home":return r.jsx(Bz,{});case"editor":return r.jsx(Kw,{});case"projects":return r.jsx(xF,{})}const t=AF[n],i=(()=>{switch(n){case"history":return r.jsx(Ql,{children:r.jsx(SF,{})});case"scheduler":return r.jsx(Ql,{children:r.jsx(CF,{navigate:e.onNavigate})});case"memory":return r.jsx(Ql,{children:r.jsx(TF,{})});case"system-prompt":return r.jsx(Ql,{children:r.jsx(EF,{})});case"settings":return r.jsx(Ql,{children:r.jsx(kF,{scope:"user"})});case"extensions":return r.jsx(Ql,{children:r.jsx(DF,{})});case"app-settings":return r.jsx(Ql,{children:r.jsx(jF,{})});case"agent-library":return r.jsx(Ql,{children:r.jsx($F,{})});default:return null}})();if(!i)return null;const s=UN[n];return t&&s?r.jsx(yF,{eyebrow:s,title:t.title,intro:t.intro,hideTitle:t.hideTitle,learnKey:n,children:i}):i}class PF extends I.Component{constructor(){super(...arguments);ai(this,"state",{error:null});ai(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,i){console.error("[ErrorBoundary]",t,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):r.jsxs("div",{className:"p-6 text-xs",children:[r.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),r.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),r.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}var $_={exports:{}},Lk;function MF(){return Lk||(Lk=1,(function(n,e){(function(t,i){n.exports=i()})(globalThis,(()=>(()=>{var t={4567:function(u,l,c){var h=this&&this.__decorate||function(x,S,T,N){var R,O=arguments.length,A=O<3?S:N===null?N=Object.getOwnPropertyDescriptor(S,T):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")A=Reflect.decorate(x,S,T,N);else for(var L=x.length-1;L>=0;L--)(R=x[L])&&(A=(O<3?R(A):O>3?R(S,T,A):R(S,T))||A);return O>3&&A&&Object.defineProperty(S,T,A),A},g=this&&this.__param||function(x,S){return function(T,N){S(T,N,x)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const m=c(9042),b=c(9924),k=c(844),C=c(4725),E=c(2585),_=c(3656);let w=l.AccessibilityManager=class extends k.Disposable{constructor(x,S,T,N){super(),this._terminal=x,this._coreBrowserService=T,this._renderService=N,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 R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3055
3055
|
`)))),this.register(this._terminal.onA11yTab((R=>this._handleTab(R)))),this.register(this._terminal.onKey((R=>this._handleKey(R.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,_.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,k.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(x){for(let S=0;S<x;S++)this._handleChar(" ")}_handleChar(x){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==x&&(this._charsToAnnounce+=x):this._charsToAnnounce+=x,x===`
|
|
3056
3056
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(x){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(x)||this._charsToConsume.push(x)}_refreshRows(x,S){this._liveRegionDebouncer.refresh(x,S,this._terminal.rows)}_renderRows(x,S){const T=this._terminal.buffer,N=T.lines.length.toString();for(let R=x;R<=S;R++){const O=T.lines.get(T.ydisp+R),A=[],L=(O==null?void 0:O.translateToString(!0,void 0,void 0,A))||"",V=(T.ydisp+R+1).toString(),Q=this._rowElements[R];Q&&(L.length===0?(Q.innerText=" ",this._rowColumns.set(Q,[0,1])):(Q.textContent=L,this._rowColumns.set(Q,A)),Q.setAttribute("aria-posinset",V),Q.setAttribute("aria-setsize",N))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(x,S){const T=x.target,N=this._rowElements[S===0?1:this._rowElements.length-2];if(T.getAttribute("aria-posinset")===(S===0?"1":`${this._terminal.buffer.lines.length}`)||x.relatedTarget!==N)return;let R,O;if(S===0?(R=T,O=this._rowElements.pop(),this._rowContainer.removeChild(O)):(R=this._rowElements.shift(),O=T,this._rowContainer.removeChild(R)),R.removeEventListener("focus",this._topBoundaryFocusListener),O.removeEventListener("focus",this._bottomBoundaryFocusListener),S===0){const A=this._createAccessibilityTreeNode();this._rowElements.unshift(A),this._rowContainer.insertAdjacentElement("afterbegin",A)}else{const A=this._createAccessibilityTreeNode();this._rowElements.push(A),this._rowContainer.appendChild(A)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(S===0?-1:1),this._rowElements[S===0?1:this._rowElements.length-2].focus(),x.preventDefault(),x.stopImmediatePropagation()}_handleSelectionChange(){var L;if(this._rowElements.length===0)return;const x=document.getSelection();if(!x)return;if(x.isCollapsed)return void(this._rowContainer.contains(x.anchorNode)&&this._terminal.clearSelection());if(!x.anchorNode||!x.focusNode)return void console.error("anchorNode and/or focusNode are null");let S={node:x.anchorNode,offset:x.anchorOffset},T={node:x.focusNode,offset:x.focusOffset};if((S.node.compareDocumentPosition(T.node)&Node.DOCUMENT_POSITION_PRECEDING||S.node===T.node&&S.offset>T.offset)&&([S,T]=[T,S]),S.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(S={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(S.node))return;const N=this._rowElements.slice(-1)[0];if(T.node.compareDocumentPosition(N)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(T={node:N,offset:((L=N.textContent)==null?void 0:L.length)??0}),!this._rowContainer.contains(T.node))return;const R=({node:V,offset:Q})=>{const ie=V instanceof Text?V.parentNode:V;let K=parseInt(ie==null?void 0:ie.getAttribute("aria-posinset"),10)-1;if(isNaN(K))return console.warn("row is invalid. Race condition?"),null;const ue=this._rowColumns.get(ie);if(!ue)return console.warn("columns is null. Race condition?"),null;let te=Q<ue.length?ue[Q]:ue.slice(-1)[0]+1;return te>=this._terminal.cols&&(++K,te=0),{row:K,column:te}},O=R(S),A=R(T);if(O&&A){if(O.row>A.row||O.row===A.row&&O.column>=A.column)throw new Error("invalid range");this._terminal.select(O.column,O.row,(A.row-O.row)*this._terminal.cols-O.column+A.column)}}_handleResize(x){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let S=this._rowContainer.children.length;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);for(;this._rowElements.length>x;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const x=this._coreBrowserService.mainDocument.createElement("div");return x.setAttribute("role","listitem"),x.tabIndex=-1,this._refreshRowDimensions(x),x}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let x=0;x<this._terminal.rows;x++)this._refreshRowDimensions(this._rowElements[x])}}_refreshRowDimensions(x){x.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=w=h([g(1,E.IInstantiationService),g(2,C.ICoreBrowserService),g(3,C.IRenderService)],w)},3614:(u,l)=>{function c(b){return b.replace(/\r?\n/g,"\r")}function h(b,k){return k?"\x1B[200~"+b+"\x1B[201~":b}function g(b,k,C,E){b=h(b=c(b),C.decPrivateModes.bracketedPasteMode&&E.rawOptions.ignoreBracketedPasteMode!==!0),C.triggerDataEvent(b,!0),k.value=""}function m(b,k,C){const E=C.getBoundingClientRect(),_=b.clientX-E.left-10,w=b.clientY-E.top-10;k.style.width="20px",k.style.height="20px",k.style.left=`${_}px`,k.style.top=`${w}px`,k.style.zIndex="1000",k.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=c,l.bracketTextForPaste=h,l.copyHandler=function(b,k){b.clipboardData&&b.clipboardData.setData("text/plain",k.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,k,C,E){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),k,C,E)},l.paste=g,l.moveTextAreaUnderMouseCursor=m,l.rightClickHandler=function(b,k,C,E,_){m(b,k,C),_&&E.rightClickSelect(b),k.value=E.selectionText,k.select()}},7239:(u,l,c)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const h=c(1505);l.ColorContrastCache=class{constructor(){this._color=new h.TwoKeyMap,this._css=new h.TwoKeyMap}setCss(g,m,b){this._css.set(g,m,b)}getCss(g,m){return this._css.get(g,m)}setColor(g,m,b){this._color.set(g,m,b)}getColor(g,m){return this._color.get(g,m)}clear(){this._color.clear(),this._css.clear()}}},3656:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(c,h,g,m){c.addEventListener(h,g,m);let b=!1;return{dispose:()=>{b||(b=!0,c.removeEventListener(h,g,m))}}}},3551:function(u,l,c){var h=this&&this.__decorate||function(w,x,S,T){var N,R=arguments.length,O=R<3?x:T===null?T=Object.getOwnPropertyDescriptor(x,S):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(w,x,S,T);else for(var A=w.length-1;A>=0;A--)(N=w[A])&&(O=(R<3?N(O):R>3?N(x,S,O):N(x,S))||O);return R>3&&O&&Object.defineProperty(x,S,O),O},g=this&&this.__param||function(w,x){return function(S,T){x(S,T,w)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const m=c(3656),b=c(8460),k=c(844),C=c(2585),E=c(4725);let _=l.Linkifier=class extends k.Disposable{get currentLink(){return this._currentLink}constructor(w,x,S,T,N){super(),this._element=w,this._mouseService=x,this._renderService=S,this._bufferService=T,this._linkProviderService=N,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,k.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,k.toDisposable)((()=>{var R;this._lastMouseEvent=void 0,(R=this._activeProviderReplies)==null||R.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,m.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,m.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,m.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(w){this._lastMouseEvent=w;const x=this._positionFromMouseEvent(w,this._element,this._mouseService);if(!x)return;this._isMouseOut=!1;const S=w.composedPath();for(let T=0;T<S.length;T++){const N=S[T];if(N.classList.contains("xterm"))break;if(N.classList.contains("xterm-hover"))return}this._lastBufferCell&&x.x===this._lastBufferCell.x&&x.y===this._lastBufferCell.y||(this._handleHover(x),this._lastBufferCell=x)}_handleHover(w){if(this._activeLine!==w.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(w,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,w)||(this._clearCurrentLink(),this._askForLink(w,!0))}_askForLink(w,x){var T,N;this._activeProviderReplies&&x||((T=this._activeProviderReplies)==null||T.forEach((R=>{R==null||R.forEach((O=>{O.link.dispose&&O.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=w.y);let S=!1;for(const[R,O]of this._linkProviderService.linkProviders.entries())x?(N=this._activeProviderReplies)!=null&&N.get(R)&&(S=this._checkLinkProviderResult(R,w,S)):O.provideLinks(w.y,(A=>{var V,Q;if(this._isMouseOut)return;const L=A==null?void 0:A.map((ie=>({link:ie})));(V=this._activeProviderReplies)==null||V.set(R,L),S=this._checkLinkProviderResult(R,w,S),((Q=this._activeProviderReplies)==null?void 0:Q.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(w.y,this._activeProviderReplies)}))}_removeIntersectingLinks(w,x){const S=new Set;for(let T=0;T<x.size;T++){const N=x.get(T);if(N)for(let R=0;R<N.length;R++){const O=N[R],A=O.link.range.start.y<w?0:O.link.range.start.x,L=O.link.range.end.y>w?this._bufferService.cols:O.link.range.end.x;for(let V=A;V<=L;V++){if(S.has(V)){N.splice(R--,1);break}S.add(V)}}}}_checkLinkProviderResult(w,x,S){var R;if(!this._activeProviderReplies)return S;const T=this._activeProviderReplies.get(w);let N=!1;for(let O=0;O<w;O++)this._activeProviderReplies.has(O)&&!this._activeProviderReplies.get(O)||(N=!0);if(!N&&T){const O=T.find((A=>this._linkAtPosition(A.link,x)));O&&(S=!0,this._handleNewLink(O))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!S)for(let O=0;O<this._activeProviderReplies.size;O++){const A=(R=this._activeProviderReplies.get(O))==null?void 0:R.find((L=>this._linkAtPosition(L.link,x)));if(A){S=!0,this._handleNewLink(A);break}}return S}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(w){if(!this._currentLink)return;const x=this._positionFromMouseEvent(w,this._element,this._mouseService);x&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,x)&&this._currentLink.link.activate(w,this._currentLink.link.text)}_clearCurrentLink(w,x){this._currentLink&&this._lastMouseEvent&&(!w||!x||this._currentLink.link.range.start.y>=w&&this._currentLink.link.range.end.y<=x)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,k.disposeArray)(this._linkCacheDisposables))}_handleNewLink(w){if(!this._lastMouseEvent)return;const x=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);x&&this._linkAtPosition(w.link,x)&&(this._currentLink=w,this._currentLink.state={decorations:{underline:w.link.decorations===void 0||w.link.decorations.underline,pointerCursor:w.link.decorations===void 0||w.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,w.link,this._lastMouseEvent),w.link.decorations={},Object.defineProperties(w.link.decorations,{pointerCursor:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.pointerCursor},set:S=>{var T;(T=this._currentLink)!=null&&T.state&&this._currentLink.state.decorations.pointerCursor!==S&&(this._currentLink.state.decorations.pointerCursor=S,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",S))}},underline:{get:()=>{var S,T;return(T=(S=this._currentLink)==null?void 0:S.state)==null?void 0:T.decorations.underline},set:S=>{var T,N,R;(T=this._currentLink)!=null&&T.state&&((R=(N=this._currentLink)==null?void 0:N.state)==null?void 0:R.decorations.underline)!==S&&(this._currentLink.state.decorations.underline=S,this._currentLink.state.isHovered&&this._fireUnderlineEvent(w.link,S))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((S=>{if(!this._currentLink)return;const T=S.start===0?0:S.start+1+this._bufferService.buffer.ydisp,N=this._bufferService.buffer.ydisp+1+S.end;if(this._currentLink.link.range.start.y>=T&&this._currentLink.link.range.end.y<=N&&(this._clearCurrentLink(T,N),this._lastMouseEvent)){const R=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);R&&this._askForLink(R,!1)}}))))}_linkHover(w,x,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!0),this._currentLink.state.decorations.pointerCursor&&w.classList.add("xterm-cursor-pointer")),x.hover&&x.hover(S,x.text)}_fireUnderlineEvent(w,x){const S=w.range,T=this._bufferService.buffer.ydisp,N=this._createLinkUnderlineEvent(S.start.x-1,S.start.y-T-1,S.end.x,S.end.y-T-1,void 0);(x?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(N)}_linkLeave(w,x,S){var T;(T=this._currentLink)!=null&&T.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(x,!1),this._currentLink.state.decorations.pointerCursor&&w.classList.remove("xterm-cursor-pointer")),x.leave&&x.leave(S,x.text)}_linkAtPosition(w,x){const S=w.range.start.y*this._bufferService.cols+w.range.start.x,T=w.range.end.y*this._bufferService.cols+w.range.end.x,N=x.y*this._bufferService.cols+x.x;return S<=N&&N<=T}_positionFromMouseEvent(w,x,S){const T=S.getCoords(w,x,this._bufferService.cols,this._bufferService.rows);if(T)return{x:T[0],y:T[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(w,x,S,T,N){return{x1:w,y1:x,x2:S,y2:T,cols:this._bufferService.cols,fg:N}}};l.Linkifier=_=h([g(1,E.IMouseService),g(2,E.IRenderService),g(3,C.IBufferService),g(4,E.ILinkProviderService)],_)},9042:(u,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(u,l,c){var h=this&&this.__decorate||function(E,_,w,x){var S,T=arguments.length,N=T<3?_:x===null?x=Object.getOwnPropertyDescriptor(_,w):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(E,_,w,x);else for(var R=E.length-1;R>=0;R--)(S=E[R])&&(N=(T<3?S(N):T>3?S(_,w,N):S(_,w))||N);return T>3&&N&&Object.defineProperty(_,w,N),N},g=this&&this.__param||function(E,_){return function(w,x){_(w,x,E)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const m=c(511),b=c(2585);let k=l.OscLinkProvider=class{constructor(E,_,w){this._bufferService=E,this._optionsService=_,this._oscLinkService=w}provideLinks(E,_){var L;const w=this._bufferService.buffer.lines.get(E-1);if(!w)return void _(void 0);const x=[],S=this._optionsService.rawOptions.linkHandler,T=new m.CellData,N=w.getTrimmedLength();let R=-1,O=-1,A=!1;for(let V=0;V<N;V++)if(O!==-1||w.hasContent(V)){if(w.loadCell(V,T),T.hasExtendedAttrs()&&T.extended.urlId){if(O===-1){O=V,R=T.extended.urlId;continue}A=T.extended.urlId!==R}else O!==-1&&(A=!0);if(A||O!==-1&&V===N-1){const Q=(L=this._oscLinkService.getLinkData(R))==null?void 0:L.uri;if(Q){const ie={start:{x:O+1,y:E},end:{x:V+(A||V!==N-1?0:1),y:E}};let K=!1;if(!(S!=null&&S.allowNonHttpProtocols))try{const ue=new URL(Q);["http:","https:"].includes(ue.protocol)||(K=!0)}catch{K=!0}K||x.push({text:Q,range:ie,activate:(ue,te)=>S?S.activate(ue,te,ie):C(0,te),hover:(ue,te)=>{var ce;return(ce=S==null?void 0:S.hover)==null?void 0:ce.call(S,ue,te,ie)},leave:(ue,te)=>{var ce;return(ce=S==null?void 0:S.leave)==null?void 0:ce.call(S,ue,te,ie)}})}A=!1,T.hasExtendedAttrs()&&T.extended.urlId?(O=V,R=T.extended.urlId):(O=-1,R=-1)}}_(x)}};function C(E,_){if(confirm(`Do you want to navigate to ${_}?
|
|
3057
3057
|
|