claude-code-session-manager 0.94.0 → 0.95.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/dist/assets/{DataModel-B0LDnnSL.js → DataModel-DZK9QZpV.js} +1 -1
  2. package/dist/assets/{History-C685Kytt.js → History-BDyJUGtR.js} +1 -1
  3. package/dist/assets/{Hooks-CwLnp0Z_.js → Hooks-CmK6l0uf.js} +1 -1
  4. package/dist/assets/{HostBilko-CwEHEKYk.js → HostBilko-D8TIx-Bx.js} +1 -1
  5. package/dist/assets/{Library-BU9np05E.js → Library-DTxpOjx8.js} +1 -1
  6. package/dist/assets/{MarkdownEditor-B74ogK2f.js → MarkdownEditor-BPJyrevq.js} +1 -1
  7. package/dist/assets/{McpServers-BLM3ftzP.js → McpServers-B_rvIYDs.js} +1 -1
  8. package/dist/assets/{Memory-DAP1t8bA.js → Memory-B-9GlHqe.js} +1 -1
  9. package/dist/assets/{Permissions-3pGLJmxQ.js → Permissions-DhMMp27n.js} +1 -1
  10. package/dist/assets/{Plugins-Q1KoLEzn.js → Plugins-DKfAlmMY.js} +2 -2
  11. package/dist/assets/{ProvenanceBadge-BnjBQiV9.js → ProvenanceBadge-ptlItdCK.js} +1 -1
  12. package/dist/assets/{SaveBar-Zq2NfcPf.js → SaveBar-CSbNSl2W.js} +1 -1
  13. package/dist/assets/Scheduler--rn1QBYc.js +16 -0
  14. package/dist/assets/{ScopeSwitcher-Cnojv22D.js → ScopeSwitcher-BJof-GWH.js} +1 -1
  15. package/dist/assets/{Settings-D5Lhj7ga.js → Settings-Dsx6XZP5.js} +1 -1
  16. package/dist/assets/{SkillReferenceGraph-BRDiE6Hv.js → SkillReferenceGraph-CGl4B89-.js} +1 -1
  17. package/dist/assets/{Skills-BQDqp-EN.js → Skills-D522Zfol.js} +1 -1
  18. package/dist/assets/{SystemPrompt-tFr19Od6.js → SystemPrompt-DKj-q39J.js} +1 -1
  19. package/dist/assets/{TagLibrary-BjyrnaRE.js → TagLibrary-BH7CG7-6.js} +1 -1
  20. package/dist/assets/{TiptapBody-DGzSg3BO.js → TiptapBody-BbcJL9az.js} +1 -1
  21. package/dist/assets/{Toggle-DzoROibf.js → Toggle-DAslvnnv.js} +1 -1
  22. package/dist/assets/{index-CCl4tz-u.js → index-Yf8e7VCB.js} +8 -8
  23. package/dist/assets/{settingsSchema-BYKVe1WM.js → settingsSchema-pzp0TgvN.js} +1 -1
  24. package/dist/index.html +1 -1
  25. package/package.json +3 -1
  26. package/scripts/README.md +3 -0
  27. package/src/main/__tests__/health-tick-liveness.test.cjs +12 -0
  28. package/src/main/__tests__/scheduler-rate-limit-pause.test.cjs +15 -0
  29. package/src/main/__tests__/scheduler-utilization-hold.test.cjs +89 -0
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/crashDiagnostics.cjs +9 -0
  32. package/src/main/health.cjs +25 -1
  33. package/src/main/lib/__tests__/loopDelay.test.cjs +68 -0
  34. package/src/main/lib/__tests__/usageCircuit.test.cjs +86 -17
  35. package/src/main/lib/loopDelay.cjs +44 -0
  36. package/src/main/lib/usageCircuit.cjs +40 -12
  37. package/src/main/scheduler.cjs +49 -3
  38. package/src/main/usage.cjs +9 -1
  39. package/src/preload/api.d.ts +17 -2
  40. package/dist/assets/Scheduler-D488ebKm.js +0 -16
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-DGzSg3BO.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-BQDqp-EN.js","./MarkdownEditor-B74ogK2f.js","./SaveBar-Zq2NfcPf.js","./ScopeSwitcher-Cnojv22D.js","./Toggle-DzoROibf.js","./ProvenanceBadge-BnjBQiV9.js","./Library-BU9np05E.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-C685Kytt.js","./Scheduler-D488ebKm.js","./Settings-D5Lhj7ga.js","./settingsSchema-BYKVe1WM.js","./Permissions-3pGLJmxQ.js","./SystemPrompt-tFr19Od6.js","./Memory-DAP1t8bA.js","./Plugins-Q1KoLEzn.js","./McpServers-BLM3ftzP.js","./Hooks-CwLnp0Z_.js","./TagLibrary-BjyrnaRE.js","./HostBilko-CwEHEKYk.js","./DataModel-B0LDnnSL.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-BbcJL9az.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-D522Zfol.js","./MarkdownEditor-BPJyrevq.js","./SaveBar-CSbNSl2W.js","./ScopeSwitcher-BJof-GWH.js","./Toggle-DAslvnnv.js","./ProvenanceBadge-ptlItdCK.js","./Library-DTxpOjx8.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-BDyJUGtR.js","./Scheduler--rn1QBYc.js","./Settings-Dsx6XZP5.js","./settingsSchema-pzp0TgvN.js","./Permissions-DhMMp27n.js","./SystemPrompt-DKj-q39J.js","./Memory-B-9GlHqe.js","./Plugins-DKfAlmMY.js","./McpServers-B_rvIYDs.js","./Hooks-CmK6l0uf.js","./TagLibrary-BH7CG7-6.js","./HostBilko-D8TIx-Bx.js","./DataModel-DZK9QZpV.js"])))=>i.map(i=>d[i]);
2
2
  var Dk=Object.defineProperty;var Ak=(i,e,t)=>e in i?Dk(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Ni=(i,e,t)=>Ak(i,typeof e!="symbol"?e+"":e,t);import{_ as Bn}from"./monaco-editor-BW5C4Iv1.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const l of r)if(l.type==="childList")for(const p of l.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&n(p)}).observe(document,{childList:!0,subtree:!0});function t(r){const l={};return r.integrity&&(l.integrity=r.integrity),r.referrerPolicy&&(l.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?l.credentials="include":r.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function n(r){if(r.ep)return;r.ep=!0;const l=t(r);fetch(r.href,l)}})();function sb(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var e_={exports:{}},rf={},t_={exports:{}},gi={};/**
3
3
  * @license React
4
4
  * react.production.min.js
@@ -2907,9 +2907,9 @@ ${P}`,N=v.createShaderModule({code:R,label:s.name});oi("verbose",()=>`[WebGPU] $
2907
2907
  * ONNX Runtime Web v1.26.0
2908
2908
  * Copyright (c) Microsoft Corporation. All rights reserved.
2909
2909
  * Licensed under the MIT License.
2910
- */var sx;function sD(){return sx||(sx=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(X=>typeof io<"u"?io:typeof Proxy<"u"?new Proxy(X,{get:(ne,he)=>(typeof io<"u"?io:ne)[he]}):X)(function(X){if(typeof io<"u")return io.apply(this,arguments);throw Error('Dynamic require of "'+X+'" is not supported')}),d=(X,ne)=>()=>(X&&(ne=X(X=0)),ne),f=(X,ne)=>{for(var he in ne)n(X,he,{get:ne[he],enumerable:!0})},g=(X,ne,he,De)=>{if(ne&&typeof ne=="object"||typeof ne=="function")for(let Se of l(ne))!p.call(X,Se)&&Se!==he&&n(X,Se,{get:()=>ne[Se],enumerable:!(De=r(ne,Se))||De.enumerable});return X},m=X=>g(n({},"__esModule",{value:!0}),X),b,T,E,k,y,S=d(()=>{b=new Map,T=[],E=(X,ne,he)=>{if(ne&&typeof ne.init=="function"&&typeof ne.createInferenceSessionHandler=="function"){let De=b.get(X);if(De===void 0)b.set(X,{backend:ne,priority:he});else{if(De.priority>he)return;if(De.priority===he&&De.backend!==ne)throw new Error(`cannot register backend "${X}" using priority ${he}`)}if(he>=0){let Se=T.indexOf(X);Se!==-1&&T.splice(Se,1);for(let Me=0;Me<T.length;Me++)if(b.get(T[Me]).priority<=he){T.splice(Me,0,X);return}T.push(X)}return}throw new TypeError("not a valid backend")},k=async X=>{let ne=b.get(X);if(!ne)return"backend not found.";if(ne.initialized)return ne.backend;if(ne.aborted)return ne.error;{let he=!!ne.initPromise;try{return he||(ne.initPromise=ne.backend.init(X)),await ne.initPromise,ne.initialized=!0,ne.backend}catch(De){return he||(ne.error=`${De}`,ne.aborted=!0),ne.error}finally{delete ne.initPromise}}},y=async X=>{let ne=X.executionProviders||[],he=ne.map(ze=>typeof ze=="string"?ze:ze.name),De=he.length===0?T:he,Se,Me=[],Ie=new Set;for(let ze of De){let et=await k(ze);typeof et=="string"?Me.push({name:ze,err:et}):(Se||(Se=et),Se===et&&Ie.add(ze))}if(!Se)throw new Error(`no available backend found. ERR: ${Me.map(ze=>`[${ze.name}] ${ze.err}`).join(", ")}`);for(let{name:ze,err:et}of Me)he.includes(ze)&&console.warn(`removing requested execution provider "${ze}" from session options because it is not available: ${et}`);let Pe=ne.filter(ze=>Ie.has(typeof ze=="string"?ze:ze.name));return[Se,new Proxy(X,{get:(ze,et)=>et==="executionProviders"?Pe:Reflect.get(ze,et)})]}}),w=d(()=>{S()}),x,A=d(()=>{x="1.26.0"}),O,$,j=d(()=>{A(),O="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(X){if(X!==void 0){if(typeof X!="string"||["verbose","info","warning","error","fatal"].indexOf(X)===-1)throw new Error(`Unsupported logging level: ${X}`);O=X}},get logLevel(){return O}},Object.defineProperty($,"logLevel",{enumerable:!0})}),L,G=d(()=>{j(),L=$}),W,re,ae=d(()=>{W=(X,ne)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=X.dims[3],he.height=X.dims[2];let De=he.getContext("2d");if(De!=null){let Se,Me;(ne==null?void 0:ne.tensorLayout)!==void 0&&ne.tensorLayout==="NHWC"?(Se=X.dims[2],Me=X.dims[3]):(Se=X.dims[3],Me=X.dims[2]);let Ie=(ne==null?void 0:ne.format)!==void 0?ne.format:"RGB",Pe=ne==null?void 0:ne.norm,ze,et;Pe===void 0||Pe.mean===void 0?ze=[255,255,255,255]:typeof Pe.mean=="number"?ze=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(ze=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(ze[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?et=[0,0,0,0]:typeof Pe.bias=="number"?et=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(et=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(et[3]=Pe.bias[3]));let rt=Me*Se,it=0,Xe=rt,Pt=rt*2,Ne=-1;Ie==="RGBA"?(it=0,Xe=rt,Pt=rt*2,Ne=rt*3):Ie==="RGB"?(it=0,Xe=rt,Pt=rt*2):Ie==="RBG"&&(it=0,Pt=rt,Xe=rt*2);for(let ut=0;ut<Me;ut++)for(let Di=0;Di<Se;Di++){let Zt=(X.data[it++]-et[0])*ze[0],Qt=(X.data[Xe++]-et[1])*ze[1],Ai=(X.data[Pt++]-et[2])*ze[2],Mt=Ne===-1?255:(X.data[Ne++]-et[3])*ze[3];De.fillStyle="rgba("+Zt+","+Qt+","+Ai+","+Mt+")",De.fillRect(Di,ut,1,1)}if("toDataURL"in he)return he.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},re=(X,ne)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(he!=null){let Se,Me,Ie;(ne==null?void 0:ne.tensorLayout)!==void 0&&ne.tensorLayout==="NHWC"?(Se=X.dims[2],Me=X.dims[1],Ie=X.dims[3]):(Se=X.dims[3],Me=X.dims[2],Ie=X.dims[1]);let Pe=ne!==void 0&&ne.format!==void 0?ne.format:"RGB",ze=ne==null?void 0:ne.norm,et,rt;ze===void 0||ze.mean===void 0?et=[255,255,255,255]:typeof ze.mean=="number"?et=[ze.mean,ze.mean,ze.mean,ze.mean]:(et=[ze.mean[0],ze.mean[1],ze.mean[2],255],ze.mean[3]!==void 0&&(et[3]=ze.mean[3])),ze===void 0||ze.bias===void 0?rt=[0,0,0,0]:typeof ze.bias=="number"?rt=[ze.bias,ze.bias,ze.bias,ze.bias]:(rt=[ze.bias[0],ze.bias[1],ze.bias[2],0],ze.bias[3]!==void 0&&(rt[3]=ze.bias[3]));let it=Me*Se;if(ne!==void 0&&(ne.format!==void 0&&Ie===4&&ne.format!=="RGBA"||Ie===3&&ne.format!=="RGB"&&ne.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,Pt=0,Ne=1,ut=2,Di=3,Zt=0,Qt=it,Ai=it*2,Mt=-1;Pe==="RGBA"?(Zt=0,Qt=it,Ai=it*2,Mt=it*3):Pe==="RGB"?(Zt=0,Qt=it,Ai=it*2):Pe==="RBG"&&(Zt=0,Ai=it,Qt=it*2),De=he.createImageData(Se,Me);for(let Mi=0;Mi<Me*Se;Pt+=Xe,Ne+=Xe,ut+=Xe,Di+=Xe,Mi++)De.data[Pt]=(X.data[Zt++]-rt[0])*et[0],De.data[Ne]=(X.data[Qt++]-rt[1])*et[1],De.data[ut]=(X.data[Ai++]-rt[2])*et[2],De.data[Di]=Mt===-1?255:(X.data[Mt++]-rt[3])*et[3]}else throw new Error("Can not access image data");return De}}),Z,pe,oe,me,we,ve,F=d(()=>{_e(),Z=(X,ne)=>{if(X===void 0)throw new Error("Image buffer must be defined");if(ne.height===void 0||ne.width===void 0)throw new Error("Image height and width must be defined");if(ne.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:he,width:De}=ne,Se=ne.norm??{mean:255,bias:0},Me,Ie;typeof Se.mean=="number"?Me=[Se.mean,Se.mean,Se.mean,Se.mean]:Me=[Se.mean[0],Se.mean[1],Se.mean[2],Se.mean[3]??255],typeof Se.bias=="number"?Ie=[Se.bias,Se.bias,Se.bias,Se.bias]:Ie=[Se.bias[0],Se.bias[1],Se.bias[2],Se.bias[3]??0];let Pe=ne.format!==void 0?ne.format:"RGBA",ze=ne.tensorFormat!==void 0&&ne.tensorFormat!==void 0?ne.tensorFormat:"RGB",et=he*De,rt=ze==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),it=4,Xe=0,Pt=1,Ne=2,ut=3,Di=0,Zt=et,Qt=et*2,Ai=-1;Pe==="RGB"&&(it=3,Xe=0,Pt=1,Ne=2,ut=-1),ze==="RGBA"?Ai=et*3:ze==="RBG"?(Di=0,Qt=et,Zt=et*2):ze==="BGR"&&(Qt=0,Zt=et,Di=et*2);for(let Mt=0;Mt<et;Mt++,Xe+=it,Ne+=it,Pt+=it,ut+=it)rt[Di++]=(X[Xe]+Ie[0])/Me[0],rt[Zt++]=(X[Pt]+Ie[1])/Me[1],rt[Qt++]=(X[Ne]+Ie[2])/Me[2],Ai!==-1&&ut!==-1&&(rt[Ai++]=(X[ut]+Ie[3])/Me[3]);return ze==="RGBA"?new Y("float32",rt,[1,4,he,De]):new Y("float32",rt,[1,3,he,De])},pe=async(X,ne)=>{let he=typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement,De=typeof ImageData<"u"&&X instanceof ImageData,Se=typeof ImageBitmap<"u"&&X instanceof ImageBitmap,Me=typeof X=="string",Ie,Pe=ne??{},ze=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=ze();rt.width=X.width,rt.height=X.height;let it=et(rt);if(it!=null){let Xe=X.height,Pt=X.width;if(ne!==void 0&&ne.resizedHeight!==void 0&&ne.resizedWidth!==void 0&&(Xe=ne.resizedHeight,Pt=ne.resizedWidth),ne!==void 0){if(Pe=ne,ne.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=Pt}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=Pt;it.drawImage(X,0,0),Ie=it.getImageData(0,0,Pt,Xe).data}else throw new Error("Can not access image data")}else if(De){let rt,it;if(ne!==void 0&&ne.resizedWidth!==void 0&&ne.resizedHeight!==void 0?(rt=ne.resizedHeight,it=ne.resizedWidth):(rt=X.height,it=X.width),ne!==void 0&&(Pe=ne),Pe.format="RGBA",Pe.height=rt,Pe.width=it,ne!==void 0){let Xe=ze();Xe.width=it,Xe.height=rt;let Pt=et(Xe);if(Pt!=null)Pt.putImageData(X,0,0),Ie=Pt.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else Ie=X.data}else if(Se){if(ne===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=ze();rt.width=X.width,rt.height=X.height;let it=et(rt);if(it!=null){let Xe=X.height,Pt=X.width;return it.drawImage(X,0,0,Pt,Xe),Ie=it.getImageData(0,0,Pt,Xe).data,Pe.height=Xe,Pe.width=Pt,Z(Ie,Pe)}else throw new Error("Can not access image data")}else{if(Me)return new Promise((rt,it)=>{let Xe=ze(),Pt=et(Xe);if(!X||!Pt)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=X,Ne.onload=()=>{Xe.width=Ne.width,Xe.height=Ne.height,Pt.drawImage(Ne,0,0,Xe.width,Xe.height);let ut=Pt.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,rt(Z(ut.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ie!==void 0)return Z(Ie,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},oe=(X,ne)=>{let{width:he,height:De,download:Se,dispose:Me}=ne,Ie=[1,De,he,4];return new Y({location:"texture",type:"float32",texture:X,dims:Ie,download:Se,dispose:Me})},me=(X,ne)=>{let{dataType:he,dims:De,download:Se,dispose:Me}=ne;return new Y({location:"gpu-buffer",type:he??"float32",gpuBuffer:X,dims:De,download:Se,dispose:Me})},we=(X,ne)=>{let{dataType:he,dims:De,download:Se,dispose:Me}=ne;return new Y({location:"ml-tensor",type:he??"float32",mlTensor:X,dims:De,download:Se,dispose:Me})},ve=(X,ne,he)=>new Y({location:"cpu-pinned",type:X,data:ne,dims:he??[ne.length]})}),J,V,se,ge,Te=d(()=>{J=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),V=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),se=!1,ge=()=>{if(!se){se=!0;let X=typeof BigInt64Array<"u"&&BigInt64Array.from,ne=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,De=typeof he<"u"&&he.from;X&&(J.set("int64",BigInt64Array),V.set(BigInt64Array,"int64")),ne&&(J.set("uint64",BigUint64Array),V.set(BigUint64Array,"uint64")),De?(J.set("float16",he),V.set(he,"float16")):J.set("float16",Uint16Array)}}}),je,Ze,ye=d(()=>{_e(),je=X=>{let ne=1;for(let he=0;he<X.length;he++){let De=X[he];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${he}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${De}`);ne*=De}return ne},Ze=(X,ne)=>{switch(X.location){case"cpu":return new Y(X.type,X.data,ne);case"cpu-pinned":return new Y({location:"cpu-pinned",data:X.data,type:X.type,dims:ne});case"texture":return new Y({location:"texture",texture:X.texture,type:X.type,dims:ne});case"gpu-buffer":return new Y({location:"gpu-buffer",gpuBuffer:X.gpuBuffer,type:X.type,dims:ne});case"ml-tensor":return new Y({location:"ml-tensor",mlTensor:X.mlTensor,type:X.type,dims:ne});default:throw new Error(`tensorReshape: tensor location ${X.location} is not supported`)}}}),Y,_e=d(()=>{ae(),F(),Te(),ye(),Y=class{constructor(X,ne,he){ge();let De,Se;if(typeof X=="object"&&"location"in X)switch(this.dataLocation=X.location,De=X.type,Se=X.dims,X.location){case"cpu-pinned":{let Ie=J.get(De);if(!Ie)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(X.data instanceof Ie))throw new TypeError(`buffer should be of type ${Ie.name}`);this.cpuData=X.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=X.texture,this.downloader=X.download,this.disposer=X.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=X.gpuBuffer,this.downloader=X.download,this.disposer=X.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=X.mlTensor,this.downloader=X.download,this.disposer=X.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ie,Pe;if(typeof X=="string")if(De=X,Pe=he,X==="string"){if(!Array.isArray(ne))throw new TypeError("A string tensor's data must be a string array.");Ie=ne}else{let ze=J.get(X);if(ze===void 0)throw new TypeError(`Unsupported tensor type: ${X}.`);if(Array.isArray(ne)){if(X==="float16"&&ze===Uint16Array||X==="uint4"||X==="int4")throw new TypeError(`Creating a ${X} tensor from number array is not supported. Please use ${ze.name} as data.`);X==="uint64"||X==="int64"?Ie=ze.from(ne,BigInt):Ie=ze.from(ne)}else if(ne instanceof ze)Ie=ne;else if(ne instanceof Uint8ClampedArray)if(X==="uint8")Ie=Uint8Array.from(ne);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(X==="float16"&&ne instanceof Uint16Array&&ze!==Uint16Array)Ie=new globalThis.Float16Array(ne.buffer,ne.byteOffset,ne.length);else throw new TypeError(`A ${De} tensor's data must be type of ${ze}`)}else if(Pe=ne,Array.isArray(X)){if(X.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let ze=typeof X[0];if(ze==="string")De="string",Ie=X;else if(ze==="boolean")De="bool",Ie=Uint8Array.from(X);else throw new TypeError(`Invalid element type of data array: ${ze}.`)}else if(X instanceof Uint8ClampedArray)De="uint8",Ie=Uint8Array.from(X);else{let ze=V.get(X.constructor);if(ze===void 0)throw new TypeError(`Unsupported type for tensor data: ${X.constructor}.`);De=ze,Ie=X}if(Pe===void 0)Pe=[Ie.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Se=Pe,this.cpuData=Ie,this.dataLocation="cpu"}let Me=je(Se);if(this.cpuData&&Me!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Me/2)===this.cpuData.length))throw new Error(`Tensor's size(${Me}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Se,this.size=Me}static async fromImage(X,ne){return pe(X,ne)}static fromTexture(X,ne){return oe(X,ne)}static fromGpuBuffer(X,ne){return me(X,ne)}static fromMLTensor(X,ne){return we(X,ne)}static fromPinnedBuffer(X,ne,he){return ve(X,ne,he)}toDataURL(X){return W(this,X)}toImageData(X){return re(this,X)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(X){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let ne=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=ne,X&&this.disposer&&(this.disposer(),this.disposer=void 0),ne}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(X){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ze(this,X)}}}),ue,Re=d(()=>{_e(),ue=Y}),He,lt,It,ct,qt,qe,Rt=d(()=>{j(),He=(X,ne)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${X}::ORT::${ne}`)},lt=(X,ne)=>{var Se;let he=((Se=new Error().stack)==null?void 0:Se.split(/\r\n|\r|\n/g))||[],De=!1;for(let Me=0;Me<he.length;Me++){if(De&&!he[Me].includes("TRACE_FUNC")){let Ie=`FUNC_${X}::${he[Me].trim().split(" ")[1]}`;ne&&(Ie+=`::${ne}`),He("CPU",Ie);return}he[Me].includes("TRACE_FUNC")&&(De=!0)}},It=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||lt("BEGIN",X)},ct=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||lt("END",X)},qt=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${X}`)},qe=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${X}`)}}),_t,ni=d(()=>{S(),Re(),Rt(),_t=class C1{constructor(ne){this.handler=ne}async run(ne,he,De){It(),qt("InferenceSession.run");let Se={},Me={};if(typeof ne!="object"||ne===null||ne instanceof ue||Array.isArray(ne))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ie=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof ue)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(he)){if(he.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ie=!1;for(let et of he){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Se[et]=null}if(typeof De=="object"&&De!==null)Me=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let Xe=he[it];(Xe===null||Xe instanceof ue)&&(et=!0,Ie=!1,Se[it]=Xe)}if(et){if(typeof De=="object"&&De!==null)Me=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Me=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof ne[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Ie)for(let et of this.outputNames)Se[et]=null;let Pe=await this.handler.run(ne,Se,Me),ze={};for(let et in Pe)if(Object.hasOwnProperty.call(Pe,et)){let rt=Pe[et];rt instanceof ue?ze[et]=rt:ze[et]=new ue(rt.type,rt.data,rt.dims)}return qe("InferenceSession.run"),ct(),ze}async release(){return this.handler.dispose()}static async create(ne,he,De,Se){It(),qt("InferenceSession.create");let Me,Ie={};if(typeof ne=="string"){if(Me=ne,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(ne instanceof Uint8Array){if(Me=ne,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(ne instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&ne instanceof SharedArrayBuffer){let rt=ne,it=0,Xe=ne.byteLength;if(typeof he=="object"&&he!==null)Ie=he;else if(typeof he=="number"){if(it=he,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(Xe=ne.byteLength-it,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||it+Xe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof Se=="object"&&Se!==null)Ie=Se;else if(typeof Se<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Me=new Uint8Array(rt,it,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,ze]=await y(Ie),et=await Pe.createInferenceSessionHandler(Me,ze);return qe("InferenceSession.create"),ct(),new C1(et)}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}}}),Ye,yt=d(()=>{ni(),Ye=_t}),ht=d(()=>{}),ke=d(()=>{}),tt=d(()=>{}),Wt=d(()=>{}),ci={};f(ci,{InferenceSession:()=>Ye,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>It,TRACE_FUNC_END:()=>ct,Tensor:()=>ue,env:()=>L,registerBackend:()=>E});var si=d(()=>{w(),G(),yt(),Re(),ht(),ke(),Rt(),tt(),Wt()}),fi=d(()=>{}),ui={};f(ui,{default:()=>mr});var Ci,di,mr,wa=d(()=>{var X;fe(),Fn(),Hn(),Ci="ort-wasm-proxy-worker",di=((X=globalThis.self)==null?void 0:X.name)===Ci,di&&(self.onmessage=ne=>{let{type:he,in:De}=ne.data;try{switch(he){case"init-wasm":Js(De.wasm).then(()=>{Uo(De).then(()=>{postMessage({type:he})},Se=>{postMessage({type:he,err:Se})})},Se=>{postMessage({type:he,err:Se})});break;case"init-ep":{let{epName:Se,env:Me}=De;xr(Me,Se).then(()=>{postMessage({type:he})},Ie=>{postMessage({type:he,err:Ie})});break}case"copy-from":{let{buffer:Se}=De,Me=oi(Se);postMessage({type:he,out:Me});break}case"create":{let{model:Se,options:Me}=De;ds(Se,Me).then(Ie=>{postMessage({type:he,out:Ie})},Ie=>{postMessage({type:he,err:Ie})});break}case"release":Ur(De),postMessage({type:he});break;case"run":{let{sessionId:Se,inputIndices:Me,inputs:Ie,outputIndices:Pe,options:ze}=De;Ke(Se,Me,Ie,Pe,new Array(Pe.length).fill(null),ze).then(et=>{et.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:et},mt([...Ie,...et]))},et=>{postMessage({type:he,err:et})});break}case"end-profiling":Vn(De),postMessage({type:he});break;default:}}catch(Se){postMessage({type:he,err:Se})}}),mr=di?null:ne=>new Worker(ne??bi,{type:"classic",name:Ci})}),zo,gr,bi,Gn,nn,vr,Rs,os,jr,_r,yr,Os,Pn,Hn=d(()=>{fi(),zo=typeof location>"u"?void 0:location.origin,gr=()=>{var X,ne;return typeof document<"u"?(X=document.currentScript)==null?void 0:X.src:typeof self<"u"?(ne=self.location)==null?void 0:ne.href:void 0},bi=gr(),Gn=()=>{if(bi&&!bi.startsWith("blob:"))return bi.substring(0,bi.lastIndexOf("/")+1)},nn=(X,ne)=>{try{let he=ne??bi;return(he?new URL(X,he):new URL(X)).origin===zo}catch{return!1}},vr=(X,ne)=>{let he=ne??bi;try{return(he?new URL(X,he):new URL(X)).href}catch{return}},Rs=(X,ne)=>`${ne??"./"}${X}`,os=async X=>{let ne=await(await fetch(X,{credentials:"same-origin"})).blob();return URL.createObjectURL(ne)},jr=async X=>(await import(X)).default,_r=(wa(),m(ui)).default,yr=async()=>{if(!bi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(bi))return[void 0,_r()];let X=await os(bi);return[X,_r(X)]},Os=void 0,Pn=async(X,ne,he,De)=>{let Se=Os&&!(X||ne);if(Se)if(bi)Se=nn(bi)||De&&!he;else if(De&&!he)Se=!0;else throw new Error("cannot determine the script source URL.");if(Se)return[void 0,Os];{let Me="ort-wasm-simd-threaded.mjs",Ie=X??vr(Me,ne),Pe=he&&Ie&&!nn(Ie,ne),ze=Pe?await os(Ie):Ie??Rs(Me,ne);return[Pe?ze:void 0,await jr(ze)]}}}),Ks,Rn,as,Es,ro,Xs,Ys,Js,zt,Fn=d(()=>{Hn(),Rn=!1,as=!1,Es=!1,ro=()=>{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}},Xs=()=>{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}},Ys=()=>{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}},Js=async X=>{if(Rn)return Promise.resolve();if(as)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");as=!0;let ne=X.initTimeout,he=X.numThreads;if(X.simd!==!1){if(X.simd==="relaxed"){if(!Ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Xs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=ro();he>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+he+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),X.numThreads=he=1);let Se=X.wasmPaths,Me=typeof Se=="string"?Se:void 0,Ie=Se==null?void 0:Se.mjs,Pe=(Ie==null?void 0:Ie.href)??Ie,ze=Se==null?void 0:Se.wasm,et=(ze==null?void 0:ze.href)??ze,rt=X.wasmBinary,[it,Xe]=await Pn(Pe,Me,he>1,!!rt||!!et),Pt=!1,Ne=[];if(ne>0&&Ne.push(new Promise(ut=>{setTimeout(()=>{Pt=!0,ut()},ne)})),Ne.push(new Promise((ut,Di)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(et||Me)Zt.locateFile=Qt=>et??Me+Qt;else if(Pe&&Pe.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Pe).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=Ai=>Qt+Ai)}Xe(Zt).then(Qt=>{as=!1,Rn=!0,Ks=Qt,ut(),it&&URL.revokeObjectURL(it)},Qt=>{as=!1,Es=!0,Di(Qt)})})),await Promise.race(Ne),Pt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${ne}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Wi,Ei,Et,zr=d(()=>{Fn(),Wi=(X,ne)=>{let he=zt(),De=he.lengthBytesUTF8(X)+1,Se=he._malloc(De);return he.stringToUTF8(X,Se,De),ne.push(Se),Se},Ei=(X,ne,he,De)=>{if(typeof X=="object"&&X!==null){if(he.has(X))throw new Error("Circular reference in options");he.add(X)}Object.entries(X).forEach(([Se,Me])=>{let Ie=ne?ne+Se:Se;if(typeof Me=="object")Ei(Me,Ie+".",he,De);else if(typeof Me=="string"||typeof Me=="number")De(Ie,Me.toString());else if(typeof Me=="boolean")De(Ie,Me?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Me}`)})},Et=X=>{let ne=zt(),he=ne.stackSave();try{let De=ne.PTR_SIZE,Se=ne.stackAlloc(2*De);ne._OrtGetLastError(Se,Se+De);let Me=Number(ne.getValue(Se,De===4?"i32":"i64")),Ie=ne.getValue(Se+De,"*"),Pe=Ie?ne.UTF8ToString(Ie):"";throw new Error(`${X} ERROR_CODE: ${Me}, ERROR_MESSAGE: ${Pe}`)}finally{ne.stackRestore(he)}}}),oo,xa=d(()=>{Fn(),zr(),oo=X=>{let ne=zt(),he=0,De=[],Se=X||{};try{if((X==null?void 0:X.logSeverityLevel)===void 0)Se.logSeverityLevel=2;else if(typeof X.logSeverityLevel!="number"||!Number.isInteger(X.logSeverityLevel)||X.logSeverityLevel<0||X.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${X.logSeverityLevel}`);if((X==null?void 0:X.logVerbosityLevel)===void 0)Se.logVerbosityLevel=0;else if(typeof X.logVerbosityLevel!="number"||!Number.isInteger(X.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${X.logVerbosityLevel}`);(X==null?void 0:X.terminate)===void 0&&(Se.terminate=!1);let Me=0;return(X==null?void 0:X.tag)!==void 0&&(Me=Wi(X.tag,De)),he=ne._OrtCreateRunOptions(Se.logSeverityLevel,Se.logVerbosityLevel,!!Se.terminate,Me),he===0&&Et("Can't create run options."),(X==null?void 0:X.extra)!==void 0&&Ei(X.extra,"",new WeakSet,(Ie,Pe)=>{let ze=Wi(Ie,De),et=Wi(Pe,De);ne._OrtAddRunConfigEntry(he,ze,et)!==0&&Et(`Can't set a run config entry: ${Ie} - ${Pe}.`)}),[he,De]}catch(Me){throw he!==0&&ne._OrtReleaseRunOptions(he),De.forEach(Ie=>ne._free(Ie)),Me}}}),ao,lo,Bo,En,Sa,Ca,ki=d(()=>{Fn(),zr(),ao=X=>{switch(X){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${X}`)}},lo=X=>{switch(X){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${X}`)}},Bo=X=>{X.extra||(X.extra={}),X.extra.session||(X.extra.session={});let ne=X.extra.session;ne.use_ort_model_bytes_directly||(ne.use_ort_model_bytes_directly="1"),X.executionProviders&&X.executionProviders.some(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(X.enableMemPattern=!1)},En=(X,ne,he,De)=>{let Se=Wi(ne,De),Me=Wi(he,De);zt()._OrtAddSessionConfigEntry(X,Se,Me)!==0&&Et(`Can't set a session config entry: ${ne} - ${he}.`)},Sa=async(X,ne,he)=>{let De=ne.executionProviders;for(let Se of De){let Me=typeof Se=="string"?Se:Se.name,Ie=[];switch(Me){case"webnn":if(Me="WEBNN",En(X,"session.disable_quant_qdq","1",he),En(X,"session.disable_qdq_constant_folding","1",he),typeof Se!="string"){let it=Se==null?void 0:Se.deviceType;it&&En(X,"deviceType",it,he)}break;case"webgpu":if(Me="JS",typeof Se!="string"){let it=Se;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);En(X,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Me}`)}let Pe=Wi(Me,he),ze=Ie.length,et=0,rt=0;if(ze>0){et=zt()._malloc(ze*zt().PTR_SIZE),he.push(et),rt=zt()._malloc(ze*zt().PTR_SIZE),he.push(rt);for(let it=0;it<ze;it++)zt().setValue(et+it*zt().PTR_SIZE,Ie[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,Ie[it][1],"*")}await zt()._OrtAppendExecutionProvider(X,Pe,et,rt,ze)!==0&&Et(`Can't append execution provider: ${Me}.`)}},Ca=async X=>{let ne=zt(),he=0,De=[],Se=X||{};Bo(Se);try{let Me=ao(Se.graphOptimizationLevel??"all"),Ie=lo(Se.executionMode??"sequential"),Pe=typeof Se.logId=="string"?Wi(Se.logId,De):0,ze=Se.logSeverityLevel??2;if(!Number.isInteger(ze)||ze<0||ze>4)throw new Error(`log severity level is not valid: ${ze}`);let et=Se.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let rt=typeof Se.optimizedModelFilePath=="string"?Wi(Se.optimizedModelFilePath,De):0;if(he=ne._OrtCreateSessionOptions(Me,!!Se.enableCpuMemArena,!!Se.enableMemPattern,Ie,!!Se.enableProfiling,0,Pe,ze,et,rt),he===0&&Et("Can't create session options."),Se.executionProviders&&await Sa(he,Se,De),Se.enableGraphCapture!==void 0){if(typeof Se.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Se.enableGraphCapture}`);En(he,"enableGraphCapture",Se.enableGraphCapture.toString(),De)}if(Se.freeDimensionOverrides)for(let[it,Xe]of Object.entries(Se.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let Pt=Wi(it,De);ne._OrtAddFreeDimensionOverride(he,Pt,Xe)!==0&&Et(`Can't set a free dimension override: ${it} - ${Xe}.`)}return Se.extra!==void 0&&Ei(Se.extra,"",new WeakSet,(it,Xe)=>{En(he,it,Xe,De)}),[he,De]}catch(Me){throw he!==0&&ne._OrtReleaseSessionOptions(he)!==0&&Et("Can't release session options."),De.forEach(Ie=>ne._free(Ie)),Me}}}),On,qi,Ln,Zs,Br,br,ls,gn,Bt=d(()=>{On=X=>{switch(X){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${X}`)}},qi=X=>{switch(X){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${X}`)}},Ln=(X,ne)=>{let he=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][X],De=typeof ne=="number"?ne:ne.reduce((Se,Me)=>Se*Me,1);return he>0?Math.ceil(De*he):void 0},Zs=X=>{switch(X){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${X}`)}},Br=X=>{switch(X){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${X}`)}},br=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",ls=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint64"||X==="int8"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",gn=X=>{switch(X){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${X}`)}}}),Ki,wr=d(()=>{fi(),Ki=async X=>{if(typeof X=="string"){let ne=await fetch(X);if(!ne.ok)throw new Error(`failed to load external data file: ${X}`);let he=ne.headers.get("Content-Length"),De=he?parseInt(he,10):0;if(De<1073741824)return new Uint8Array(await ne.arrayBuffer());{if(!ne.body)throw new Error(`failed to load external data file: ${X}, no response body.`);let Se=ne.body.getReader(),Me;try{Me=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let ze=Math.ceil(De/65536);Me=new WebAssembly.Memory({initial:ze,maximum:ze}).buffer}else throw Pe}let Ie=0;for(;;){let{done:Pe,value:ze}=await Se.read();if(Pe)break;let et=ze.byteLength;new Uint8Array(Me,Ie,et).set(ze),Ie+=et}return new Uint8Array(Me,0,De)}}else return X instanceof Blob?new Uint8Array(await X.arrayBuffer()):X instanceof Uint8Array?X:new Uint8Array(X)}}),cs,Uo,xr,Wn,Ls,Sr,oi,ds,Ur,ks,Ke,Vn,mt,fe=d(()=>{si(),xa(),ki(),Bt(),Fn(),zr(),wr(),cs=(X,ne)=>{zt()._OrtInit(X,ne)!==0&&Et("Can't initialize onnxruntime.")},Uo=async X=>{cs(X.wasm.numThreads,Br(X.logLevel))},xr=async(X,ne)=>{var De,Se;(Se=(De=zt()).asyncInit)==null||Se.call(De);let he=X.webgpu.adapter;if(ne==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(he){if(typeof he.limits!="object"||typeof he.features!="object"||typeof he.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Me=X.webgpu.powerPreference;if(Me!==void 0&&Me!=="low-power"&&Me!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Me}"`);let Ie=X.webgpu.forceFallbackAdapter;if(Ie!==void 0&&typeof Ie!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ie}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Me,forceFallbackAdapter:Ie}),!he)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(ne==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wn=new Map,Ls=X=>{let ne=zt(),he=ne.stackSave();try{let De=ne.PTR_SIZE,Se=ne.stackAlloc(2*De);ne._OrtGetInputOutputCount(X,Se,Se+De)!==0&&Et("Can't get session input/output count.");let Me=De===4?"i32":"i64";return[Number(ne.getValue(Se,Me)),Number(ne.getValue(Se+De,Me))]}finally{ne.stackRestore(he)}},Sr=(X,ne)=>{let he=zt(),De=he.stackSave(),Se=0;try{let Me=he.PTR_SIZE,Ie=he.stackAlloc(2*Me);he._OrtGetInputOutputMetadata(X,ne,Ie,Ie+Me)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(he.getValue(Ie,"*"));Se=Number(he.getValue(Ie+Me,"*"));let ze=he.HEAP32[Se/4];if(ze===0)return[Pe,0];let et=he.HEAPU32[Se/4+1],rt=[];for(let it=0;it<et;it++){let Xe=Number(he.getValue(Se+8+it*Me,"*"));rt.push(Xe!==0?he.UTF8ToString(Xe):Number(he.getValue(Se+8+(it+et)*Me,"*")))}return[Pe,ze,rt]}finally{he.stackRestore(De),Se!==0&&he._OrtFree(Se)}},oi=X=>{let ne=zt(),he=ne._malloc(X.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${X.byteLength}.`);return ne.HEAPU8.set(X,he),[he,X.byteLength]},ds=async(X,ne)=>{var rt,it,Xe;let he,De,Se=zt();Array.isArray(X)?[he,De]=X:X.buffer===Se.HEAPU8.buffer?[he,De]=[X.byteOffset,X.byteLength]:[he,De]=oi(X);let Me=0,Ie=0,Pe=[],ze=[],et=[];try{if([Ie,Pe]=await Ca(ne),(ne==null?void 0:ne.externalData)&&Se.mountExternalData){let Mi=[];for(let hi of ne.externalData){let vn=typeof hi=="string"?hi:hi.path;Mi.push(Ki(typeof hi=="string"?hi:hi.data).then($n=>{Se.mountExternalData(vn,$n)}))}await Promise.all(Mi)}for(let Mi of(ne==null?void 0:ne.executionProviders)??[])if((typeof Mi=="string"?Mi:Mi.name)==="webnn"){if(Se.shouldTransferToMLTensor=!1,typeof Mi!="string"){let hi=Mi,vn=hi==null?void 0:hi.context,$n=hi==null?void 0:hi.gpuDevice,qn=hi==null?void 0:hi.deviceType,ka=hi==null?void 0:hi.powerPreference;vn?Se.currentContext=vn:$n?Se.currentContext=await Se.webnnCreateMLContext($n):Se.currentContext=await Se.webnnCreateMLContext({deviceType:qn,powerPreference:ka})}else Se.currentContext=await Se.webnnCreateMLContext();break}Me=await Se._OrtCreateSession(he,De,Ie),(rt=Se.webgpuOnCreateSession)==null||rt.call(Se,Me),Me===0&&Et("Can't create a session."),(it=Se.jsepOnCreateSession)==null||it.call(Se),Se.currentContext&&(Se.webnnRegisterMLContext(Me,Se.currentContext),Se.currentContext=void 0,Se.shouldTransferToMLTensor=!0);let[Pt,Ne]=Ls(Me),ut=!!(ne!=null&&ne.enableGraphCapture),Di=[],Zt=[],Qt=[],Ai=[],Mt=[];for(let Mi=0;Mi<Pt;Mi++){let[hi,vn,$n]=Sr(Me,Mi);hi===0&&Et("Can't get an input name."),ze.push(hi);let qn=Se.UTF8ToString(hi);Di.push(qn),Qt.push(vn===0?{name:qn,isTensor:!1}:{name:qn,isTensor:!0,type:qi(vn),shape:$n})}for(let Mi=0;Mi<Ne;Mi++){let[hi,vn,$n]=Sr(Me,Mi+Pt);hi===0&&Et("Can't get an output name."),et.push(hi);let qn=Se.UTF8ToString(hi);Zt.push(qn),Ai.push(vn===0?{name:qn,isTensor:!1}:{name:qn,isTensor:!0,type:qi(vn),shape:$n})}return Wn.set(Me,[Me,ze,et,null,ut,!1]),[Me,Di,Zt,Qt,Ai]}catch(Pt){throw ze.forEach(Ne=>Se._OrtFree(Ne)),et.forEach(Ne=>Se._OrtFree(Ne)),Me!==0&&Se._OrtReleaseSession(Me)!==0&&Et("Can't release session."),Pt}finally{Se._free(he),Ie!==0&&Se._OrtReleaseSessionOptions(Ie)!==0&&Et("Can't release session options."),Pe.forEach(Pt=>Se._free(Pt)),(Xe=Se.unmountExternalData)==null||Xe.call(Se)}},Ur=X=>{var ze,et,rt;let ne=zt(),he=Wn.get(X);if(!he)throw new Error(`cannot release session. invalid session id: ${X}`);let[De,Se,Me,Ie,Pe]=he;Ie&&(Pe&&ne._OrtClearBoundOutputs(Ie.handle)!==0&&Et("Can't clear bound outputs."),ne._OrtReleaseBinding(Ie.handle)!==0&&Et("Can't release IO binding.")),(ze=ne.jsepOnReleaseSession)==null||ze.call(ne,X),(et=ne.webnnOnReleaseSession)==null||et.call(ne,X),(rt=ne.webgpuOnReleaseSession)==null||rt.call(ne,X),Se.forEach(it=>ne._OrtFree(it)),Me.forEach(it=>ne._OrtFree(it)),ne._OrtReleaseSession(De)!==0&&Et("Can't release session."),Wn.delete(X)},ks=async(X,ne,he,De,Se,Me,Ie=!1)=>{if(!X){ne.push(0);return}let Pe=zt(),ze=Pe.PTR_SIZE,et=X[0],rt=X[1],it=X[3],Xe=it,Pt,Ne;if(et==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ie&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Me} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=X[2].gpuBuffer;Ne=Ln(On(et),rt);{let Qt=Pe.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pt=Qt(De,Me,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=X[2].mlTensor;Ne=Ln(On(et),rt);let Qt=Pe.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pt=Qt(De,Zt,On(et),rt)}else{let Zt=X[2];if(Array.isArray(Zt)){Ne=ze*Zt.length,Pt=Pe._malloc(Ne),he.push(Pt);for(let Qt=0;Qt<Zt.length;Qt++){if(typeof Zt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Pe.setValue(Pt+Qt*ze,Wi(Zt[Qt],he),"*")}}else{let Qt=Pe.webnnIsGraphInput,Ai=Pe.webnnIsGraphOutput;if(et!=="string"&&Qt&&Ai){let Mt=Pe.UTF8ToString(Se);if(Qt(De,Mt)||Ai(De,Mt)){let Mi=On(et);Ne=Ln(Mi,rt),Xe="ml-tensor";let hi=Pe.webnnCreateTemporaryTensor,vn=Pe.webnnUploadTensor;if(!hi||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let $n=await hi(De,Mi,rt);vn($n,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),Pt=$n}else Ne=Zt.byteLength,Pt=Pe._malloc(Ne),he.push(Pt),Pe.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),Pt)}else Ne=Zt.byteLength,Pt=Pe._malloc(Ne),he.push(Pt),Pe.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),Pt)}}let ut=Pe.stackSave(),Di=Pe.stackAlloc(4*rt.length);try{rt.forEach((Qt,Ai)=>Pe.setValue(Di+Ai*ze,Qt,ze===4?"i32":"i64"));let Zt=Pe._OrtCreateTensor(On(et),Pt,Ne,Di,rt.length,gn(Xe));Zt===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Me}.`),ne.push(Zt)}finally{Pe.stackRestore(ut)}},Ke=async(X,ne,he,De,Se,Me)=>{var Kn,hl,dc;let Ie=zt(),Pe=Ie.PTR_SIZE,ze=Wn.get(X);if(!ze)throw new Error(`cannot run inference. invalid session id: ${X}`);let et=ze[0],rt=ze[1],it=ze[2],Xe=ze[3],Pt=ze[4];ze[5];let Ne=ne.length,ut=De.length,Di=0,Zt=[],Qt=[],Ai=[],Mt=[],Mi=[],hi=Ie.stackSave(),vn=Ie.stackAlloc(Ne*Pe),$n=Ie.stackAlloc(Ne*Pe),qn=Ie.stackAlloc(ut*Pe),ka=Ie.stackAlloc(ut*Pe);try{[Di,Zt]=oo(Me),qt("wasm prepareInputOutputTensor");for(let li=0;li<Ne;li++)await ks(he[li],Qt,Mt,X,rt[ne[li]],ne[li],Pt);for(let li=0;li<ut;li++)await ks(Se[li],Ai,Mt,X,it[De[li]],Ne+De[li],Pt);qe("wasm prepareInputOutputTensor");for(let li=0;li<Ne;li++)Ie.setValue(vn+li*Pe,Qt[li],"*"),Ie.setValue($n+li*Pe,rt[ne[li]],"*");for(let li=0;li<ut;li++)Ie.setValue(qn+li*Pe,Ai[li],"*"),Ie.setValue(ka+li*Pe,it[De[li]],"*");(Kn=Ie.jsepOnRunStart)==null||Kn.call(Ie,et),(hl=Ie.webnnOnRunStart)==null||hl.call(Ie,et);let _n;_n=await Ie._OrtRun(et,$n,vn,Ne,ka,ut,qn,Di),_n!==0&&Et("failed to call OrtRun().");let er=[],uc=[];qt("wasm ProcessOutputTensor");for(let li=0;li<ut;li++){let Ns=Number(Ie.getValue(qn+li*Pe,"*"));if(Ns===Ai[li]||Mi.includes(Ai[li])){er.push(Se[li]),Ns!==Ai[li]&&Ie._OrtReleaseTensor(Ns)!==0&&Et("Can't release tensor.");continue}let bd=Ie.stackSave(),kr=Ie.stackAlloc(4*Pe),Go=!1,an,Xn=0;try{Ie._OrtGetTensorData(Ns,kr,kr+Pe,kr+2*Pe,kr+3*Pe)!==0&&Et(`Can't access output tensor data on index ${li}.`);let pl=Pe===4?"i32":"i64",Yn=Number(Ie.getValue(kr,pl));Xn=Ie.getValue(kr+Pe,"*");let hc=Ie.getValue(kr+Pe*2,"*"),wd=Number(Ie.getValue(kr+Pe*3,pl)),Tr=[];for(let ln=0;ln<wd;ln++)Tr.push(Number(Ie.getValue(hc+ln*Pe,pl)));Ie._OrtFree(hc)!==0&&Et("Can't free memory for tensor dims.");let Ms=Tr.reduce((ln,Vi)=>ln*Vi,1);an=qi(Yn);let tr=Xe==null?void 0:Xe.outputPreferredLocations[De[li]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Vi=0;Vi<Ms;Vi++){let js=Ie.getValue(Xn+Vi*Pe,"*"),pc=Ie.getValue(Xn+(Vi+1)*Pe,"*"),fc=Vi===Ms-1?void 0:pc-js;ln.push(Ie.UTF8ToString(js,fc))}er.push([an,Tr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ms>0){let ln=Ie.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Vi=ln(Xn),js=Ln(Yn,Ms);if(js===void 0||!br(an))throw new Error(`Unsupported data type: ${an}`);Go=!0,er.push([an,Tr,{gpuBuffer:Vi,download:Ie.jsepCreateDownloader(Vi,js,an),dispose:()=>{Ie._OrtReleaseTensor(Ns)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ms>0){let ln=Ie.webnnEnsureTensor,Vi=Ie.webnnIsGraphInputOutputTypeSupported;if(!ln||!Vi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ln(Yn,Ms)===void 0||!ls(an))throw new Error(`Unsupported data type: ${an}`);if(!Vi(X,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let js=await ln(X,Xn,Yn,Tr,!1);Go=!0,er.push([an,Tr,{mlTensor:js,download:Ie.webnnCreateMLTensorDownloader(Xn,an),dispose:()=>{Ie.webnnReleaseTensorId(Xn),Ie._OrtReleaseTensor(Ns)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ms>0){let ln=Ie.webnnCreateMLTensorDownloader(Xn,an)(),Vi=er.length;Go=!0,uc.push((async()=>{let js=[Vi,await ln];return Ie.webnnReleaseTensorId(Xn),Ie._OrtReleaseTensor(Ns),js})()),er.push([an,Tr,[],"cpu"])}else{let ln=Zs(an),Vi=new ln(Ms);new Uint8Array(Vi.buffer,Vi.byteOffset,Vi.byteLength).set(Ie.HEAPU8.subarray(Xn,Xn+Vi.byteLength)),er.push([an,Tr,Vi,"cpu"])}}finally{Ie.stackRestore(bd),an==="string"&&Xn&&Ie._free(Xn),Go||Ie._OrtReleaseTensor(Ns)}}Xe&&!Pt&&(Ie._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),Wn.set(X,[et,rt,it,Xe,Pt,!1]));for(let[li,Ns]of await Promise.all(uc))er[li][2]=Ns;return qe("wasm ProcessOutputTensor"),er}finally{(dc=Ie.webnnOnRunEnd)==null||dc.call(Ie,et),Ie.stackRestore(hi),Qt.forEach(_n=>Ie._OrtReleaseTensor(_n)),Ai.forEach(_n=>Ie._OrtReleaseTensor(_n)),Mt.forEach(_n=>Ie._free(_n)),Di!==0&&Ie._OrtReleaseRunOptions(Di),Zt.forEach(_n=>Ie._free(_n))}},Vn=X=>{let ne=zt(),he=Wn.get(X);if(!he)throw new Error("invalid session id");let De=he[0],Se=ne._OrtEndProfiling(De);Se===0&&Et("Can't get an profile file name."),ne._OrtFree(Se)},mt=X=>{let ne=[];for(let he of X){let De=he[2];!Array.isArray(De)&&"buffer"in De&&ne.push(De.buffer)}return ne}}),Le,Je,Tt,ii,ai,$i,Pi,sn,Ui,on,Ri,$s,Gr,co,Qs,yd,uo,ho,ac=d(()=>{si(),fe(),Fn(),Hn(),Le=()=>!!L.wasm.proxy&&typeof document<"u",Tt=!1,ii=!1,ai=!1,sn=new Map,Ui=(X,ne)=>{let he=sn.get(X);he?he.push(ne):sn.set(X,[ne])},on=()=>{if(Tt||!ii||ai||!Je)throw new Error("worker not ready")},Ri=X=>{switch(X.data.type){case"init-wasm":Tt=!1,X.data.err?(ai=!0,Pi[1](X.data.err)):(ii=!0,Pi[0]()),$i&&(URL.revokeObjectURL($i),$i=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let ne=sn.get(X.data.type);X.data.err?ne.shift()[1](X.data.err):ne.shift()[0](X.data.out);break}}},$s=async()=>{if(!ii){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(ai)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Le())return new Promise((X,ne)=>{Je==null||Je.terminate(),yr().then(([he,De])=>{try{Je=De,Je.onerror=Me=>ne(Me),Je.onmessage=Ri,Pi=[X,ne];let Se={type:"init-wasm",in:L};if(!Se.in.wasm.wasmPaths&&he){let Me=Gn();Me&&(Se.in.wasm.wasmPaths=Me)}Je.postMessage(Se),$i=he}catch(Se){ne(Se)}},ne)});try{await Js(L.wasm),await Uo(L),ii=!0}catch(X){throw ai=!0,X}finally{Tt=!1}}},Gr=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("init-ep",[ne,he]);let De={type:"init-ep",in:{epName:X,env:L}};Je.postMessage(De)});await xr(L,X)},co=async X=>Le()?(on(),new Promise((ne,he)=>{Ui("copy-from",[ne,he]);let De={type:"copy-from",in:{buffer:X}};Je.postMessage(De,[X.buffer])})):oi(X),Qs=async(X,ne)=>{if(Le()){if(ne!=null&&ne.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,De)=>{Ui("create",[he,De]);let Se={type:"create",in:{model:X,options:{...ne}}},Me=[];X instanceof Uint8Array&&Me.push(X.buffer),Je.postMessage(Se,Me)})}else return ds(X,ne)},yd=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("release",[ne,he]);let De={type:"release",in:X};Je.postMessage(De)});Ur(X)},uo=async(X,ne,he,De,Se,Me)=>{if(Le()){if(he.some(Ie=>Ie[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Se.some(Ie=>Ie))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise((Ie,Pe)=>{Ui("run",[Ie,Pe]);let ze=he,et={type:"run",in:{sessionId:X,inputIndices:ne,inputs:ze,outputIndices:De,options:Me}};Je.postMessage(et,mt(ze))})}else return Ke(X,ne,he,De,Se,Me)},ho=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("end-profiling",[ne,he]);let De={type:"end-profiling",in:X};Je.postMessage(De)});Vn(X)}}),ll,po,Ea,cl=d(()=>{si(),ac(),Bt(),fi(),wr(),ll=(X,ne)=>{switch(X.location){case"cpu":return[X.type,X.dims,X.data,"cpu"];case"gpu-buffer":return[X.type,X.dims,{gpuBuffer:X.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[X.type,X.dims,{mlTensor:X.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${X.location} for ${ne()}`)}},po=X=>{switch(X[3]){case"cpu":return new ue(X[0],X[2],X[1]);case"gpu-buffer":{let ne=X[0];if(!br(ne))throw new Error(`not supported data type: ${ne} for deserializing GPU tensor`);let{gpuBuffer:he,download:De,dispose:Se}=X[2];return ue.fromGpuBuffer(he,{dataType:ne,dims:X[1],download:De,dispose:Se})}case"ml-tensor":{let ne=X[0];if(!ls(ne))throw new Error(`not supported data type: ${ne} for deserializing MLTensor tensor`);let{mlTensor:he,download:De,dispose:Se}=X[2];return ue.fromMLTensor(he,{dataType:ne,dims:X[1],download:De,dispose:Se})}default:throw new Error(`invalid data location: ${X[3]}`)}},Ea=class{async fetchModelAndCopyToWasmMemory(X){return co(await Ki(X))}async loadModel(X,ne){It();let he;typeof X=="string"?he=await this.fetchModelAndCopyToWasmMemory(X):he=X,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,ne),ct()}async dispose(){return yd(this.sessionId)}async run(X,ne,he){It();let De=[],Se=[];Object.entries(X).forEach(it=>{let Xe=it[0],Pt=it[1],Ne=this.inputNames.indexOf(Xe);if(Ne===-1)throw new Error(`invalid input '${Xe}'`);De.push(Pt),Se.push(Ne)});let Me=[],Ie=[];Object.entries(ne).forEach(it=>{let Xe=it[0],Pt=it[1],Ne=this.outputNames.indexOf(Xe);if(Ne===-1)throw new Error(`invalid output '${Xe}'`);Me.push(Pt),Ie.push(Ne)});let Pe=De.map((it,Xe)=>ll(it,()=>`input "${this.inputNames[Se[Xe]]}"`)),ze=Me.map((it,Xe)=>it?ll(it,()=>`output "${this.outputNames[Ie[Xe]]}"`):null),et=await uo(this.sessionId,Se,Pe,Ie,ze,he),rt={};for(let it=0;it<et.length;it++)rt[this.outputNames[Ie[it]]]=Me[it]??po(et[it]);return ct(),rt}startProfiling(){}endProfiling(){ho(this.sessionId)}}}),Cr={};f(Cr,{OnnxruntimeWebAssemblyBackend:()=>Er,initializeFlags:()=>Hr,wasmBackend:()=>fo});var Hr,Er,fo,lc=d(()=>{si(),ac(),cl(),Hr=()=>{(typeof L.wasm.initTimeout!="number"||L.wasm.initTimeout<0)&&(L.wasm.initTimeout=0);let X=L.wasm.simd;if(typeof X!="boolean"&&X!==void 0&&X!=="fixed"&&X!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${X}". Reset it to \`false\` and ignore SIMD feature checking.`),L.wasm.simd=!1),typeof L.wasm.proxy!="boolean"&&(L.wasm.proxy=!1),typeof L.wasm.trace!="boolean"&&(L.wasm.trace=!1),typeof L.wasm.numThreads!="number"||!Number.isInteger(L.wasm.numThreads)||L.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)L.wasm.numThreads=1;else{let ne=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;L.wasm.numThreads=Math.min(4,Math.ceil((ne||1)/2))}},Er=class{async init(X){Hr(),await $s(),await Gr(X)}async createInferenceSessionHandler(X,ne){let he=new Ea;return await he.loadModel(X,ne),he}},fo=new Er}),cc={};f(cc,{InferenceSession:()=>Ye,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>It,TRACE_FUNC_END:()=>ct,Tensor:()=>ue,default:()=>ul,env:()=>L,registerBackend:()=>E}),si(),si(),si();var dl="1.26.0",ul=ci;{let X=(lc(),m(Cr)).wasmBackend;E("cpu",X,10),E("wasm",X,10)}return Object.defineProperty(L.versions,"web",{value:dl,enumerable:!0}),m(cc)})();i.exports=t})(d_)),d_.exports}var rx;function rD(){return rx||(rx=1,(function(i){var e=Xa&&Xa.__createBinding||(Object.create?(function(x,A,O,$){$===void 0&&($=O);var j=Object.getOwnPropertyDescriptor(A,O);(!j||("get"in j?!A.__esModule:j.writable||j.configurable))&&(j={enumerable:!0,get:function(){return A[O]}}),Object.defineProperty(x,$,j)}):(function(x,A,O,$){$===void 0&&($=O),x[$]=A[O]})),t=Xa&&Xa.__setModuleDefault||(Object.create?(function(x,A){Object.defineProperty(x,"default",{enumerable:!0,value:A})}):function(x,A){x.default=A}),n=Xa&&Xa.__importStar||function(x){if(x&&x.__esModule)return x;var A={};if(x!=null)for(var O in x)O!=="default"&&Object.prototype.hasOwnProperty.call(x,O)&&e(A,x,O);return t(A,x),A};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(sD()),l=pb(),p=fb(),a=lm(),d=Pv(),f=x1(),g=S1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",T="silero_vad_legacy.onnx",E=x=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async A=>{A.getTracks().forEach(O=>{O.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:A=>{A.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=E;const k=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(x,A,O,$,j){await O.audioWorklet.addModule(x),A.processorOptions={...A.processorOptions??{},frameSamples:$};const L=new AudioWorkletNode(O,"vad-helper-worklet",A);return L.port.onmessage=async G=>{const W=G.data;if(!(typeof W=="object"&&W&&"message"in W)){console.error("Invalid message event",W);return}switch(W.message){case d.Message.AudioFrame:{if(!("data"in W&&W.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const re=new Float32Array(W.data);await j(re);break}}},L}async function S(x,A,O){const $=new g.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:A});a.log.debug("using script processor");const L=x.createScriptProcessor(4096,1,1);let G=!1;return L.onaudioprocess=async W=>{if(!G){G=!0;try{const re=W.inputBuffer.getChannelData(0);W.outputBuffer.getChannelData(0).fill(0);const Z=$.process(re);for(const pe of Z)await O(pe)}catch(re){console.error("Error processing audio:",re)}finally{G=!1}}},L.connect(x.destination),L}class w{constructor(A,O,$,j,L=!1,G=null,W=null,re=null,ae=null,Z=null,pe=null,oe="uninitialized",me=!1){this.options=A,this.frameProcessor=O,this.model=$,this.frameSamples=j,this.listening=L,this.errored=G,this._stream=W,this._audioContext=re,this._vadNode=ae,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=pe,this.initializationState=oe,this.ownsAudioContext=me,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=we=>{this.initializationState="errored",this.errored=we},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(we){throw we instanceof Error?this.setErrored(we.message):this.setErrored(String(we)),we}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"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await S(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),a.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{a.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:we,audioContext:ve,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(we);const J=new MediaStreamAudioSourceNode(ve,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=J,J.connect(F);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:we,mediaStreamAudioSourceNode:ve}=this.getAudioInstances();await this.options.pauseStream(we),ve.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ve;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:we}=this.getAudioInstances();we instanceof AudioWorkletNode&&we.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ve=this._audioContext)==null?void 0:ve.close())},this.setOptions=we=>{this.frameProcessor.setOptions(we)},this.processFrame=async we=>{await this.frameProcessor.process(we,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=we=>{switch(we.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(we.probs,we.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(we.audio);break}}}static async new(A={}){const O={...(0,i.getDefaultRealTimeVADOptions)(A.model??i.DEFAULT_MODEL),...A};(0,p.validateOptions)(O),i.ort.env.wasm.wasmPaths=O.onnxWASMBasePath,O.ortConfig!==void 0&&O.ortConfig(i.ort);const $=O.model==="v5"?b:T,j=O.baseAssetPath+$,L=O.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let G;try{G=await L(i.ort,()=>(0,l.defaultModelFetcher)(j))}catch(pe){throw console.error(`Encountered an error while loading model file ${j}`),pe}const W=O.model==="v5"?512:1536,re=W/16,ae=new p.FrameProcessor(G.process,G.reset_state,{positiveSpeechThreshold:O.positiveSpeechThreshold,negativeSpeechThreshold:O.negativeSpeechThreshold,redemptionMs:O.redemptionMs,preSpeechPadMs:O.preSpeechPadMs,minSpeechMs:O.minSpeechMs,submitUserSpeechOnPause:O.submitUserSpeechOnPause},re),Z=new w(O,ae,G,W);if(O.startOnLoad)try{await Z.start()}catch(pe){throw console.error("Error starting micVad",pe),pe}return Z}}i.MicVAD=w})(Xa)),Xa}var ox;function oD(){return ox||(ox=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=y1();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=pb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=fb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=Pv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=iD();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=nD();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=rD();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return a.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return a.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return a.getDefaultRealTimeVADOptions}})})(a_)),a_}var aD=oD();function mg(i,e,t,n,r){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,r)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const pt={debug:(i,e,t)=>mg(i,"debug",e,t),info:(i,e,t)=>mg(i,"info",e,t),warn:(i,e,t)=>mg(i,"warn",e,t),error:(i,e,t,n)=>mg(i,"error",e,t,n)},E1=16e3,lD=6,ih=E1*lD,cD=400,dD=E1*cD/1e3,ax=300,lx=2e3,cx=1500,dx=3e3,uD=600,k1=.5,T1=.35,ux=.85,hx=.7;let pr=null,ga=!1,qs=!1;const oy=new Set;function gg(i){for(const e of Array.from(oy))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let u_=0;const px=2;let ph=!1,D1=!1;function A1(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";pt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),hD(`error:${e.message||"unknown"}`)})}function fv(){return pr||(pr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),A1(pr),pt.info("speech","worker spawned"),pr)}let vg=!1;function hD(i){if(!ph){if(vg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(vg=!0,u_+=1,D1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:u_}),gg({reason:i,respawned:!1,finalOnly:!0}),u_>px){if(ph=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:px}),pr)try{pr.terminate()}catch{}pr=null,ga=!1,qs=!1,gg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),vg=!1;return}if(pr)try{pr.terminate()}catch{}pr=null,ga=!1,qs=!1;try{pr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),A1(pr),qs=!0,pr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),gg({reason:i,respawned:!0,finalOnly:!0})}catch(e){ph=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),gg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{vg=!1}}}function pD(i,e){if(ga||qs)return;qs=!0;const t=fv();pt.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(i==null||i(r.data.status,r.data.message),r.data.status==="ready"&&(ga=!0,qs=!1,pt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(qs=!1,pt.error("speech","preloadModel: worker reported error",{error:r.data.error}),i==null||i("error",r.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function fD(){pt.info("speech","resetModel: clearing load flags"),ga=!1,qs=!1}function Rv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function mD(i){const e=fv();return!ga&&!qs&&(qs=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const r=l=>{var p,a,d;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",r),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(l.data.error??"Transcription failed")))):((d=l.data)==null?void 0:d.type)==="status"&&l.data.status==="ready"&&(ga=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function I1(i){let e=fv(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let g=null,m=0,b=!1,T=0,E=!1,k=!1,y=0,S=0,w=0,x=-1,A=ax,O=0,$=null,j="",L="",G=!1,W=0;function re(ge,Te){const je=Math.min(ge.length,Te.length);let Ze=0;for(;Ze<je&&ge.charCodeAt(Ze)===Te.charCodeAt(Ze);)Ze++;return Ze}function ae(ge){const Te=re(j,ge);return j=ge,Te>L.length&&(L=ge.slice(0,Te)),L.length>ge.length&&(L=ge),L}const Z=()=>(g||(g=new Float32Array(ih)),g),pe=()=>{m=0},oe=ge=>{const Te=Z(),je=ge.length;if(je>=ih){Te.set(ge.subarray(je-ih)),m=ih;return}if(m+je<=ih){Te.set(ge,m),m+=je;return}const Ze=m+je-ih;Te.copyWithin(0,Ze,m),m-=Ze,Te.set(ge,m),m+=je},me=()=>{$&&(clearTimeout($),$=null)},we=()=>{me(),b=!1,E=!1,k=!1,A=ax,j="",L="",G=!1,W=0,pe()},ve=()=>{if(t||!b||k||E||$)return;if(m<dD){$=setTimeout(()=>{$=null,ve()},A);return}const ge=performance.now()-y;if(ge<A&&y!==0){$=setTimeout(()=>{$=null,ve()},A-ge);return}if(D1||ph||i.partialsEnabled&&!i.partialsEnabled())return;const Te=Z(),je=new Float32Array(m);je.set(Te.subarray(0,m)),S+=1,w=S,E=!0,O=performance.now(),y=O,e.postMessage({type:"transcribe-partial",audio:je,seq:S},[je.buffer])},F=ge=>ge.length===0?Promise.resolve():ph?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Te=>{d.push(Te),S+=1;const je=S;x=je,e.postMessage({type:"transcribe",audio:ge,seq:je},[ge.buffer])}),J=ge=>{const Te=F(ge);return f.add(Te),Te.finally(()=>{f.delete(Te)}),Te},V=ge=>{var Te,je,Ze,ye,Y;if(ge.data.type==="result"){const _e=ge.data.text,ue=ge.data.seq??0;ue&&ue<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ue,latestFinalSeq:x}),!t&&_e&&i.onFinal(_e),(Te=d.shift())==null||Te()}else if(ge.data.type==="partial"){const _e=ge.data.seq??0,ue=ge.data.text??"",Re=performance.now()-O;E=!1,Re>=dx?(k=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Re),seq:_e})):Re>=cx&&(A=Math.min(A*2,lx),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Re),newIntervalMs:A,seq:_e})),G||(G=!0,Re>uD&&A<500&&(A=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Re),newIntervalMs:500})));const He=_e!==w||_e<=x;if(!t&&!He&&ue){const lt=ae(ue);lt&&((je=i.onPartial)==null||je.call(i,lt),W===0&&(W=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(W-T)})))}ve()}else if(ge.data.type==="partial-error"){const _e=performance.now()-O;E=!1,_e>=dx?(k=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(_e),seq:ge.data.seq})):_e>=cx&&(A=Math.min(A*2,lx),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(_e),newIntervalMs:A,seq:ge.data.seq})),pt.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),ve()}else ge.data.type==="error"?(t||i.onError(ge.data.error),(Ze=d.shift())==null||Ze()):ge.data.type==="status"?(t||(ye=i.onModelStatus)==null||ye.call(i,ge.data.status,ge.data.message),ge.data.status==="ready"&&(ga=!0,qs=!1)):ge.data.type==="progress"&&(t||(Y=i.onProgress)==null||Y.call(i,ge.data.pct))};e.addEventListener("message",V);const se=ge=>{var Te,je;if(!t){for(pt.warn("speech","createRecognition: worker death event",ge),(Te=i.onStatusChange)==null||Te.call(i,"restarting");d.length;)(je=d.shift())==null||je();if(f.clear(),me(),E=!1,ge.respawned){try{e.removeEventListener("message",V)}catch{}e=fv(),e.addEventListener("message",V)}}};return oy.add(se),{start:async()=>{if(!t){if(ph){i.onError("Speech recognition disabled — please reload the app.");return}!ga&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:ga,modelLoading:qs});try{const ge=new URL("vad/",document.baseURI).href;pt.info("speech","vad: asset base resolved",{vadBase:ge}),JT();const Te=i.inputDeviceId||null,je={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Te&&(je.deviceId={exact:Te}),pt.info("speech","getUserMedia",{hasDeviceId:!!Te,deviceIdPrefix:Te?Te.slice(0,8):null});const Ze=await navigator.mediaDevices.getUserMedia({audio:je});r=Ze,l=new AudioContext;for(const ye of Ze.getAudioTracks())ye.addEventListener("ended",()=>{t||(pt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(r),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ye){pt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),a=null,p=null}n=await aD.MicVAD.new({audioContext:l,getStream:async()=>Ze,resumeStream:async()=>Ze,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:k1,negativeSpeechThreshold:T1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,Y)=>{var _e;t||((_e=i.onFrame)==null||_e.call(i,ye),b&&(oe(Y),ve()))},onSpeechStart:()=>{var ye;t||(we(),b=!0,T=performance.now(),(ye=i.onSpeechStart)==null||ye.call(i))},onSpeechEnd:ye=>{var Y;t||((Y=i.onStatusChange)==null||Y.call(i,"transcribing"),we(),J(ye))},onVADMisfire:()=>{var ye,Y;t||((ye=i.onStatusChange)==null||ye.call(i,"idle"),we(),(Y=i.onMisfire)==null||Y.call(i))}}),pt.info("speech","vad: ort wasm files loaded",{files:YT()}),n.start()}catch(ge){const Te=ge instanceof Error?ge.message:"Microphone access denied",je=ge instanceof Error?ge.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:Te,stack:je}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(Ze=>Ze.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(Te)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(we();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ge,Te)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:Te})}catch(je){pt.warn("speech","setVadThresholds failed",{error:je instanceof Error?je.message:String(je)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,we(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}oy.delete(se),e.removeEventListener("message",V)}}}let zf=null;const ay=new Set,ly=new Set;function gD(){for(const i of ay)try{i()}catch{}}function cy(){for(const i of ly)try{i()}catch{}}function vD(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function _D(i){if(!window.speechSynthesis)return;const e=vD(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{zf=performance.now(),gD()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(zf=null,cy())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(zf=null,cy())},window.speechSynthesis.speak(t)}function P1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),zf=null,cy())}function R1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function yD(){return zf}function bD(i){return ay.add(i),()=>{ay.delete(i)}}function wD(i){return ly.add(i),()=>{ly.delete(i)}}function xD(i){R1()&&(i.setVadThresholds(ux,hx),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bD(()=>{i.setVadThresholds(ux,hx),pt.info("voice","tts.duck.on")}),t=wD(()=>{i.setVadThresholds(k1,T1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const SD=[{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 CD(i){const e=i.trim();return SD.find(t=>t.match.test(e))??null}const ED=4e4;let hd=null;function fh(){hd&&clearTimeout(hd),hd=setTimeout(()=>{hd=null,Ct.getState().stopRecording()},ED)}function _g(){hd&&(clearTimeout(hd),hd=null)}let ic=null,Zl=null;const kD=.04,TD=.3;let mv=0,dy=0;function DD(i){Zl!==null&&cancelAnimationFrame(Zl);const e=()=>{if(ic===null||Ct.getState().submitCountdownStartAt===null){Zl=null;return}const t=performance.now();if(t-dy<200&&mv>TD){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:mv.toFixed(2),msIntoCountdown:Math.round(r)}),Xl(),fh();return}const n=O1();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let l=0;for(let a=0;a<r.length;a++){const d=(r[a]-128)/128;l+=d*d}const p=Math.sqrt(l/r.length);if(p>kD){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Xl(),fh();return}}Zl=requestAnimationFrame(e)};Zl=requestAnimationFrame(e)}function fx(i){ic&&clearTimeout(ic);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),ic=setTimeout(()=>{var r;ic=null,Ct.setState({submitCountdownStartAt:null});const n=St.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=pi.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(pi.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),pi.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){pt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}fh()},e),DD(t)}function Xl(){Zl!==null&&(cancelAnimationFrame(Zl),Zl=null),ic&&(clearTimeout(ic),ic=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let rs=null,Is=null,ff=null;function O1(){var i;return((i=rs==null?void 0:rs.getAnalyser)==null?void 0:i.call(rs))??null}const yg=1e4;let Bf=null;function bg(){Bf&&(clearTimeout(Bf),Bf=null)}let Qg=null,ev=null;function wg(){Qg=null,ev&&(ev(),ev=null)}const AD=1500,ID=9e4;let xg=0,tv=null,uy=-1;function Sg(){tv&&(clearTimeout(tv),tv=null,uy=-1)}const PD=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=Un((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++xg,n=()=>{t===xg&&(Sg(),uy=t,tv=setTimeout(()=>{uy===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},ID))};n(),pD((r,l)=>{t===xg&&(r==="ready"?(Sg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(Sg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===xg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),Sg(),fD(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(rs){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Rv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=I1({inputDeviceId:l,onStatusChange:a=>{i(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&i({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{mv=a.isSpeech,dy=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),_g(),Xl(),R1()){const d=yD(),f=d!==null?performance.now()-d:null;P1(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else pt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),fh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&pt.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var b;fh();const d=a.trim();if(!d||PD.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(ff){ff(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=St.getState().tabs.find(T=>T.id===t))==null?void 0:b.status)==="dormant"){pi.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&fx(t);const T=window;T.__transcripts&&(T.__transcripts.push({tabId:t,text:d}),T.__transcripts.length>500&&T.__transcripts.shift());return}const g=CD(d);if(g){pt.info("voice","voice-command",{tabId:t,label:g.label,transcript:d}),window.api.pty.write({tabId:t,data:g.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Xl();const T=window;T.__transcripts&&(T.__transcripts.push({tabId:t,text:d}),T.__transcripts.length>500&&T.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&fx(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{pt.error("voice","recognition error",{err:a}),Xl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,_g(),rs==null||rs.destroy(),rs=null,ff=null,nt.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?i({modelStatus:"ready",loadingProgress:100}):a==="loading"&&i({modelStatus:"loading"})},onProgress:a=>i({loadingProgress:Math.round(a)})});rs=p,ff=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),fh(),p.start().then(()=>{rs===p&&(Is==null||Is(),Is=xD(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),nt.error(`Could not start mic: ${d}`)})}catch(p){i({error:p instanceof Error?p.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,p,a;return((a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.getDevicePref)==null?void 0:a.call(p))??Promise.resolve(null)}).then(l=>r((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{pt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=rs;t&&(_g(),Xl(),mv=0,dy=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),rs===t&&(rs=null,ff=null),e().hotkeyState==="stopping"&&(bg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=rs;if(!t)return;_g(),Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){pt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),rs===t&&(rs=null);const{useSessions:n}=await Bn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>OT);return{useSessions:l}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},setExternalRecording:t=>i({externalRecording:t}),toggleTTS:()=>i(t=>({ttsEnabled:!t.ttsEnabled})),setAutoSubmit:t=>i({autoSubmit:t}),setSubmitDelayMs:t=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(t)))}),cancelSubmit:()=>Xl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(pt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:t}),i({permissionState:t}))},setLevelMeterEnabled:t=>{e().levelMeterEnabled!==t&&i({levelMeterEnabled:t})},setTurnDetectorRuntimeState:t=>{e().turnDetectorState!==t&&(i({turnDetectorState:t}),t==="load_failed"?pt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&&pt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:t=>{e().wizardArmed!==t&&i({wizardArmed:t})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:t,source:n,mode:r,tabId:l})=>{const p=e(),{canRecord:a,reason:d}=gv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){pt.warn("voice-hotkey","miss-model-loading",{modelStatus:p.modelStatus,reason:d});return}if(p.hotkeyState==="recording"||p.isRecording){(r==="toggle"||n==="global")&&(i({hotkeyState:"stopping"}),bg(),Bf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:yg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},yg),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),wg(),Qg={tabId:l,source:n,mode:r},ev=Ct.subscribe((f,g)=>{if(Qg&&f.modelStatus==="ready"&&g.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Qg;if(wg(),!m.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),Ct.getState().startRecording(m.tabId)}});return}if(!l){pt.warn("voice-hotkey","no-active-tab",{source:n});return}pt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){wg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),bg(),Bf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:yg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},yg),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(wg(),Xl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(bg(),i({hotkeyState:"destroyed"}))}})),RD=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),gv=i=>Rv()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=Ct,i.__transcripts=[]}const Yf=6e4,OD=3e5,LD=.25,$D=5e3,Jf=Un(()=>({data:null,refreshing:!1}));let mx=!1,iv=null,h_=Yf,Cg=!1,Za=null;function ND(i,e){if(i.kind==="ok")return{delayMs:Yf,nextBackoffMs:Yf};const t=Math.min(e*2,OD),n=t*LD;let r=t+(Math.random()*2-1)*n;const l=i.kind==="meter_rate_limited"?i.retryAfterMs:void 0;return typeof l=="number"&&Number.isFinite(l)&&l>r&&(r=l),{delayMs:r,nextBackoffMs:t}}function gx(){return n1(window.api.billing.fetch(),$D,"billing.fetch")}function vx(i){Jf.setState({data:i,refreshing:!1})}async function mb(){Jf.setState({refreshing:!0});let i=Yf;try{const e=await gx();Za&&(Za.cancel(),Za=null),vx(e);const{delayMs:t,nextBackoffMs:n}=ND(e,h_);h_=n,i=t}catch(e){h_=Yf,Jf.setState({refreshing:!1});const t=s1({error:e,retry:gx,onRetrySuccess:n=>{Za=null,vx(n)},onStillFailing:n=>{Za=null,Cg||(Cg=!0,nt.warn(`Billing usage fetch: ${n}`))}});if(t)Za=t;else if(!Cg){Cg=!0;const n=e instanceof Error?e.message:String(e);nt.warn(`Billing usage fetch failed: ${n}`)}}iv=setTimeout(mb,i)}function MD(){mx||(mx=!0,mb())}function L1(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function jD(){iv!==null&&(clearTimeout(iv),iv=null),Za&&(Za.cancel(),Za=null),mb()}function Zf(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),r=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${r} ${e[1]}`:`${n} ${r}`}function Qa(i){const e=/(opus|sonnet|haiku|fable)/i.exec(i);return e?e[1].toLowerCase():null}const Eg=new Map,zD=3e4;function gb(i){const[e,t]=B.useState(()=>{var n;return i?((n=Eg.get(i))==null?void 0:n.value)??null:null});return B.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=Eg.get(i);if(l&&Date.now()-l.ts<zD){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;Eg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;Eg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function BD(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:r})=>({key:e,label:t,icon:n,hint:r}))}const hy="sm.almanac.sidebarWidth",$1=180,N1=480,py=252;function UD(){try{const i=parseInt(localStorage.getItem(hy)??"",10);if(Number.isFinite(i))return Math.min(N1,Math.max($1,i))}catch{}return py}const GD=52,M1="sm.almanac.sidebarCollapsed";function HD(){try{return localStorage.getItem(M1)==="1"}catch{}return!1}const j1="sm.almanac.collapsedGroups";function FD(){try{const i=localStorage.getItem(j1);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(t=>t==="Workspace"||t==="Configure"||t==="Tools")):new Set}catch{return new Set}}function WD(){const i=St(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Nr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function VD({active:i,onNavigate:e,onNewSession:t}){const[n,r]=B.useState(()=>FD()),l=B.useCallback(L=>{r(G=>{const W=new Set(G);W.has(L)?W.delete(L):W.add(L);try{localStorage.setItem(j1,JSON.stringify(Array.from(W)))}catch{}return W})},[]),[p,a]=B.useState(()=>HD()),d=B.useCallback(()=>{a(L=>{const G=!L;try{localStorage.setItem(M1,G?"1":"0")}catch{}return G})},[]),f=St(L=>L.tabs),g=St(L=>L.activeTabId),m=f.find(L=>L.id===g)??null,b=WD(),T=Ii(L=>L.navFace),E=MT(T),k=E.filter(L=>L.group==="Workspace"),y=E.filter(L=>L.group==="Configure"),S=BD(E),w=T==="home"&&!p,[x,A]=B.useState(()=>UD()),O=B.useRef(x);O.current=x;const $=B.useCallback(L=>{L.preventDefault();const G=L.clientX,W=O.current;let re=W;const ae=pe=>{re=Math.min(N1,Math.max($1,W+(pe.clientX-G))),A(re)},Z=()=>{window.removeEventListener("pointermove",ae),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(hy,String(re))}catch{}};window.addEventListener("pointermove",ae),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=B.useCallback(()=>{A(py);try{localStorage.setItem(hy,String(py))}catch{}},[]);return c.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?GD:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[c.jsx(qD,{tab:m,navFace:T,onNewSession:t,rail:p,onToggleRail:d}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:w?c.jsxs(c.Fragment,{children:[c.jsx(p_,{label:"Workspace",desc:o_.Workspace,collapsed:n.has("Workspace"),count:k.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&k.map(L=>c.jsx(f_,{item:L,active:i===L.key,live:L.liveKind?b[L.liveKind]:!1,onClick:()=>e(L.key),rail:!1},L.key)),c.jsx(p_,{label:"Configure",desc:o_.Configure,collapsed:n.has("Configure"),count:y.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&y.map(L=>c.jsx(f_,{item:L,active:i===L.key,live:!1,onClick:()=>e(L.key),rail:!1},L.key)),S.length>0&&c.jsx(p_,{label:"Tools",desc:o_.Tools,collapsed:n.has("Tools"),count:S.length,onToggle:()=>l("Tools")}),S.length>0&&!n.has("Tools")&&S.map(L=>c.jsx(_x,{tool:L,active:i===L.key,onClick:()=>e(L.key),rail:!1},L.key))]}):c.jsx("div",{className:"pt-2",children:E.map(L=>L.group==="Tools"?c.jsx(_x,{tool:{key:L.key,label:L.label,icon:L.icon,hint:L.hint},active:i===L.key,onClick:()=>e(L.key),rail:p},L.key):c.jsx(f_,{item:L,active:i===L.key,live:L.liveKind?b[L.liveKind]:!1,onClick:()=>e(L.key),rail:p},L.key))})}),c.jsx(KD,{rail:p,navFace:T}),!p&&c.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:$,onDoubleClick:j,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 qD({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=gb((i==null?void 0:i.cwd)??null);return n?c.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[c.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:c.jsx(Vs,{name:"plus",size:15,stroke:1.8})}),c.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:c.jsx(Vs,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?c.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),c.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:c.jsx(Vs,{name:"chevron",size:13,stroke:1.8})})})]}),c.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:c.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:[c.jsx(Vs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):c.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),c.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:c.jsx(Vs,{name:"chevron",size:13,stroke:1.8})})})]}),c.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[c.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),c.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),c.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),c.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:c.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:[c.jsx(Vs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function p_({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return c.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[c.jsxs("button",{onClick:r,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[c.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),c.jsx("span",{className:"flex-1",children:i}),t&&c.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&c.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 f_({item:i,active:e,live:t,onClick:n,rail:r}){return c.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&c.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),c.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:c.jsx(Vs,{name:i.icon,size:17,stroke:1.6})}),!r&&c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsx("span",{className:"block truncate",children:i.label}),i.hint&&c.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&c.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&c.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 _x({tool:i,active:e,onClick:t,rail:n}){return c.jsxs("button",{onClick:t,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${n?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&c.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),c.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:c.jsx(Vs,{name:i.icon,size:15,stroke:1.6})}),!n&&c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsx("span",{className:"block truncate",children:i.label}),i.hint&&c.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function KD({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=St(d=>d.tabs),r=St(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=B.useState(null);return B.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return YS(l.presetId).then(f=>{d||a((f==null?void 0:f.model)??null)}).catch(()=>{d||a(null)}),()=>{d=!0}},[l==null?void 0:l.presetId]),i?c.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):c.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:[c.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")&&c.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Zf(p)}`:"Claude Code"})]})}const Cn={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},XD={dialog:50};function YD(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function JD(i,e,t){return{tabId:i,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function ZD(i,e,t){const n=Date.now(),r={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,d)=>a.length>d?a.slice(0,d-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];r.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,d=a.input,f={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])d&&g in d&&(f[g]=d[g]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),b=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,T=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,E=b?b.split("/").pop()??b:T?p(T,28):"";l.push({id:0,kind:"tool-use",at:n,label:E?`${a.name} · ${E}`:a.name,target:b??T,toolName:a.name}),m&&b&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(b.split("/").pop()??b,34)}`,target:b,toolName:a.name})}break}case"plan":{const a=e.data,d=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);r.plans=[{at:n,content:d??""},...i.plans].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"plan-revision",at:n,label:"Plan revised"});break}case"agent_spawn":{const a=e.data;r.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,d=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,g=a.output_tokens??a.outputTokens??0,m=d+f+g;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+g,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(d/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const a=e.data;r.agents=YD(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const nv=Un((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,r)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:JD(t,n,r)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:r}).then(async a=>{const d=e().tabs[t];if(!d)return;if(!a.ok){const{toast:g}=await Bn(async()=>{const{toast:m}=await Promise.resolve().then(()=>e1);return{toast:m}},void 0,import.meta.url);g.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...d,path:null}}});return}i({tabs:{...e().tabs,[t]:{...d,path:a.path}}});const f=await window.api.transcripts.buffer(t);e().ingestBatch(t,f,{replay:!0})}).catch(a=>console.error("[live] transcripts.subscribe failed:",t,a))},unsubscribe:t=>{const n={...e().refs};if(!n[t])return;if(n[t]--,n[t]>0){i({refs:n});return}delete n[t];const r=e().unsubs[t];r==null||r();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,r)=>{e().ingestBatch(t,[n],r)},ingestBatch:(t,n,r)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const d of n){const{next:f,newActivity:g}=ZD(p,d,r);p=f,a=a.concat(g)}if(a.length>0){let d=l.activitySeq;const f=a.map(g=>({...g,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function QD(i){const e=nv(r=>r.subscribe),t=nv(r=>r.unsubscribe),n=nv(r=>i?r.tabs[i.id]:void 0);return B.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>t(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,t]),n}function z1(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${r}h`:r>0?`${r}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function fy(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function yx(i,e){const t=fy(e);if(t==null)return`${i} — usage unavailable`;const n=z1((e==null?void 0:e.resets_at)??null),r=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${r} — click to open Home`}const B1=B.createContext(null);function e2({panelId:i,children:e}){return c.jsx(B1.Provider,{value:i,children:e})}function Ov(i){const e=B.useContext(B1),t=i??e;return Ii(n=>t==null||n.focusedPanelId===t)}function vb(i){const e=Ov(i),t=B.useRef(e);return t.current=e,t}const t2=5e3;let U1=null;const my=new Set;let m_=0,Uf=null;function i2(){my.forEach(i=>i())}async function bx(){try{U1=await window.api.schedule.sessionSlots(),i2()}catch{}}function n2(){Uf==null&&(bx(),Uf=setInterval(()=>{bx()},t2))}function s2(){Uf!=null&&(clearInterval(Uf),Uf=null)}function _b(i){const e=Ov(i),[,t]=B.useState(0);return B.useEffect(()=>{const n=()=>t(r=>r+1);return my.add(n),()=>{my.delete(n)}},[]),B.useEffect(()=>{if(e)return m_+=1,n2(),()=>{m_-=1,m_<=0&&s2()}},[e]),U1}const r2=360*60*1e3;let G1=null;const gy=new Set;let g_=0,Gf=null;async function wx(){try{G1=await window.api.app.updateStatus(),gy.forEach(i=>i())}catch{}}function o2(){Gf==null&&(wx(),Gf=setInterval(()=>{wx()},r2))}function a2(){Gf!=null&&(clearInterval(Gf),Gf=null)}function l2(){const[,i]=B.useState(0);return B.useEffect(()=>{const e=()=>i(t=>t+1);return gy.add(e),g_+=1,o2(),()=>{gy.delete(e),g_-=1,g_<=0&&a2()}},[]),G1}function c2({total:i,inUse:e,size:t}){const n=Math.min(Math.max(e,0),i),r=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return c.jsx(c.Fragment,{children:Array.from({length:i},(l,p)=>c.jsx("span",{"data-testid":"slot-dot","data-filled":p<n?"true":"false",className:`${r} ${p<n?"bg-accent border-accent":"bg-bg border-line"}`},p))})}function d2({onNavigate:i}){const e=St(ae=>ae.tabs),t=St(ae=>ae.activeTabId),n=e.find(ae=>ae.id===t)??null,r=QD(n),l=(r==null?void 0:r.lastEventAt)??0,p=Jf(ae=>ae.data),a=Nr(ae=>{var Z;return((Z=ae.snapshot)==null?void 0:Z.paused)??null}),d=gb((n==null?void 0:n.cwd)??null),f=_b(),g=l2(),[,m]=B.useState(0);B.useEffect(()=>{const ae=setInterval(()=>m(Z=>Z+1),6e4);return()=>clearInterval(ae)},[]);const b=(r==null?void 0:r.todos)??[],[T,E]=B.useState(!1),k=B.useRef(null);B.useEffect(()=>{if(!T)return;const ae=Z=>{k.current&&!k.current.contains(Z.target)&&E(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[T]),B.useEffect(()=>{b.length===0&&E(!1)},[b.length]);const y=L1(p),S=(y==null?void 0:y.usage.five_hour)??null,w=(y==null?void 0:y.usage.seven_day)??null,x=fy(S),A=fy(w),O=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",$=l>0?p2(Date.now()-l):"—",j=(f==null?void 0:f.total)??5,L=f?Math.min(Math.max(f.inUse,0),f.total):0,G=f?`${L} / ${j}`:`— / ${j}`,W=f&&f.holders.length>0?`
2910
+ */var sx;function sD(){return sx||(sx=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(X=>typeof io<"u"?io:typeof Proxy<"u"?new Proxy(X,{get:(ne,he)=>(typeof io<"u"?io:ne)[he]}):X)(function(X){if(typeof io<"u")return io.apply(this,arguments);throw Error('Dynamic require of "'+X+'" is not supported')}),d=(X,ne)=>()=>(X&&(ne=X(X=0)),ne),f=(X,ne)=>{for(var he in ne)n(X,he,{get:ne[he],enumerable:!0})},g=(X,ne,he,De)=>{if(ne&&typeof ne=="object"||typeof ne=="function")for(let Se of l(ne))!p.call(X,Se)&&Se!==he&&n(X,Se,{get:()=>ne[Se],enumerable:!(De=r(ne,Se))||De.enumerable});return X},m=X=>g(n({},"__esModule",{value:!0}),X),b,T,E,k,y,S=d(()=>{b=new Map,T=[],E=(X,ne,he)=>{if(ne&&typeof ne.init=="function"&&typeof ne.createInferenceSessionHandler=="function"){let De=b.get(X);if(De===void 0)b.set(X,{backend:ne,priority:he});else{if(De.priority>he)return;if(De.priority===he&&De.backend!==ne)throw new Error(`cannot register backend "${X}" using priority ${he}`)}if(he>=0){let Se=T.indexOf(X);Se!==-1&&T.splice(Se,1);for(let Me=0;Me<T.length;Me++)if(b.get(T[Me]).priority<=he){T.splice(Me,0,X);return}T.push(X)}return}throw new TypeError("not a valid backend")},k=async X=>{let ne=b.get(X);if(!ne)return"backend not found.";if(ne.initialized)return ne.backend;if(ne.aborted)return ne.error;{let he=!!ne.initPromise;try{return he||(ne.initPromise=ne.backend.init(X)),await ne.initPromise,ne.initialized=!0,ne.backend}catch(De){return he||(ne.error=`${De}`,ne.aborted=!0),ne.error}finally{delete ne.initPromise}}},y=async X=>{let ne=X.executionProviders||[],he=ne.map(ze=>typeof ze=="string"?ze:ze.name),De=he.length===0?T:he,Se,Me=[],Ie=new Set;for(let ze of De){let et=await k(ze);typeof et=="string"?Me.push({name:ze,err:et}):(Se||(Se=et),Se===et&&Ie.add(ze))}if(!Se)throw new Error(`no available backend found. ERR: ${Me.map(ze=>`[${ze.name}] ${ze.err}`).join(", ")}`);for(let{name:ze,err:et}of Me)he.includes(ze)&&console.warn(`removing requested execution provider "${ze}" from session options because it is not available: ${et}`);let Pe=ne.filter(ze=>Ie.has(typeof ze=="string"?ze:ze.name));return[Se,new Proxy(X,{get:(ze,et)=>et==="executionProviders"?Pe:Reflect.get(ze,et)})]}}),w=d(()=>{S()}),x,A=d(()=>{x="1.26.0"}),O,$,j=d(()=>{A(),O="warning",$={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(X){if(X!==void 0){if(typeof X!="string"||["verbose","info","warning","error","fatal"].indexOf(X)===-1)throw new Error(`Unsupported logging level: ${X}`);O=X}},get logLevel(){return O}},Object.defineProperty($,"logLevel",{enumerable:!0})}),L,G=d(()=>{j(),L=$}),W,re,ae=d(()=>{W=(X,ne)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=X.dims[3],he.height=X.dims[2];let De=he.getContext("2d");if(De!=null){let Se,Me;(ne==null?void 0:ne.tensorLayout)!==void 0&&ne.tensorLayout==="NHWC"?(Se=X.dims[2],Me=X.dims[3]):(Se=X.dims[3],Me=X.dims[2]);let Ie=(ne==null?void 0:ne.format)!==void 0?ne.format:"RGB",Pe=ne==null?void 0:ne.norm,ze,et;Pe===void 0||Pe.mean===void 0?ze=[255,255,255,255]:typeof Pe.mean=="number"?ze=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(ze=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(ze[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?et=[0,0,0,0]:typeof Pe.bias=="number"?et=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(et=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(et[3]=Pe.bias[3]));let rt=Me*Se,it=0,Xe=rt,Pt=rt*2,Ne=-1;Ie==="RGBA"?(it=0,Xe=rt,Pt=rt*2,Ne=rt*3):Ie==="RGB"?(it=0,Xe=rt,Pt=rt*2):Ie==="RBG"&&(it=0,Pt=rt,Xe=rt*2);for(let ut=0;ut<Me;ut++)for(let Di=0;Di<Se;Di++){let Zt=(X.data[it++]-et[0])*ze[0],Qt=(X.data[Xe++]-et[1])*ze[1],Ai=(X.data[Pt++]-et[2])*ze[2],Mt=Ne===-1?255:(X.data[Ne++]-et[3])*ze[3];De.fillStyle="rgba("+Zt+","+Qt+","+Ai+","+Mt+")",De.fillRect(Di,ut,1,1)}if("toDataURL"in he)return he.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},re=(X,ne)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(he!=null){let Se,Me,Ie;(ne==null?void 0:ne.tensorLayout)!==void 0&&ne.tensorLayout==="NHWC"?(Se=X.dims[2],Me=X.dims[1],Ie=X.dims[3]):(Se=X.dims[3],Me=X.dims[2],Ie=X.dims[1]);let Pe=ne!==void 0&&ne.format!==void 0?ne.format:"RGB",ze=ne==null?void 0:ne.norm,et,rt;ze===void 0||ze.mean===void 0?et=[255,255,255,255]:typeof ze.mean=="number"?et=[ze.mean,ze.mean,ze.mean,ze.mean]:(et=[ze.mean[0],ze.mean[1],ze.mean[2],255],ze.mean[3]!==void 0&&(et[3]=ze.mean[3])),ze===void 0||ze.bias===void 0?rt=[0,0,0,0]:typeof ze.bias=="number"?rt=[ze.bias,ze.bias,ze.bias,ze.bias]:(rt=[ze.bias[0],ze.bias[1],ze.bias[2],0],ze.bias[3]!==void 0&&(rt[3]=ze.bias[3]));let it=Me*Se;if(ne!==void 0&&(ne.format!==void 0&&Ie===4&&ne.format!=="RGBA"||Ie===3&&ne.format!=="RGB"&&ne.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,Pt=0,Ne=1,ut=2,Di=3,Zt=0,Qt=it,Ai=it*2,Mt=-1;Pe==="RGBA"?(Zt=0,Qt=it,Ai=it*2,Mt=it*3):Pe==="RGB"?(Zt=0,Qt=it,Ai=it*2):Pe==="RBG"&&(Zt=0,Ai=it,Qt=it*2),De=he.createImageData(Se,Me);for(let Mi=0;Mi<Me*Se;Pt+=Xe,Ne+=Xe,ut+=Xe,Di+=Xe,Mi++)De.data[Pt]=(X.data[Zt++]-rt[0])*et[0],De.data[Ne]=(X.data[Qt++]-rt[1])*et[1],De.data[ut]=(X.data[Ai++]-rt[2])*et[2],De.data[Di]=Mt===-1?255:(X.data[Mt++]-rt[3])*et[3]}else throw new Error("Can not access image data");return De}}),Z,pe,oe,me,we,ve,F=d(()=>{_e(),Z=(X,ne)=>{if(X===void 0)throw new Error("Image buffer must be defined");if(ne.height===void 0||ne.width===void 0)throw new Error("Image height and width must be defined");if(ne.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:he,width:De}=ne,Se=ne.norm??{mean:255,bias:0},Me,Ie;typeof Se.mean=="number"?Me=[Se.mean,Se.mean,Se.mean,Se.mean]:Me=[Se.mean[0],Se.mean[1],Se.mean[2],Se.mean[3]??255],typeof Se.bias=="number"?Ie=[Se.bias,Se.bias,Se.bias,Se.bias]:Ie=[Se.bias[0],Se.bias[1],Se.bias[2],Se.bias[3]??0];let Pe=ne.format!==void 0?ne.format:"RGBA",ze=ne.tensorFormat!==void 0&&ne.tensorFormat!==void 0?ne.tensorFormat:"RGB",et=he*De,rt=ze==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),it=4,Xe=0,Pt=1,Ne=2,ut=3,Di=0,Zt=et,Qt=et*2,Ai=-1;Pe==="RGB"&&(it=3,Xe=0,Pt=1,Ne=2,ut=-1),ze==="RGBA"?Ai=et*3:ze==="RBG"?(Di=0,Qt=et,Zt=et*2):ze==="BGR"&&(Qt=0,Zt=et,Di=et*2);for(let Mt=0;Mt<et;Mt++,Xe+=it,Ne+=it,Pt+=it,ut+=it)rt[Di++]=(X[Xe]+Ie[0])/Me[0],rt[Zt++]=(X[Pt]+Ie[1])/Me[1],rt[Qt++]=(X[Ne]+Ie[2])/Me[2],Ai!==-1&&ut!==-1&&(rt[Ai++]=(X[ut]+Ie[3])/Me[3]);return ze==="RGBA"?new Y("float32",rt,[1,4,he,De]):new Y("float32",rt,[1,3,he,De])},pe=async(X,ne)=>{let he=typeof HTMLImageElement<"u"&&X instanceof HTMLImageElement,De=typeof ImageData<"u"&&X instanceof ImageData,Se=typeof ImageBitmap<"u"&&X instanceof ImageBitmap,Me=typeof X=="string",Ie,Pe=ne??{},ze=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=ze();rt.width=X.width,rt.height=X.height;let it=et(rt);if(it!=null){let Xe=X.height,Pt=X.width;if(ne!==void 0&&ne.resizedHeight!==void 0&&ne.resizedWidth!==void 0&&(Xe=ne.resizedHeight,Pt=ne.resizedWidth),ne!==void 0){if(Pe=ne,ne.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=Pt}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=Pt;it.drawImage(X,0,0),Ie=it.getImageData(0,0,Pt,Xe).data}else throw new Error("Can not access image data")}else if(De){let rt,it;if(ne!==void 0&&ne.resizedWidth!==void 0&&ne.resizedHeight!==void 0?(rt=ne.resizedHeight,it=ne.resizedWidth):(rt=X.height,it=X.width),ne!==void 0&&(Pe=ne),Pe.format="RGBA",Pe.height=rt,Pe.width=it,ne!==void 0){let Xe=ze();Xe.width=it,Xe.height=rt;let Pt=et(Xe);if(Pt!=null)Pt.putImageData(X,0,0),Ie=Pt.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else Ie=X.data}else if(Se){if(ne===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=ze();rt.width=X.width,rt.height=X.height;let it=et(rt);if(it!=null){let Xe=X.height,Pt=X.width;return it.drawImage(X,0,0,Pt,Xe),Ie=it.getImageData(0,0,Pt,Xe).data,Pe.height=Xe,Pe.width=Pt,Z(Ie,Pe)}else throw new Error("Can not access image data")}else{if(Me)return new Promise((rt,it)=>{let Xe=ze(),Pt=et(Xe);if(!X||!Pt)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=X,Ne.onload=()=>{Xe.width=Ne.width,Xe.height=Ne.height,Pt.drawImage(Ne,0,0,Xe.width,Xe.height);let ut=Pt.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,rt(Z(ut.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Ie!==void 0)return Z(Ie,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},oe=(X,ne)=>{let{width:he,height:De,download:Se,dispose:Me}=ne,Ie=[1,De,he,4];return new Y({location:"texture",type:"float32",texture:X,dims:Ie,download:Se,dispose:Me})},me=(X,ne)=>{let{dataType:he,dims:De,download:Se,dispose:Me}=ne;return new Y({location:"gpu-buffer",type:he??"float32",gpuBuffer:X,dims:De,download:Se,dispose:Me})},we=(X,ne)=>{let{dataType:he,dims:De,download:Se,dispose:Me}=ne;return new Y({location:"ml-tensor",type:he??"float32",mlTensor:X,dims:De,download:Se,dispose:Me})},ve=(X,ne,he)=>new Y({location:"cpu-pinned",type:X,data:ne,dims:he??[ne.length]})}),J,V,se,ge,Te=d(()=>{J=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),V=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),se=!1,ge=()=>{if(!se){se=!0;let X=typeof BigInt64Array<"u"&&BigInt64Array.from,ne=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,De=typeof he<"u"&&he.from;X&&(J.set("int64",BigInt64Array),V.set(BigInt64Array,"int64")),ne&&(J.set("uint64",BigUint64Array),V.set(BigUint64Array,"uint64")),De?(J.set("float16",he),V.set(he,"float16")):J.set("float16",Uint16Array)}}}),je,Ze,ye=d(()=>{_e(),je=X=>{let ne=1;for(let he=0;he<X.length;he++){let De=X[he];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${he}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${De}`);ne*=De}return ne},Ze=(X,ne)=>{switch(X.location){case"cpu":return new Y(X.type,X.data,ne);case"cpu-pinned":return new Y({location:"cpu-pinned",data:X.data,type:X.type,dims:ne});case"texture":return new Y({location:"texture",texture:X.texture,type:X.type,dims:ne});case"gpu-buffer":return new Y({location:"gpu-buffer",gpuBuffer:X.gpuBuffer,type:X.type,dims:ne});case"ml-tensor":return new Y({location:"ml-tensor",mlTensor:X.mlTensor,type:X.type,dims:ne});default:throw new Error(`tensorReshape: tensor location ${X.location} is not supported`)}}}),Y,_e=d(()=>{ae(),F(),Te(),ye(),Y=class{constructor(X,ne,he){ge();let De,Se;if(typeof X=="object"&&"location"in X)switch(this.dataLocation=X.location,De=X.type,Se=X.dims,X.location){case"cpu-pinned":{let Ie=J.get(De);if(!Ie)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(X.data instanceof Ie))throw new TypeError(`buffer should be of type ${Ie.name}`);this.cpuData=X.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=X.texture,this.downloader=X.download,this.disposer=X.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=X.gpuBuffer,this.downloader=X.download,this.disposer=X.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=X.mlTensor,this.downloader=X.download,this.disposer=X.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Ie,Pe;if(typeof X=="string")if(De=X,Pe=he,X==="string"){if(!Array.isArray(ne))throw new TypeError("A string tensor's data must be a string array.");Ie=ne}else{let ze=J.get(X);if(ze===void 0)throw new TypeError(`Unsupported tensor type: ${X}.`);if(Array.isArray(ne)){if(X==="float16"&&ze===Uint16Array||X==="uint4"||X==="int4")throw new TypeError(`Creating a ${X} tensor from number array is not supported. Please use ${ze.name} as data.`);X==="uint64"||X==="int64"?Ie=ze.from(ne,BigInt):Ie=ze.from(ne)}else if(ne instanceof ze)Ie=ne;else if(ne instanceof Uint8ClampedArray)if(X==="uint8")Ie=Uint8Array.from(ne);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(X==="float16"&&ne instanceof Uint16Array&&ze!==Uint16Array)Ie=new globalThis.Float16Array(ne.buffer,ne.byteOffset,ne.length);else throw new TypeError(`A ${De} tensor's data must be type of ${ze}`)}else if(Pe=ne,Array.isArray(X)){if(X.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let ze=typeof X[0];if(ze==="string")De="string",Ie=X;else if(ze==="boolean")De="bool",Ie=Uint8Array.from(X);else throw new TypeError(`Invalid element type of data array: ${ze}.`)}else if(X instanceof Uint8ClampedArray)De="uint8",Ie=Uint8Array.from(X);else{let ze=V.get(X.constructor);if(ze===void 0)throw new TypeError(`Unsupported type for tensor data: ${X.constructor}.`);De=ze,Ie=X}if(Pe===void 0)Pe=[Ie.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Se=Pe,this.cpuData=Ie,this.dataLocation="cpu"}let Me=je(Se);if(this.cpuData&&Me!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Me/2)===this.cpuData.length))throw new Error(`Tensor's size(${Me}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Se,this.size=Me}static async fromImage(X,ne){return pe(X,ne)}static fromTexture(X,ne){return oe(X,ne)}static fromGpuBuffer(X,ne){return me(X,ne)}static fromMLTensor(X,ne){return we(X,ne)}static fromPinnedBuffer(X,ne,he){return ve(X,ne,he)}toDataURL(X){return W(this,X)}toImageData(X){return re(this,X)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(X){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let ne=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=ne,X&&this.disposer&&(this.disposer(),this.disposer=void 0),ne}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(X){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Ze(this,X)}}}),ue,Re=d(()=>{_e(),ue=Y}),He,lt,It,ct,qt,qe,Rt=d(()=>{j(),He=(X,ne)=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeStamp(`${X}::ORT::${ne}`)},lt=(X,ne)=>{var Se;let he=((Se=new Error().stack)==null?void 0:Se.split(/\r\n|\r|\n/g))||[],De=!1;for(let Me=0;Me<he.length;Me++){if(De&&!he[Me].includes("TRACE_FUNC")){let Ie=`FUNC_${X}::${he[Me].trim().split(" ")[1]}`;ne&&(Ie+=`::${ne}`),He("CPU",Ie);return}he[Me].includes("TRACE_FUNC")&&(De=!0)}},It=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||lt("BEGIN",X)},ct=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||lt("END",X)},qt=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.time(`ORT::${X}`)},qe=X=>{(typeof $.trace>"u"?!$.wasm.trace:!$.trace)||console.timeEnd(`ORT::${X}`)}}),_t,ni=d(()=>{S(),Re(),Rt(),_t=class C1{constructor(ne){this.handler=ne}async run(ne,he,De){It(),qt("InferenceSession.run");let Se={},Me={};if(typeof ne!="object"||ne===null||ne instanceof ue||Array.isArray(ne))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Ie=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof ue)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(he)){if(he.length===0)throw new TypeError("'fetches' cannot be an empty array.");Ie=!1;for(let et of he){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Se[et]=null}if(typeof De=="object"&&De!==null)Me=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let Xe=he[it];(Xe===null||Xe instanceof ue)&&(et=!0,Ie=!1,Se[it]=Xe)}if(et){if(typeof De=="object"&&De!==null)Me=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Me=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof ne[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Ie)for(let et of this.outputNames)Se[et]=null;let Pe=await this.handler.run(ne,Se,Me),ze={};for(let et in Pe)if(Object.hasOwnProperty.call(Pe,et)){let rt=Pe[et];rt instanceof ue?ze[et]=rt:ze[et]=new ue(rt.type,rt.data,rt.dims)}return qe("InferenceSession.run"),ct(),ze}async release(){return this.handler.dispose()}static async create(ne,he,De,Se){It(),qt("InferenceSession.create");let Me,Ie={};if(typeof ne=="string"){if(Me=ne,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(ne instanceof Uint8Array){if(Me=ne,typeof he=="object"&&he!==null)Ie=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(ne instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&ne instanceof SharedArrayBuffer){let rt=ne,it=0,Xe=ne.byteLength;if(typeof he=="object"&&he!==null)Ie=he;else if(typeof he=="number"){if(it=he,!Number.isSafeInteger(it))throw new RangeError("'byteOffset' must be an integer.");if(it<0||it>=rt.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${rt.byteLength}).`);if(Xe=ne.byteLength-it,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||it+Xe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof Se=="object"&&Se!==null)Ie=Se;else if(typeof Se<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Me=new Uint8Array(rt,it,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,ze]=await y(Ie),et=await Pe.createInferenceSessionHandler(Me,ze);return qe("InferenceSession.create"),ct(),new C1(et)}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}}}),Ye,yt=d(()=>{ni(),Ye=_t}),ht=d(()=>{}),ke=d(()=>{}),tt=d(()=>{}),Wt=d(()=>{}),ci={};f(ci,{InferenceSession:()=>Ye,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>It,TRACE_FUNC_END:()=>ct,Tensor:()=>ue,env:()=>L,registerBackend:()=>E});var si=d(()=>{w(),G(),yt(),Re(),ht(),ke(),Rt(),tt(),Wt()}),fi=d(()=>{}),ui={};f(ui,{default:()=>mr});var Ci,di,mr,wa=d(()=>{var X;fe(),Fn(),Hn(),Ci="ort-wasm-proxy-worker",di=((X=globalThis.self)==null?void 0:X.name)===Ci,di&&(self.onmessage=ne=>{let{type:he,in:De}=ne.data;try{switch(he){case"init-wasm":Js(De.wasm).then(()=>{Uo(De).then(()=>{postMessage({type:he})},Se=>{postMessage({type:he,err:Se})})},Se=>{postMessage({type:he,err:Se})});break;case"init-ep":{let{epName:Se,env:Me}=De;xr(Me,Se).then(()=>{postMessage({type:he})},Ie=>{postMessage({type:he,err:Ie})});break}case"copy-from":{let{buffer:Se}=De,Me=oi(Se);postMessage({type:he,out:Me});break}case"create":{let{model:Se,options:Me}=De;ds(Se,Me).then(Ie=>{postMessage({type:he,out:Ie})},Ie=>{postMessage({type:he,err:Ie})});break}case"release":Ur(De),postMessage({type:he});break;case"run":{let{sessionId:Se,inputIndices:Me,inputs:Ie,outputIndices:Pe,options:ze}=De;Ke(Se,Me,Ie,Pe,new Array(Pe.length).fill(null),ze).then(et=>{et.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:et},mt([...Ie,...et]))},et=>{postMessage({type:he,err:et})});break}case"end-profiling":Vn(De),postMessage({type:he});break;default:}}catch(Se){postMessage({type:he,err:Se})}}),mr=di?null:ne=>new Worker(ne??bi,{type:"classic",name:Ci})}),zo,gr,bi,Gn,nn,vr,Rs,os,jr,_r,yr,Os,Pn,Hn=d(()=>{fi(),zo=typeof location>"u"?void 0:location.origin,gr=()=>{var X,ne;return typeof document<"u"?(X=document.currentScript)==null?void 0:X.src:typeof self<"u"?(ne=self.location)==null?void 0:ne.href:void 0},bi=gr(),Gn=()=>{if(bi&&!bi.startsWith("blob:"))return bi.substring(0,bi.lastIndexOf("/")+1)},nn=(X,ne)=>{try{let he=ne??bi;return(he?new URL(X,he):new URL(X)).origin===zo}catch{return!1}},vr=(X,ne)=>{let he=ne??bi;try{return(he?new URL(X,he):new URL(X)).href}catch{return}},Rs=(X,ne)=>`${ne??"./"}${X}`,os=async X=>{let ne=await(await fetch(X,{credentials:"same-origin"})).blob();return URL.createObjectURL(ne)},jr=async X=>(await import(X)).default,_r=(wa(),m(ui)).default,yr=async()=>{if(!bi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(bi))return[void 0,_r()];let X=await os(bi);return[X,_r(X)]},Os=void 0,Pn=async(X,ne,he,De)=>{let Se=Os&&!(X||ne);if(Se)if(bi)Se=nn(bi)||De&&!he;else if(De&&!he)Se=!0;else throw new Error("cannot determine the script source URL.");if(Se)return[void 0,Os];{let Me="ort-wasm-simd-threaded.mjs",Ie=X??vr(Me,ne),Pe=he&&Ie&&!nn(Ie,ne),ze=Pe?await os(Ie):Ie??Rs(Me,ne);return[Pe?ze:void 0,await jr(ze)]}}}),Ks,Rn,as,Es,ro,Xs,Ys,Js,zt,Fn=d(()=>{Hn(),Rn=!1,as=!1,Es=!1,ro=()=>{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}},Xs=()=>{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}},Ys=()=>{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}},Js=async X=>{if(Rn)return Promise.resolve();if(as)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");as=!0;let ne=X.initTimeout,he=X.numThreads;if(X.simd!==!1){if(X.simd==="relaxed"){if(!Ys())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Xs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=ro();he>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+he+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),X.numThreads=he=1);let Se=X.wasmPaths,Me=typeof Se=="string"?Se:void 0,Ie=Se==null?void 0:Se.mjs,Pe=(Ie==null?void 0:Ie.href)??Ie,ze=Se==null?void 0:Se.wasm,et=(ze==null?void 0:ze.href)??ze,rt=X.wasmBinary,[it,Xe]=await Pn(Pe,Me,he>1,!!rt||!!et),Pt=!1,Ne=[];if(ne>0&&Ne.push(new Promise(ut=>{setTimeout(()=>{Pt=!0,ut()},ne)})),Ne.push(new Promise((ut,Di)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(et||Me)Zt.locateFile=Qt=>et??Me+Qt;else if(Pe&&Pe.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Pe).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=Ai=>Qt+Ai)}Xe(Zt).then(Qt=>{as=!1,Rn=!0,Ks=Qt,ut(),it&&URL.revokeObjectURL(it)},Qt=>{as=!1,Es=!0,Di(Qt)})})),await Promise.race(Ne),Pt)throw new Error(`WebAssembly backend initializing failed due to timeout: ${ne}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Wi,Ei,Et,zr=d(()=>{Fn(),Wi=(X,ne)=>{let he=zt(),De=he.lengthBytesUTF8(X)+1,Se=he._malloc(De);return he.stringToUTF8(X,Se,De),ne.push(Se),Se},Ei=(X,ne,he,De)=>{if(typeof X=="object"&&X!==null){if(he.has(X))throw new Error("Circular reference in options");he.add(X)}Object.entries(X).forEach(([Se,Me])=>{let Ie=ne?ne+Se:Se;if(typeof Me=="object")Ei(Me,Ie+".",he,De);else if(typeof Me=="string"||typeof Me=="number")De(Ie,Me.toString());else if(typeof Me=="boolean")De(Ie,Me?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Me}`)})},Et=X=>{let ne=zt(),he=ne.stackSave();try{let De=ne.PTR_SIZE,Se=ne.stackAlloc(2*De);ne._OrtGetLastError(Se,Se+De);let Me=Number(ne.getValue(Se,De===4?"i32":"i64")),Ie=ne.getValue(Se+De,"*"),Pe=Ie?ne.UTF8ToString(Ie):"";throw new Error(`${X} ERROR_CODE: ${Me}, ERROR_MESSAGE: ${Pe}`)}finally{ne.stackRestore(he)}}}),oo,xa=d(()=>{Fn(),zr(),oo=X=>{let ne=zt(),he=0,De=[],Se=X||{};try{if((X==null?void 0:X.logSeverityLevel)===void 0)Se.logSeverityLevel=2;else if(typeof X.logSeverityLevel!="number"||!Number.isInteger(X.logSeverityLevel)||X.logSeverityLevel<0||X.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${X.logSeverityLevel}`);if((X==null?void 0:X.logVerbosityLevel)===void 0)Se.logVerbosityLevel=0;else if(typeof X.logVerbosityLevel!="number"||!Number.isInteger(X.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${X.logVerbosityLevel}`);(X==null?void 0:X.terminate)===void 0&&(Se.terminate=!1);let Me=0;return(X==null?void 0:X.tag)!==void 0&&(Me=Wi(X.tag,De)),he=ne._OrtCreateRunOptions(Se.logSeverityLevel,Se.logVerbosityLevel,!!Se.terminate,Me),he===0&&Et("Can't create run options."),(X==null?void 0:X.extra)!==void 0&&Ei(X.extra,"",new WeakSet,(Ie,Pe)=>{let ze=Wi(Ie,De),et=Wi(Pe,De);ne._OrtAddRunConfigEntry(he,ze,et)!==0&&Et(`Can't set a run config entry: ${Ie} - ${Pe}.`)}),[he,De]}catch(Me){throw he!==0&&ne._OrtReleaseRunOptions(he),De.forEach(Ie=>ne._free(Ie)),Me}}}),ao,lo,Bo,En,Sa,Ca,ki=d(()=>{Fn(),zr(),ao=X=>{switch(X){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${X}`)}},lo=X=>{switch(X){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${X}`)}},Bo=X=>{X.extra||(X.extra={}),X.extra.session||(X.extra.session={});let ne=X.extra.session;ne.use_ort_model_bytes_directly||(ne.use_ort_model_bytes_directly="1"),X.executionProviders&&X.executionProviders.some(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(X.enableMemPattern=!1)},En=(X,ne,he,De)=>{let Se=Wi(ne,De),Me=Wi(he,De);zt()._OrtAddSessionConfigEntry(X,Se,Me)!==0&&Et(`Can't set a session config entry: ${ne} - ${he}.`)},Sa=async(X,ne,he)=>{let De=ne.executionProviders;for(let Se of De){let Me=typeof Se=="string"?Se:Se.name,Ie=[];switch(Me){case"webnn":if(Me="WEBNN",En(X,"session.disable_quant_qdq","1",he),En(X,"session.disable_qdq_constant_folding","1",he),typeof Se!="string"){let it=Se==null?void 0:Se.deviceType;it&&En(X,"deviceType",it,he)}break;case"webgpu":if(Me="JS",typeof Se!="string"){let it=Se;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);En(X,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Me}`)}let Pe=Wi(Me,he),ze=Ie.length,et=0,rt=0;if(ze>0){et=zt()._malloc(ze*zt().PTR_SIZE),he.push(et),rt=zt()._malloc(ze*zt().PTR_SIZE),he.push(rt);for(let it=0;it<ze;it++)zt().setValue(et+it*zt().PTR_SIZE,Ie[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,Ie[it][1],"*")}await zt()._OrtAppendExecutionProvider(X,Pe,et,rt,ze)!==0&&Et(`Can't append execution provider: ${Me}.`)}},Ca=async X=>{let ne=zt(),he=0,De=[],Se=X||{};Bo(Se);try{let Me=ao(Se.graphOptimizationLevel??"all"),Ie=lo(Se.executionMode??"sequential"),Pe=typeof Se.logId=="string"?Wi(Se.logId,De):0,ze=Se.logSeverityLevel??2;if(!Number.isInteger(ze)||ze<0||ze>4)throw new Error(`log severity level is not valid: ${ze}`);let et=Se.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let rt=typeof Se.optimizedModelFilePath=="string"?Wi(Se.optimizedModelFilePath,De):0;if(he=ne._OrtCreateSessionOptions(Me,!!Se.enableCpuMemArena,!!Se.enableMemPattern,Ie,!!Se.enableProfiling,0,Pe,ze,et,rt),he===0&&Et("Can't create session options."),Se.executionProviders&&await Sa(he,Se,De),Se.enableGraphCapture!==void 0){if(typeof Se.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Se.enableGraphCapture}`);En(he,"enableGraphCapture",Se.enableGraphCapture.toString(),De)}if(Se.freeDimensionOverrides)for(let[it,Xe]of Object.entries(Se.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let Pt=Wi(it,De);ne._OrtAddFreeDimensionOverride(he,Pt,Xe)!==0&&Et(`Can't set a free dimension override: ${it} - ${Xe}.`)}return Se.extra!==void 0&&Ei(Se.extra,"",new WeakSet,(it,Xe)=>{En(he,it,Xe,De)}),[he,De]}catch(Me){throw he!==0&&ne._OrtReleaseSessionOptions(he)!==0&&Et("Can't release session options."),De.forEach(Ie=>ne._free(Ie)),Me}}}),On,qi,Ln,Zs,Br,br,ls,gn,Bt=d(()=>{On=X=>{switch(X){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${X}`)}},qi=X=>{switch(X){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${X}`)}},Ln=(X,ne)=>{let he=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][X],De=typeof ne=="number"?ne:ne.reduce((Se,Me)=>Se*Me,1);return he>0?Math.ceil(De*he):void 0},Zs=X=>{switch(X){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${X}`)}},Br=X=>{switch(X){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${X}`)}},br=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",ls=X=>X==="float32"||X==="float16"||X==="int32"||X==="int64"||X==="uint32"||X==="uint64"||X==="int8"||X==="uint8"||X==="bool"||X==="uint4"||X==="int4",gn=X=>{switch(X){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${X}`)}}}),Ki,wr=d(()=>{fi(),Ki=async X=>{if(typeof X=="string"){let ne=await fetch(X);if(!ne.ok)throw new Error(`failed to load external data file: ${X}`);let he=ne.headers.get("Content-Length"),De=he?parseInt(he,10):0;if(De<1073741824)return new Uint8Array(await ne.arrayBuffer());{if(!ne.body)throw new Error(`failed to load external data file: ${X}, no response body.`);let Se=ne.body.getReader(),Me;try{Me=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let ze=Math.ceil(De/65536);Me=new WebAssembly.Memory({initial:ze,maximum:ze}).buffer}else throw Pe}let Ie=0;for(;;){let{done:Pe,value:ze}=await Se.read();if(Pe)break;let et=ze.byteLength;new Uint8Array(Me,Ie,et).set(ze),Ie+=et}return new Uint8Array(Me,0,De)}}else return X instanceof Blob?new Uint8Array(await X.arrayBuffer()):X instanceof Uint8Array?X:new Uint8Array(X)}}),cs,Uo,xr,Wn,Ls,Sr,oi,ds,Ur,ks,Ke,Vn,mt,fe=d(()=>{si(),xa(),ki(),Bt(),Fn(),zr(),wr(),cs=(X,ne)=>{zt()._OrtInit(X,ne)!==0&&Et("Can't initialize onnxruntime.")},Uo=async X=>{cs(X.wasm.numThreads,Br(X.logLevel))},xr=async(X,ne)=>{var De,Se;(Se=(De=zt()).asyncInit)==null||Se.call(De);let he=X.webgpu.adapter;if(ne==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(he){if(typeof he.limits!="object"||typeof he.features!="object"||typeof he.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Me=X.webgpu.powerPreference;if(Me!==void 0&&Me!=="low-power"&&Me!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Me}"`);let Ie=X.webgpu.forceFallbackAdapter;if(Ie!==void 0&&typeof Ie!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Ie}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Me,forceFallbackAdapter:Ie}),!he)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(ne==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wn=new Map,Ls=X=>{let ne=zt(),he=ne.stackSave();try{let De=ne.PTR_SIZE,Se=ne.stackAlloc(2*De);ne._OrtGetInputOutputCount(X,Se,Se+De)!==0&&Et("Can't get session input/output count.");let Me=De===4?"i32":"i64";return[Number(ne.getValue(Se,Me)),Number(ne.getValue(Se+De,Me))]}finally{ne.stackRestore(he)}},Sr=(X,ne)=>{let he=zt(),De=he.stackSave(),Se=0;try{let Me=he.PTR_SIZE,Ie=he.stackAlloc(2*Me);he._OrtGetInputOutputMetadata(X,ne,Ie,Ie+Me)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(he.getValue(Ie,"*"));Se=Number(he.getValue(Ie+Me,"*"));let ze=he.HEAP32[Se/4];if(ze===0)return[Pe,0];let et=he.HEAPU32[Se/4+1],rt=[];for(let it=0;it<et;it++){let Xe=Number(he.getValue(Se+8+it*Me,"*"));rt.push(Xe!==0?he.UTF8ToString(Xe):Number(he.getValue(Se+8+(it+et)*Me,"*")))}return[Pe,ze,rt]}finally{he.stackRestore(De),Se!==0&&he._OrtFree(Se)}},oi=X=>{let ne=zt(),he=ne._malloc(X.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${X.byteLength}.`);return ne.HEAPU8.set(X,he),[he,X.byteLength]},ds=async(X,ne)=>{var rt,it,Xe;let he,De,Se=zt();Array.isArray(X)?[he,De]=X:X.buffer===Se.HEAPU8.buffer?[he,De]=[X.byteOffset,X.byteLength]:[he,De]=oi(X);let Me=0,Ie=0,Pe=[],ze=[],et=[];try{if([Ie,Pe]=await Ca(ne),(ne==null?void 0:ne.externalData)&&Se.mountExternalData){let Mi=[];for(let hi of ne.externalData){let vn=typeof hi=="string"?hi:hi.path;Mi.push(Ki(typeof hi=="string"?hi:hi.data).then($n=>{Se.mountExternalData(vn,$n)}))}await Promise.all(Mi)}for(let Mi of(ne==null?void 0:ne.executionProviders)??[])if((typeof Mi=="string"?Mi:Mi.name)==="webnn"){if(Se.shouldTransferToMLTensor=!1,typeof Mi!="string"){let hi=Mi,vn=hi==null?void 0:hi.context,$n=hi==null?void 0:hi.gpuDevice,qn=hi==null?void 0:hi.deviceType,ka=hi==null?void 0:hi.powerPreference;vn?Se.currentContext=vn:$n?Se.currentContext=await Se.webnnCreateMLContext($n):Se.currentContext=await Se.webnnCreateMLContext({deviceType:qn,powerPreference:ka})}else Se.currentContext=await Se.webnnCreateMLContext();break}Me=await Se._OrtCreateSession(he,De,Ie),(rt=Se.webgpuOnCreateSession)==null||rt.call(Se,Me),Me===0&&Et("Can't create a session."),(it=Se.jsepOnCreateSession)==null||it.call(Se),Se.currentContext&&(Se.webnnRegisterMLContext(Me,Se.currentContext),Se.currentContext=void 0,Se.shouldTransferToMLTensor=!0);let[Pt,Ne]=Ls(Me),ut=!!(ne!=null&&ne.enableGraphCapture),Di=[],Zt=[],Qt=[],Ai=[],Mt=[];for(let Mi=0;Mi<Pt;Mi++){let[hi,vn,$n]=Sr(Me,Mi);hi===0&&Et("Can't get an input name."),ze.push(hi);let qn=Se.UTF8ToString(hi);Di.push(qn),Qt.push(vn===0?{name:qn,isTensor:!1}:{name:qn,isTensor:!0,type:qi(vn),shape:$n})}for(let Mi=0;Mi<Ne;Mi++){let[hi,vn,$n]=Sr(Me,Mi+Pt);hi===0&&Et("Can't get an output name."),et.push(hi);let qn=Se.UTF8ToString(hi);Zt.push(qn),Ai.push(vn===0?{name:qn,isTensor:!1}:{name:qn,isTensor:!0,type:qi(vn),shape:$n})}return Wn.set(Me,[Me,ze,et,null,ut,!1]),[Me,Di,Zt,Qt,Ai]}catch(Pt){throw ze.forEach(Ne=>Se._OrtFree(Ne)),et.forEach(Ne=>Se._OrtFree(Ne)),Me!==0&&Se._OrtReleaseSession(Me)!==0&&Et("Can't release session."),Pt}finally{Se._free(he),Ie!==0&&Se._OrtReleaseSessionOptions(Ie)!==0&&Et("Can't release session options."),Pe.forEach(Pt=>Se._free(Pt)),(Xe=Se.unmountExternalData)==null||Xe.call(Se)}},Ur=X=>{var ze,et,rt;let ne=zt(),he=Wn.get(X);if(!he)throw new Error(`cannot release session. invalid session id: ${X}`);let[De,Se,Me,Ie,Pe]=he;Ie&&(Pe&&ne._OrtClearBoundOutputs(Ie.handle)!==0&&Et("Can't clear bound outputs."),ne._OrtReleaseBinding(Ie.handle)!==0&&Et("Can't release IO binding.")),(ze=ne.jsepOnReleaseSession)==null||ze.call(ne,X),(et=ne.webnnOnReleaseSession)==null||et.call(ne,X),(rt=ne.webgpuOnReleaseSession)==null||rt.call(ne,X),Se.forEach(it=>ne._OrtFree(it)),Me.forEach(it=>ne._OrtFree(it)),ne._OrtReleaseSession(De)!==0&&Et("Can't release session."),Wn.delete(X)},ks=async(X,ne,he,De,Se,Me,Ie=!1)=>{if(!X){ne.push(0);return}let Pe=zt(),ze=Pe.PTR_SIZE,et=X[0],rt=X[1],it=X[3],Xe=it,Pt,Ne;if(et==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Ie&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Me} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=X[2].gpuBuffer;Ne=Ln(On(et),rt);{let Qt=Pe.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pt=Qt(De,Me,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=X[2].mlTensor;Ne=Ln(On(et),rt);let Qt=Pe.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pt=Qt(De,Zt,On(et),rt)}else{let Zt=X[2];if(Array.isArray(Zt)){Ne=ze*Zt.length,Pt=Pe._malloc(Ne),he.push(Pt);for(let Qt=0;Qt<Zt.length;Qt++){if(typeof Zt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Pe.setValue(Pt+Qt*ze,Wi(Zt[Qt],he),"*")}}else{let Qt=Pe.webnnIsGraphInput,Ai=Pe.webnnIsGraphOutput;if(et!=="string"&&Qt&&Ai){let Mt=Pe.UTF8ToString(Se);if(Qt(De,Mt)||Ai(De,Mt)){let Mi=On(et);Ne=Ln(Mi,rt),Xe="ml-tensor";let hi=Pe.webnnCreateTemporaryTensor,vn=Pe.webnnUploadTensor;if(!hi||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let $n=await hi(De,Mi,rt);vn($n,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),Pt=$n}else Ne=Zt.byteLength,Pt=Pe._malloc(Ne),he.push(Pt),Pe.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),Pt)}else Ne=Zt.byteLength,Pt=Pe._malloc(Ne),he.push(Pt),Pe.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),Pt)}}let ut=Pe.stackSave(),Di=Pe.stackAlloc(4*rt.length);try{rt.forEach((Qt,Ai)=>Pe.setValue(Di+Ai*ze,Qt,ze===4?"i32":"i64"));let Zt=Pe._OrtCreateTensor(On(et),Pt,Ne,Di,rt.length,gn(Xe));Zt===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Me}.`),ne.push(Zt)}finally{Pe.stackRestore(ut)}},Ke=async(X,ne,he,De,Se,Me)=>{var Kn,hl,dc;let Ie=zt(),Pe=Ie.PTR_SIZE,ze=Wn.get(X);if(!ze)throw new Error(`cannot run inference. invalid session id: ${X}`);let et=ze[0],rt=ze[1],it=ze[2],Xe=ze[3],Pt=ze[4];ze[5];let Ne=ne.length,ut=De.length,Di=0,Zt=[],Qt=[],Ai=[],Mt=[],Mi=[],hi=Ie.stackSave(),vn=Ie.stackAlloc(Ne*Pe),$n=Ie.stackAlloc(Ne*Pe),qn=Ie.stackAlloc(ut*Pe),ka=Ie.stackAlloc(ut*Pe);try{[Di,Zt]=oo(Me),qt("wasm prepareInputOutputTensor");for(let li=0;li<Ne;li++)await ks(he[li],Qt,Mt,X,rt[ne[li]],ne[li],Pt);for(let li=0;li<ut;li++)await ks(Se[li],Ai,Mt,X,it[De[li]],Ne+De[li],Pt);qe("wasm prepareInputOutputTensor");for(let li=0;li<Ne;li++)Ie.setValue(vn+li*Pe,Qt[li],"*"),Ie.setValue($n+li*Pe,rt[ne[li]],"*");for(let li=0;li<ut;li++)Ie.setValue(qn+li*Pe,Ai[li],"*"),Ie.setValue(ka+li*Pe,it[De[li]],"*");(Kn=Ie.jsepOnRunStart)==null||Kn.call(Ie,et),(hl=Ie.webnnOnRunStart)==null||hl.call(Ie,et);let _n;_n=await Ie._OrtRun(et,$n,vn,Ne,ka,ut,qn,Di),_n!==0&&Et("failed to call OrtRun().");let er=[],uc=[];qt("wasm ProcessOutputTensor");for(let li=0;li<ut;li++){let Ns=Number(Ie.getValue(qn+li*Pe,"*"));if(Ns===Ai[li]||Mi.includes(Ai[li])){er.push(Se[li]),Ns!==Ai[li]&&Ie._OrtReleaseTensor(Ns)!==0&&Et("Can't release tensor.");continue}let bd=Ie.stackSave(),kr=Ie.stackAlloc(4*Pe),Go=!1,an,Xn=0;try{Ie._OrtGetTensorData(Ns,kr,kr+Pe,kr+2*Pe,kr+3*Pe)!==0&&Et(`Can't access output tensor data on index ${li}.`);let pl=Pe===4?"i32":"i64",Yn=Number(Ie.getValue(kr,pl));Xn=Ie.getValue(kr+Pe,"*");let hc=Ie.getValue(kr+Pe*2,"*"),wd=Number(Ie.getValue(kr+Pe*3,pl)),Tr=[];for(let ln=0;ln<wd;ln++)Tr.push(Number(Ie.getValue(hc+ln*Pe,pl)));Ie._OrtFree(hc)!==0&&Et("Can't free memory for tensor dims.");let Ms=Tr.reduce((ln,Vi)=>ln*Vi,1);an=qi(Yn);let tr=Xe==null?void 0:Xe.outputPreferredLocations[De[li]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Vi=0;Vi<Ms;Vi++){let js=Ie.getValue(Xn+Vi*Pe,"*"),pc=Ie.getValue(Xn+(Vi+1)*Pe,"*"),fc=Vi===Ms-1?void 0:pc-js;ln.push(Ie.UTF8ToString(js,fc))}er.push([an,Tr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ms>0){let ln=Ie.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Vi=ln(Xn),js=Ln(Yn,Ms);if(js===void 0||!br(an))throw new Error(`Unsupported data type: ${an}`);Go=!0,er.push([an,Tr,{gpuBuffer:Vi,download:Ie.jsepCreateDownloader(Vi,js,an),dispose:()=>{Ie._OrtReleaseTensor(Ns)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ms>0){let ln=Ie.webnnEnsureTensor,Vi=Ie.webnnIsGraphInputOutputTypeSupported;if(!ln||!Vi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ln(Yn,Ms)===void 0||!ls(an))throw new Error(`Unsupported data type: ${an}`);if(!Vi(X,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let js=await ln(X,Xn,Yn,Tr,!1);Go=!0,er.push([an,Tr,{mlTensor:js,download:Ie.webnnCreateMLTensorDownloader(Xn,an),dispose:()=>{Ie.webnnReleaseTensorId(Xn),Ie._OrtReleaseTensor(Ns)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ms>0){let ln=Ie.webnnCreateMLTensorDownloader(Xn,an)(),Vi=er.length;Go=!0,uc.push((async()=>{let js=[Vi,await ln];return Ie.webnnReleaseTensorId(Xn),Ie._OrtReleaseTensor(Ns),js})()),er.push([an,Tr,[],"cpu"])}else{let ln=Zs(an),Vi=new ln(Ms);new Uint8Array(Vi.buffer,Vi.byteOffset,Vi.byteLength).set(Ie.HEAPU8.subarray(Xn,Xn+Vi.byteLength)),er.push([an,Tr,Vi,"cpu"])}}finally{Ie.stackRestore(bd),an==="string"&&Xn&&Ie._free(Xn),Go||Ie._OrtReleaseTensor(Ns)}}Xe&&!Pt&&(Ie._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),Wn.set(X,[et,rt,it,Xe,Pt,!1]));for(let[li,Ns]of await Promise.all(uc))er[li][2]=Ns;return qe("wasm ProcessOutputTensor"),er}finally{(dc=Ie.webnnOnRunEnd)==null||dc.call(Ie,et),Ie.stackRestore(hi),Qt.forEach(_n=>Ie._OrtReleaseTensor(_n)),Ai.forEach(_n=>Ie._OrtReleaseTensor(_n)),Mt.forEach(_n=>Ie._free(_n)),Di!==0&&Ie._OrtReleaseRunOptions(Di),Zt.forEach(_n=>Ie._free(_n))}},Vn=X=>{let ne=zt(),he=Wn.get(X);if(!he)throw new Error("invalid session id");let De=he[0],Se=ne._OrtEndProfiling(De);Se===0&&Et("Can't get an profile file name."),ne._OrtFree(Se)},mt=X=>{let ne=[];for(let he of X){let De=he[2];!Array.isArray(De)&&"buffer"in De&&ne.push(De.buffer)}return ne}}),Le,Je,Tt,ii,ai,$i,Pi,sn,Ui,on,Ri,$s,Gr,co,Qs,yd,uo,ho,ac=d(()=>{si(),fe(),Fn(),Hn(),Le=()=>!!L.wasm.proxy&&typeof document<"u",Tt=!1,ii=!1,ai=!1,sn=new Map,Ui=(X,ne)=>{let he=sn.get(X);he?he.push(ne):sn.set(X,[ne])},on=()=>{if(Tt||!ii||ai||!Je)throw new Error("worker not ready")},Ri=X=>{switch(X.data.type){case"init-wasm":Tt=!1,X.data.err?(ai=!0,Pi[1](X.data.err)):(ii=!0,Pi[0]()),$i&&(URL.revokeObjectURL($i),$i=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let ne=sn.get(X.data.type);X.data.err?ne.shift()[1](X.data.err):ne.shift()[0](X.data.out);break}}},$s=async()=>{if(!ii){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(ai)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Le())return new Promise((X,ne)=>{Je==null||Je.terminate(),yr().then(([he,De])=>{try{Je=De,Je.onerror=Me=>ne(Me),Je.onmessage=Ri,Pi=[X,ne];let Se={type:"init-wasm",in:L};if(!Se.in.wasm.wasmPaths&&he){let Me=Gn();Me&&(Se.in.wasm.wasmPaths=Me)}Je.postMessage(Se),$i=he}catch(Se){ne(Se)}},ne)});try{await Js(L.wasm),await Uo(L),ii=!0}catch(X){throw ai=!0,X}finally{Tt=!1}}},Gr=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("init-ep",[ne,he]);let De={type:"init-ep",in:{epName:X,env:L}};Je.postMessage(De)});await xr(L,X)},co=async X=>Le()?(on(),new Promise((ne,he)=>{Ui("copy-from",[ne,he]);let De={type:"copy-from",in:{buffer:X}};Je.postMessage(De,[X.buffer])})):oi(X),Qs=async(X,ne)=>{if(Le()){if(ne!=null&&ne.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,De)=>{Ui("create",[he,De]);let Se={type:"create",in:{model:X,options:{...ne}}},Me=[];X instanceof Uint8Array&&Me.push(X.buffer),Je.postMessage(Se,Me)})}else return ds(X,ne)},yd=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("release",[ne,he]);let De={type:"release",in:X};Je.postMessage(De)});Ur(X)},uo=async(X,ne,he,De,Se,Me)=>{if(Le()){if(he.some(Ie=>Ie[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Se.some(Ie=>Ie))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise((Ie,Pe)=>{Ui("run",[Ie,Pe]);let ze=he,et={type:"run",in:{sessionId:X,inputIndices:ne,inputs:ze,outputIndices:De,options:Me}};Je.postMessage(et,mt(ze))})}else return Ke(X,ne,he,De,Se,Me)},ho=async X=>{if(Le())return on(),new Promise((ne,he)=>{Ui("end-profiling",[ne,he]);let De={type:"end-profiling",in:X};Je.postMessage(De)});Vn(X)}}),ll,po,Ea,cl=d(()=>{si(),ac(),Bt(),fi(),wr(),ll=(X,ne)=>{switch(X.location){case"cpu":return[X.type,X.dims,X.data,"cpu"];case"gpu-buffer":return[X.type,X.dims,{gpuBuffer:X.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[X.type,X.dims,{mlTensor:X.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${X.location} for ${ne()}`)}},po=X=>{switch(X[3]){case"cpu":return new ue(X[0],X[2],X[1]);case"gpu-buffer":{let ne=X[0];if(!br(ne))throw new Error(`not supported data type: ${ne} for deserializing GPU tensor`);let{gpuBuffer:he,download:De,dispose:Se}=X[2];return ue.fromGpuBuffer(he,{dataType:ne,dims:X[1],download:De,dispose:Se})}case"ml-tensor":{let ne=X[0];if(!ls(ne))throw new Error(`not supported data type: ${ne} for deserializing MLTensor tensor`);let{mlTensor:he,download:De,dispose:Se}=X[2];return ue.fromMLTensor(he,{dataType:ne,dims:X[1],download:De,dispose:Se})}default:throw new Error(`invalid data location: ${X[3]}`)}},Ea=class{async fetchModelAndCopyToWasmMemory(X){return co(await Ki(X))}async loadModel(X,ne){It();let he;typeof X=="string"?he=await this.fetchModelAndCopyToWasmMemory(X):he=X,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,ne),ct()}async dispose(){return yd(this.sessionId)}async run(X,ne,he){It();let De=[],Se=[];Object.entries(X).forEach(it=>{let Xe=it[0],Pt=it[1],Ne=this.inputNames.indexOf(Xe);if(Ne===-1)throw new Error(`invalid input '${Xe}'`);De.push(Pt),Se.push(Ne)});let Me=[],Ie=[];Object.entries(ne).forEach(it=>{let Xe=it[0],Pt=it[1],Ne=this.outputNames.indexOf(Xe);if(Ne===-1)throw new Error(`invalid output '${Xe}'`);Me.push(Pt),Ie.push(Ne)});let Pe=De.map((it,Xe)=>ll(it,()=>`input "${this.inputNames[Se[Xe]]}"`)),ze=Me.map((it,Xe)=>it?ll(it,()=>`output "${this.outputNames[Ie[Xe]]}"`):null),et=await uo(this.sessionId,Se,Pe,Ie,ze,he),rt={};for(let it=0;it<et.length;it++)rt[this.outputNames[Ie[it]]]=Me[it]??po(et[it]);return ct(),rt}startProfiling(){}endProfiling(){ho(this.sessionId)}}}),Cr={};f(Cr,{OnnxruntimeWebAssemblyBackend:()=>Er,initializeFlags:()=>Hr,wasmBackend:()=>fo});var Hr,Er,fo,lc=d(()=>{si(),ac(),cl(),Hr=()=>{(typeof L.wasm.initTimeout!="number"||L.wasm.initTimeout<0)&&(L.wasm.initTimeout=0);let X=L.wasm.simd;if(typeof X!="boolean"&&X!==void 0&&X!=="fixed"&&X!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${X}". Reset it to \`false\` and ignore SIMD feature checking.`),L.wasm.simd=!1),typeof L.wasm.proxy!="boolean"&&(L.wasm.proxy=!1),typeof L.wasm.trace!="boolean"&&(L.wasm.trace=!1),typeof L.wasm.numThreads!="number"||!Number.isInteger(L.wasm.numThreads)||L.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)L.wasm.numThreads=1;else{let ne=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;L.wasm.numThreads=Math.min(4,Math.ceil((ne||1)/2))}},Er=class{async init(X){Hr(),await $s(),await Gr(X)}async createInferenceSessionHandler(X,ne){let he=new Ea;return await he.loadModel(X,ne),he}},fo=new Er}),cc={};f(cc,{InferenceSession:()=>Ye,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>qt,TRACE_EVENT_END:()=>qe,TRACE_FUNC_BEGIN:()=>It,TRACE_FUNC_END:()=>ct,Tensor:()=>ue,default:()=>ul,env:()=>L,registerBackend:()=>E}),si(),si(),si();var dl="1.26.0",ul=ci;{let X=(lc(),m(Cr)).wasmBackend;E("cpu",X,10),E("wasm",X,10)}return Object.defineProperty(L.versions,"web",{value:dl,enumerable:!0}),m(cc)})();i.exports=t})(d_)),d_.exports}var rx;function rD(){return rx||(rx=1,(function(i){var e=Xa&&Xa.__createBinding||(Object.create?(function(x,A,O,$){$===void 0&&($=O);var j=Object.getOwnPropertyDescriptor(A,O);(!j||("get"in j?!A.__esModule:j.writable||j.configurable))&&(j={enumerable:!0,get:function(){return A[O]}}),Object.defineProperty(x,$,j)}):(function(x,A,O,$){$===void 0&&($=O),x[$]=A[O]})),t=Xa&&Xa.__setModuleDefault||(Object.create?(function(x,A){Object.defineProperty(x,"default",{enumerable:!0,value:A})}):function(x,A){x.default=A}),n=Xa&&Xa.__importStar||function(x){if(x&&x.__esModule)return x;var A={};if(x!=null)for(var O in x)O!=="default"&&Object.prototype.hasOwnProperty.call(x,O)&&e(A,x,O);return t(A,x),A};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(sD()),l=pb(),p=fb(),a=lm(),d=Pv(),f=x1(),g=S1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",T="silero_vad_legacy.onnx",E=x=>({...p.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{a.log.debug("VAD misfire")},onSpeechStart:()=>{a.log.debug("Detected speech start")},onSpeechEnd:()=>{a.log.debug("Detected speech end")},onSpeechRealStart:()=>{a.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async A=>{A.getTracks().forEach(O=>{O.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:A=>{A.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=E;const k=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(x,A,O,$,j){await O.audioWorklet.addModule(x),A.processorOptions={...A.processorOptions??{},frameSamples:$};const L=new AudioWorkletNode(O,"vad-helper-worklet",A);return L.port.onmessage=async G=>{const W=G.data;if(!(typeof W=="object"&&W&&"message"in W)){console.error("Invalid message event",W);return}switch(W.message){case d.Message.AudioFrame:{if(!("data"in W&&W.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const re=new Float32Array(W.data);await j(re);break}}},L}async function S(x,A,O){const $=new g.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:A});a.log.debug("using script processor");const L=x.createScriptProcessor(4096,1,1);let G=!1;return L.onaudioprocess=async W=>{if(!G){G=!0;try{const re=W.inputBuffer.getChannelData(0);W.outputBuffer.getChannelData(0).fill(0);const Z=$.process(re);for(const pe of Z)await O(pe)}catch(re){console.error("Error processing audio:",re)}finally{G=!1}}},L.connect(x.destination),L}class w{constructor(A,O,$,j,L=!1,G=null,W=null,re=null,ae=null,Z=null,pe=null,oe="uninitialized",me=!1){this.options=A,this.frameProcessor=O,this.model=$,this.frameSamples=j,this.listening=L,this.errored=G,this._stream=W,this._audioContext=re,this._vadNode=ae,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=pe,this.initializationState=oe,this.ownsAudioContext=me,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=we=>{this.initializationState="errored",this.errored=we},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(we){throw we instanceof Error?this.setErrored(we.message):this.setErrored(String(we)),we}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"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await S(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),a.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{a.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:we,audioContext:ve,vadNode:F}=this.getAudioInstances();this._stream=await this.options.resumeStream(we);const J=new MediaStreamAudioSourceNode(ve,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=J,J.connect(F);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:we,mediaStreamAudioSourceNode:ve}=this.getAudioInstances();await this.options.pauseStream(we),ve.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ve;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:we}=this.getAudioInstances();we instanceof AudioWorkletNode&&we.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ve=this._audioContext)==null?void 0:ve.close())},this.setOptions=we=>{this.frameProcessor.setOptions(we)},this.processFrame=async we=>{await this.frameProcessor.process(we,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=we=>{switch(we.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(we.probs,we.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(we.audio);break}}}static async new(A={}){const O={...(0,i.getDefaultRealTimeVADOptions)(A.model??i.DEFAULT_MODEL),...A};(0,p.validateOptions)(O),i.ort.env.wasm.wasmPaths=O.onnxWASMBasePath,O.ortConfig!==void 0&&O.ortConfig(i.ort);const $=O.model==="v5"?b:T,j=O.baseAssetPath+$,L=O.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let G;try{G=await L(i.ort,()=>(0,l.defaultModelFetcher)(j))}catch(pe){throw console.error(`Encountered an error while loading model file ${j}`),pe}const W=O.model==="v5"?512:1536,re=W/16,ae=new p.FrameProcessor(G.process,G.reset_state,{positiveSpeechThreshold:O.positiveSpeechThreshold,negativeSpeechThreshold:O.negativeSpeechThreshold,redemptionMs:O.redemptionMs,preSpeechPadMs:O.preSpeechPadMs,minSpeechMs:O.minSpeechMs,submitUserSpeechOnPause:O.submitUserSpeechOnPause},re),Z=new w(O,ae,G,W);if(O.startOnLoad)try{await Z.start()}catch(pe){throw console.error("Error starting micVad",pe),pe}return Z}}i.MicVAD=w})(Xa)),Xa}var ox;function oD(){return ox||(ox=1,(function(i){Object.defineProperty(i,"__esModule",{value:!0}),i.getDefaultRealTimeVADOptions=i.MicVAD=i.DEFAULT_MODEL=i.utils=i.NonRealTimeVAD=i.Message=i.FrameProcessor=i.defaultModelFetcher=i.baseAssetPath=void 0;var e=y1();Object.defineProperty(i,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var t=pb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=fb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=Pv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=iD();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=nD();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=rD();Object.defineProperty(i,"DEFAULT_MODEL",{enumerable:!0,get:function(){return a.DEFAULT_MODEL}}),Object.defineProperty(i,"MicVAD",{enumerable:!0,get:function(){return a.MicVAD}}),Object.defineProperty(i,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return a.getDefaultRealTimeVADOptions}})})(a_)),a_}var aD=oD();function mg(i,e,t,n,r){var p,a;try{(a=(p=window.api)==null?void 0:p.logs)==null||a.write(i,e,t,n,r)}catch{}const l=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?l(`[${i}]`,t,n):l(`[${i}]`,t)}const pt={debug:(i,e,t)=>mg(i,"debug",e,t),info:(i,e,t)=>mg(i,"info",e,t),warn:(i,e,t)=>mg(i,"warn",e,t),error:(i,e,t,n)=>mg(i,"error",e,t,n)},E1=16e3,lD=6,ih=E1*lD,cD=400,dD=E1*cD/1e3,ax=300,lx=2e3,cx=1500,dx=3e3,uD=600,k1=.5,T1=.35,ux=.85,hx=.7;let pr=null,ga=!1,qs=!1;const oy=new Set;function gg(i){for(const e of Array.from(oy))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let u_=0;const px=2;let ph=!1,D1=!1;function A1(i){i.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const t=e.data.level||"info";pt[t]("whisperWorker",e.data.message??"",e.data.meta)}),i.addEventListener("error",e=>{pt.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),hD(`error:${e.message||"unknown"}`)})}function fv(){return pr||(pr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),A1(pr),pt.info("speech","worker spawned"),pr)}let vg=!1;function hD(i){if(!ph){if(vg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(vg=!0,u_+=1,D1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:u_}),gg({reason:i,respawned:!1,finalOnly:!0}),u_>px){if(ph=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:px}),pr)try{pr.terminate()}catch{}pr=null,ga=!1,qs=!1,gg({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),vg=!1;return}if(pr)try{pr.terminate()}catch{}pr=null,ga=!1,qs=!1;try{pr=new Worker(new URL(""+new URL("whisperWorker-C7ZGQwKg.js",import.meta.url).href,import.meta.url),{type:"module"}),A1(pr),qs=!0,pr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),gg({reason:i,respawned:!0,finalOnly:!0})}catch(e){ph=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),gg({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{vg=!1}}}function pD(i,e){if(ga||qs)return;qs=!0;const t=fv();pt.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(i==null||i(r.data.status,r.data.message),r.data.status==="ready"&&(ga=!0,qs=!1,pt.info("speech","preloadModel: ready"),t.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(qs=!1,pt.error("speech","preloadModel: worker reported error",{error:r.data.error}),i==null||i("error",r.data.error),t.removeEventListener("message",n))};t.addEventListener("message",n),t.postMessage({type:"load"})}function fD(){pt.info("speech","resetModel: clearing load flags"),ga=!1,qs=!1}function Rv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function mD(i){const e=fv();return!ga&&!qs&&(qs=!0,e.postMessage({type:"load"})),new Promise((t,n)=>{const r=l=>{var p,a,d;((p=l.data)==null?void 0:p.type)==="result"?(e.removeEventListener("message",r),t((l.data.text??"").trim())):((a=l.data)==null?void 0:a.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(l.data.error??"Transcription failed")))):((d=l.data)==null?void 0:d.type)==="status"&&l.data.status==="ready"&&(ga=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function I1(i){let e=fv(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let g=null,m=0,b=!1,T=0,E=!1,k=!1,y=0,S=0,w=0,x=-1,A=ax,O=0,$=null,j="",L="",G=!1,W=0;function re(ge,Te){const je=Math.min(ge.length,Te.length);let Ze=0;for(;Ze<je&&ge.charCodeAt(Ze)===Te.charCodeAt(Ze);)Ze++;return Ze}function ae(ge){const Te=re(j,ge);return j=ge,Te>L.length&&(L=ge.slice(0,Te)),L.length>ge.length&&(L=ge),L}const Z=()=>(g||(g=new Float32Array(ih)),g),pe=()=>{m=0},oe=ge=>{const Te=Z(),je=ge.length;if(je>=ih){Te.set(ge.subarray(je-ih)),m=ih;return}if(m+je<=ih){Te.set(ge,m),m+=je;return}const Ze=m+je-ih;Te.copyWithin(0,Ze,m),m-=Ze,Te.set(ge,m),m+=je},me=()=>{$&&(clearTimeout($),$=null)},we=()=>{me(),b=!1,E=!1,k=!1,A=ax,j="",L="",G=!1,W=0,pe()},ve=()=>{if(t||!b||k||E||$)return;if(m<dD){$=setTimeout(()=>{$=null,ve()},A);return}const ge=performance.now()-y;if(ge<A&&y!==0){$=setTimeout(()=>{$=null,ve()},A-ge);return}if(D1||ph||i.partialsEnabled&&!i.partialsEnabled())return;const Te=Z(),je=new Float32Array(m);je.set(Te.subarray(0,m)),S+=1,w=S,E=!0,O=performance.now(),y=O,e.postMessage({type:"transcribe-partial",audio:je,seq:S},[je.buffer])},F=ge=>ge.length===0?Promise.resolve():ph?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Te=>{d.push(Te),S+=1;const je=S;x=je,e.postMessage({type:"transcribe",audio:ge,seq:je},[ge.buffer])}),J=ge=>{const Te=F(ge);return f.add(Te),Te.finally(()=>{f.delete(Te)}),Te},V=ge=>{var Te,je,Ze,ye,Y;if(ge.data.type==="result"){const _e=ge.data.text,ue=ge.data.seq??0;ue&&ue<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:ue,latestFinalSeq:x}),!t&&_e&&i.onFinal(_e),(Te=d.shift())==null||Te()}else if(ge.data.type==="partial"){const _e=ge.data.seq??0,ue=ge.data.text??"",Re=performance.now()-O;E=!1,Re>=dx?(k=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Re),seq:_e})):Re>=cx&&(A=Math.min(A*2,lx),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Re),newIntervalMs:A,seq:_e})),G||(G=!0,Re>uD&&A<500&&(A=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Re),newIntervalMs:500})));const He=_e!==w||_e<=x;if(!t&&!He&&ue){const lt=ae(ue);lt&&((je=i.onPartial)==null||je.call(i,lt),W===0&&(W=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(W-T)})))}ve()}else if(ge.data.type==="partial-error"){const _e=performance.now()-O;E=!1,_e>=dx?(k=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(_e),seq:ge.data.seq})):_e>=cx&&(A=Math.min(A*2,lx),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(_e),newIntervalMs:A,seq:ge.data.seq})),pt.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),ve()}else ge.data.type==="error"?(t||i.onError(ge.data.error),(Ze=d.shift())==null||Ze()):ge.data.type==="status"?(t||(ye=i.onModelStatus)==null||ye.call(i,ge.data.status,ge.data.message),ge.data.status==="ready"&&(ga=!0,qs=!1)):ge.data.type==="progress"&&(t||(Y=i.onProgress)==null||Y.call(i,ge.data.pct))};e.addEventListener("message",V);const se=ge=>{var Te,je;if(!t){for(pt.warn("speech","createRecognition: worker death event",ge),(Te=i.onStatusChange)==null||Te.call(i,"restarting");d.length;)(je=d.shift())==null||je();if(f.clear(),me(),E=!1,ge.respawned){try{e.removeEventListener("message",V)}catch{}e=fv(),e.addEventListener("message",V)}}};return oy.add(se),{start:async()=>{if(!t){if(ph){i.onError("Speech recognition disabled — please reload the app.");return}!ga&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:ga,modelLoading:qs});try{const ge=new URL("vad/",document.baseURI).href;pt.info("speech","vad: asset base resolved",{vadBase:ge}),JT();const Te=i.inputDeviceId||null,je={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Te&&(je.deviceId={exact:Te}),pt.info("speech","getUserMedia",{hasDeviceId:!!Te,deviceIdPrefix:Te?Te.slice(0,8):null});const Ze=await navigator.mediaDevices.getUserMedia({audio:je});r=Ze,l=new AudioContext;for(const ye of Ze.getAudioTracks())ye.addEventListener("ended",()=>{t||(pt.warn("speech","mic track ended (permission revoked or device removed)"),i.onError("Microphone disconnected or permission revoked"))});try{a=l.createMediaStreamSource(r),p=l.createAnalyser(),p.fftSize=2048,p.smoothingTimeConstant=.3,a.connect(p)}catch(ye){pt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),a=null,p=null}n=await aD.MicVAD.new({audioContext:l,getStream:async()=>Ze,resumeStream:async()=>Ze,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:k1,negativeSpeechThreshold:T1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,Y)=>{var _e;t||((_e=i.onFrame)==null||_e.call(i,ye),b&&(oe(Y),ve()))},onSpeechStart:()=>{var ye;t||(we(),b=!0,T=performance.now(),(ye=i.onSpeechStart)==null||ye.call(i))},onSpeechEnd:ye=>{var Y;t||((Y=i.onStatusChange)==null||Y.call(i,"transcribing"),we(),J(ye))},onVADMisfire:()=>{var ye,Y;t||((ye=i.onStatusChange)==null||ye.call(i,"idle"),we(),(Y=i.onMisfire)==null||Y.call(i))}}),pt.info("speech","vad: ort wasm files loaded",{files:YT()}),n.start()}catch(ge){const Te=ge instanceof Error?ge.message:"Microphone access denied",je=ge instanceof Error?ge.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:Te,stack:je}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(Ze=>Ze.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(Te)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(we();f.size>0;)await Promise.all(Array.from(f));if(n){try{await n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ge,Te)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:Te})}catch(je){pt.warn("speech","setVadThresholds failed",{error:je instanceof Error?je.message:String(je)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,we(),n){try{n.destroy()}catch{}n=null}if(p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.close()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}oy.delete(se),e.removeEventListener("message",V)}}}let zf=null;const ay=new Set,ly=new Set;function gD(){for(const i of ay)try{i()}catch{}}function cy(){for(const i of ly)try{i()}catch{}}function vD(i){return i.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function _D(i){if(!window.speechSynthesis)return;const e=vD(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{zf=performance.now(),gD()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(zf=null,cy())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(zf=null,cy())},window.speechSynthesis.speak(t)}function P1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),zf=null,cy())}function R1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function yD(){return zf}function bD(i){return ay.add(i),()=>{ay.delete(i)}}function wD(i){return ly.add(i),()=>{ly.delete(i)}}function xD(i){R1()&&(i.setVadThresholds(ux,hx),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=bD(()=>{i.setVadThresholds(ux,hx),pt.info("voice","tts.duck.on")}),t=wD(()=>{i.setVadThresholds(k1,T1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const SD=[{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 CD(i){const e=i.trim();return SD.find(t=>t.match.test(e))??null}const ED=4e4;let hd=null;function fh(){hd&&clearTimeout(hd),hd=setTimeout(()=>{hd=null,Ct.getState().stopRecording()},ED)}function _g(){hd&&(clearTimeout(hd),hd=null)}let ic=null,Zl=null;const kD=.04,TD=.3;let mv=0,dy=0;function DD(i){Zl!==null&&cancelAnimationFrame(Zl);const e=()=>{if(ic===null||Ct.getState().submitCountdownStartAt===null){Zl=null;return}const t=performance.now();if(t-dy<200&&mv>TD){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:mv.toFixed(2),msIntoCountdown:Math.round(r)}),Xl(),fh();return}const n=O1();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let l=0;for(let a=0;a<r.length;a++){const d=(r[a]-128)/128;l+=d*d}const p=Math.sqrt(l/r.length);if(p>kD){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Xl(),fh();return}}Zl=requestAnimationFrame(e)};Zl=requestAnimationFrame(e)}function fx(i){ic&&clearTimeout(ic);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),ic=setTimeout(()=>{var r;ic=null,Ct.setState({submitCountdownStartAt:null});const n=St.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=pi.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(pi.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),pi.getState().clearPendingVoiceText(i))}else try{window.api.pty.write({tabId:i,data:"\r"})}catch(l){pt.warn("voice","submit pty.write failed",{error:l instanceof Error?l.message:String(l)})}fh()},e),DD(t)}function Xl(){Zl!==null&&(cancelAnimationFrame(Zl),Zl=null),ic&&(clearTimeout(ic),ic=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let rs=null,Is=null,ff=null;function O1(){var i;return((i=rs==null?void 0:rs.getAnalyser)==null?void 0:i.call(rs))??null}const yg=1e4;let Bf=null;function bg(){Bf&&(clearTimeout(Bf),Bf=null)}let Qg=null,ev=null;function wg(){Qg=null,ev&&(ev(),ev=null)}const AD=1500,ID=9e4;let xg=0,tv=null,uy=-1;function Sg(){tv&&(clearTimeout(tv),tv=null,uy=-1)}const PD=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=Un((i,e)=>({isRecording:!1,externalRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;pt.info("voice","initModel: kicking off preload"),i({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const t=++xg,n=()=>{t===xg&&(Sg(),uy=t,tv=setTimeout(()=>{uy===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},ID))};n(),pD((r,l)=>{t===xg&&(r==="ready"?(Sg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(Sg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===xg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),Sg(),fD(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(rs){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Rv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=I1({inputDeviceId:l,onStatusChange:a=>{i(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&i({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{mv=a.isSpeech,dy=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),_g(),Xl(),R1()){const d=yD(),f=d!==null?performance.now()-d:null;P1(),i({lastBargeInAt:performance.now()}),pt.info("voice","barge-in",{tabId:t,utteranceOffsetMs:f})}else pt.debug("voice","barge-in.no-op",{tabId:t})},onMisfire:()=>{i({lastPartial:"",statusPill:"idle"}),fh();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&pt.warn("voice","barge-in.misfire",{tabId:t,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{var b;fh();const d=a.trim();if(!d||PD.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(ff){ff(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=St.getState().tabs.find(T=>T.id===t))==null?void 0:b.status)==="dormant"){pi.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&fx(t);const T=window;T.__transcripts&&(T.__transcripts.push({tabId:t,text:d}),T.__transcripts.length>500&&T.__transcripts.shift());return}const g=CD(d);if(g){pt.info("voice","voice-command",{tabId:t,label:g.label,transcript:d}),window.api.pty.write({tabId:t,data:g.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Xl();const T=window;T.__transcripts&&(T.__transcripts.push({tabId:t,text:d}),T.__transcripts.length>500&&T.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&fx(t);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:t,text:d}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:a=>{pt.error("voice","recognition error",{err:a}),Xl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,_g(),rs==null||rs.destroy(),rs=null,ff=null,nt.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?i({modelStatus:"ready",loadingProgress:100}):a==="loading"&&i({modelStatus:"loading"})},onProgress:a=>i({loadingProgress:Math.round(a)})});rs=p,ff=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),fh(),p.start().then(()=>{rs===p&&(Is==null||Is(),Is=xD(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),nt.error(`Could not start mic: ${d}`)})}catch(p){i({error:p instanceof Error?p.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var l,p,a;return((a=(p=(l=window.api)==null?void 0:l.voice)==null?void 0:p.getDevicePref)==null?void 0:a.call(p))??Promise.resolve(null)}).then(l=>r((l==null?void 0:l.selectedDeviceId)??null)).catch(l=>{pt.warn("voice","getDevicePref failed; using default device",{error:l instanceof Error?l.message:String(l)}),r(null)})},stopRecording:()=>{const t=rs;t&&(_g(),Xl(),mv=0,dy=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),rs===t&&(rs=null,ff=null),e().hotkeyState==="stopping"&&(bg(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=rs;if(!t)return;_g(),Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:""});try{await t.stop()}catch(l){pt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}t.destroy(),rs===t&&(rs=null);const{useSessions:n}=await Bn(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>OT);return{useSessions:l}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},setExternalRecording:t=>i({externalRecording:t}),toggleTTS:()=>i(t=>({ttsEnabled:!t.ttsEnabled})),setAutoSubmit:t=>i({autoSubmit:t}),setSubmitDelayMs:t=>i({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(t)))}),cancelSubmit:()=>Xl(),setPartialsEnabled:t=>{e().partialsEnabled!==t&&(i({partialsEnabled:t}),t||i({lastPartial:""}))},clearError:()=>i({error:null,errorKind:null}),setPermissionState:t=>{e().permissionState!==t&&(pt.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:t}),i({permissionState:t}))},setLevelMeterEnabled:t=>{e().levelMeterEnabled!==t&&i({levelMeterEnabled:t})},setTurnDetectorRuntimeState:t=>{e().turnDetectorState!==t&&(i({turnDetectorState:t}),t==="load_failed"?pt.warn("voice-turn","voice-turn.load_failed"):t==="runtime_error"?pt.warn("voice-turn","voice-turn.runtime_error"):t==="disabled"&&pt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:t=>{e().wizardArmed!==t&&i({wizardArmed:t})},openWizard:()=>{e().wizardOpen||i({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&i({wizardOpen:!1})},armHotkey:({phase:t,source:n,mode:r,tabId:l})=>{const p=e(),{canRecord:a,reason:d}=gv(p);if(t==="down"){if(d==="error"||d==="load-timeout"){p.resetAndRetryModel(),pt.info("voice-hotkey","down.retry",{source:n,reason:d});return}if(!a&&d!=="loading"){pt.warn("voice-hotkey","miss-model-loading",{modelStatus:p.modelStatus,reason:d});return}if(p.hotkeyState==="recording"||p.isRecording){(r==="toggle"||n==="global")&&(i({hotkeyState:"stopping"}),bg(),Bf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:yg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},yg),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),wg(),Qg={tabId:l,source:n,mode:r},ev=Ct.subscribe((f,g)=>{if(Qg&&f.modelStatus==="ready"&&g.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Qg;if(wg(),!m.tabId){pt.warn("voice-hotkey","armed-promote-no-tab",{source:m.source}),i({hotkeyState:"idle"});return}pt.info("voice-hotkey","armed-promote",m),i({hotkeyState:"recording"}),Ct.getState().startRecording(m.tabId)}});return}if(!l){pt.warn("voice-hotkey","no-active-tab",{source:n});return}pt.info("voice-hotkey","start",{source:n,mode:r,tabId:l}),p.startRecording(l),e().isRecording?i({hotkeyState:"recording"}):(pt.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),i({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(p.hotkeyState==="armed"){wg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),bg(),Bf=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:yg}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},yg),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(wg(),Xl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(bg(),i({hotkeyState:"destroyed"}))}})),RD=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),gv=i=>Rv()?i.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:i.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:i.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:i.modelStatus==="error"?{canRecord:!1,reason:i.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const i=window;i.__voice=Ct,i.__transcripts=[]}const Yf=6e4,OD=3e5,LD=.25,$D=5e3,Jf=Un(()=>({data:null,refreshing:!1}));let mx=!1,iv=null,h_=Yf,Cg=!1,Za=null;function ND(i,e){if(i.kind==="ok")return{delayMs:Yf,nextBackoffMs:Yf};const t=Math.min(e*2,OD),n=t*LD;let r=t+(Math.random()*2-1)*n;const l=i.kind==="meter_rate_limited"?i.retryAfterMs:void 0;return typeof l=="number"&&Number.isFinite(l)&&l>r&&(r=l),{delayMs:r,nextBackoffMs:t}}function gx(){return n1(window.api.billing.fetch(),$D,"billing.fetch")}function vx(i){Jf.setState({data:i,refreshing:!1})}async function mb(){Jf.setState({refreshing:!0});let i=Yf;try{const e=await gx();Za&&(Za.cancel(),Za=null),vx(e);const{delayMs:t,nextBackoffMs:n}=ND(e,h_);h_=n,i=t}catch(e){h_=Yf,Jf.setState({refreshing:!1});const t=s1({error:e,retry:gx,onRetrySuccess:n=>{Za=null,vx(n)},onStillFailing:n=>{Za=null,Cg||(Cg=!0,nt.warn(`Billing usage fetch: ${n}`))}});if(t)Za=t;else if(!Cg){Cg=!0;const n=e instanceof Error?e.message:String(e);nt.warn(`Billing usage fetch failed: ${n}`)}}iv=setTimeout(mb,i)}function MD(){mx||(mx=!0,mb())}function L1(i){return i?i.kind==="ok"||i.kind==="ok-stale"?i.data:(i.kind==="auth"||i.kind==="meter_rate_limited")&&i.cached?i.cached:null:null}function jD(){iv!==null&&(clearTimeout(iv),iv=null),Za&&(Za.cancel(),Za=null),mb()}function Zf(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku|fable)[-_](\d+)[-_.]?(\d+)?/i.exec(i);if(!t)return i;const n=t[1].charAt(0).toUpperCase()+t[1].slice(1).toLowerCase(),r=t[3]?`${t[2]}.${t[3]}`:t[2];return e?`${n} ${r} ${e[1]}`:`${n} ${r}`}function Qa(i){const e=/(opus|sonnet|haiku|fable)/i.exec(i);return e?e[1].toLowerCase():null}const Eg=new Map,zD=3e4;function gb(i){const[e,t]=B.useState(()=>{var n;return i?((n=Eg.get(i))==null?void 0:n.value)??null:null});return B.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=Eg.get(i);if(l&&Date.now()-l.ts<zD){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;Eg.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;Eg.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function BD(i){return i.filter(e=>e.group==="Tools").map(({key:e,label:t,icon:n,hint:r})=>({key:e,label:t,icon:n,hint:r}))}const hy="sm.almanac.sidebarWidth",$1=180,N1=480,py=252;function UD(){try{const i=parseInt(localStorage.getItem(hy)??"",10);if(Number.isFinite(i))return Math.min(N1,Math.max($1,i))}catch{}return py}const GD=52,M1="sm.almanac.sidebarCollapsed";function HD(){try{return localStorage.getItem(M1)==="1"}catch{}return!1}const j1="sm.almanac.collapsedGroups";function FD(){try{const i=localStorage.getItem(j1);if(!i)return new Set;const e=JSON.parse(i);return Array.isArray(e)?new Set(e.filter(t=>t==="Workspace"||t==="Configure"||t==="Tools")):new Set}catch{return new Set}}function WD(){const i=St(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:Nr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function VD({active:i,onNavigate:e,onNewSession:t}){const[n,r]=B.useState(()=>FD()),l=B.useCallback(L=>{r(G=>{const W=new Set(G);W.has(L)?W.delete(L):W.add(L);try{localStorage.setItem(j1,JSON.stringify(Array.from(W)))}catch{}return W})},[]),[p,a]=B.useState(()=>HD()),d=B.useCallback(()=>{a(L=>{const G=!L;try{localStorage.setItem(M1,G?"1":"0")}catch{}return G})},[]),f=St(L=>L.tabs),g=St(L=>L.activeTabId),m=f.find(L=>L.id===g)??null,b=WD(),T=Ii(L=>L.navFace),E=MT(T),k=E.filter(L=>L.group==="Workspace"),y=E.filter(L=>L.group==="Configure"),S=BD(E),w=T==="home"&&!p,[x,A]=B.useState(()=>UD()),O=B.useRef(x);O.current=x;const $=B.useCallback(L=>{L.preventDefault();const G=L.clientX,W=O.current;let re=W;const ae=pe=>{re=Math.min(N1,Math.max($1,W+(pe.clientX-G))),A(re)},Z=()=>{window.removeEventListener("pointermove",ae),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(hy,String(re))}catch{}};window.addEventListener("pointermove",ae),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=B.useCallback(()=>{A(py);try{localStorage.setItem(hy,String(py))}catch{}},[]);return c.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?GD:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[c.jsx(qD,{tab:m,navFace:T,onNewSession:t,rail:p,onToggleRail:d}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:w?c.jsxs(c.Fragment,{children:[c.jsx(p_,{label:"Workspace",desc:o_.Workspace,collapsed:n.has("Workspace"),count:k.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&k.map(L=>c.jsx(f_,{item:L,active:i===L.key,live:L.liveKind?b[L.liveKind]:!1,onClick:()=>e(L.key),rail:!1},L.key)),c.jsx(p_,{label:"Configure",desc:o_.Configure,collapsed:n.has("Configure"),count:y.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&y.map(L=>c.jsx(f_,{item:L,active:i===L.key,live:!1,onClick:()=>e(L.key),rail:!1},L.key)),S.length>0&&c.jsx(p_,{label:"Tools",desc:o_.Tools,collapsed:n.has("Tools"),count:S.length,onToggle:()=>l("Tools")}),S.length>0&&!n.has("Tools")&&S.map(L=>c.jsx(_x,{tool:L,active:i===L.key,onClick:()=>e(L.key),rail:!1},L.key))]}):c.jsx("div",{className:"pt-2",children:E.map(L=>L.group==="Tools"?c.jsx(_x,{tool:{key:L.key,label:L.label,icon:L.icon,hint:L.hint},active:i===L.key,onClick:()=>e(L.key),rail:p},L.key):c.jsx(f_,{item:L,active:i===L.key,live:L.liveKind?b[L.liveKind]:!1,onClick:()=>e(L.key),rail:p},L.key))})}),c.jsx(KD,{rail:p,navFace:T}),!p&&c.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:$,onDoubleClick:j,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 qD({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=gb((i==null?void 0:i.cwd)??null);return n?c.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[c.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:c.jsx(Vs,{name:"plus",size:15,stroke:1.8})}),c.jsx("button",{onClick:r,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:c.jsx(Vs,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?c.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),c.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:c.jsx(Vs,{name:"chevron",size:13,stroke:1.8})})})]}),c.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:c.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:[c.jsx(Vs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):c.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),c.jsx("button",{onClick:r,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:c.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:c.jsx(Vs,{name:"chevron",size:13,stroke:1.8})})})]}),c.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[c.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),c.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),c.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),c.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:c.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:[c.jsx(Vs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function p_({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return c.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[c.jsxs("button",{onClick:r,"aria-expanded":!t,title:t?`Expand ${i}`:`Collapse ${i}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[c.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),c.jsx("span",{className:"flex-1",children:i}),t&&c.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&c.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 f_({item:i,active:e,live:t,onClick:n,rail:r}){return c.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":i.key==="terminal"?"tour-sessions":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&c.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),c.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:c.jsx(Vs,{name:i.icon,size:17,stroke:1.6})}),!r&&c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsx("span",{className:"block truncate",children:i.label}),i.hint&&c.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&c.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&c.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 _x({tool:i,active:e,onClick:t,rail:n}){return c.jsxs("button",{onClick:t,title:i.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${n?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&c.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),c.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:c.jsx(Vs,{name:i.icon,size:15,stroke:1.6})}),!n&&c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsx("span",{className:"block truncate",children:i.label}),i.hint&&c.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function KD({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=St(d=>d.tabs),r=St(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=B.useState(null);return B.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return YS(l.presetId).then(f=>{d||a((f==null?void 0:f.model)??null)}).catch(()=>{d||a(null)}),()=>{d=!0}},[l==null?void 0:l.presetId]),i?c.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):c.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:[c.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")&&c.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Zf(p)}`:"Claude Code"})]})}const Cn={dialog:"z-50",tour:"z-[500]",contextMenu:"z-[600]",contextMenuScrim:"z-[590]",contextMenuDialog:"z-[700]",toast:"z-[900]",recording:"z-[1000]"},XD={dialog:50};function YD(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function JD(i,e,t){return{tabId:i,sessionUuid:t,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}function ZD(i,e,t){const n=Date.now(),r={...i,lastEventAt:t!=null&&t.replay?i.lastEventAt:n},l=[],p=(a,d)=>a.length>d?a.slice(0,d-1)+"…":a;switch(e.kind){case"todo_write":{const a=Array.isArray(e.data)?e.data:[];r.todos=a,t!=null&&t.replay||l.push({id:0,kind:"todo-update",at:n,label:`Todos · ${a.length} item${a.length!==1?"s":""}`});break}case"tool_use":{const a=e.data,d=a.input,f={};for(const g of["command","file_path","pattern","url","query","subagent_type","description"])d&&g in d&&(f[g]=d[g]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const g=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),b=typeof(g==null?void 0:g.file_path)=="string"?g.file_path:void 0,T=typeof(g==null?void 0:g.command)=="string"?g.command:void 0,E=b?b.split("/").pop()??b:T?p(T,28):"";l.push({id:0,kind:"tool-use",at:n,label:E?`${a.name} · ${E}`:a.name,target:b??T,toolName:a.name}),m&&b&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(b.split("/").pop()??b,34)}`,target:b,toolName:a.name})}break}case"plan":{const a=e.data,d=typeof a=="string"?a:(a==null?void 0:a.plan)??JSON.stringify(a);r.plans=[{at:n,content:d??""},...i.plans].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"plan-revision",at:n,label:"Plan revised"});break}case"agent_spawn":{const a=e.data;r.agents=[{id:a==null?void 0:a.toolUseId,at:n,subagentType:a==null?void 0:a.subagent_type,description:a==null?void 0:a.description,lastActivityAt:n},...i.agents].slice(0,50),t!=null&&t.replay||l.push({id:0,kind:"agent-spawn",at:n,label:a!=null&&a.subagent_type?`Agent: ${p(a.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const a=e.data,d=(i.usage.inputTokens||0)+(i.usage.outputTokens||0),f=a.input_tokens??a.inputTokens??0,g=a.output_tokens??a.outputTokens??0,m=d+f+g;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+g,cacheCreationInputTokens:(i.usage.cacheCreationInputTokens||0)+(a.cache_creation_input_tokens??a.cacheCreationInputTokens??0),cacheReadInputTokens:(i.usage.cacheReadInputTokens||0)+(a.cache_read_input_tokens??a.cacheReadInputTokens??0)},!(t!=null&&t.replay)&&Math.floor(m/1e3)>Math.floor(d/1e3)&&l.push({id:0,kind:"usage-tick",at:n,label:`${Math.floor(m/1e3)}k tokens`});break}case"tool_result":{const a=e.data;r.agents=YD(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const nv=Un((i,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(t,n,r)=>{const l={...e().refs};if(l[t]=(l[t]??0)+1,i({refs:l}),l[t]>1)return;i({tabs:{...e().tabs,[t]:JD(t,n,r)}});const p=window.api.transcripts.onEvent(t,a=>e().ingestBatch(t,a));i({unsubs:{...e().unsubs,[t]:p}}),window.api.transcripts.subscribe({tabId:t,cwd:n,sessionUuid:r}).then(async a=>{const d=e().tabs[t];if(!d)return;if(!a.ok){const{toast:g}=await Bn(async()=>{const{toast:m}=await Promise.resolve().then(()=>e1);return{toast:m}},void 0,import.meta.url);g.error(`Live view unavailable: ${a.error??"subscribe failed"}`),i({tabs:{...e().tabs,[t]:{...d,path:null}}});return}i({tabs:{...e().tabs,[t]:{...d,path:a.path}}});const f=await window.api.transcripts.buffer(t);e().ingestBatch(t,f,{replay:!0})}).catch(a=>console.error("[live] transcripts.subscribe failed:",t,a))},unsubscribe:t=>{const n={...e().refs};if(!n[t])return;if(n[t]--,n[t]>0){i({refs:n});return}delete n[t];const r=e().unsubs[t];r==null||r();const l={...e().unsubs};delete l[t];const p={...e().tabs};delete p[t],window.api.transcripts.unsubscribe(t),i({refs:n,unsubs:l,tabs:p})},ingest:(t,n,r)=>{e().ingestBatch(t,[n],r)},ingestBatch:(t,n,r)=>{const l=e().tabs[t];if(!l||n.length===0)return;let p=l,a=[];for(const d of n){const{next:f,newActivity:g}=ZD(p,d,r);p=f,a=a.concat(g)}if(a.length>0){let d=l.activitySeq;const f=a.map(g=>({...g,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function QD(i){const e=nv(r=>r.subscribe),t=nv(r=>r.unsubscribe),n=nv(r=>i?r.tabs[i.id]:void 0);return B.useEffect(()=>{if(i)return e(i.id,i.cwd,i.sessionId),()=>t(i.id)},[i==null?void 0:i.id,i==null?void 0:i.cwd,i==null?void 0:i.sessionId,e,t]),n}function z1(i){if(!i)return null;const e=new Date(i);if(Number.isNaN(e.getTime()))return null;const t=e.getTime()-Date.now();if(t<=0)return{rel:"now",abs:""};const n=Math.floor(t/864e5),r=Math.floor(t%864e5/36e5),l=Math.floor(t%36e5/6e4),p=n>0?`${n}d ${r}h`:r>0?`${r}h ${l}m`:`${l}m`,a=n>=1?e.toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"short",hour:"numeric",minute:"2-digit"}):e.toLocaleTimeString("en-US",{timeZone:"America/Los_Angeles",hour:"numeric",minute:"2-digit"});return{rel:p,abs:`${a} PT`}}function fy(i){return!i||typeof i.utilization!="number"||Number.isNaN(i.utilization)?null:Math.round(i.utilization)}function yx(i,e){const t=fy(e);if(t==null)return`${i} — usage unavailable`;const n=z1((e==null?void 0:e.resets_at)??null),r=n?` · resets in ${n.rel}${n.abs?` (${n.abs})`:""}`:"";return`${i} · ${t}% used${r} — click to open Home`}function VB(i,e){return i?i==="session"||i==="five_hour"?"Session · 5h":i==="weekly_all"?"Weekly · all models":i==="weekly_scoped"?"Weekly · scoped":i:null}const B1=B.createContext(null);function e2({panelId:i,children:e}){return c.jsx(B1.Provider,{value:i,children:e})}function Ov(i){const e=B.useContext(B1),t=i??e;return Ii(n=>t==null||n.focusedPanelId===t)}function vb(i){const e=Ov(i),t=B.useRef(e);return t.current=e,t}const t2=5e3;let U1=null;const my=new Set;let m_=0,Uf=null;function i2(){my.forEach(i=>i())}async function bx(){try{U1=await window.api.schedule.sessionSlots(),i2()}catch{}}function n2(){Uf==null&&(bx(),Uf=setInterval(()=>{bx()},t2))}function s2(){Uf!=null&&(clearInterval(Uf),Uf=null)}function _b(i){const e=Ov(i),[,t]=B.useState(0);return B.useEffect(()=>{const n=()=>t(r=>r+1);return my.add(n),()=>{my.delete(n)}},[]),B.useEffect(()=>{if(e)return m_+=1,n2(),()=>{m_-=1,m_<=0&&s2()}},[e]),U1}const r2=360*60*1e3;let G1=null;const gy=new Set;let g_=0,Gf=null;async function wx(){try{G1=await window.api.app.updateStatus(),gy.forEach(i=>i())}catch{}}function o2(){Gf==null&&(wx(),Gf=setInterval(()=>{wx()},r2))}function a2(){Gf!=null&&(clearInterval(Gf),Gf=null)}function l2(){const[,i]=B.useState(0);return B.useEffect(()=>{const e=()=>i(t=>t+1);return gy.add(e),g_+=1,o2(),()=>{gy.delete(e),g_-=1,g_<=0&&a2()}},[]),G1}function c2({total:i,inUse:e,size:t}){const n=Math.min(Math.max(e,0),i),r=t==="md"?"w-3.5 h-3.5 rounded-full border":"w-2 h-2 rounded-full border";return c.jsx(c.Fragment,{children:Array.from({length:i},(l,p)=>c.jsx("span",{"data-testid":"slot-dot","data-filled":p<n?"true":"false",className:`${r} ${p<n?"bg-accent border-accent":"bg-bg border-line"}`},p))})}function d2({onNavigate:i}){const e=St(ae=>ae.tabs),t=St(ae=>ae.activeTabId),n=e.find(ae=>ae.id===t)??null,r=QD(n),l=(r==null?void 0:r.lastEventAt)??0,p=Jf(ae=>ae.data),a=Nr(ae=>{var Z;return((Z=ae.snapshot)==null?void 0:Z.paused)??null}),d=gb((n==null?void 0:n.cwd)??null),f=_b(),g=l2(),[,m]=B.useState(0);B.useEffect(()=>{const ae=setInterval(()=>m(Z=>Z+1),6e4);return()=>clearInterval(ae)},[]);const b=(r==null?void 0:r.todos)??[],[T,E]=B.useState(!1),k=B.useRef(null);B.useEffect(()=>{if(!T)return;const ae=Z=>{k.current&&!k.current.contains(Z.target)&&E(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[T]),B.useEffect(()=>{b.length===0&&E(!1)},[b.length]);const y=L1(p),S=(y==null?void 0:y.usage.five_hour)??null,w=(y==null?void 0:y.usage.seven_day)??null,x=fy(S),A=fy(w),O=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",$=l>0?p2(Date.now()-l):"—",j=(f==null?void 0:f.total)??5,L=f?Math.min(Math.max(f.inUse,0),f.total):0,G=f?`${L} / ${j}`:`— / ${j}`,W=f&&f.holders.length>0?`
2911
2911
  `+f.holders.slice(0,5).map(ae=>ae.owner).join(`
2912
- `):"",re=`${G} Claude sessions running${W}`;return c.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:[c.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:O?"Connected to Anthropic":"Disconnected",children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-sage":"bg-fg-faint"}`}),c.jsx("span",{children:O?"connected":"offline"})]}),c.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:yx("Session (5h window)",S),"data-testid":"footer-usage-session",children:["session ",c.jsx("span",{className:"text-fg",children:x!=null?`${x}%`:"—"})]}),c.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:yx("Weekly window (all models)",w),"data-testid":"footer-usage-weekly",children:["weekly ",c.jsx("span",{className:"text-fg",children:A!=null?`${A}%`:"—"})]}),a&&c.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&c.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&c.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),c.jsxs("span",{className:"text-fg-faint",children:["last activity: ",c.jsx("span",{className:"text-fg-dim",children:$})]}),b.length>0&&c.jsx(u2,{ref:k,todos:b,open:T,onToggle:()=>E(ae=>!ae)}),c.jsx("span",{className:"flex-1"}),c.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:re,"data-testid":"footer-active-sessions",children:f&&f.total===0?c.jsx("span",{className:"text-fg-faint",children:"pool paused"}):c.jsx(c2,{total:j,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),g!=null&&g.behind&&g.latest?c.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",g.current," → v",g.latest]}):c.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.94.0"]})]})}const u2=B.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return c.jsxs("div",{ref:r,className:"relative",children:[c.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[c.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),c.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),c.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),c.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&c.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 ${Cn.dialog}`,"data-testid":"footer-todos-popover",children:c.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>c.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[c.jsx(h2,{status:p.status}),c.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function h2({status:i}){return i==="completed"?c.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?c.jsx("span",{className:"w-3 shrink-0",children:c.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):c.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function p2(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function f2({onClose:i,onSent:e}){const t=St(j=>j.tabs),[n,r]=B.useState(""),[l,p]=B.useState(()=>Object.fromEntries(t.map(j=>[j.id,!0]))),[a,d]=B.useState(!1),[f,g]=B.useState({}),m=B.useRef(null),b=B.useRef(e);B.useEffect(()=>{b.current=e},[e]),B.useEffect(()=>{p(j=>{const L={};for(const G of t)L[G.id]=j[G.id]??!0;return L})},[t]),B.useEffect(()=>{var j;(j=m.current)==null||j.focus()},[]),B.useEffect(()=>window.api.pty.onWriteError(L=>{g(G=>L.tabId in G?{...G,[L.tabId]:"skipped"}:G)}),[]),B.useEffect(()=>{if(Object.keys(f).length===0)return;const j=Object.values(f).filter(G=>G==="sent").length,L=window.setTimeout(()=>b.current(j),1500);return()=>window.clearTimeout(L)},[f]);const T=t.filter(j=>l[j.id]).map(j=>j.id),E=T.length,k=Object.keys(f).length>0,y=n.length>0&&E>0&&!a&&!k,S=()=>{if(!y)return;d(!0);const j=St.getState().tabs,L=new Set(j.map(W=>W.id)),G={};for(const W of T)L.has(W)?(window.api.pty.write({tabId:W,data:n+"\r"}),G[W]="sent"):G[W]="skipped";g(G),d(!1)},w=j=>{if(j.key==="Escape"){j.preventDefault(),j.stopPropagation(),i();return}j.key==="Enter"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),S())},x=t.length>0&&t.every(j=>l[j.id]),A=()=>{const j=!x;p(Object.fromEntries(t.map(L=>[L.id,j])))},O=Object.values(f).some(j=>j==="skipped"),$=k?O?"Sent (some skipped)":"Sent":`Send to ${E} tab${E===1?"":"s"}`;return c.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:w,"data-testid":"broadcast-bar",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),c.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),c.jsx("textarea",{ref:m,value:n,onChange:j=>r(j.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"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[c.jsx("input",{type:"checkbox",checked:x,onChange:A,className:"accent-accent"}),c.jsxs("span",{children:["All tabs (",E,"/",t.length,")"]})]}),c.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(j=>c.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[c.jsx("input",{type:"checkbox",checked:!!l[j.id],onChange:L=>p(G=>({...G,[j.id]:L.target.checked})),className:"accent-accent"}),c.jsx("span",{className:"truncate max-w-[12rem]",children:j.label}),f[j.id]==="sent"&&c.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[j.id]==="skipped"&&c.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},j.id))})]}),c.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[c.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),c.jsx("button",{onClick:S,disabled:!y,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:$})]})]})}function m2({tabId:i,cwd:e,onClose:t}){const n=jf(E=>E.watchersForTab(i)),r=jf(E=>E.add),l=jf(E=>E.remove),p=B.useRef(null),[a,d]=B.useState(""),[f,g]=B.useState(""),[m,b]=B.useState(!1);B.useEffect(()=>{const E=k=>{k.key==="Escape"&&t()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]),B.useEffect(()=>{const E=k=>{p.current&&!p.current.contains(k.target)&&t()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[t]);const T=async()=>{const E=f.trim();if(!E||m)return;b(!0);const k=await r({tabId:i,label:a.trim(),command:E,cwd:e});b(!1),k&&(d(""),g(""))};return c.jsxs("div",{ref:p,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[c.jsxs("div",{className:"flex items-center mb-2",children:[c.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),c.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),c.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[c.jsx("input",{value:a,onChange:E=>d(E.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"}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("input",{value:f,onChange:E=>g(E.target.value),onKeyDown:E=>{E.key==="Enter"&&T()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),c.jsx("button",{onClick:T,disabled:!f.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),c.jsxs("span",{className:"text-fg-faint",children:["cwd: ",c.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?c.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):c.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(E=>{const k=E.lines[E.lines.length-1];return c.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-medium text-fg truncate",children:E.label}),c.jsxs("span",{className:"text-fg-faint",children:[E.lineCount," line",E.lineCount===1?"":"s"]}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:()=>l(E.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${E.watcherId}`,children:"stop"})]}),c.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:E.command,children:E.command}),c.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:c.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},E.watcherId)})})]})}/**
2912
+ `):"",re=`${G} Claude sessions running${W}`;return c.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:[c.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:O?"Connected to Anthropic":"Disconnected",children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-sage":"bg-fg-faint"}`}),c.jsx("span",{children:O?"connected":"offline"})]}),c.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:yx("Session (5h window)",S),"data-testid":"footer-usage-session",children:["session ",c.jsx("span",{className:"text-fg",children:x!=null?`${x}%`:"—"})]}),c.jsxs("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:yx("Weekly window (all models)",w),"data-testid":"footer-usage-weekly",children:["weekly ",c.jsx("span",{className:"text-fg",children:A!=null?`${A}%`:"—"})]}),a&&c.jsxs("button",{onClick:()=>i==null?void 0:i("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${a.reason==="auth"||a.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&c.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&c.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),c.jsxs("span",{className:"text-fg-faint",children:["last activity: ",c.jsx("span",{className:"text-fg-dim",children:$})]}),b.length>0&&c.jsx(u2,{ref:k,todos:b,open:T,onToggle:()=>E(ae=>!ae)}),c.jsx("span",{className:"flex-1"}),c.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"flex items-center gap-1 hover:text-fg transition-colors",title:re,"data-testid":"footer-active-sessions",children:f&&f.total===0?c.jsx("span",{className:"text-fg-faint",children:"pool paused"}):c.jsx(c2,{total:j,inUse:(f==null?void 0:f.inUse)??0,size:"sm"})}),g!=null&&g.behind&&g.latest?c.jsxs("span",{className:"text-amber-300",title:"A newer version is published — update the app. A stale npx cache can pin an old version.","data-testid":"footer-version",children:["v",g.current," → v",g.latest]}):c.jsxs("span",{className:"text-fg-dim","data-testid":"footer-version",children:["v",(g==null?void 0:g.current)??"0.95.0"]})]})}const u2=B.forwardRef(function({todos:e,open:t,onToggle:n},r){const l={completed:e.filter(p=>p.status==="completed").length,in_progress:e.filter(p=>p.status==="in_progress").length,pending:e.filter(p=>p.status==="pending").length};return c.jsxs("div",{ref:r,className:"relative",children:[c.jsxs("button",{onClick:n,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[c.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),c.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),c.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),c.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&c.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 ${Cn.dialog}`,"data-testid":"footer-todos-popover",children:c.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>c.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[c.jsx(h2,{status:p.status}),c.jsx("span",{className:p.status==="completed"?"text-fg-faint line-through":p.status==="in_progress"?"text-fg":"text-fg-dim",children:p.status==="in_progress"&&p.activeForm?p.activeForm:p.content})]},a))})})]})});function h2({status:i}){return i==="completed"?c.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?c.jsx("span",{className:"w-3 shrink-0",children:c.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):c.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function p2(i){const e=Math.max(0,Math.floor(i/1e3));if(e<60)return`${e}s ago`;const t=Math.floor(e/60);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ago`}function f2({onClose:i,onSent:e}){const t=St(j=>j.tabs),[n,r]=B.useState(""),[l,p]=B.useState(()=>Object.fromEntries(t.map(j=>[j.id,!0]))),[a,d]=B.useState(!1),[f,g]=B.useState({}),m=B.useRef(null),b=B.useRef(e);B.useEffect(()=>{b.current=e},[e]),B.useEffect(()=>{p(j=>{const L={};for(const G of t)L[G.id]=j[G.id]??!0;return L})},[t]),B.useEffect(()=>{var j;(j=m.current)==null||j.focus()},[]),B.useEffect(()=>window.api.pty.onWriteError(L=>{g(G=>L.tabId in G?{...G,[L.tabId]:"skipped"}:G)}),[]),B.useEffect(()=>{if(Object.keys(f).length===0)return;const j=Object.values(f).filter(G=>G==="sent").length,L=window.setTimeout(()=>b.current(j),1500);return()=>window.clearTimeout(L)},[f]);const T=t.filter(j=>l[j.id]).map(j=>j.id),E=T.length,k=Object.keys(f).length>0,y=n.length>0&&E>0&&!a&&!k,S=()=>{if(!y)return;d(!0);const j=St.getState().tabs,L=new Set(j.map(W=>W.id)),G={};for(const W of T)L.has(W)?(window.api.pty.write({tabId:W,data:n+"\r"}),G[W]="sent"):G[W]="skipped";g(G),d(!1)},w=j=>{if(j.key==="Escape"){j.preventDefault(),j.stopPropagation(),i();return}j.key==="Enter"&&(j.metaKey||j.ctrlKey)&&(j.preventDefault(),S())},x=t.length>0&&t.every(j=>l[j.id]),A=()=>{const j=!x;p(Object.fromEntries(t.map(L=>[L.id,j])))},O=Object.values(f).some(j=>j==="skipped"),$=k?O?"Sent (some skipped)":"Sent":`Send to ${E} tab${E===1?"":"s"}`;return c.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:w,"data-testid":"broadcast-bar",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),c.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),c.jsx("textarea",{ref:m,value:n,onChange:j=>r(j.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"}),c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[c.jsx("input",{type:"checkbox",checked:x,onChange:A,className:"accent-accent"}),c.jsxs("span",{children:["All tabs (",E,"/",t.length,")"]})]}),c.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(j=>c.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[c.jsx("input",{type:"checkbox",checked:!!l[j.id],onChange:L=>p(G=>({...G,[j.id]:L.target.checked})),className:"accent-accent"}),c.jsx("span",{className:"truncate max-w-[12rem]",children:j.label}),f[j.id]==="sent"&&c.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[j.id]==="skipped"&&c.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},j.id))})]}),c.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[c.jsx("button",{onClick:i,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),c.jsx("button",{onClick:S,disabled:!y,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:$})]})]})}function m2({tabId:i,cwd:e,onClose:t}){const n=jf(E=>E.watchersForTab(i)),r=jf(E=>E.add),l=jf(E=>E.remove),p=B.useRef(null),[a,d]=B.useState(""),[f,g]=B.useState(""),[m,b]=B.useState(!1);B.useEffect(()=>{const E=k=>{k.key==="Escape"&&t()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[t]),B.useEffect(()=>{const E=k=>{p.current&&!p.current.contains(k.target)&&t()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[t]);const T=async()=>{const E=f.trim();if(!E||m)return;b(!0);const k=await r({tabId:i,label:a.trim(),command:E,cwd:e});b(!1),k&&(d(""),g(""))};return c.jsxs("div",{ref:p,className:"absolute right-2 top-full mt-1 z-30 w-[420px] max-w-[calc(100vw-1rem)] bg-bg-elev border border-line rounded shadow-lg p-3 text-xs",role:"dialog","aria-label":"Watchers","data-testid":"watchers-popover",children:[c.jsxs("div",{className:"flex items-center mb-2",children:[c.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),c.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),c.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[c.jsx("input",{value:a,onChange:E=>d(E.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"}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("input",{value:f,onChange:E=>g(E.target.value),onKeyDown:E=>{E.key==="Enter"&&T()},placeholder:"shell command — e.g. npm test --watch",className:"flex-1 bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint font-mono","data-testid":"watcher-command-input"}),c.jsx("button",{onClick:T,disabled:!f.trim()||m,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"watcher-add",children:"Add"})]}),c.jsxs("span",{className:"text-fg-faint",children:["cwd: ",c.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?c.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):c.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(E=>{const k=E.lines[E.lines.length-1];return c.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"font-medium text-fg truncate",children:E.label}),c.jsxs("span",{className:"text-fg-faint",children:[E.lineCount," line",E.lineCount===1?"":"s"]}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:()=>l(E.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${E.watcherId}`,children:"stop"})]}),c.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:E.command,children:E.command}),c.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:c.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},E.watcherId)})})]})}/**
2913
2913
  * dockview-core
2914
2914
  * @version 6.6.1
2915
2915
  * @link https://github.com/mathuo/dockview
@@ -2920,7 +2920,7 @@ ${P}`,N=v.createShaderModule({code:R,label:s.name});oi("verbose",()=>`[WebGPU] $
2920
2920
  * @link https://github.com/mathuo/dockview
2921
2921
  * @license MIT
2922
2922
  */const bC=(i,e)=>{const[,t]=Ot.useState(0),n=Ot.useRef(i.componentProps);return Ot.useImperativeHandle(e,()=>({update:r=>{n.current=Object.assign(Object.assign({},n.current),r),t(l=>l+1)}}),[]),Ot.createElement(i.component,n.current)};bC.displayName="DockviewReactJsBridge";const pI=(()=>{let i=1;return{next:()=>`dockview_react_portal_key_${(i++).toString()}`}})(),fI=Ot.createContext({});class ya{constructor(e,t,n,r,l){this.parent=e,this.portalStore=t,this.component=n,this.parameters=r,this.context=l,this._initialProps={},this.disposed=!1,this.createPortal()}update(e){if(this.disposed)throw new Error("invalid operation: resource is already disposed");this.componentInstance?this.componentInstance.update(e):this._initialProps=Object.assign(Object.assign({},this._initialProps),e)}createPortal(){if(this.disposed)throw new Error("invalid operation: resource is already disposed");if(!mI(this.component))throw new Error("Dockview: Only React.memo(...), React.ForwardRef(...) and functional components are accepted as components");const e=Ot.createElement(Ot.forwardRef(bC),{component:this.component,componentProps:this.parameters,ref:r=>{this.componentInstance=r,Object.keys(this._initialProps).length>0&&(this.componentInstance.update(this._initialProps),this._initialProps={})}}),t=this.context?Ot.createElement(fI.Provider,{value:this.context},e):e,n=hI.createPortal(t,this.parent,pI.next());this.ref={portal:n,disposable:this.portalStore.addPortal(n)}}dispose(){var e;(e=this.ref)===null||e===void 0||e.disposable.dispose(),this.disposed=!0}}const Nv=()=>{const[i,e]=Ot.useState([]);Ot.useDebugValue(`Portal count: ${i.length}`);const t=Ot.useCallback(n=>{e(l=>[...l,n]);let r=!1;return tn.from(()=>{if(r)throw new Error("invalid operation: resource already disposed");r=!0,e(l=>l.filter(p=>p!==n))})},[]);return[i,t]};function mI(i){return typeof i=="function"||!!(i!=null&&i.$$typeof)}class zx{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._onDidFocus=new Ve,this.onDidFocus=this._onDidFocus.event,this._onDidBlur=new Ve,this.onDidBlur=this._onDidBlur.event,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}focus(){}init(e){this.part=new ya(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,containerApi:e.containerApi})}update(e){var t;(t=this.part)===null||t===void 0||t.update({params:e.params})}layout(e,t){}dispose(){var e;this._onDidFocus.dispose(),this._onDidBlur.dispose(),(e=this.part)===null||e===void 0||e.dispose()}}class Bx{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}focus(){}init(e){this.part=new ya(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,containerApi:e.containerApi,tabLocation:e.tabLocation})}update(e){var t;(t=this.part)===null||t===void 0||t.update({params:e.params})}layout(e,t){}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}class Ux{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new ya(this.element,this.reactPortalStore,this.component,{group:e.group,containerApi:e.containerApi})}focus(){}update(e){var t,n,r;this.parameters&&(this.parameters.params=e.params),(t=this.part)===null||t===void 0||t.update({params:(r=(n=this.parameters)===null||n===void 0?void 0:n.params)!==null&&r!==void 0?r:{}})}layout(e,t){}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}class gI{get element(){return this._element}get part(){return this._part}constructor(e,t,n){this.component=e,this.reactPortalStore=t,this._group=n,this.mutableDisposable=new An,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.mutableDisposable.value=new Vt(this._group.model.onDidAddPanel(()=>{this.updatePanels()}),this._group.model.onDidRemovePanel(()=>{this.updatePanels()}),this._group.model.onDidActivePanelChange(()=>{this.updateActivePanel()}),e.api.onDidActiveChange(()=>{this.updateGroupActive()}),e.api.onDidLocationChange(t=>{this.updateLocation(t.location)})),this._part=new ya(this.element,this.reactPortalStore,this.component,{api:e.api,containerApi:e.containerApi,panels:this._group.model.panels,activePanel:this._group.model.activePanel,isGroupActive:this._group.api.isActive,group:this._group,headerPosition:this._group.model.headerPosition,location:e.api.location})}dispose(){var e;this.mutableDisposable.dispose(),(e=this._part)===null||e===void 0||e.dispose()}update(e){var t;(t=this._part)===null||t===void 0||t.update(e.params)}updatePanels(){this.update({params:{panels:this._group.model.panels}})}updateActivePanel(){this.update({params:{activePanel:this._group.model.activePanel}})}updateGroupActive(){this.update({params:{isGroupActive:this._group.api.isActive}})}updateLocation(e){this.update({params:{location:e}})}}class vI{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new ya(this._element,this.reactPortalStore,this.component,e)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}class Gx{get element(){return this._element}constructor(e,t){this.component=e,this.reactPortalStore=t,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.display="inline-flex"}init(e){this.part=new ya(this._element,this.reactPortalStore,this.component,{tabGroup:e.tabGroup,api:e.api})}update(e){var t;(t=this.part)===null||t===void 0||t.update({tabGroup:e.tabGroup})}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}class Hx{get element(){return this._element}constructor(e,t){this.component=e,this.reactPortalStore=t,this._element=document.createElement("div"),this._element.className="dv-react-part",this._element.style.display="inline-flex"}init(e){this.part=new ya(this._element,this.reactPortalStore,this.component,{group:e.group,api:e.api})}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}function nh(i,e){return i?t=>new gI(i,e,t):void 0}const Rg="props.defaultTabComponent";function _I(i){return Ey.reduce((t,n)=>(n in i&&(t[n]=i[n]),t),{})}const wC=Ot.forwardRef((i,e)=>{const t=Ot.useRef(null),n=Ot.useRef(void 0),[r,l]=Nv();Ot.useImperativeHandle(e,()=>t.current,[]);const p=Ot.useRef({});return Ot.useEffect(()=>{const a={};Ey.forEach(d=>{const f=d,g=i[f];f in i&&g!==p.current[f]&&(a[f]=g)}),n.current&&n.current.updateOptions(a),p.current=i},Ey.map(a=>i[a])),Ot.useEffect(()=>{var a;if(!t.current)return;const d=(a=i.tabComponents)!==null&&a!==void 0?a:{};i.defaultTabComponent&&(d[Rg]=i.defaultTabComponent);const f={createLeftHeaderActionComponent:nh(i.leftHeaderActionsComponent,{addPortal:l}),createRightHeaderActionComponent:nh(i.rightHeaderActionsComponent,{addPortal:l}),createPrefixHeaderActionComponent:nh(i.prefixHeaderActionsComponent,{addPortal:l}),createComponent:E=>new zx(E.id,i.components[E.name],{addPortal:l}),createTabComponent(E){return new Bx(E.id,d[E.name],{addPortal:l})},createWatermarkComponent:i.watermarkComponent?()=>new Ux("watermark",i.watermarkComponent,{addPortal:l}):void 0,defaultTabComponent:i.defaultTabComponent?Rg:void 0,createContextMenuItemComponent:E=>{if(E.component)return new vI(E.id,E.component,{addPortal:l})}},g=_I(i);if(i.tabGroupChipComponent){const E=i.tabGroupChipComponent;g.createTabGroupChipComponent=()=>new Gx(E,{addPortal:l})}if(i.groupDragGhostComponent){const E=i.groupDragGhostComponent;g.createGroupDragGhostComponent=()=>new Hx(E,{addPortal:l})}const m=lI(t.current,Object.assign(Object.assign({},g),f)),{clientWidth:b,clientHeight:T}=t.current;return m.layout(b,T),i.onReady&&i.onReady({api:m}),n.current=m,()=>{n.current=void 0,m.dispose()}},[]),Ot.useEffect(()=>{if(!n.current)return()=>{};const a=n.current.onDidDrop(d=>{i.onDidDrop&&i.onDidDrop(d)});return()=>{a.dispose()}},[i.onDidDrop]),Ot.useEffect(()=>{if(!n.current)return()=>{};const a=n.current.onWillDrop(d=>{i.onWillDrop&&i.onWillDrop(d)});return()=>{a.dispose()}},[i.onWillDrop]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createTabGroupChipComponent:i.tabGroupChipComponent?()=>new Gx(i.tabGroupChipComponent,{addPortal:l}):void 0})},[i.tabGroupChipComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createGroupDragGhostComponent:i.groupDragGhostComponent?()=>new Hx(i.groupDragGhostComponent,{addPortal:l}):void 0})},[i.groupDragGhostComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createComponent:a=>new zx(a.id,i.components[a.name],{addPortal:l})})},[i.components]),Ot.useEffect(()=>{var a;if(!n.current)return;const d=(a=i.tabComponents)!==null&&a!==void 0?a:{};i.defaultTabComponent&&(d[Rg]=i.defaultTabComponent),n.current.updateOptions({defaultTabComponent:i.defaultTabComponent?Rg:void 0,createTabComponent(f){return new Bx(f.id,d[f.name],{addPortal:l})}})},[i.tabComponents,i.defaultTabComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createWatermarkComponent:i.watermarkComponent?()=>new Ux("watermark",i.watermarkComponent,{addPortal:l}):void 0})},[i.watermarkComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createRightHeaderActionComponent:nh(i.rightHeaderActionsComponent,{addPortal:l})})},[i.rightHeaderActionsComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createLeftHeaderActionComponent:nh(i.leftHeaderActionsComponent,{addPortal:l})})},[i.leftHeaderActionsComponent]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createPrefixHeaderActionComponent:nh(i.prefixHeaderActionsComponent,{addPortal:l})})},[i.prefixHeaderActionsComponent]),Ot.createElement("div",{style:{height:"100%",width:"100%"},ref:t},r)});wC.displayName="DockviewComponent";class Fx extends aI{constructor(e,t,n,r){super(e,t),this.reactComponent=n,this.reactPortalStore=r}getComponent(){var e,t;return new ya(this.element,this.reactPortalStore,this.reactComponent,{params:(t=(e=this._params)===null||e===void 0?void 0:e.params)!==null&&t!==void 0?t:{},api:this.api,containerApi:new Z1(this._params.accessor)})}}function yI(i){return yy.reduce((t,n)=>(n in i&&(t[n]=i[n]),t),{})}const bI=Ot.forwardRef((i,e)=>{const t=Ot.useRef(null),n=Ot.useRef(void 0),[r,l]=Nv();Ot.useImperativeHandle(e,()=>t.current,[]);const p=Ot.useRef({});return Ot.useEffect(()=>{const a={};yy.forEach(d=>{const f=d,g=i[f];f in i&&g!==p.current[f]&&(a[f]=g)}),n.current&&n.current.updateOptions(a),p.current=i},yy.map(a=>i[a])),Ot.useEffect(()=>{if(!t.current)return()=>{};const a={createComponent:m=>new Fx(m.id,m.name,i.components[m.name],{addPortal:l})},d=cI(t.current,Object.assign(Object.assign({},yI(i)),a)),{clientWidth:f,clientHeight:g}=t.current;return d.layout(f,g),i.onReady&&i.onReady({api:d}),n.current=d,()=>{n.current=void 0,d.dispose()}},[]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createComponent:a=>new Fx(a.id,a.name,i.components[a.name],{addPortal:l})})},[i.components]),Ot.createElement("div",{style:{height:"100%",width:"100%"},ref:t},r)});bI.displayName="SplitviewComponent";class Wx extends _C{constructor(e,t,n,r){super(e,t),this.reactComponent=n,this.reactPortalStore=r}getComponent(){var e,t;return new ya(this.element,this.reactPortalStore,this.reactComponent,{params:(t=(e=this._params)===null||e===void 0?void 0:e.params)!==null&&t!==void 0?t:{},api:this.api,containerApi:new Q1(this._params.accessor)})}}function wI(i){return Sy.reduce((t,n)=>(n in i&&(t[n]=i[n]),t),{})}const xI=Ot.forwardRef((i,e)=>{const t=Ot.useRef(null),n=Ot.useRef(void 0),[r,l]=Nv();Ot.useImperativeHandle(e,()=>t.current,[]);const p=Ot.useRef({});return Ot.useEffect(()=>{const a={};Sy.forEach(d=>{const f=d,g=i[f];f in i&&g!==p.current[f]&&(a[f]=g)}),n.current&&n.current.updateOptions(a),p.current=i},Sy.map(a=>i[a])),Ot.useEffect(()=>{if(!t.current)return()=>{};const a={createComponent:m=>new Wx(m.id,m.name,i.components[m.name],{addPortal:l})},d=dI(t.current,Object.assign(Object.assign({},wI(i)),a)),{clientWidth:f,clientHeight:g}=t.current;return d.layout(f,g),i.onReady&&i.onReady({api:d}),n.current=d,()=>{n.current=void 0,d.dispose()}},[]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createComponent:a=>new Wx(a.id,a.name,i.components[a.name],{addPortal:l})})},[i.components]),Ot.createElement("div",{style:{height:"100%",width:"100%"},ref:t},r)});xI.displayName="GridviewComponent";class Og{get element(){return this._element}constructor(e,t,n){this.id=e,this.component=t,this.reactPortalStore=n,this._element=document.createElement("div"),this._element.style.height="100%",this._element.style.width="100%"}init(e){this.part=new ya(this.element,this.reactPortalStore,this.component,{params:e.params,api:e.api,title:e.title,containerApi:e.containerApi})}toJSON(){return{id:this.id}}update(e){var t;(t=this.part)===null||t===void 0||t.update(e.params)}dispose(){var e;(e=this.part)===null||e===void 0||e.dispose()}}function SI(i){return Cy.reduce((t,n)=>(n in i&&(t[n]=i[n]),t),{})}const CI=Ot.forwardRef((i,e)=>{const t=Ot.useRef(null),n=Ot.useRef(void 0),[r,l]=Nv();Ot.useImperativeHandle(e,()=>t.current,[]);const p=Ot.useRef({});return Ot.useEffect(()=>{const a={};Cy.forEach(d=>{const f=d,g=i[f];f in i&&g!==p.current[f]&&(a[f]=g)}),n.current&&n.current.updateOptions(a),p.current=i},Cy.map(a=>i[a])),Ot.useEffect(()=>{var a;if(!t.current)return()=>{};const d=(a=i.headerComponents)!==null&&a!==void 0?a:{},f={createComponent:T=>new Og(T.id,i.components[T.name],{addPortal:l}),createHeaderComponent:T=>new Og(T.id,d[T.name],{addPortal:l})},g=uI(t.current,Object.assign(Object.assign({},SI(i)),f)),{clientWidth:m,clientHeight:b}=t.current;return g.layout(m,b),i.onReady&&i.onReady({api:g}),n.current=g,()=>{n.current=void 0,g.dispose()}},[]),Ot.useEffect(()=>{n.current&&n.current.updateOptions({createComponent:a=>new Og(a.id,i.components[a.name],{addPortal:l})})},[i.components]),Ot.useEffect(()=>{var a;if(!n.current)return;const d=(a=i.headerComponents)!==null&&a!==void 0?a:{};n.current.updateOptions({createHeaderComponent:f=>new Og(f.id,d[f.name],{addPortal:l})})},[i.headerComponents]),Ot.useEffect(()=>{if(!n.current)return()=>{};const a=n.current.onDidDrop(d=>{i.onDidDrop&&i.onDidDrop(d)});return()=>{a.dispose()}},[i.onDidDrop]),Ot.createElement("div",{style:{height:"100%",width:"100%"},ref:t},r)});CI.displayName="PaneviewComponent";const Vx=new WeakMap;function EI(i,e){var p;const t=Vx.get(e);if(t!==void 0)return t;let n=0;for(const a of e.ticketHistory??[])a.status==="needs-input"&&(n=1);let r=0;for(const a of e.turns)r+=((p=a.toolUses)==null?void 0:p.length)??0;const l=`${i}:${e.running?1:0}:${e.queuedPosition??0}:${e.turns.length}:${r}:${n}`;return Vx.set(e,l),l}function qx(i){const e=[];for(const t of Object.keys(i))e.push(EI(t,i[t]));return e.join("|")}function Mv(){const[i,e]=B.useState(()=>pi.getState().chats);return B.useEffect(()=>{let t=qx(pi.getState().chats);return e(pi.getState().chats),pi.subscribe(n=>{const r=qx(n.chats);r!==t&&(t=r,e(n.chats))})},[]),i}let mh=null;const ky=new Set;let Lg=null;function kI(){return mh?Promise.resolve(mh):Lg||(Lg=window.api.app.homeDir().then(i=>(mh=i,ky.forEach(e=>e(i)),i)),Lg)}function Ab(){const[i,e]=B.useState(mh);return B.useEffect(()=>{if(mh){e(mh);return}const t=n=>e(n);return ky.add(t),kI(),()=>{ky.delete(t)}},[]),i}async function TI(i){const e={};try{const t=await window.api.config.readJson(`${i}/package.json`);if(t.exists&&t.data){const n=t.data.name;typeof n=="string"&&(e.name=n)}}catch{}try{const t=await window.api.config.readText(`${i}/.git/config`);if(t.exists&&t.text){const n=t.text.match(/\[remote "origin"\][^\[]*url\s*=\s*([^\n]+)/);if(n){let r=n[1].trim();r=r.replace(/^git@([^:]+):/,"$1/").replace(/\.git$/,"").replace(/^https?:\/\//,""),e.gitRemote=r}}}catch{}try{const t=await window.api.config.readText(`${i}/.git/HEAD`);if(t.exists&&t.text){const n=t.text.match(/ref: refs\/heads\/(.+)/);n&&(e.lastBranch=n[1].trim())}}catch{}try{const t=await window.api.config.readText(`${i}/CLAUDE.md`);t.exists&&t.text&&(e.claudemdPreview=t.text.slice(0,200))}catch{}if(!e.name){const t=i.split("/");e.name=t[t.length-1]||i}return e}function al(i){const e=i.trim().replace(/\/{2,}/g,"/");return e==="/"?"/":e.replace(/\/+$/,"")}function Lo(i){const e=i.split("/").filter(Boolean);return e.length>0?e[e.length-1]:i}function DI(i,e){var n;const t=new Map;for(const r of i){const l=(n=e[r.encoded])==null?void 0:n.cwd;if(typeof l!="string"||l.trim()==="")continue;const p=al(l);if(!p)continue;const a=AI(e[r.encoded]),d=t.get(p);if(!d){t.set(p,{cwd:p,name:Lo(p),encoded:r.encoded,encodedIds:[r.encoded],sessionCount:r.sessionCount,sizeBytes:r.sizeBytes,lastSession:r.lastSession,details:a});continue}d.encodedIds.push(r.encoded),d.sessionCount+=r.sessionCount,d.sizeBytes+=r.sizeBytes,r.lastSession>d.lastSession&&(d.encoded=r.encoded,d.details=a),d.lastSession=Math.max(d.lastSession,r.lastSession)}return[...t.values()].sort((r,l)=>l.lastSession-r.lastSession)}function AI(i){if(!i)return{};const{cwd:e,...t}=i;return t}function xC(i){return i.replace(/-/g,"/")}const II=64*1024;async function SC(i){const t=(await window.api.config.listDir(i,{filesOnly:!0})).entries.filter(n=>n.name.endsWith(".jsonl")).sort((n,r)=>n.size-r.size);for(const n of t){const r=await window.api.config.readText(n.path,{maxBytes:II});if(!(!r.exists||!r.text)){for(const l of r.text.split(`
2923
- `))if(l.includes('"cwd"'))try{const p=JSON.parse(l);if(typeof p.cwd=="string"&&p.cwd.length>0)return p.cwd}catch{}}}return null}let gh={rows:[],enriched:{},loading:!0,resolving:!0};const Ty=new Set;let Kx=null,nc=0;function PI(){Ty.forEach(i=>i())}function vh(i){gh={...gh,...i},PI()}const Dy=6;async function Ay(i,e,t){const n=new Array(i.length);let r=0;const l=Array.from({length:Math.min(e,i.length)},async()=>{for(;;){const p=r++;if(p>=i.length)return;n[p]=await t(i[p])}});return await Promise.all(l),n}async function RI(i){const e=++nc;vh({loading:!0,resolving:!0});try{const t=await window.api.config.listDir(`${i}/.claude/projects`,{dirsOnly:!0});if(e!==nc)return;const n=t.entries,r=await Ay(n,Dy,async l=>{const a=(await window.api.config.listDir(l.path,{filesOnly:!0})).entries.filter(g=>g.name.endsWith(".jsonl")),d=a.reduce((g,m)=>Math.max(g,m.mtimeMs),0),f=a.reduce((g,m)=>g+m.size,0);return{encoded:l.name,displayPath:xC(l.name),sessionCount:a.length,lastSession:d,path:l.path,sizeBytes:f}});if(e!==nc)return;r.sort((l,p)=>p.lastSession-l.lastSession),vh({rows:r,enriched:{},loading:!1,resolving:!0}),OI(r,e)}catch(t){console.error("[useKnownProjects] scan failed:",t),e===nc&&vh({loading:!1,resolving:!1})}}async function OI(i,e){const t={};if(await Ay(i,Dy,async l=>{if(e===nc){if(l.sessionCount===0){t[l.encoded]=null;return}try{const p=await SC(l.path);t[l.encoded]=p?al(p):null}catch{t[l.encoded]=null}}}),e!==nc)return;const n={};for(const l of i)n[l.encoded]={cwd:t[l.encoded]??null};vh({enriched:n,resolving:!1});const r=[...new Set(Object.values(t).filter(l=>!!l))];await Ay(r,Dy,async l=>{if(e!==nc)return;let p={};try{p=await TI(l)}catch{return}if(e!==nc)return;const a={...gh.enriched};for(const[d,f]of Object.entries(t))f===l&&(a[d]={cwd:l,...p});vh({enriched:a})})}function vd(){const i=Ab(),[,e]=B.useState(0),t=St(b=>b.addTab);B.useEffect(()=>{const b=()=>e(T=>T+1);return Ty.add(b),()=>{Ty.delete(b)}},[]),B.useEffect(()=>{i&&Kx!==i&&(Kx=i,RI(i))},[i]);const{rows:n,enriched:r,loading:l,resolving:p}=gh,a=B.useMemo(()=>DI(n,r),[n,r]),d=async b=>{const T=crypto.randomUUID();t({id:T,cwd:b,startupCommand:null,presetId:"projects-tab",dormant:!0})},f=async b=>{var k;let T=((k=r[b.encoded])==null?void 0:k.cwd)??null;if(T||(T=await SC(b.path)),!T&&(T=await window.api.app.pickDirectory(),!T))return;const E=crypto.randomUUID();t({id:E,cwd:T,startupCommand:null,presetId:"projects-tab",dormant:!0})},g=async b=>{try{const T=await window.api.app.archiveProject(b);return T.ok&&vh({rows:gh.rows.filter(E=>E.encoded!==b),enriched:Object.fromEntries(Object.entries(gh.enriched).filter(([E])=>E!==b))}),T}catch(T){return{ok:!1,error:T instanceof Error?T.message:"Archive failed"}}};return{rows:n,enriched:r,projects:a,loading:l,resolving:p,openProject:d,openInSession:f,archiveProject:g,archiveProjectByCwd:async b=>{let T={ok:!0};for(const E of b.encodedIds)if(T=await g(E),!T.ok)return T;return T}}}function LI(i,e,t){var r,l;const n=new Map;for(const p of Object.keys(e)){if(!((r=e[p])!=null&&r.running))continue;const a=(l=t[p])==null?void 0:l.cwd;if(!a)continue;const d=al(a);n.set(d,(n.get(d)??0)+1)}return i.map(p=>({encoded:p.encoded,name:p.name,cwd:p.cwd,dotSeed:p.cwd,liveCount:n.get(p.cwd)??0,lastActivityMs:p.lastSession}))}function b_(i){return{owner:i.owner,kind:"session",at:i.at,project:null,epicTitle:null,openTarget:null,epicId:null}}function $I(i,e,t,n){return i.map(r=>{const l=r.owner;if(l.startsWith("scheduler:")){const p=l.slice(10),a=e.find(g=>g.slug===p);if(!a)return b_(r);const d=a.sourcePromptId??null,f=d?n[d]:void 0;return{owner:l,kind:"scheduler job",at:r.at,project:a.cwd?Lo(a.cwd):null,epicTitle:(f==null?void 0:f.goalText)??null,openTarget:"scheduler",epicId:null}}if(l.startsWith("chat:")){const p=l.slice(5),a=t[p],d=n[p];return!(a!=null&&a.running)||!d?b_(r):{owner:l,kind:"chat run",at:r.at,project:Lo(d.cwd),epicTitle:d.goalText,openTarget:"terminal",epicId:p}}return b_(r)})}function Xx(i,e){for(const t of Object.keys(e))if(e[t].claudeSessionId===i)return e[t].goalText;return null}const NI=1440*60*1e3;function MI(i){const e=(i.statusHistory??[]).find(n=>n.to==="quarantined");if(!e)return null;const t=Date.parse(e.at);return Number.isNaN(t)?null:t}function jI(i,e,t,n=Date.now()){var l;const r=[];for(const p of Object.keys(i)){const a=i[p];r.push({id:`proposed:${p}`,kind:"proposed-epic",label:"Proposed Epic — awaiting approval",detail:a.goalText,meta:a.tag?`tag: ${a.tag}`:"Filed for you to decide on. Nothing has run.",project:Lo(a.cwd),epicId:p,jobSlug:null})}for(const p of Object.keys(e)){const a=((l=e[p])==null?void 0:l.ticketHistory)??[],d=a[a.length-1];!d||d.status!=="needs-input"||r.push({id:`needs-input:${d.id}`,kind:"needs-input",label:"Session is asking a question",detail:d.text,meta:"Stopped mid-run, waiting on your reply.",project:Lo(d.cwd),epicId:p,jobSlug:null})}for(const p of t){if(p.status==="quarantined"){const a=MI(p),d=a!=null?n-a:null,f=d!=null&&d>=NI;r.push({id:`job:${p.slug}`,kind:"job-quarantined",label:f?"Quarantined PRD — stale, needs adoption":"Scheduler PRD quarantined",detail:p.title||p.slug,meta:d!=null?`No createdVia provenance for ${Math.round(d/(3600*1e3))}h — adopt it to run, or archive from the Scheduler tab.`:"No createdVia provenance. Adopt it to run, or archive from the Scheduler tab.",project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug,escalated:f});continue}if(p.status==="running"&&p.overrun){const{ratio:a,ranMs:d,estimateMinutes:f}=p.overrun;r.push({id:`job:${p.slug}`,kind:"job-overrunning",label:"Scheduler job running over its own estimate",detail:p.title||p.slug,meta:`Ran ${Math.round(d/6e4)}m vs ${f}m estimate (${a.toFixed(1)}x). Check the run log, then let it finish or cancel it via scheduler_cancel_job.`,project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug});continue}p.status!=="failed"&&p.status!=="needs_review"||r.push({id:`job:${p.slug}`,kind:"job-failed",label:p.status==="failed"?"Scheduler job failed":"Scheduler job needs review",detail:p.title||p.slug,meta:p.error??"No error detail recorded.",project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug})}return r}let Iy=null;function jv(i){Iy=i,window.dispatchEvent(new CustomEvent("sm:select-prompt-session",{detail:i}))}function zI(){const i=Iy;return Iy=null,i}const Yx=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function BI(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)>>>0;return e}function CC(i){return Yx[BI(i)%Yx.length]}function EC(i,e,t,n){const r=e.find(l=>l.cwd===i);r?n(r.id):t({cwd:i,startupCommand:null,dormant:!0})}function kC(i){return i>=90?{dot:"bg-accent",bar:"bg-accent",track:"bg-accent/15",text:"text-accent"}:i>=70?{dot:"bg-honey",bar:"bg-honey",track:"bg-honey/15",text:"text-honey-dark"}:{dot:"bg-sage",bar:"bg-sage",track:"bg-sage/15",text:"text-sage"}}function UI(i){return i?i.split("_").map(e=>/^\d/.test(e)?e:e.charAt(0).toUpperCase()+e.slice(1)).join(" "):null}function _f({label:i,sub:e,window:t,big:n=!1}){if(!t)return null;const r=t.utilization,l=Math.max(0,Math.min(100,r)),p=r>100,a=z1(t.resets_at),d=kC(r);return c.jsxs("div",{className:n?"py-[18px]":"py-[15px]",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-2.5",children:[c.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[c.jsx("span",{className:`w-[9px] h-[9px] rounded-full shrink-0 ${d.dot}`}),c.jsx("span",{className:`font-semibold text-fg ${n?"text-base":"text-[15px]"}`,children:i}),e&&c.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint bg-bg border border-line px-2 py-px rounded-full whitespace-nowrap",children:e})]}),c.jsxs("span",{className:`font-mono font-semibold leading-none tracking-tight shrink-0 ${n?"text-2xl":"text-xl"} ${p?"text-accent":d.text}`,children:[Math.round(r),"%"]})]}),c.jsx("div",{className:`rounded-full overflow-hidden ${n?"h-3":"h-2.5"} ${d.track}`,children:c.jsx("div",{className:`h-full rounded-full transition-[width] duration-500 ${d.bar}`,style:{width:`${l}%`}})}),a&&c.jsxs("div",{className:"flex items-center justify-between mt-2.5 gap-3",children:[c.jsxs("span",{className:"text-[12.5px] text-fg-dim",children:["resets in"," ",c.jsx("strong",{className:"text-fg font-semibold",children:a.rel}),a.abs&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-fg-faint",children:" · "}),c.jsx("span",{className:"font-mono text-xs text-fg-faint",children:a.abs})]})]}),p&&c.jsx("span",{className:"text-[11.5px] font-semibold text-accent",children:"over limit"})]})]})}function GI({extra:i}){const e=i.utilization??0,t=e>100,n=kC(e);return c.jsxs("div",{className:"border-t border-line pt-[15px] pb-[15px]",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-2.5",children:[c.jsxs("div",{className:"flex items-center gap-2.5",children:[c.jsx("span",{className:`w-[9px] h-[9px] rounded-full shrink-0 ${n.dot}`}),c.jsx("span",{className:"text-[15px] font-semibold text-fg",children:"Extra usage"}),c.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint bg-bg border border-line px-2 py-px rounded-full whitespace-nowrap",children:"pay-as-you-go"})]}),c.jsxs("span",{className:`font-mono text-base font-semibold tabular-nums ${t?"text-accent":"text-fg"}`,children:[(i.used_credits??0).toFixed(2)," ",c.jsxs("span",{className:"text-fg-faint font-normal",children:["/ ",(i.monthly_limit??0).toFixed(2)," ",i.currency??""]})]})]}),c.jsx("div",{className:`h-2.5 rounded-full overflow-hidden ${n.track}`,children:c.jsx("div",{className:`h-full rounded-full transition-[width] duration-500 ${n.bar}`,style:{width:`${Math.min(e,100)}%`}})}),c.jsxs("div",{className:"flex items-center justify-between mt-2.5 gap-3",children:[c.jsxs("span",{className:"text-[12.5px] text-fg-dim",children:["monthly credit limit · resets"," ",c.jsx("span",{className:"font-mono text-xs text-fg-faint",children:"1st of month"})]}),t&&c.jsx("span",{className:"text-[11.5px] font-semibold text-accent",children:"over limit"})]})]})}function HI({data:i,updatedAt:e}){const t=i.usage,n=UI(i.subscriptionType),r=t.extra_usage,l=e!=null?`${Math.max(0,Math.round((Date.now()-e)/1e3))}s ago`:null;return c.jsxs("section",{className:"bg-bg-hi border border-line rounded-2xl px-6 py-1.5",children:[(n||i.rateLimitTier||l)&&c.jsxs("div",{className:"flex items-baseline justify-between pt-3 pb-1 mb-1",children:[c.jsxs("div",{className:"flex items-baseline gap-2",children:[n&&c.jsx("span",{className:"text-xs text-fg-dim font-mono",children:n}),i.rateLimitTier&&c.jsx("span",{className:"text-[10px] text-fg-faint font-mono",children:i.rateLimitTier})]}),l&&c.jsxs("span",{className:"text-[10px] text-fg-faint",children:["updated ",l]})]}),c.jsxs("div",{className:"divide-y divide-line",children:[c.jsx(_f,{label:"Session",sub:"5-hour",window:t.five_hour,big:!0}),c.jsx(_f,{label:"Weekly",sub:"all models",window:t.seven_day}),c.jsx(_f,{label:"Weekly",sub:"Opus",window:t.seven_day_opus}),c.jsx(_f,{label:"Weekly",sub:"Sonnet",window:t.seven_day_sonnet}),c.jsx(_f,{label:"Weekly",sub:"OAuth apps",window:t.seven_day_oauth_apps})]}),(r==null?void 0:r.is_enabled)&&c.jsx(GI,{extra:r})]})}function Ib({open:i,onClose:e,title:t,sub:n,keyVals:r,tail:l,footer:p,children:a}){const[d,f]=B.useState(!1);if(B.useEffect(()=>{if(!i){f(!1);return}const b=requestAnimationFrame(()=>f(!0));return()=>cancelAnimationFrame(b)},[i]),B.useEffect(()=>{if(!i)return;const b=T=>{T.key==="Escape"&&(T.stopPropagation(),e())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[i,e]),!i)return null;const g=b=>{b.target===b.currentTarget&&e()},m=c.jsxs("div",{className:`fixed inset-0 ${Cn.dialog}`,"data-testid":"home-drawer-root",children:[c.jsx("div",{className:`absolute inset-0 bg-black/50 transition-opacity duration-[220ms] ${d?"opacity-100":"opacity-0"}`,onClick:g,"data-testid":"home-drawer-backdrop"}),c.jsxs("aside",{role:"dialog","aria-modal":"true","aria-label":t,className:`absolute top-0 right-0 h-full w-full max-w-[420px] bg-bg-hi border-l border-line shadow-xl flex flex-col transition-transform duration-[220ms] ${d?"translate-x-0":"translate-x-full"}`,style:{transitionTimingFunction:"cubic-bezier(.32,.72,.28,1)"},"data-testid":"home-drawer",children:[c.jsxs("header",{className:"px-5 py-4 border-b border-line flex items-start justify-between gap-3 shrink-0",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"m-0 font-serif text-[18px] font-semibold text-fg truncate",children:t}),n&&c.jsx("div",{className:"text-[12px] text-fg-faint truncate mt-0.5",children:n})]}),c.jsx("button",{onClick:e,className:"shrink-0 rounded-md border border-line bg-bg px-2.5 py-1 text-[12px] font-semibold text-fg-dim hover:bg-bg-elev","aria-label":"Close",children:"Close"})]}),c.jsxs("div",{className:"flex-1 min-h-0 overflow-auto px-5 py-4 grid gap-4 content-start",children:[a,r.length>0&&c.jsx("dl",{className:"m-0 grid gap-2",style:{gridTemplateColumns:"minmax(0,100px) minmax(0,1fr)"},children:r.map(b=>c.jsxs("div",{className:"contents",children:[c.jsx("dt",{className:"m-0 font-mono text-[11px] uppercase tracking-[0.05em] text-fg-faint",children:b.label}),c.jsx("dd",{className:"m-0 text-[12.5px] text-fg break-words",children:b.value})]},b.label))}),l&&l.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2",children:"Live tail"}),c.jsx("div",{className:"grid gap-2",children:l.map(b=>c.jsxs("div",{className:"bg-bg border border-line rounded-lg px-3 py-2",children:[c.jsx("div",{className:"font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint mb-1",children:b.role}),c.jsx("div",{className:"text-[12px] text-fg-dim leading-[1.5] whitespace-pre-wrap break-words line-clamp-6",children:b.text})]},b.id))})]})]}),p&&c.jsx("footer",{className:"px-5 py-3.5 border-t border-line flex gap-2 justify-end shrink-0",children:p})]})]});return typeof document<"u"&&document.body?dm.createPortal(m,document.body):m}function FI({open:i,onClose:e,projects:t,onConfirm:n}){const[r,l]=B.useState(null);B.useEffect(()=>{var a;i&&l(((a=t[0])==null?void 0:a.cwd)??null)},[i,t]);const p=t.find(a=>a.cwd===r)??null;return c.jsx(Ib,{open:i,onClose:e,title:"New session",sub:"Pick a project to start it in",keyVals:[],footer:c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:e,className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg border border-line bg-bg text-fg-dim hover:bg-bg-elev",children:"Cancel"}),c.jsx("button",{onClick:()=>{r&&(n(r),e())},disabled:!r,className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg bg-accent text-bg-hi hover:bg-accent-dark disabled:opacity-50",children:p?`Continue in ${p.name} → Epics`:"Continue"})]}),children:t.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-2",children:"No known projects yet."}):c.jsx("div",{role:"radiogroup","aria-label":"Project",className:"grid gap-1.5",children:t.map(a=>c.jsxs("label",{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg border cursor-pointer ${r===a.cwd?"border-accent bg-accent/10":"border-line bg-bg hover:bg-bg-elev/60"}`,children:[c.jsx("input",{type:"radio",name:"new-epic-project",value:a.cwd,checked:r===a.cwd,onChange:()=>l(a.cwd),className:"accent-accent"}),c.jsx("span",{className:"min-w-0 flex-1 text-[13px] text-fg truncate",title:a.cwd,children:a.name})]},a.encoded))})})}function WI({job:i,onClose:e,onOpenScheduler:t,onRunNow:n}){const r=B.useRef(null);return B.useEffect(()=>{const l=a=>{r.current&&!r.current.contains(a.target)&&e()},p=a=>{a.key==="Escape"&&e()};return document.addEventListener("mousedown",l),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",p)}},[e]),c.jsxs("div",{ref:r,"data-testid":"queue-job-popover",className:"absolute z-20 top-full left-0 mt-1.5 w-[226px] bg-bg-hi border border-line rounded-[11px] shadow-xl px-3.5 py-3",children:[c.jsx("div",{className:"font-mono text-[12px] font-semibold text-fg truncate mb-1.5",children:i.title||i.slug}),c.jsxs("dl",{className:"m-0 grid gap-1 mb-3",style:{gridTemplateColumns:"minmax(0,60px) minmax(0,1fr)"},children:[c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Slug"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim truncate",children:i.slug}),c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Project"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim truncate",children:i.cwd?VI(i.cwd):"—"}),i.estimateMinutes!=null&&c.jsxs(c.Fragment,{children:[c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Est."}),c.jsxs("dd",{className:"m-0 font-mono text-[11px] text-fg-dim",children:["~",i.estimateMinutes,"m"]})]}),c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Status"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim",children:i.status})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("button",{onClick:t,className:"text-[11.5px] font-semibold px-2.5 py-[5px] rounded-md border border-line bg-bg text-fg-dim hover:bg-bg-elev text-left",children:"Open in Scheduler →"}),n&&c.jsx("button",{onClick:n,title:"Wakes the scheduler to check for due jobs immediately — does not force this specific job to run out of turn or bypass the concurrency cap.",className:"text-[11.5px] font-semibold px-2.5 py-[5px] rounded-md bg-accent text-bg-hi hover:bg-accent-dark text-left",children:"Nudge scheduler now"})]})]})}function VI(i){const e=i.split("/").filter(Boolean);return e.length>0?e[e.length-1]:i}const TC="sm.terminal.settings",Py="sm:terminal:settings",Ry=10,Oy=22,DC=13,$g={theme:"dark",fontSize:DC};function zv(){try{const i=localStorage.getItem(TC);if(!i)return $g;const e=JSON.parse(i);return{theme:e.theme==="light"||e.theme==="paper"||e.theme==="dark"?e.theme:$g.theme,fontSize:typeof e.fontSize=="number"&&e.fontSize>=Ry&&e.fontSize<=Oy?e.fontSize:$g.fontSize}}catch{return $g}}function qI(i){try{localStorage.setItem(TC,JSON.stringify(i))}catch{}window.dispatchEvent(new CustomEvent(Py,{detail:i}))}function Pb(i){const e=t=>{i(t.detail)};return window.addEventListener(Py,e),()=>window.removeEventListener(Py,e)}const va={dark:{background:"#0b0d10",foreground:"#e6e8ec",cursor:"#d97757",selectionBackground:"#3a4250",black:"#1a1f27",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#e6e8ec",brightBlack:"#545c68",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff"},light:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"#cce5ff",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#a45a16",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#9a6700",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#1f2328"},paper:{background:"#f6efe1",foreground:"#2a221a",cursor:"#a7532f",selectionBackground:"#e0d3b8",black:"#2a221a",red:"#b8443c",green:"#5c6f3a",yellow:"#8e641a",blue:"#3a6ea5",magenta:"#8a4a8c",cyan:"#38767e",white:"#5b4a36",brightBlack:"#796b54",brightRed:"#b8493f",brightGreen:"#65714a",brightYellow:"#8c641e",brightBlue:"#416ea1",brightMagenta:"#925494",brightCyan:"#3e757d",brightWhite:"#2a221a"}},KI=["dark","light","paper"];function XI(){const[i,e]=B.useState(()=>zv()),t=r=>{e(l=>{const p={...l,...r};return qI(p),p})},n=r=>{t({fontSize:Math.min(Oy,Math.max(Ry,i.fontSize+r))})};return c.jsxs("section",{className:"mb-6","data-testid":"home-terminal-appearance",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Terminal appearance"}),c.jsx("span",{className:"font-mono text-[12px] text-fg-faint",children:"every terminal, this machine"})]}),c.jsxs("div",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[c.jsxs("p",{className:"mt-0 mb-4 text-[13px] text-fg-dim leading-relaxed",children:["Applies to ",c.jsx("strong",{className:"text-fg",children:"every terminal in the app at once"})," — project Terminal tabs, an Epic’s Terminal view of its session, and the inline permission prompt. It is not per project, per session, or per tab. It does not restyle the app chrome (there is no app theme switch), and the code editor keeps its own separate paper/dark setting in the Editor tab’s Display menu. Stored in this machine’s browser storage as ",c.jsx("code",{className:"font-mono text-[12px]",children:"sm.terminal.settings"}),", applied live without restarting a session."]}),c.jsxs("div",{className:"grid gap-5",style:{gridTemplateColumns:"minmax(0,1fr) 220px"},children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-1.5",children:"Theme"}),c.jsx("div",{className:"grid grid-cols-3 gap-2",children:KI.map(r=>c.jsxs("button",{type:"button",onClick:()=>t({theme:r}),"aria-pressed":i.theme===r,"data-testid":`terminal-theme-${r}`,className:`px-2 py-2 rounded-lg text-[11px] font-medium border transition-colors ${i.theme===r?"bg-bg border-accent text-fg":"bg-bg border-line text-fg-dim hover:text-fg hover:border-fg-faint"}`,children:[c.jsx(YI,{theme:r}),c.jsx("div",{className:"mt-1.5 capitalize",children:r})]},r))})]}),c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[c.jsx("span",{className:"text-[10px] uppercase tracking-wider text-fg-faint",children:"Font size"}),c.jsxs("span",{className:"font-mono text-[11px] text-fg-dim",children:[i.fontSize,"px"]})]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("button",{type:"button",onClick:()=>n(-1),disabled:i.fontSize<=Ry,"aria-label":"Decrease font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"−"}),c.jsx("button",{type:"button",onClick:()=>t({fontSize:DC}),className:"flex-1 py-1.5 rounded border border-line bg-bg text-[11px] text-fg-dim hover:text-fg hover:border-fg-faint",children:"reset"}),c.jsx("button",{type:"button",onClick:()=>n(1),disabled:i.fontSize>=Oy,"aria-label":"Increase font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"+"})]}),c.jsxs("div",{className:"mt-3 rounded border border-line px-3 py-2 font-mono",style:{background:va[i.theme].background,color:va[i.theme].foreground,fontSize:`${i.fontSize}px`,lineHeight:1.35},"aria-hidden":!0,children:[c.jsx("span",{style:{color:va[i.theme].green},children:"$"})," claude"]})]})]})]})]})}function YI({theme:i}){const e=va[i];return c.jsxs("div",{"aria-hidden":!0,className:"w-full h-5 rounded border relative overflow-hidden",style:{background:e.background,borderColor:"rgba(0,0,0,0.15)"},children:[c.jsx("div",{style:{position:"absolute",top:3,left:4,width:"40%",height:2,background:e.foreground}}),c.jsx("div",{style:{position:"absolute",top:9,left:4,width:"25%",height:2,background:e.green??e.foreground}}),c.jsx("div",{style:{position:"absolute",top:15,left:4,width:"55%",height:2,background:e.cyan??e.foreground}})]})}const Jx="The MCP tool catalog is unavailable.";function JI(){const[i,e]=B.useState({tools:[],loaded:!1,error:null});return B.useEffect(()=>{let t=!1;return Promise.resolve().then(()=>window.api.mcp.catalog()).then(n=>{var r;t||(!(n!=null&&n.ok)||!((r=n.tools)!=null&&r.length)?e({tools:[],loaded:!0,error:Jx}):e({tools:n.tools,loaded:!0,error:null}))}).catch(()=>{t||e({tools:[],loaded:!0,error:Jx})}),()=>{t=!0}},[]),i}const ZI=["scheduler","chat","feedback","help"],QI={scheduler:"Scheduler",chat:"Chat",feedback:"Feedback",help:"Help"};function eP(){const{tools:i,loaded:e,error:t}=JI(),[n,r]=B.useState(!1);if(!e)return null;if(t||i.length===0)return c.jsxs("section",{className:"mb-6","data-testid":"home-agent-tools",children:[c.jsx("h2",{className:"m-0 mb-2 font-serif text-[22px] font-medium",children:"Agent tools"}),c.jsx("p",{className:"m-0 text-xs text-fg-faint","data-testid":"home-agent-tools-error",children:"The MCP tool catalog is unavailable."})]});const l=ZI.map(p=>({group:p,tools:i.filter(a=>a.group===p)})).filter(p=>p.tools.length>0);return c.jsxs("section",{className:"mb-6","data-testid":"home-agent-tools",children:[c.jsxs("button",{type:"button",onClick:()=>r(p=>!p),"aria-expanded":n,"data-testid":"home-agent-tools-toggle",className:"flex w-full items-baseline gap-2 text-left",children:[c.jsx("span",{className:"font-serif text-[22px] font-medium",children:"Agent tools"}),c.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:["· ",i.length," MCP tools ",n?"▾":"▸"]})]}),n&&c.jsx("div",{className:"mt-3 grid gap-3 border border-line rounded-xl bg-bg-hi px-5 py-4",children:l.map(({group:p,tools:a})=>c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"mb-1 font-mono text-[10px] font-semibold uppercase tracking-wide text-fg-faint",children:QI[p]}),a.map(d=>c.jsxs("div",{"data-testid":`home-agent-tool-${d.name}`,className:"flex items-baseline gap-3 min-w-0 py-0.5",children:[c.jsx("span",{className:"shrink-0 font-mono text-[12px] font-semibold text-fg",children:d.name}),c.jsx("span",{"data-testid":"home-agent-tool-purpose",title:d.purpose,className:"min-w-0 line-clamp-1 text-xs text-fg-dim",children:d.purpose})]},d.name))]},p))})]})}function tP(i){const e=Date.now()-i;if(e<6e4)return"just now";const t=Math.floor(e/6e4);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ${t%60}m ago`}function iP({since:i,error:e,onRetry:t}){return c.jsxs("div",{className:"flex items-center justify-between mb-3 border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:[c.jsxs("span",{children:["stale · last updated ",tP(i)]}),c.jsx("button",{onClick:t,className:"ml-3 underline hover:no-underline",children:"Retry"})]})}function nP({message:i,expiredAt:e,onRetry:t}){const n=e!=null&&e<Date.now(),r=e?new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}):null,l=!n&&/^HTTP \d+/.test(i);return c.jsxs("div",{className:"mb-3 border border-red-800/40 rounded px-3 py-2 bg-red-950/20 text-xs text-red-300",children:[c.jsxs("div",{className:"font-medium mb-1",children:[n?`Credentials expired at ${r}`:"Authentication failed",l&&c.jsxs("span",{className:"font-normal ml-1 text-red-400/70",children:["(",i,")"]})]}),c.jsxs("div",{className:"text-red-400/80",children:["Run ",c.jsx("code",{className:"font-mono bg-red-950/40 px-1 rounded",children:"claude"})," in a terminal to refresh, then"," ",c.jsx("button",{onClick:t,className:"underline hover:no-underline",children:"Retry"}),"."]})]})}function sP(){return c.jsx("div",{className:"border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:"temporary network error — retrying in 5s"})}function rP({onRetry:i}){return c.jsxs("div",{className:"flex items-center justify-between border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:[c.jsx("span",{children:"usage meter is rate-limited — showing last known values"}),c.jsx("button",{onClick:i,className:"ml-3 underline hover:no-underline",children:"Retry"})]})}function oP({message:i}){const e=i.includes("not found")||i.includes("ENOENT");return c.jsxs("div",{className:"border border-line rounded px-3 py-2 bg-bg-elev text-xs text-fg-dim",children:[c.jsx("div",{className:"font-medium mb-1 text-fg",children:e?"Not signed in":"Cannot read credentials"}),c.jsx("div",{className:"text-fg-faint",children:e?c.jsxs(c.Fragment,{children:["Run ",c.jsx("code",{className:"font-mono bg-bg px-1 rounded",children:"claude login"})," in a terminal tab to sign in."]}):c.jsxs(c.Fragment,{children:["Cannot read ",c.jsx("code",{className:"font-mono bg-bg px-1 rounded",children:"~/.claude/.credentials.json"})," — ",i]})})]})}function aP({result:i,onRetry:e}){switch(i.kind){case"ok":return null;case"ok-stale":return c.jsx(iP,{since:i.staleSince,error:i.lastError,onRetry:e});case"auth":return c.jsx(nP,{message:i.message,expiredAt:i.expiredAt,onRetry:e});case"transient":return c.jsx(sP,{});case"meter_rate_limited":return c.jsx(rP,{onRetry:e});case"config":return c.jsx(oP,{message:i.message})}}const AC={feature:{description:"Plans new functionality from the stated objective, then delegates the build to /develop.",initialPromptTemplate:"You are planning new functionality. Treat the goal below as the full objective — establish scope, then decompose and queue the work as scheduled PRDs via the /develop skill, rather than editing files inline in this conversation: this interactive session is a planner-tier model and the headless claude -p executor does the typing."},bug:{description:"Diagnoses a reported failure before queuing a fix via /develop — reproduction first.",initialPromptTemplate:"You are diagnosing a reported bug. If a reference (log, stack trace, repro steps) is attached, read it and reproduce the failure before writing a fix — do not guess at root cause from the description alone. If nothing is attached, reproduce it yourself first. Once root cause is established, queue the fix as a scheduled PRD via the /develop skill rather than typing it inline: this interactive session is a planner-tier model and the headless claude -p executor does the typing."},discussion:{description:"Open-ended research/decision conversation — no code changes expected.",initialPromptTemplate:"You are in an open-ended discussion. The goal is a decision or shared understanding, not a code change — do not start editing files unless the human explicitly asks you to after the discussion lands somewhere."},build:{description:"Prepares and publishes a release build to this project's configured registry.",initialPromptTemplate:"You are preparing a release build. Treat the goal below as the full objective — verify the project's build target configuration before publishing."},"project-home-builder":{description:"Reads this project and writes one self-contained overview page (home.html) for Project Home.",initialPromptTemplate:"You are generating this project's Project Home page. Read the real project first — its manifest, README/docs, directory structure, key scripts, and recent git history. Then write ONE self-contained HTML overview page (inline CSS only, no external scripts, fonts, or images) covering what the project is, who it is for, its structure, how to run it, and its key commands. Never fabricate a claim — an omitted section beats an invented one. Save it by calling the `project_home_write` MCP tool exactly once with the full HTML. If `project_home_write` is unavailable or errors, report that plainly and STOP — never build infrastructure in this project as a workaround."},"bilko-host-publisher":{description:"Publishes this project's Project Home page (home.html) to bilko.run as a static-path listing via the bilko-host MCP's gated publish pipeline.",initialPromptTemplate:"You are publishing this project to bilko.run. Read `session-manager-operations/architecture/bilko-host-integration.md` first — it is the source of truth for the pipeline, the bundle path, and the non-negotiables (ship the Project Home page verbatim; never bypass a failing gate on your own initiative). Call `bilko-host__get_host_contract` and read `~/Projects/Bilko/mcp-host-server/src/gates/*.ts` live before publishing — never assume a cached understanding of the gates, they can change independently of this app's release cycle. Then follow `.claude/agents/bilko-host-publisher.md` as your operating protocol."}},lP=["feature","bug","discussion","project-home-builder"];function IC(i){return AC[i]}function yf(i){return{path:i,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function w_(i,e,t){const n={...i,diskRaw:e.raw,diskData:e.data,exists:e.exists,parseError:e.parseError,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.raw,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}function x_(i,e,t){const n={...i,diskRaw:e.text,diskData:null,exists:e.exists,parseError:null,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.text,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}const Of=Un((i,e)=>({files:{},watchRefs:{},loadJson:async t=>{const n=e().files[t];i({files:{...e().files,[t]:{...n??yf(t),busy:!0}}});const r=await window.api.config.readJson(t),l=e().files[t]??yf(t);i({files:{...e().files,[t]:w_(l,r,!1)}})},loadText:async(t,n=!1)=>{const r=e().files[t];i({files:{...e().files,[t]:{...r??yf(t),busy:!0}}});const l=await window.api.config.readText(t),p=e().files[t]??yf(t);i({files:{...e().files,[t]:x_(p,l,n)}})},setDraft:(t,n)=>{const r=e().files[t]??yf(t),l=n!==r.diskRaw;i({files:{...e().files,[t]:{...r,draftRaw:n,dirty:l}}})},revert:t=>{const n=e().files[t];n&&i({files:{...e().files,[t]:{...n,draftRaw:n.diskRaw,dirty:!1}}})},saveJson:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};let r;try{r=n.draftRaw.trim()===""?{}:JSON.parse(n.draftRaw)}catch(d){return{ok:!1,error:`invalid JSON: ${d.message}`}}i({files:{...e().files,[t]:{...n,busy:!0}}});const l=await window.api.config.writeJson(t,r);if(!l.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:l.error};const p=await window.api.config.readJson(t),a=w_({...n,busy:!1},p,!1);return i({files:{...e().files,[t]:{...a,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};i({files:{...e().files,[t]:{...n,busy:!0}}});const r=await window.api.config.writeText(t,n.draftRaw);if(!r.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:r.error};const l=await window.api.config.readText(t),p=x_({...n,busy:!1},l,!1);return i({files:{...e().files,[t]:{...p,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:t=>{const n={...e().watchRefs};n[t]=(n[t]??0)+1,i({watchRefs:n}),n[t]===1&&window.api.config.watch([t])},unwatchFile:t=>{const n={...e().watchRefs};n[t]&&(n[t]--,n[t]<=0&&(delete n[t],window.api.config.unwatch([t])),i({watchRefs:n}))},onExternalChange:t=>{e().files[t]&&(t.endsWith(".json")?window.api.config.readJson(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:w_(l,r,!0)}})}):window.api.config.readText(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:x_(l,r,!0)}})}))}}));function cP(){return window.api.config.onChanged(({path:i})=>{Of.getState().onExternalChange(i)})}function _h(...i){return i.filter(Boolean).map((e,t)=>t===0?e.replace(/\/+$/,""):e.replace(/^\/+|\/+$/g,"")).join("/")}const im={scopes:["user","project","local"],resolve:(i,e,t)=>i==="user"?_h(e,".claude","settings.json"):t?i==="project"?_h(t,".claude","settings.json"):_h(t,".claude","settings.local.json"):null},S_={scopes:["user","project","local"],resolve:(i,e,t)=>i==="user"?_h(e,".claude","CLAUDE.md"):t?i==="project"?_h(t,"CLAUDE.md"):_h(t,"CLAUDE.local.md"):null},VB=im,qB={user:{label:"User",hint:"~/.claude/ — applies to all projects"},project:{label:"Project",hint:"<cwd>/.claude/ — checked into git"},local:{label:"Local",hint:"<cwd>/.claude/…local — gitignored, per-machine"}},dP=[];function Ng(i){return Array.isArray(i)?"array":i!==null&&typeof i=="object"?"object":"scalar"}function uP(i){const e=i.filter(t=>t.data!==void 0);return e.length===0?{kind:"object",children:{}}:PC(e,[])}function PC(i,e){const t=dP.includes(e.join(".")),n=i.every(g=>Ng(g.data)==="object"),r=i.every(g=>Ng(g.data)==="array");if(n){const g=new Set;for(const b of i)for(const T of Object.keys(b.data))g.add(T);const m={};for(const b of g){const T=i.filter(E=>b in E.data).map(E=>({scope:E.scope,data:E.data[b]}));m[b]=PC(T,[...e,b])}return{kind:"object",children:m}}if(r&&!t){const g=[];for(const m of[...i].reverse())for(const b of m.data)g.push({value:b,fromScope:m.scope,index:g.length});return{kind:"array",items:g}}const l=[...i].reverse(),p=l[0],a=l.slice(1).map(g=>({scope:g.scope,value:g.data})),d=Ng(p.data),f=a.some(g=>Ng(g.value)!==d);return{kind:"leaf",value:p.data,winner:p.scope,shadowed:a,...f?{typeMismatch:!0}:{}}}function RC(i,e){if(e.length===0)return i;if(i.kind!=="object")return null;const[t,...n]=e,r=i.children[t];return r?RC(r,n):null}function hP(i,e,t){if(e.length===0)return t;const[n,...r]=e,l=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};return l[n]=hP(l[n],r,t),l}const pP=["user","project","local"];function fP(i,e){const t=[];for(const n of pP){const r=e[n];if(!r)continue;const l=i[r];if(!l||!l.exists)continue;const p=l.draftRaw??"";if(p.trim())try{t.push({scope:n,data:JSON.parse(p)})}catch{}}return t}const mP=3e4;function OC(i){const e=Ab(),t=B.useMemo(()=>{if(!e)return{};const a={};for(const d of im.scopes){const f=im.resolve(d,e,i);f&&(a[d]=f)}return a},[e,i]),n=Of(a=>a.files),r=Of(a=>a.loadJson),l=Of(a=>a.watchFile),p=Of(a=>a.unwatchFile);return B.useEffect(()=>{const a=Object.values(t).filter(Boolean);a.forEach(f=>{n[f]||r(f),l(f)});const d=window.setInterval(()=>{a.forEach(f=>r(f))},mP);return()=>{clearInterval(d),a.forEach(f=>p(f))}},[JSON.stringify(t)]),B.useMemo(()=>uP(fP(n,t)),[n,t])}function LC(i,e){const t=RC(i,e);return!t||t.kind!=="leaf"?{value:null,source:null}:{value:typeof t.value=="string"?t.value:null,source:t.winner}}function $C(i,e){return!i||!e?"effort — (model default)":e==="epic"?`effort ${i} (this session)`:e==="persona"?`effort ${i} (persona)`:e==="persona-overlay"?`effort ${i} (project persona)`:`effort ${i} (${e} settings.json)`}function gP(i){return i==="epic"?"Effort was chosen for this session only and is passed to the CLI as --effort, overriding the agent persona and settings.json.":i==="persona"||i==="persona-overlay"?"Effort comes from the agent persona and is passed to the CLI as --effort, overriding settings.json.":i?"The persona sets no effort, so the settings.json effortLevel applies.":"No effort is set by the persona or settings.json, so the model default applies."}function vP(i,e,t={}){const n=t.model&&t.model!=="inherit"?t.model:null,r=t.effort&&t.effort!=="inherit"&&t.effort!=="auto"?t.effort:null;if(r)return{...i,epicModel:n,effortLevel:r,effortSource:"epic"};if(i.personaEffort&&(i.personaEffortSource==="persona"||i.personaEffortSource==="persona-overlay"))return{...i,epicModel:n,effortLevel:i.personaEffort,effortSource:i.personaEffortSource};const{value:l,source:p}=LC(e,["effortLevel"]);return{...i,epicModel:n,effortLevel:l,effortSource:p}}function NC(i,e,t){const n=OC(i),[r,l]=B.useState(null);return B.useEffect(()=>{if(!i||!e){l(null);return}let p=!1;return l(null),window.api.agents.resolveModelInfo({cwd:i,agentType:e}).then(a=>{p||l(a)},()=>{p||l(null)}),()=>{p=!0}},[i,e]),!i||!e||!r?null:vP(r,n,t)}const MC=[{id:"project",label:"Project & Tab",realm:"machine",blurb:"A PROJECT is a cwd; a TAB is one open project.",tone:{chip:"bg-bg-elev text-fg-dim",border:"border-line",dot:"bg-fg-faint"}},{id:"epic",label:"Epic (PromptSession)",realm:"project",blurb:"The central aggregate root — one unit of work, one claude session.",tone:{chip:"bg-accent-muted text-accent-dark",border:"border-accent",dot:"bg-accent"}},{id:"scheduler",label:"Scheduler",realm:"project",blurb:"PRDs + the headless jobs that execute them.",tone:{chip:"bg-butter/30 text-honey-dark",border:"border-honey",dot:"bg-honey"}},{id:"agents",label:"Agents & Taxonomy",realm:"machine",blurb:"The ACTOR and MISSION halves of AIM.",tone:{chip:"bg-sage/20 text-sage-dark",border:"border-sage",dot:"bg-sage"}},{id:"memory",label:"Memory",realm:"machine",blurb:"Workspace, cross-project, and per-agent memory.",tone:{chip:"bg-hive-teal/20 text-hive-teal",border:"border-hive-teal",dot:"bg-hive-teal"}},{id:"transcript",label:"Transcript & Usage",realm:"machine",blurb:"The Claude CLI's own JSONL, classified events, and billing.",tone:{chip:"bg-bg-hi text-fg-dim",border:"border-rule",dot:"bg-fg-dim"}},{id:"brief",label:"Project Home & Publishing",realm:"project",blurb:"The synthesized Brief, generated pages, and bilko.run publish state.",tone:{chip:"bg-accent-muted/60 text-accent-dark",border:"border-accent-muted",dot:"bg-accent-muted"}},{id:"config",label:"Machine Config",realm:"machine",blurb:"Settings, layout, and the single-writer ownership map.",tone:{chip:"bg-line text-fg-faint",border:"border-rule",dot:"bg-fg-faint"}}];function KB(i){const e=MC.find(t=>t.id===i);if(!e)throw new Error(`unknown ErdGroupId: ${i}`);return e}const Rb=[{id:"project",name:"Project",aka:"cwd — Main Project",group:"project",store:{path:"identity only, no record of its own — folded at read time from ~/.claude/projects/<encoded>",format:"in-memory",definedIn:"src/renderer/lib/knownProjectAggregate.ts (aggregateProjectsByCwd) "},summary:"A folder whose cwd never resolved from transcript content is DROPPED, never guessed — the naive decode once reported 2044 phantom projects.",fields:[{name:"cwd",type:"string",key:"pk",note:"resolved working directory — the project's identity"},{name:"name",type:"string",note:"display name: the cwd's last path segment"},{name:"encoded",type:"string",note:"representative transcript folder (most recently active)"},{name:"encodedIds",type:"string[]",note:"every ~/.claude/projects/<encoded> folder that resolved to this cwd"},{name:"sessionCount",type:"number"},{name:"sizeBytes",type:"number"},{name:"lastSession",type:"number"}]},{id:"tab",name:"PersistedTab",aka:"TAB",group:"project",store:{path:"~/.config/session-manager/tabs.json",format:"json",definedIn:"src/main/sessionsStore.cjs "},summary:"One TAB per project — extra sessions within a project are Epics, not tabs.",fields:[{name:"id",type:"string",key:"pk"},{name:"sessionId",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"label",type:"string"},{name:"presetId",type:"string | null"}]},{id:"epic",name:"PromptSession",aka:"EPIC",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> sessions[id]",format:"json",writer:"epics",definedIn:"src/main/lib/epicMint.cjs (ensureEpic) + src/renderer/state/promptSessions.ts "},summary:"The central aggregate root — created in exactly ONE place, a human pressing New Epic.",fields:[{name:"id",type:"string",key:"pk"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"goalText",type:"string",note:"the original top-level prompt text that started this goal"},{name:"claudeSessionId",type:"string",note:"independently minted — never shared with any tab.sessionId"},{name:"status",type:"'proposed' | 'active' | 'completed'"},{name:"createdAt",type:"string"},{name:"completedAt",type:"string | null"},{name:"resumedFromId",type:"string",optional:!0,key:"fk",ref:"epic.id"},{name:"tag",type:"TicketTag",optional:!0,key:"fk",ref:"tag.tag"},{name:"openingPrompt",type:"string | null",optional:!0},{name:"source",type:"EpicSource",optional:!0,note:"{ producer, prdSlug?, runId?, sourceTabId?, fromCwd?, fromEpicId? }"},{name:"agentType",type:"string",optional:!0,key:"fk",ref:"agentPersona.name"},{name:"sections",type:"EpicIntakeSection[]",optional:!0},{name:"worktree",type:"{ dir, branch, baseCwd, status, conflictReason? }",optional:!0,note:"own git worktree on branch 'sm-epic/<id>' when Active"}],notes:["SINGLE-CREATOR LAW, fail-closed in epicMint.cjs — the New Epic IPC handler and crossProjectFeedback.cjs are the only mint authorities.","Every Epic is born proposed; nothing is created directly as active.","EPIC : claude-session is 1:1 — Chat and Terminal are two VIEWS over one session.","Title + objective are fixed for the life of the session — iterate in follow-up messages, don't repurpose."]},{id:"epicEvent",name:"PromptSessionEvent",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> events[]",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts + src/main/lib/activeIndexMerge.cjs "},summary:"One step in an Epic's Prompt → PRD → Response → ... → Closed chain.",fields:[{name:"id",type:"string",key:"pk"},{name:"promptSessionId",type:"string",key:"fk",ref:"epic.id"},{name:"kind",type:"'prompt' | 'prd_created' | 'response' | 'closed'"},{name:"causedByEventId",type:"string | null",key:"fk",ref:"epicEvent.id",note:"must be the session's current tail event — a chain, not a tree"},{name:"at",type:"string"},{name:"prdSlug",type:"string",optional:!0,key:"fk",ref:"prd.slug"},{name:"text",type:"string",optional:!0},{name:"outcome",type:"'completed' | 'failed' | 'needs_review'",optional:!0},{name:"validation",type:"'unvalidated' | 'validating' | 'verified' | 'refuted'",optional:!0}]},{id:"epicTranscriptTurn",name:"PromptSessionTranscriptTurn",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/transcripts/<epicId>.jsonl",format:"jsonl",writer:"epics",definedIn:"src/main/promptSessionTranscript.cjs "},summary:"The durable per-Epic transcript store, kept alongside the CLI's own JSONL as a fallback source of turns.",fields:[{name:"v",type:"1"},{name:"epicId",type:"string",key:"fk",ref:"epic.id"},{name:"eventId",type:"string | null",key:"fk",ref:"epicEvent.id"},{name:"role",type:"'user' | 'assistant'"},{name:"at",type:"string"},{name:"text",type:"string"}]},{id:"epicArchive",name:"PromptSessionArchive",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/<epicId>.json",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts (promptSessionArchivePath) "},summary:"On-disk archive written once at completion — freezes the Epic, its events, and its transcript.",fields:[{name:"session",type:"PromptSession"},{name:"events",type:"PromptSessionEvent[]"},{name:"transcript",type:"string"},{name:"archivedAt",type:"string"},{name:"durableTurns",type:"Array<{ role, text, at }>",optional:!0}]},{id:"prd",name:"PRD",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/epics/<epicId>/prds/<slug>.md",format:"markdown",writer:"scheduler",definedIn:"src/main/lib/prdLocations.cjs + scheduler_create_prd MCP tool "},summary:"PRD authoring is API-only via the scheduler_create_prd MCP tool — a PRD joins an EXISTING Epic and never conjures one.",fields:[{name:"slug",type:"string",key:"pk",note:"<nn>-<kebab-title>.md filename stem"},{name:"title",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"epicId",type:"string | null",key:"fk",ref:"epic.id",note:"derived from the PRD's DIRECTORY — fact on disk"},{name:"sourcePromptId",type:"string",optional:!0,key:"fk",ref:"epic.id",note:"frontmatter intent — can disagree with epicId"},{name:"sourceTabId",type:"string",optional:!0},{name:"estimateMinutes",type:"number"},{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'bilko-host-publisher'",optional:!0,key:"fk",ref:"tag.tag"},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug",note:"the SOLE ordering primitive"},{name:"goal",type:"string"},{name:"acceptanceCriteria",type:"string[]"},{name:"implementationNotes",type:"string"},{name:"outOfScope",type:"string[]",optional:!0},{name:"createdVia",type:"string",optional:!0},{name:"issuedAt",type:"string",optional:!0}],notes:["Flat scheduler/prds/ is RETIRED — auto-consolidated into prds-archived/ on every reconcile() pass.","epicId is derived from the DIRECTORY (fact on disk) while sourcePromptId is frontmatter intent and can disagree."]},{id:"scheduleJob",name:"ScheduleJob",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/queueStore.cjs + src/main/lib/scheduleJobSchema.cjs "},summary:"dependsOn is the SOLE ordering primitive — parallelGroup is a display hint, never a barrier.",fields:[{name:"slug",type:"string",key:"pk",note:"shared identity with the PRD it executes"},{name:"title",type:"string"},{name:"cwd",type:"string | null",key:"fk",ref:"project.cwd"},{name:"parallelGroup",type:"number"},{name:"estimateMinutes",type:"number | null"},{name:"bodyPreview",type:"string"},{name:"status",type:"'pending' | 'running' | 'investigating' | 'completed' | 'failed' | 'needs_review' | 'quarantined'"},{name:"runId",type:"string | null",key:"fk",ref:"runLog.runId"},{name:"startedAt",type:"string | null"},{name:"finishedAt",type:"string | null"},{name:"exitCode",type:"number | null"},{name:"error",type:"string | null"},{name:"sessionId",type:"string",optional:!0},{name:"runtime",type:"ScheduleJobRuntime",optional:!0,note:"{ pid, runId, startedAt, sessionId?, cwd? }"},{name:"verifierVerdict",type:"string",optional:!0},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug"},{name:"originSessionId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"sourceTabId",type:"string | null",optional:!0},{name:"sourcePromptId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id",note:"authoritative — derived from the PRD directory"},{name:"statusHistory",type:"ScheduleJobStatusHistoryEntry[]",optional:!0}],notes:["Every launch must take a slot from lib/sessionSlots.cjs — the single machine-wide concurrency limit.","--model is always pinned on every claude -p call site.","A job in needs_review is a QUESTION routed back to the authoring Epic and never creates work on its own."]},{id:"scheduleJobStatusHistory",name:"ScheduleJobStatusHistoryEntry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[].statusHistory[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/scheduleJobTransitions.cjs "},summary:"Bounded trail (~20 entries) of accepted status transitions for one ScheduleJob.",fields:[{name:"from",type:"string | null"},{name:"to",type:"string"},{name:"reason",type:"string | null"},{name:"source",type:"string | null"},{name:"at",type:"string"}]},{id:"scheduleHistoryEntry",name:"Schedule history entry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/history.jsonl",format:"jsonl",writer:"scheduler",definedIn:"src/main/lib/queueStore.cjs "},summary:"Terminal jobs aged out of queue.json land here, one JSON object per line.",fields:[{name:"slug",type:"string",key:"fk",ref:"prd.slug"},{name:"status",type:"ScheduleJobStatus"},{name:"finishedAt",type:"string | null"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"runId",type:"string | null",optional:!0,key:"fk",ref:"runLog.runId"}]},{id:"scheduleConfig",name:"ScheduleConfig",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> config",format:"json",writer:"scheduler",definedIn:"src/main/lib/schedulerConfig.cjs "},summary:"Per-project auto-fire policy and utilization gate.",fields:[{name:"enabled",type:"boolean",note:"legacy on/off, kept for v0.4 backwards compat"},{name:"offsetMinutes",type:"number"},{name:"defaultCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"firePolicy",type:"'manual' | 'on-reset' | 'when-available'"},{name:"utilizationThreshold",type:"number"},{name:"schemaVersion",type:"1"}]},{id:"runLog",name:"Run log",group:"scheduler",store:{path:"~/.claude/session-manager/scheduled-plans/runs/<runId>/",format:"directory",definedIn:"src/main/scheduler.cjs (RUNS_DIR) "},summary:"One directory per headless claude -p invocation — stdout/stderr/exit capture for a ScheduleJob's run.",fields:[{name:"runId",type:"string",key:"pk"}]},{id:"agentPersona",name:"AgentPersona",aka:"ACTOR — also an ACTION when scoped",group:"agents",store:{path:"~/.claude/agents/<name>.md",format:"markdown",definedIn:"src/main/agentLibrary.cjs + src/main/lib/agentPersonaSchema.cjs "},summary:"One global persona — an ACTION is this same persona given a project scope, not a fourth concept.",fields:[{name:"name",type:"string",key:"pk"},{name:"description",type:"string | null"},{name:"tools",type:"string[]"},{name:"model",type:"string | null",note:"wins over the Settings default for this Epic"},{name:"color",type:"string | null"},{name:"tags",type:"AgentPersonaTag[]",key:"fk",ref:"tag.tag"},{name:"projects",type:"string[]",key:"fk",ref:"project.cwd",note:"'*' means every project"},{name:"action",type:"string | null"},{name:"actionLabel",type:"string | null"},{name:"title",type:"string | null",optional:!0},{name:"path",type:"string"},{name:"body",type:"string"},{name:"overridingProjects",type:"string[]"}]},{id:"tag",name:"Tag",aka:"MISSION — EpicTag",group:"agents",store:{path:"src/renderer/lib/tagLibrary.ts (TAG_LIBRARY)",format:"code",definedIn:"src/renderer/lib/tagLibrary.ts + src/renderer/lib/agentTagDefs.ts "},summary:"The closed 5-taxonomy union — Epic creation is agentType (who) + tag (what), two independent selections.",fields:[{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'bilko-host-publisher'",key:"pk"},{name:"label",type:"string"},{name:"description",type:"string"},{name:"developEagerness",type:"'expected-default' | 'available-not-assumed'"},{name:"developsVia",type:"string"}]},{id:"memoryEntry",name:"MemoryEntry",group:"memory",store:{path:"~/.claude/projects/<encodedCwd>/memory/<name>.md",format:"markdown",definedIn:"src/main/memoryTool.cjs "},summary:"One workspace memory file, semantically organized by topic.",fields:[{name:"name",type:"string",key:"pk"},{name:"path",type:"string"},{name:"mtimeMs",type:"number"},{name:"bytes",type:"number"},{name:"workspace",type:"string",key:"fk",ref:"project.cwd",note:"carried on MemoryListResult, denormalized here — the directory this entry lives under"}]},{id:"memoryCluster",name:"MemoryCluster",group:"memory",store:{path:"~/.claude/session-manager/memory-clusters/<encodedCwd>.json",format:"json",definedIn:"src/main/memoryAggregate.cjs "},summary:"Derived grouping of related MemoryEntry files, computed and cached per workspace.",fields:[{name:"id",type:"string",key:"pk"},{name:"name",type:"string"},{name:"summary",type:"string"},{name:"memberSlugs",type:"string[]",key:"fk",ref:"memoryEntry.name"},{name:"links",type:"MemoryClusterLink[]",note:"{ from, to, label? }"}]},{id:"agentMemoryEntry",name:"AgentMemoryEntry",group:"memory",store:{path:"~/.claude/session-manager/agent-memory/<agentId>/",format:"directory",definedIn:"src/renderer/state/agentMemory.ts "},summary:"Per-subagent memory, keyed by agent name rather than workspace cwd.",fields:[{name:"id",type:"string",key:"pk"},{name:"body",type:"string"},{name:"category",type:"'command' | 'preference' | 'pattern' | 'failure' | 'workflow' | null"},{name:"createdAt",type:"number"},{name:"updatedAt",type:"number"},{name:"bytes",type:"number"},{name:"agentId",type:"string",key:"fk",ref:"agentPersona.name",note:"carried on AgentMemoryListResult, denormalized here — the directory this entry lives under"}]},{id:"claudeTranscript",name:"Claude transcript",group:"transcript",store:{path:"~/.claude/projects/<encodedCwd>/<sessionUuid>.jsonl",format:"jsonl",definedIn:"written by the Claude Code CLI; tailed by src/main/transcripts.cjs "},summary:"The CLI's own append-only transcript — Session Manager only tails and classifies it, never writes it.",fields:[{name:"sessionUuid",type:"string",key:"pk"},{name:"encodedCwd",type:"string",key:"fk",ref:"project.cwd"}]},{id:"transcriptEvent",name:"TranscriptEvent",group:"transcript",store:{path:"in-memory ring buffer, broadcast as transcript:event:<tabId>",format:"in-memory",definedIn:"src/main/transcripts.cjs -> src/renderer/state/live.ts "},summary:"Classified, bounded-preview view over one raw transcript line — never the source of truth.",fields:[{name:"kind",type:"TranscriptEventKind"},{name:"data",type:"unknown"},{name:"raw",type:"unknown"},{name:"previewText",type:"string"},{name:"ref",type:"TranscriptEventRef | null",note:"{ filePath, byteOffset, byteLength }"},{name:"tabId",type:"string",key:"fk",ref:"tab.id"}]},{id:"historyRollupDay",name:"History rollup day",group:"transcript",store:{path:"~/.claude/session-manager/history-rollup.jsonl",format:"jsonl",definedIn:"src/main/lib/historyRollup.cjs "},summary:"One finalized day-per-project analytics row (History tab is analytics/cost/charts only).",fields:[{name:"date",type:"string",key:"pk"},{name:"projectCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"promptCount",type:"number"},{name:"inputTokens",type:"number"},{name:"outputTokens",type:"number"},{name:"estimatedCostUsd",type:"number"}]},{id:"billingUsage",name:"UsageSnapshot",group:"transcript",store:{path:"~/.claude/session-manager/billing-cache.json",format:"json",definedIn:"src/main/usage.cjs (CACHE_PATH) "},summary:"Cached rolling-window utilization percentages from the account's billing API.",fields:[{name:"five_hour",type:"UsageWindow | null"},{name:"seven_day",type:"UsageWindow | null"},{name:"seven_day_sonnet",type:"UsageWindow | null"},{name:"seven_day_opus",type:"UsageWindow | null"},{name:"seven_day_oauth_apps",type:"UsageWindow | null"},{name:"extra_usage",type:"{ is_enabled, monthly_limit, used_credits, utilization, currency } | null"}]},{id:"projectBrief",name:"ProjectBrief",group:"brief",store:{path:"<cwd>/session-manager-operations/project-brief/brief.json",format:"json",writer:"project-home",definedIn:"src/main/projectBrief.cjs "},summary:"The synthesized project Brief — generated, with a hand-edit escape hatch.",fields:[{name:"version",type:"number"},{name:"synthesizedAt",type:"string"},{name:"editedAt",type:"string | null"},{name:"model",type:"string"},{name:"purpose",type:"string"},{name:"what",type:"string[]"},{name:"areas",type:"ProjectBriefArea[]",note:"{ name, files, note, epic, heat }"},{name:"scope",type:"ProjectBriefScopeEntry[]",note:"{ when, kind, text, src }"},{name:"conventions",type:"string[]"},{name:"pins",type:"{ what: boolean; conventions: boolean }"},{name:"pinned",type:"{ what: string[] | null; conventions: string[] | null }"}]},{id:"projectPages",name:"ProjectPagesOutput",group:"brief",store:{path:"<cwd>/session-manager-operations/project-pages/ (home.html)",format:"directory",writer:"project-home",definedIn:"project_home_write MCP tool (src/main/lib/projectHomeAdminRoutes.cjs)"},summary:"One self-contained overview page, written only via project_home_write.",fields:[{name:"html",type:"string | null"},{name:"mtimeMs",type:"number | null"}]},{id:"bilkoPublishState",name:"BilkoHostPublishState",group:"brief",store:{path:"<cwd>/session-manager-operations/bilko-host/publish-state.json",format:"json",writer:"bilko-host",definedIn:"src/renderer/lib/bilkoHost.ts + bilko-host MCP "},summary:"The bilko.run relay is intentionally still live — never delete or decommission it.",fields:[{name:"status",type:"'not-published' | 'bundle-ready' | 'publishing' | 'published' | 'publish-failed'"},{name:"slug",type:"string"},{name:"url",type:"string",optional:!0},{name:"lastAttemptAt",type:"string",optional:!0},{name:"lastError",type:"string",optional:!0}]},{id:"settingsScope",name:"Settings (scoped)",group:"config",store:{path:"~/.claude/settings.json + <cwd>/.claude/settings.json + <cwd>/.claude/settings.local.json",format:"json",definedIn:"src/main/config.cjs + src/renderer/state/config.ts + src/renderer/lib/mergeScopes.ts "},summary:"Substrate, not per-Epic curation — model is the one field carved out per-Epic (persona wins over Settings).",fields:[{name:"scope",type:"'system' | 'project' | 'local'",key:"pk"},{name:"cwd",type:"string",optional:!0,key:"fk",ref:"project.cwd"},{name:"model",type:"string",optional:!0}]},{id:"layoutEnvelope",name:"LayoutEnvelope",group:"config",store:{path:"~/.claude/session-manager/workbench-layout.json",format:"json",definedIn:"src/main/layoutStore.cjs + src/renderer/state/layout.ts "},summary:"Persisted dockview panel layout, pruned against the live panel registry on hydrate.",fields:[{name:"version",type:"number"},{name:"panels",type:"string[]",key:"fk",ref:"tab.id"},{name:"dockview",type:"Record<string, unknown>",note:"opaque SerializedDockview blob"}]},{id:"opsNamespace",name:"Ops namespace ownership",aka:"the SINGLE-WRITER LAW",group:"config",store:{path:"src/main/lib/opsOwnership.cjs (OWNERS)",format:"code",definedIn:"src/main/lib/opsOwnership.cjs (assertOpsWrite) "},summary:"Fail-closed — a new top-level ops folder must land in OWNERS (or the deliberately-unowned list) in the same PR that creates it.",fields:[{name:"namespace",type:"string",key:"pk",note:"e.g. 'prompt-sessions', 'scheduler', 'project-brief', 'bilko-host'"},{name:"writer",type:"string",note:"e.g. 'epics', 'scheduler', 'project-home', 'bilko-host'"}]}];function XB(i){const e=Rb.find(t=>t.id===i);if(!e)throw new Error(`unknown ErdEntity id: ${i}`);return e}const jC=[{from:"tab",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"epic",to:"agentPersona",cardinality:"N-1",label:"actor",optional:!0},{from:"epic",to:"epic",cardinality:"N-1",label:"resumed from",optional:!0},{from:"epic",to:"claudeTranscript",cardinality:"1-1",label:"1:1 session"},{from:"epicEvent",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicEvent",to:"epicEvent",cardinality:"N-1",label:"caused by",optional:!0},{from:"epicEvent",to:"prd",cardinality:"N-1",label:"about",optional:!0},{from:"epicTranscriptTurn",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicTranscriptTurn",to:"epicEvent",cardinality:"N-1",label:"labeled by",optional:!0},{from:"epicArchive",to:"epic",cardinality:"1-1",label:"freezes"},{from:"prd",to:"epic",cardinality:"N-1",label:"joins (directory fact)"},{from:"prd",to:"epic",cardinality:"N-1",via:"sourcePromptId",label:"authored from (frontmatter intent)",optional:!0},{from:"prd",to:"project",cardinality:"N-1",label:"belongs to"},{from:"prd",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"scheduleJob",to:"prd",cardinality:"1-1",label:"executes"},{from:"scheduleJob",to:"prd",cardinality:"N-N",via:"dependsOn",label:"depends on",optional:!0},{from:"scheduleJob",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleJob",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleJob",to:"scheduleJob",cardinality:"N-N",via:"dependsOn",label:"depends on (self)",optional:!0},{from:"scheduleJobStatusHistory",to:"scheduleJob",cardinality:"N-1",label:"transitions of"},{from:"scheduleHistoryEntry",to:"prd",cardinality:"N-1",label:"archives"},{from:"scheduleHistoryEntry",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleHistoryEntry",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleConfig",to:"project",cardinality:"1-1",label:"configures"},{from:"agentPersona",to:"tag",cardinality:"N-N",label:"tagged with"},{from:"agentPersona",to:"project",cardinality:"N-N",label:"action button in"},{from:"memoryEntry",to:"project",cardinality:"N-1",label:"workspace"},{from:"memoryCluster",to:"memoryEntry",cardinality:"1-N",label:"clusters"},{from:"agentMemoryEntry",to:"agentPersona",cardinality:"N-1",label:"belongs to"},{from:"transcriptEvent",to:"tab",cardinality:"N-1",label:"classified for"},{from:"transcriptEvent",to:"claudeTranscript",cardinality:"N-1",label:"classified from"},{from:"claudeTranscript",to:"project",cardinality:"N-1",label:"belongs to"},{from:"historyRollupDay",to:"project",cardinality:"N-N",label:"aggregates"},{from:"billingUsage",to:"scheduleConfig",cardinality:"1-N",label:"gates when-available firing"},{from:"projectBrief",to:"project",cardinality:"1-1",label:"describes"},{from:"projectBrief",to:"epic",cardinality:"N-1",via:"areas[].epic",label:"traces to",optional:!0},{from:"projectPages",to:"project",cardinality:"1-1",label:"generated for"},{from:"bilkoPublishState",to:"project",cardinality:"1-1",label:"publishes"},{from:"settingsScope",to:"project",cardinality:"N-1",label:"scoped to",optional:!0},{from:"layoutEnvelope",to:"tab",cardinality:"1-N",label:"panels for"},{from:"opsNamespace",to:"epic",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"prd",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"projectBrief",cardinality:"1-N",label:"governs writes"}];function _P(i){return jC.filter(e=>e.from===i||e.to===i)}function YB(i){const e=new Set;for(const t of _P(i)){const n=t.from===i?t.to:t.from;n!==i&&e.add(n)}return[...e]}function JB(i){switch(i){case"1-1":return"1—1";case"1-N":return"1—N";case"N-1":return"N—1";case"N-N":return"N—N"}}const Zx=220,Qx=7,yP=44,bP=16,wP=10,xP=96,SP=28,Mg=24;function CP(i){const e=Math.min(i,Qx)+(i>Qx?1:0);return yP+e*bP+wP}function EP(i){const e=i.x+i.w,t=i.y+i.h*.35,n=i.y+i.h*.65,r=e+48;return{d:`M ${e} ${t} C ${r} ${t}, ${r} ${n}, ${e} ${n}`,mx:r,my:(t+n)/2}}function ZB(i=Rb,e=jC){const t=MC.map(f=>f.id).filter(f=>i.some(g=>g.group===f)),n=[],r=new Map;t.forEach((f,g)=>{const m=Mg+g*(Zx+xP);let b=Mg;for(const T of i){if(T.group!==f)continue;const E=CP(T.fields.length),k={id:T.id,group:f,x:m,y:b,w:Zx,h:E};n.push(k),r.set(T.id,k),b+=E+SP}});const l=new Set(i.map(f=>f.id)),p=[];for(const f of e){if(!l.has(f.from)||!l.has(f.to))continue;const g=r.get(f.from),m=r.get(f.to);if(!g||!m)continue;if(f.from===f.to){const O=EP(g);p.push({relation:f,...O});continue}const b=g.x<m.x,T=b?g.x+g.w:g.x,E=g.y+g.h/2,k=b?m.x:m.x+m.w,y=m.y+m.h/2,S=Math.max(40,Math.abs(k-T)/2),w=T+(b?S:-S),x=k+(b?-S:S),A=`M ${T} ${E} C ${w} ${E}, ${x} ${y}, ${k} ${y}`;p.push({relation:f,d:A,mx:(T+k)/2,my:(E+y)/2})}const a=n.reduce((f,g)=>Math.max(f,g.x+g.w),0),d=n.reduce((f,g)=>Math.max(f,g.y+g.h),0);return{boxes:n,edges:p,width:a+Mg,height:d+Mg}}const Ob=[];function kP({onNavigate:i}){const e=B.useMemo(()=>{const g=new Date().getHours();return g<5?"Up late":g<12?"Good morning":g<18?"Good afternoon":"Good evening"},[]);UP();const t=AP(),n=DP(),r=St(g=>g.tabs),l=St(g=>g.addTab),p=St(g=>g.setActive),[a,d]=B.useState(!1),f=g=>{EC(g,r,l,p),i==null||i("terminal")};return c.jsxs("div",{className:"h-full overflow-auto",children:[c.jsxs("div",{className:"mx-auto max-w-[1080px] px-[34px] py-[26px] text-fg",children:[c.jsx(RP,{greeting:e,projectCount:n.length,needsCount:t.length,onNavigate:i,onOpenNewEpic:()=>d(!0)}),c.jsxs("div",{className:"grid gap-[18px] mb-7",style:{gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr) 220px"},children:[c.jsx(zP,{}),c.jsx(BP,{projectRows:n}),c.jsx(MP,{onNavigate:i})]}),c.jsx(NP,{rows:t,onNavigate:i}),c.jsx(WP,{onNavigate:i}),c.jsx(FP,{onNavigate:i}),c.jsx(eP,{}),c.jsx(IP,{}),c.jsx(PP,{onNavigate:i}),c.jsx(XI,{})]}),c.jsx(FI,{open:a,onClose:()=>d(!1),projects:n,onConfirm:f})]})}const TP=B.memo(kP);function DP(){const{projects:i}=vd(),e=Mv(),t=ti(n=>n.sessions);return B.useMemo(()=>LI(i,e,t),[i,e,t])}function AP(){const i=ti(n=>n.sessions),e=Mv(),t=Nr(n=>{var r;return(r=n.snapshot)==null?void 0:r.jobs})??Ob;return B.useMemo(()=>{const n={};for(const r of Object.keys(i)){const l=i[r];l.status==="proposed"&&(n[r]={id:r,cwd:l.cwd,goalText:l.goalText,tag:l.tag})}return jI(n,e,t)},[i,e,t])}function IP(){const i=OC(null),{value:e,source:t}=LC(i,["effortLevel"]),n=$C(e,t);return c.jsxs("section",{className:"mb-6",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Agents"}),c.jsxs("span",{className:"font-mono text-[12px] text-fg-faint","data-testid":"home-agents-effort",title:"Machine-wide effective reasoning effort — the settings.json scope chain's current winner, independent of any one project.",children:["1 tag per session · ",n]})]}),c.jsx("div",{className:"grid gap-2",children:lP.map(r=>{const l=AC[r],p=t1(r);return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[13px] px-4 py-[13px]",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("span",{className:`font-mono text-[10.5px] font-semibold uppercase tracking-[0.06em] px-1.5 py-0.5 rounded ${p.bg} ${p.text}`,children:p.label}),c.jsx("span",{className:"text-[12px] text-fg-faint",children:l.description})]}),c.jsx("p",{className:"m-0 text-[12.5px] text-fg-dim leading-[1.5] font-mono whitespace-pre-wrap",children:l.initialPromptTemplate})]},r)})})]})}function PP({onNavigate:i}){return c.jsx("section",{className:"mb-6",children:c.jsxs("button",{type:"button","data-testid":"home-data-model-card",onClick:()=>i==null?void 0:i("data-model"),className:"w-full text-left bg-bg-hi border border-line rounded-[14px] px-4 py-[14px] flex items-center justify-between hover:bg-bg-elev/40 transition-colors",children:[c.jsxs("span",{children:[c.jsx("span",{className:"block font-serif text-[16px] font-medium text-fg",children:"Data Model"}),c.jsxs("span",{className:"block text-[12.5px] text-fg-dim",children:[Rb.length," entities — what Session Manager persists, and how it joins"]})]}),c.jsx("span",{className:"font-mono text-[11px] text-accent shrink-0",children:"Open →"})]})})}function RP({greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r}){const[l,p]=B.useState(!1);return c.jsxs(c.Fragment,{children:[c.jsx(OP,{greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r,legendOpen:l,onToggleLegend:()=>p(a=>!a)}),l&&c.jsx($P,{})]})}function OP({greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r,legendOpen:l,onToggleLegend:p}){const a=_b(),d=(a==null?void 0:a.total)??5,f=(a==null?void 0:a.inUse)??0,g=()=>{var m;(m=document.getElementById("home-needs-you"))==null||m.scrollIntoView({behavior:"smooth",block:"start"})};return c.jsxs("header",{className:"mb-[18px] flex items-end gap-4",children:[c.jsxs("div",{children:[c.jsxs("div",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-1.5",children:["This machine · ",e," project",e===1?"":"s"]}),c.jsxs("h1",{className:"m-0 font-serif text-[30px] font-semibold leading-[1.1] text-fg tracking-[-0.01em]",children:[i,". ",c.jsxs("span",{className:"text-accent",children:[f," of ",d]})," slots busy,"," ",t>0?c.jsxs("button",{onClick:g,className:"underline decoration-dotted underline-offset-4 text-honey-dark hover:text-honey",children:[t," thing",t>1?"s":""]}):c.jsx("span",{className:"text-sage",children:"nothing"})," ","need",t===1?"s":""," you."]})]}),c.jsxs("div",{className:"ml-auto flex gap-2 shrink-0",children:[c.jsx(C_,{onClick:p,children:l?"Hide interactions":"Interactions"}),c.jsx(C_,{onClick:()=>n==null?void 0:n("history"),children:"All history"}),c.jsx(C_,{primary:!0,onClick:r,children:"New epic"})]})]})}const LP=[{term:"Usage card",description:"Read-only — shows the live 5-hour and weekly billing windows. Not clickable."},{term:"Queued job",description:`Click a job row to open a popover with its real details (project, estimate, status) and actions — Open in Scheduler, plus Nudge scheduler now while it's pending. Use "Open Scheduler →" in the card header to jump straight to the Scheduler tab.`},{term:"Needs-you row",description:"Click a row to expand it inline, then Approve & start / Discard a proposed session, Open a session waiting on input, Retry / view a failed job, or Adopt / view a quarantined PRD."},{term:"Active session row",description:"Click Open to jump to the Scheduler tab (job) or the session's Terminal view."},{term:"Recent row",description:"Click resume to open a new Terminal tab that resumes that transcript session."},{term:"Project row",description:"Click a project to activate its open Terminal tab, or open a new dormant one."},{term:"New session",description:"Opens a project picker; confirming activates-or-opens that project's tab and lands you in its Sessions workspace to start the session."}];function $P(){return c.jsxs("div",{className:"mb-7 bg-bg-hi border border-line rounded-[13px] px-4 py-[13px]",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2.5",children:"Interactions"}),c.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"minmax(0,140px) minmax(0,1fr)"},children:LP.map(i=>c.jsxs("div",{className:"contents",children:[c.jsx("div",{className:"text-[12.5px] font-semibold text-fg underline decoration-dotted underline-offset-4",children:i.term}),c.jsx("div",{className:"text-[12.5px] text-fg-dim leading-[1.5]",children:i.description})]},i.term))})]})}function C_({children:i,onClick:e,primary:t}){return c.jsx("button",{onClick:e,className:t?"rounded-lg bg-accent text-bg-hi px-4 py-2 text-[12.5px] font-semibold hover:bg-accent-dark":"rounded-lg border border-line bg-bg-hi px-4 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:i})}function NP({rows:i,onNavigate:e}){const[t,n]=B.useState(null),[r,l]=B.useState(null),p=m=>{if(!(!m.epicId||r)){l(m.id);try{const b=ti.getState().approveProposed(m.epicId,"Home needs-you");if(!b){nt.error("This session is no longer awaiting approval.");return}pi.getState().send({tabId:b.id,sessionId:b.claudeSessionId,cwd:b.cwd,prompt:b.openingPrompt||b.goalText}),nt.info("Session approved and started.")}finally{l(null),n(null)}}},a=m=>{!m.epicId||r||(l(m.id),ti.getState().markCompleted(m.epicId,"Home needs-you discard").catch(()=>{}).finally(()=>{l(null),n(null)}))},d=m=>{m.epicId&&(jv(m.epicId),e==null||e("terminal"))},f=m=>{!m.jobSlug||r||(l(m.id),window.api.schedule.resetJob(m.jobSlug).then(b=>{b.ok?nt.info(`${m.jobSlug} reset to pending.`):nt.error(b.error??"Could not reset job.")}).catch(b=>nt.error(b instanceof Error?b.message:String(b))).finally(()=>{l(null),n(null)}))},g=m=>{!m.jobSlug||r||(l(m.id),window.api.schedule.adoptPrd(m.jobSlug).then(b=>{b.ok?nt.info(`${m.jobSlug} adopted — will run on the next tick.`):nt.error(b.message??"Could not adopt PRD.")}).catch(b=>nt.error(b instanceof Error?b.message:String(b))).finally(()=>{l(null),n(null)}))};return c.jsxs("section",{id:"home-needs-you",className:"mb-6 scroll-mt-4",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Needs you"}),c.jsx("span",{className:"font-mono text-[12px] text-fg-faint",children:i.length?`${i.length} open`:"all clear"})]}),i.length===0&&c.jsx("div",{className:"bg-bg-hi border border-line rounded-[11px] px-4 py-[18px] text-center text-[13px] text-fg-faint",children:"Nothing waiting on you. Proposed Epics, mid-run questions, and failed jobs will surface here."}),c.jsx("div",{className:"grid gap-[7px]",children:i.map(m=>{const b=t===m.id,T=m.kind==="job-failed"?"bg-accent":m.kind==="job-quarantined"?m.escalated?"bg-accent":"bg-honey":m.kind==="needs-input"?"bg-honey":"bg-sage";return c.jsxs("div",{className:`border rounded-[11px] overflow-hidden ${b?"bg-bg-hi border-line":"bg-bg border-line/60"}`,children:[c.jsxs("button",{onClick:()=>n(b?null:m.id),className:"w-full grid items-center gap-2.5 px-[13px] py-[10px] text-left",style:{gridTemplateColumns:"6px minmax(0,1fr) auto"},children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T}`}),c.jsxs("span",{className:"min-w-0",children:[c.jsx("span",{className:"block text-[12.5px] font-semibold text-fg",children:m.label}),c.jsxs("span",{className:"block text-[11.5px] text-fg-faint truncate",children:[m.project?`${m.project} · `:"",m.detail]})]}),c.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:b?"▴":"▾"})]}),b&&c.jsxs("div",{className:"border-t border-line px-[13px] pt-[11px] pb-3 grid gap-2.5",children:[c.jsx("div",{className:"text-[12.5px] text-fg-dim leading-relaxed",children:m.meta}),c.jsxs("div",{className:"flex gap-2",children:[m.kind==="proposed-epic"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>p(m),disabled:r===m.id,children:"Approve & start"}),c.jsx(nd,{quiet:!0,onClick:()=>a(m),disabled:r===m.id,children:"Discard"})]}),m.kind==="needs-input"&&c.jsx(nd,{onClick:()=>d(m),children:"Open session"}),m.kind==="job-failed"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>f(m),disabled:r===m.id,children:"Retry now"}),c.jsx(nd,{quiet:!0,onClick:()=>e==null?void 0:e("scheduler"),children:"View in Scheduler"})]}),m.kind==="job-quarantined"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>g(m),disabled:r===m.id,children:"Adopt PRD"}),c.jsx(nd,{quiet:!0,onClick:()=>e==null?void 0:e("scheduler"),children:"View in Scheduler"})]})]})]})]},m.id)})})]})}function nd({children:i,onClick:e,disabled:t,quiet:n}){return c.jsx("button",{onClick:e,disabled:t,className:n?"rounded-md border border-line bg-bg px-3 py-[5px] text-[11.5px] font-semibold text-fg-dim hover:bg-bg-elev disabled:opacity-50":"rounded-md bg-accent text-bg-hi px-3 py-[5px] text-[11.5px] font-semibold hover:bg-accent-dark disabled:opacity-50",children:i})}function MP({onNavigate:i}){const e=Nr(p=>{var a;return(a=p.snapshot)==null?void 0:a.jobs})??Ob,t=B.useMemo(()=>e.filter(p=>p.status==="pending").slice(0,4),[e]),[n,r]=B.useState(null),l=()=>{window.api.schedule.runNow().catch(p=>nt.error(p instanceof Error?p.message:String(p))),r(null)};return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[14px] px-4 py-[14px]",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2.5",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint",children:"Queued"}),c.jsx("button",{onClick:()=>i==null?void 0:i("scheduler"),className:"font-mono text-[10.5px] text-accent hover:underline",children:"Open Scheduler →"})]}),t.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-1",children:"Nothing pending."}):c.jsx("div",{className:"space-y-2.5",children:t.map(p=>c.jsxs("div",{className:"relative",children:[c.jsxs("button",{onClick:()=>r(n===p.slug?null:p.slug),className:"w-full text-left hover:bg-bg/40 rounded-md -mx-1 px-1 py-0.5 transition-colors",children:[c.jsx("div",{className:"font-mono text-[11.5px] font-semibold text-fg truncate",children:p.title||p.slug}),c.jsxs("div",{className:"text-[11px] text-fg-faint truncate",children:[p.cwd?Lo(p.cwd):"—",p.estimateMinutes!=null?` · ~${p.estimateMinutes}m`:""]})]}),n===p.slug&&c.jsx(WI,{job:p,onClose:()=>r(null),onOpenScheduler:()=>{r(null),i==null||i("scheduler")},onRunNow:p.status==="pending"?l:void 0})]},p.slug))})]})}function jP({slots:i}){const e=(i==null?void 0:i.min)??0,t=(i==null?void 0:i.max)??10,n=(i==null?void 0:i.total)??5,r=(i==null?void 0:i.envOverride)??!1,[l,p]=B.useState(null),[a,d]=B.useState(!1),f=l??n,g=m=>{p(m),d(!0),window.api.schedule.setSessionSlots(m).catch(()=>{}).finally(()=>{d(!1),p(null)})};return c.jsxs("span",{className:"flex items-center gap-2.5 shrink-0",title:r?"Pinned by SM_SESSION_SLOTS env var":"Max concurrent claude -p sessions on this machine (0 pauses new launches)",children:[c.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:"Max slots"}),c.jsx("input",{type:"range",min:e,max:t,step:1,value:f,disabled:r||a,onChange:m=>g(Number(m.target.value)),className:"w-24 accent-accent disabled:opacity-40 disabled:cursor-not-allowed"}),c.jsx("span",{className:"font-mono text-[12px] font-semibold text-fg w-4 text-right",children:f})]})}function zP(){const i=Jf(t=>t.data),e=L1(i);return c.jsxs("div",{className:"space-y-3",children:[i&&i.kind!=="ok"&&i.kind!=="ok-stale"&&c.jsx(aP,{result:i,onRetry:jD}),!i&&c.jsx("div",{className:"text-xs text-fg-faint",children:"loading usage…"}),e&&c.jsx(HI,{data:e,updatedAt:e.fetchedAt})]})}function BP({projectRows:i}){const e=St(l=>l.tabs),t=St(l=>l.addTab),n=St(l=>l.setActive),r=l=>{EC(l,e,t,n),Ii.getState().setEpicsWorkspaceOpen(!1)};return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[14px] px-4 py-[14px]",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2.5",children:"Projects"}),i.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-2",children:"No known projects yet."}):c.jsx("div",{className:"space-y-1",children:i.map(l=>c.jsxs("button",{onClick:()=>r(l.cwd),className:"w-full flex items-center gap-2.5 text-left px-2 py-1.5 rounded-lg hover:bg-bg/60 transition-colors",title:l.cwd,children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:CC(l.dotSeed)}}),c.jsx("span",{className:"flex-1 min-w-0 text-[13px] text-fg truncate",children:l.name}),l.liveCount>0?c.jsxs("span",{className:"font-mono text-[11px] text-accent whitespace-nowrap",children:[l.liveCount," live"]}):c.jsx("span",{className:"font-mono text-[11px] text-fg-faint whitespace-nowrap",children:nm(l.lastActivityMs)})]},l.encoded))})]})}function UP(){const{projects:i}=vd(),e=B.useMemo(()=>i.map(t=>t.cwd).join(`
2923
+ `))if(l.includes('"cwd"'))try{const p=JSON.parse(l);if(typeof p.cwd=="string"&&p.cwd.length>0)return p.cwd}catch{}}}return null}let gh={rows:[],enriched:{},loading:!0,resolving:!0};const Ty=new Set;let Kx=null,nc=0;function PI(){Ty.forEach(i=>i())}function vh(i){gh={...gh,...i},PI()}const Dy=6;async function Ay(i,e,t){const n=new Array(i.length);let r=0;const l=Array.from({length:Math.min(e,i.length)},async()=>{for(;;){const p=r++;if(p>=i.length)return;n[p]=await t(i[p])}});return await Promise.all(l),n}async function RI(i){const e=++nc;vh({loading:!0,resolving:!0});try{const t=await window.api.config.listDir(`${i}/.claude/projects`,{dirsOnly:!0});if(e!==nc)return;const n=t.entries,r=await Ay(n,Dy,async l=>{const a=(await window.api.config.listDir(l.path,{filesOnly:!0})).entries.filter(g=>g.name.endsWith(".jsonl")),d=a.reduce((g,m)=>Math.max(g,m.mtimeMs),0),f=a.reduce((g,m)=>g+m.size,0);return{encoded:l.name,displayPath:xC(l.name),sessionCount:a.length,lastSession:d,path:l.path,sizeBytes:f}});if(e!==nc)return;r.sort((l,p)=>p.lastSession-l.lastSession),vh({rows:r,enriched:{},loading:!1,resolving:!0}),OI(r,e)}catch(t){console.error("[useKnownProjects] scan failed:",t),e===nc&&vh({loading:!1,resolving:!1})}}async function OI(i,e){const t={};if(await Ay(i,Dy,async l=>{if(e===nc){if(l.sessionCount===0){t[l.encoded]=null;return}try{const p=await SC(l.path);t[l.encoded]=p?al(p):null}catch{t[l.encoded]=null}}}),e!==nc)return;const n={};for(const l of i)n[l.encoded]={cwd:t[l.encoded]??null};vh({enriched:n,resolving:!1});const r=[...new Set(Object.values(t).filter(l=>!!l))];await Ay(r,Dy,async l=>{if(e!==nc)return;let p={};try{p=await TI(l)}catch{return}if(e!==nc)return;const a={...gh.enriched};for(const[d,f]of Object.entries(t))f===l&&(a[d]={cwd:l,...p});vh({enriched:a})})}function vd(){const i=Ab(),[,e]=B.useState(0),t=St(b=>b.addTab);B.useEffect(()=>{const b=()=>e(T=>T+1);return Ty.add(b),()=>{Ty.delete(b)}},[]),B.useEffect(()=>{i&&Kx!==i&&(Kx=i,RI(i))},[i]);const{rows:n,enriched:r,loading:l,resolving:p}=gh,a=B.useMemo(()=>DI(n,r),[n,r]),d=async b=>{const T=crypto.randomUUID();t({id:T,cwd:b,startupCommand:null,presetId:"projects-tab",dormant:!0})},f=async b=>{var k;let T=((k=r[b.encoded])==null?void 0:k.cwd)??null;if(T||(T=await SC(b.path)),!T&&(T=await window.api.app.pickDirectory(),!T))return;const E=crypto.randomUUID();t({id:E,cwd:T,startupCommand:null,presetId:"projects-tab",dormant:!0})},g=async b=>{try{const T=await window.api.app.archiveProject(b);return T.ok&&vh({rows:gh.rows.filter(E=>E.encoded!==b),enriched:Object.fromEntries(Object.entries(gh.enriched).filter(([E])=>E!==b))}),T}catch(T){return{ok:!1,error:T instanceof Error?T.message:"Archive failed"}}};return{rows:n,enriched:r,projects:a,loading:l,resolving:p,openProject:d,openInSession:f,archiveProject:g,archiveProjectByCwd:async b=>{let T={ok:!0};for(const E of b.encodedIds)if(T=await g(E),!T.ok)return T;return T}}}function LI(i,e,t){var r,l;const n=new Map;for(const p of Object.keys(e)){if(!((r=e[p])!=null&&r.running))continue;const a=(l=t[p])==null?void 0:l.cwd;if(!a)continue;const d=al(a);n.set(d,(n.get(d)??0)+1)}return i.map(p=>({encoded:p.encoded,name:p.name,cwd:p.cwd,dotSeed:p.cwd,liveCount:n.get(p.cwd)??0,lastActivityMs:p.lastSession}))}function b_(i){return{owner:i.owner,kind:"session",at:i.at,project:null,epicTitle:null,openTarget:null,epicId:null}}function $I(i,e,t,n){return i.map(r=>{const l=r.owner;if(l.startsWith("scheduler:")){const p=l.slice(10),a=e.find(g=>g.slug===p);if(!a)return b_(r);const d=a.sourcePromptId??null,f=d?n[d]:void 0;return{owner:l,kind:"scheduler job",at:r.at,project:a.cwd?Lo(a.cwd):null,epicTitle:(f==null?void 0:f.goalText)??null,openTarget:"scheduler",epicId:null}}if(l.startsWith("chat:")){const p=l.slice(5),a=t[p],d=n[p];return!(a!=null&&a.running)||!d?b_(r):{owner:l,kind:"chat run",at:r.at,project:Lo(d.cwd),epicTitle:d.goalText,openTarget:"terminal",epicId:p}}return b_(r)})}function Xx(i,e){for(const t of Object.keys(e))if(e[t].claudeSessionId===i)return e[t].goalText;return null}const NI=1440*60*1e3;function MI(i){const e=(i.statusHistory??[]).find(n=>n.to==="quarantined");if(!e)return null;const t=Date.parse(e.at);return Number.isNaN(t)?null:t}function jI(i,e,t,n=Date.now()){var l;const r=[];for(const p of Object.keys(i)){const a=i[p];r.push({id:`proposed:${p}`,kind:"proposed-epic",label:"Proposed Epic — awaiting approval",detail:a.goalText,meta:a.tag?`tag: ${a.tag}`:"Filed for you to decide on. Nothing has run.",project:Lo(a.cwd),epicId:p,jobSlug:null})}for(const p of Object.keys(e)){const a=((l=e[p])==null?void 0:l.ticketHistory)??[],d=a[a.length-1];!d||d.status!=="needs-input"||r.push({id:`needs-input:${d.id}`,kind:"needs-input",label:"Session is asking a question",detail:d.text,meta:"Stopped mid-run, waiting on your reply.",project:Lo(d.cwd),epicId:p,jobSlug:null})}for(const p of t){if(p.status==="quarantined"){const a=MI(p),d=a!=null?n-a:null,f=d!=null&&d>=NI;r.push({id:`job:${p.slug}`,kind:"job-quarantined",label:f?"Quarantined PRD — stale, needs adoption":"Scheduler PRD quarantined",detail:p.title||p.slug,meta:d!=null?`No createdVia provenance for ${Math.round(d/(3600*1e3))}h — adopt it to run, or archive from the Scheduler tab.`:"No createdVia provenance. Adopt it to run, or archive from the Scheduler tab.",project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug,escalated:f});continue}if(p.status==="running"&&p.overrun){const{ratio:a,ranMs:d,estimateMinutes:f}=p.overrun;r.push({id:`job:${p.slug}`,kind:"job-overrunning",label:"Scheduler job running over its own estimate",detail:p.title||p.slug,meta:`Ran ${Math.round(d/6e4)}m vs ${f}m estimate (${a.toFixed(1)}x). Check the run log, then let it finish or cancel it via scheduler_cancel_job.`,project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug});continue}p.status!=="failed"&&p.status!=="needs_review"||r.push({id:`job:${p.slug}`,kind:"job-failed",label:p.status==="failed"?"Scheduler job failed":"Scheduler job needs review",detail:p.title||p.slug,meta:p.error??"No error detail recorded.",project:p.cwd?Lo(p.cwd):null,epicId:null,jobSlug:p.slug})}return r}let Iy=null;function jv(i){Iy=i,window.dispatchEvent(new CustomEvent("sm:select-prompt-session",{detail:i}))}function zI(){const i=Iy;return Iy=null,i}const Yx=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function BI(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)>>>0;return e}function CC(i){return Yx[BI(i)%Yx.length]}function EC(i,e,t,n){const r=e.find(l=>l.cwd===i);r?n(r.id):t({cwd:i,startupCommand:null,dormant:!0})}function kC(i){return i>=90?{dot:"bg-accent",bar:"bg-accent",track:"bg-accent/15",text:"text-accent"}:i>=70?{dot:"bg-honey",bar:"bg-honey",track:"bg-honey/15",text:"text-honey-dark"}:{dot:"bg-sage",bar:"bg-sage",track:"bg-sage/15",text:"text-sage"}}function UI(i){return i?i.split("_").map(e=>/^\d/.test(e)?e:e.charAt(0).toUpperCase()+e.slice(1)).join(" "):null}function _f({label:i,sub:e,window:t,big:n=!1}){if(!t)return null;const r=t.utilization,l=Math.max(0,Math.min(100,r)),p=r>100,a=z1(t.resets_at),d=kC(r);return c.jsxs("div",{className:n?"py-[18px]":"py-[15px]",children:[c.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-2.5",children:[c.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[c.jsx("span",{className:`w-[9px] h-[9px] rounded-full shrink-0 ${d.dot}`}),c.jsx("span",{className:`font-semibold text-fg ${n?"text-base":"text-[15px]"}`,children:i}),e&&c.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint bg-bg border border-line px-2 py-px rounded-full whitespace-nowrap",children:e})]}),c.jsxs("span",{className:`font-mono font-semibold leading-none tracking-tight shrink-0 ${n?"text-2xl":"text-xl"} ${p?"text-accent":d.text}`,children:[Math.round(r),"%"]})]}),c.jsx("div",{className:`rounded-full overflow-hidden ${n?"h-3":"h-2.5"} ${d.track}`,children:c.jsx("div",{className:`h-full rounded-full transition-[width] duration-500 ${d.bar}`,style:{width:`${l}%`}})}),a&&c.jsxs("div",{className:"flex items-center justify-between mt-2.5 gap-3",children:[c.jsxs("span",{className:"text-[12.5px] text-fg-dim",children:["resets in"," ",c.jsx("strong",{className:"text-fg font-semibold",children:a.rel}),a.abs&&c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-fg-faint",children:" · "}),c.jsx("span",{className:"font-mono text-xs text-fg-faint",children:a.abs})]})]}),p&&c.jsx("span",{className:"text-[11.5px] font-semibold text-accent",children:"over limit"})]})]})}function GI({extra:i}){const e=i.utilization??0,t=e>100,n=kC(e);return c.jsxs("div",{className:"border-t border-line pt-[15px] pb-[15px]",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-2.5",children:[c.jsxs("div",{className:"flex items-center gap-2.5",children:[c.jsx("span",{className:`w-[9px] h-[9px] rounded-full shrink-0 ${n.dot}`}),c.jsx("span",{className:"text-[15px] font-semibold text-fg",children:"Extra usage"}),c.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint bg-bg border border-line px-2 py-px rounded-full whitespace-nowrap",children:"pay-as-you-go"})]}),c.jsxs("span",{className:`font-mono text-base font-semibold tabular-nums ${t?"text-accent":"text-fg"}`,children:[(i.used_credits??0).toFixed(2)," ",c.jsxs("span",{className:"text-fg-faint font-normal",children:["/ ",(i.monthly_limit??0).toFixed(2)," ",i.currency??""]})]})]}),c.jsx("div",{className:`h-2.5 rounded-full overflow-hidden ${n.track}`,children:c.jsx("div",{className:`h-full rounded-full transition-[width] duration-500 ${n.bar}`,style:{width:`${Math.min(e,100)}%`}})}),c.jsxs("div",{className:"flex items-center justify-between mt-2.5 gap-3",children:[c.jsxs("span",{className:"text-[12.5px] text-fg-dim",children:["monthly credit limit · resets"," ",c.jsx("span",{className:"font-mono text-xs text-fg-faint",children:"1st of month"})]}),t&&c.jsx("span",{className:"text-[11.5px] font-semibold text-accent",children:"over limit"})]})]})}function HI({data:i,updatedAt:e}){const t=i.usage,n=UI(i.subscriptionType),r=t.extra_usage,l=e!=null?`${Math.max(0,Math.round((Date.now()-e)/1e3))}s ago`:null;return c.jsxs("section",{className:"bg-bg-hi border border-line rounded-2xl px-6 py-1.5",children:[(n||i.rateLimitTier||l)&&c.jsxs("div",{className:"flex items-baseline justify-between pt-3 pb-1 mb-1",children:[c.jsxs("div",{className:"flex items-baseline gap-2",children:[n&&c.jsx("span",{className:"text-xs text-fg-dim font-mono",children:n}),i.rateLimitTier&&c.jsx("span",{className:"text-[10px] text-fg-faint font-mono",children:i.rateLimitTier})]}),l&&c.jsxs("span",{className:"text-[10px] text-fg-faint",children:["updated ",l]})]}),c.jsxs("div",{className:"divide-y divide-line",children:[c.jsx(_f,{label:"Session",sub:"5-hour",window:t.five_hour,big:!0}),c.jsx(_f,{label:"Weekly",sub:"all models",window:t.seven_day}),c.jsx(_f,{label:"Weekly",sub:"Opus",window:t.seven_day_opus}),c.jsx(_f,{label:"Weekly",sub:"Sonnet",window:t.seven_day_sonnet}),c.jsx(_f,{label:"Weekly",sub:"OAuth apps",window:t.seven_day_oauth_apps})]}),(r==null?void 0:r.is_enabled)&&c.jsx(GI,{extra:r})]})}function Ib({open:i,onClose:e,title:t,sub:n,keyVals:r,tail:l,footer:p,children:a}){const[d,f]=B.useState(!1);if(B.useEffect(()=>{if(!i){f(!1);return}const b=requestAnimationFrame(()=>f(!0));return()=>cancelAnimationFrame(b)},[i]),B.useEffect(()=>{if(!i)return;const b=T=>{T.key==="Escape"&&(T.stopPropagation(),e())};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[i,e]),!i)return null;const g=b=>{b.target===b.currentTarget&&e()},m=c.jsxs("div",{className:`fixed inset-0 ${Cn.dialog}`,"data-testid":"home-drawer-root",children:[c.jsx("div",{className:`absolute inset-0 bg-black/50 transition-opacity duration-[220ms] ${d?"opacity-100":"opacity-0"}`,onClick:g,"data-testid":"home-drawer-backdrop"}),c.jsxs("aside",{role:"dialog","aria-modal":"true","aria-label":t,className:`absolute top-0 right-0 h-full w-full max-w-[420px] bg-bg-hi border-l border-line shadow-xl flex flex-col transition-transform duration-[220ms] ${d?"translate-x-0":"translate-x-full"}`,style:{transitionTimingFunction:"cubic-bezier(.32,.72,.28,1)"},"data-testid":"home-drawer",children:[c.jsxs("header",{className:"px-5 py-4 border-b border-line flex items-start justify-between gap-3 shrink-0",children:[c.jsxs("div",{className:"min-w-0",children:[c.jsx("h2",{className:"m-0 font-serif text-[18px] font-semibold text-fg truncate",children:t}),n&&c.jsx("div",{className:"text-[12px] text-fg-faint truncate mt-0.5",children:n})]}),c.jsx("button",{onClick:e,className:"shrink-0 rounded-md border border-line bg-bg px-2.5 py-1 text-[12px] font-semibold text-fg-dim hover:bg-bg-elev","aria-label":"Close",children:"Close"})]}),c.jsxs("div",{className:"flex-1 min-h-0 overflow-auto px-5 py-4 grid gap-4 content-start",children:[a,r.length>0&&c.jsx("dl",{className:"m-0 grid gap-2",style:{gridTemplateColumns:"minmax(0,100px) minmax(0,1fr)"},children:r.map(b=>c.jsxs("div",{className:"contents",children:[c.jsx("dt",{className:"m-0 font-mono text-[11px] uppercase tracking-[0.05em] text-fg-faint",children:b.label}),c.jsx("dd",{className:"m-0 text-[12.5px] text-fg break-words",children:b.value})]},b.label))}),l&&l.length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2",children:"Live tail"}),c.jsx("div",{className:"grid gap-2",children:l.map(b=>c.jsxs("div",{className:"bg-bg border border-line rounded-lg px-3 py-2",children:[c.jsx("div",{className:"font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint mb-1",children:b.role}),c.jsx("div",{className:"text-[12px] text-fg-dim leading-[1.5] whitespace-pre-wrap break-words line-clamp-6",children:b.text})]},b.id))})]})]}),p&&c.jsx("footer",{className:"px-5 py-3.5 border-t border-line flex gap-2 justify-end shrink-0",children:p})]})]});return typeof document<"u"&&document.body?dm.createPortal(m,document.body):m}function FI({open:i,onClose:e,projects:t,onConfirm:n}){const[r,l]=B.useState(null);B.useEffect(()=>{var a;i&&l(((a=t[0])==null?void 0:a.cwd)??null)},[i,t]);const p=t.find(a=>a.cwd===r)??null;return c.jsx(Ib,{open:i,onClose:e,title:"New session",sub:"Pick a project to start it in",keyVals:[],footer:c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:e,className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg border border-line bg-bg text-fg-dim hover:bg-bg-elev",children:"Cancel"}),c.jsx("button",{onClick:()=>{r&&(n(r),e())},disabled:!r,className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg bg-accent text-bg-hi hover:bg-accent-dark disabled:opacity-50",children:p?`Continue in ${p.name} → Epics`:"Continue"})]}),children:t.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-2",children:"No known projects yet."}):c.jsx("div",{role:"radiogroup","aria-label":"Project",className:"grid gap-1.5",children:t.map(a=>c.jsxs("label",{className:`flex items-center gap-2.5 px-3 py-2 rounded-lg border cursor-pointer ${r===a.cwd?"border-accent bg-accent/10":"border-line bg-bg hover:bg-bg-elev/60"}`,children:[c.jsx("input",{type:"radio",name:"new-epic-project",value:a.cwd,checked:r===a.cwd,onChange:()=>l(a.cwd),className:"accent-accent"}),c.jsx("span",{className:"min-w-0 flex-1 text-[13px] text-fg truncate",title:a.cwd,children:a.name})]},a.encoded))})})}function WI({job:i,onClose:e,onOpenScheduler:t,onRunNow:n}){const r=B.useRef(null);return B.useEffect(()=>{const l=a=>{r.current&&!r.current.contains(a.target)&&e()},p=a=>{a.key==="Escape"&&e()};return document.addEventListener("mousedown",l),document.addEventListener("keydown",p),()=>{document.removeEventListener("mousedown",l),document.removeEventListener("keydown",p)}},[e]),c.jsxs("div",{ref:r,"data-testid":"queue-job-popover",className:"absolute z-20 top-full left-0 mt-1.5 w-[226px] bg-bg-hi border border-line rounded-[11px] shadow-xl px-3.5 py-3",children:[c.jsx("div",{className:"font-mono text-[12px] font-semibold text-fg truncate mb-1.5",children:i.title||i.slug}),c.jsxs("dl",{className:"m-0 grid gap-1 mb-3",style:{gridTemplateColumns:"minmax(0,60px) minmax(0,1fr)"},children:[c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Slug"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim truncate",children:i.slug}),c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Project"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim truncate",children:i.cwd?VI(i.cwd):"—"}),i.estimateMinutes!=null&&c.jsxs(c.Fragment,{children:[c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Est."}),c.jsxs("dd",{className:"m-0 font-mono text-[11px] text-fg-dim",children:["~",i.estimateMinutes,"m"]})]}),c.jsx("dt",{className:"m-0 font-mono text-[10px] uppercase tracking-[0.05em] text-fg-faint",children:"Status"}),c.jsx("dd",{className:"m-0 font-mono text-[11px] text-fg-dim",children:i.status})]}),c.jsxs("div",{className:"flex flex-col gap-1.5",children:[c.jsx("button",{onClick:t,className:"text-[11.5px] font-semibold px-2.5 py-[5px] rounded-md border border-line bg-bg text-fg-dim hover:bg-bg-elev text-left",children:"Open in Scheduler →"}),n&&c.jsx("button",{onClick:n,title:"Wakes the scheduler to check for due jobs immediately — does not force this specific job to run out of turn or bypass the concurrency cap.",className:"text-[11.5px] font-semibold px-2.5 py-[5px] rounded-md bg-accent text-bg-hi hover:bg-accent-dark text-left",children:"Nudge scheduler now"})]})]})}function VI(i){const e=i.split("/").filter(Boolean);return e.length>0?e[e.length-1]:i}const TC="sm.terminal.settings",Py="sm:terminal:settings",Ry=10,Oy=22,DC=13,$g={theme:"dark",fontSize:DC};function zv(){try{const i=localStorage.getItem(TC);if(!i)return $g;const e=JSON.parse(i);return{theme:e.theme==="light"||e.theme==="paper"||e.theme==="dark"?e.theme:$g.theme,fontSize:typeof e.fontSize=="number"&&e.fontSize>=Ry&&e.fontSize<=Oy?e.fontSize:$g.fontSize}}catch{return $g}}function qI(i){try{localStorage.setItem(TC,JSON.stringify(i))}catch{}window.dispatchEvent(new CustomEvent(Py,{detail:i}))}function Pb(i){const e=t=>{i(t.detail)};return window.addEventListener(Py,e),()=>window.removeEventListener(Py,e)}const va={dark:{background:"#0b0d10",foreground:"#e6e8ec",cursor:"#d97757",selectionBackground:"#3a4250",black:"#1a1f27",red:"#e06c75",green:"#98c379",yellow:"#e5c07b",blue:"#61afef",magenta:"#c678dd",cyan:"#56b6c2",white:"#e6e8ec",brightBlack:"#545c68",brightRed:"#e06c75",brightGreen:"#98c379",brightYellow:"#e5c07b",brightBlue:"#61afef",brightMagenta:"#c678dd",brightCyan:"#56b6c2",brightWhite:"#ffffff"},light:{background:"#ffffff",foreground:"#1f2328",cursor:"#0969da",selectionBackground:"#cce5ff",black:"#24292f",red:"#cf222e",green:"#116329",yellow:"#a45a16",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#6e7781",brightBlack:"#57606a",brightRed:"#a40e26",brightGreen:"#1a7f37",brightYellow:"#9a6700",brightBlue:"#218bff",brightMagenta:"#a475f9",brightCyan:"#3192aa",brightWhite:"#1f2328"},paper:{background:"#f6efe1",foreground:"#2a221a",cursor:"#a7532f",selectionBackground:"#e0d3b8",black:"#2a221a",red:"#b8443c",green:"#5c6f3a",yellow:"#8e641a",blue:"#3a6ea5",magenta:"#8a4a8c",cyan:"#38767e",white:"#5b4a36",brightBlack:"#796b54",brightRed:"#b8493f",brightGreen:"#65714a",brightYellow:"#8c641e",brightBlue:"#416ea1",brightMagenta:"#925494",brightCyan:"#3e757d",brightWhite:"#2a221a"}},KI=["dark","light","paper"];function XI(){const[i,e]=B.useState(()=>zv()),t=r=>{e(l=>{const p={...l,...r};return qI(p),p})},n=r=>{t({fontSize:Math.min(Oy,Math.max(Ry,i.fontSize+r))})};return c.jsxs("section",{className:"mb-6","data-testid":"home-terminal-appearance",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Terminal appearance"}),c.jsx("span",{className:"font-mono text-[12px] text-fg-faint",children:"every terminal, this machine"})]}),c.jsxs("div",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[c.jsxs("p",{className:"mt-0 mb-4 text-[13px] text-fg-dim leading-relaxed",children:["Applies to ",c.jsx("strong",{className:"text-fg",children:"every terminal in the app at once"})," — project Terminal tabs, an Epic’s Terminal view of its session, and the inline permission prompt. It is not per project, per session, or per tab. It does not restyle the app chrome (there is no app theme switch), and the code editor keeps its own separate paper/dark setting in the Editor tab’s Display menu. Stored in this machine’s browser storage as ",c.jsx("code",{className:"font-mono text-[12px]",children:"sm.terminal.settings"}),", applied live without restarting a session."]}),c.jsxs("div",{className:"grid gap-5",style:{gridTemplateColumns:"minmax(0,1fr) 220px"},children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-1.5",children:"Theme"}),c.jsx("div",{className:"grid grid-cols-3 gap-2",children:KI.map(r=>c.jsxs("button",{type:"button",onClick:()=>t({theme:r}),"aria-pressed":i.theme===r,"data-testid":`terminal-theme-${r}`,className:`px-2 py-2 rounded-lg text-[11px] font-medium border transition-colors ${i.theme===r?"bg-bg border-accent text-fg":"bg-bg border-line text-fg-dim hover:text-fg hover:border-fg-faint"}`,children:[c.jsx(YI,{theme:r}),c.jsx("div",{className:"mt-1.5 capitalize",children:r})]},r))})]}),c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[c.jsx("span",{className:"text-[10px] uppercase tracking-wider text-fg-faint",children:"Font size"}),c.jsxs("span",{className:"font-mono text-[11px] text-fg-dim",children:[i.fontSize,"px"]})]}),c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("button",{type:"button",onClick:()=>n(-1),disabled:i.fontSize<=Ry,"aria-label":"Decrease font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"−"}),c.jsx("button",{type:"button",onClick:()=>t({fontSize:DC}),className:"flex-1 py-1.5 rounded border border-line bg-bg text-[11px] text-fg-dim hover:text-fg hover:border-fg-faint",children:"reset"}),c.jsx("button",{type:"button",onClick:()=>n(1),disabled:i.fontSize>=Oy,"aria-label":"Increase font size",className:"flex-1 py-1.5 rounded border border-line bg-bg text-fg-dim hover:text-fg hover:border-fg-faint disabled:opacity-40 disabled:cursor-not-allowed",children:"+"})]}),c.jsxs("div",{className:"mt-3 rounded border border-line px-3 py-2 font-mono",style:{background:va[i.theme].background,color:va[i.theme].foreground,fontSize:`${i.fontSize}px`,lineHeight:1.35},"aria-hidden":!0,children:[c.jsx("span",{style:{color:va[i.theme].green},children:"$"})," claude"]})]})]})]})]})}function YI({theme:i}){const e=va[i];return c.jsxs("div",{"aria-hidden":!0,className:"w-full h-5 rounded border relative overflow-hidden",style:{background:e.background,borderColor:"rgba(0,0,0,0.15)"},children:[c.jsx("div",{style:{position:"absolute",top:3,left:4,width:"40%",height:2,background:e.foreground}}),c.jsx("div",{style:{position:"absolute",top:9,left:4,width:"25%",height:2,background:e.green??e.foreground}}),c.jsx("div",{style:{position:"absolute",top:15,left:4,width:"55%",height:2,background:e.cyan??e.foreground}})]})}const Jx="The MCP tool catalog is unavailable.";function JI(){const[i,e]=B.useState({tools:[],loaded:!1,error:null});return B.useEffect(()=>{let t=!1;return Promise.resolve().then(()=>window.api.mcp.catalog()).then(n=>{var r;t||(!(n!=null&&n.ok)||!((r=n.tools)!=null&&r.length)?e({tools:[],loaded:!0,error:Jx}):e({tools:n.tools,loaded:!0,error:null}))}).catch(()=>{t||e({tools:[],loaded:!0,error:Jx})}),()=>{t=!0}},[]),i}const ZI=["scheduler","chat","feedback","help"],QI={scheduler:"Scheduler",chat:"Chat",feedback:"Feedback",help:"Help"};function eP(){const{tools:i,loaded:e,error:t}=JI(),[n,r]=B.useState(!1);if(!e)return null;if(t||i.length===0)return c.jsxs("section",{className:"mb-6","data-testid":"home-agent-tools",children:[c.jsx("h2",{className:"m-0 mb-2 font-serif text-[22px] font-medium",children:"Agent tools"}),c.jsx("p",{className:"m-0 text-xs text-fg-faint","data-testid":"home-agent-tools-error",children:"The MCP tool catalog is unavailable."})]});const l=ZI.map(p=>({group:p,tools:i.filter(a=>a.group===p)})).filter(p=>p.tools.length>0);return c.jsxs("section",{className:"mb-6","data-testid":"home-agent-tools",children:[c.jsxs("button",{type:"button",onClick:()=>r(p=>!p),"aria-expanded":n,"data-testid":"home-agent-tools-toggle",className:"flex w-full items-baseline gap-2 text-left",children:[c.jsx("span",{className:"font-serif text-[22px] font-medium",children:"Agent tools"}),c.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:["· ",i.length," MCP tools ",n?"▾":"▸"]})]}),n&&c.jsx("div",{className:"mt-3 grid gap-3 border border-line rounded-xl bg-bg-hi px-5 py-4",children:l.map(({group:p,tools:a})=>c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"mb-1 font-mono text-[10px] font-semibold uppercase tracking-wide text-fg-faint",children:QI[p]}),a.map(d=>c.jsxs("div",{"data-testid":`home-agent-tool-${d.name}`,className:"flex items-baseline gap-3 min-w-0 py-0.5",children:[c.jsx("span",{className:"shrink-0 font-mono text-[12px] font-semibold text-fg",children:d.name}),c.jsx("span",{"data-testid":"home-agent-tool-purpose",title:d.purpose,className:"min-w-0 line-clamp-1 text-xs text-fg-dim",children:d.purpose})]},d.name))]},p))})]})}function tP(i){const e=Date.now()-i;if(e<6e4)return"just now";const t=Math.floor(e/6e4);return t<60?`${t}m ago`:`${Math.floor(t/60)}h ${t%60}m ago`}function iP({since:i,error:e,onRetry:t}){return c.jsxs("div",{className:"flex items-center justify-between mb-3 border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:[c.jsxs("span",{children:["stale · last updated ",tP(i)]}),c.jsx("button",{onClick:t,className:"ml-3 underline hover:no-underline",children:"Retry"})]})}function nP({message:i,expiredAt:e,onRetry:t}){const n=e!=null&&e<Date.now(),r=e?new Date(e).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short"}):null,l=!n&&/^HTTP \d+/.test(i);return c.jsxs("div",{className:"mb-3 border border-red-800/40 rounded px-3 py-2 bg-red-950/20 text-xs text-red-300",children:[c.jsxs("div",{className:"font-medium mb-1",children:[n?`Credentials expired at ${r}`:"Authentication failed",l&&c.jsxs("span",{className:"font-normal ml-1 text-red-400/70",children:["(",i,")"]})]}),c.jsxs("div",{className:"text-red-400/80",children:["Run ",c.jsx("code",{className:"font-mono bg-red-950/40 px-1 rounded",children:"claude"})," in a terminal to refresh, then"," ",c.jsx("button",{onClick:t,className:"underline hover:no-underline",children:"Retry"}),"."]})]})}function sP(){return c.jsx("div",{className:"border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:"temporary network error — retrying in 5s"})}function rP({onRetry:i}){return c.jsxs("div",{className:"flex items-center justify-between border border-yellow-800/40 rounded px-3 py-1.5 bg-yellow-950/20 text-xs text-yellow-300",children:[c.jsx("span",{children:"usage meter is rate-limited — showing last known values"}),c.jsx("button",{onClick:i,className:"ml-3 underline hover:no-underline",children:"Retry"})]})}function oP({message:i}){const e=i.includes("not found")||i.includes("ENOENT");return c.jsxs("div",{className:"border border-line rounded px-3 py-2 bg-bg-elev text-xs text-fg-dim",children:[c.jsx("div",{className:"font-medium mb-1 text-fg",children:e?"Not signed in":"Cannot read credentials"}),c.jsx("div",{className:"text-fg-faint",children:e?c.jsxs(c.Fragment,{children:["Run ",c.jsx("code",{className:"font-mono bg-bg px-1 rounded",children:"claude login"})," in a terminal tab to sign in."]}):c.jsxs(c.Fragment,{children:["Cannot read ",c.jsx("code",{className:"font-mono bg-bg px-1 rounded",children:"~/.claude/.credentials.json"})," — ",i]})})]})}function aP({result:i,onRetry:e}){switch(i.kind){case"ok":return null;case"ok-stale":return c.jsx(iP,{since:i.staleSince,error:i.lastError,onRetry:e});case"auth":return c.jsx(nP,{message:i.message,expiredAt:i.expiredAt,onRetry:e});case"transient":return c.jsx(sP,{});case"meter_rate_limited":return c.jsx(rP,{onRetry:e});case"config":return c.jsx(oP,{message:i.message})}}const AC={feature:{description:"Plans new functionality from the stated objective, then delegates the build to /develop.",initialPromptTemplate:"You are planning new functionality. Treat the goal below as the full objective — establish scope, then decompose and queue the work as scheduled PRDs via the /develop skill, rather than editing files inline in this conversation: this interactive session is a planner-tier model and the headless claude -p executor does the typing."},bug:{description:"Diagnoses a reported failure before queuing a fix via /develop — reproduction first.",initialPromptTemplate:"You are diagnosing a reported bug. If a reference (log, stack trace, repro steps) is attached, read it and reproduce the failure before writing a fix — do not guess at root cause from the description alone. If nothing is attached, reproduce it yourself first. Once root cause is established, queue the fix as a scheduled PRD via the /develop skill rather than typing it inline: this interactive session is a planner-tier model and the headless claude -p executor does the typing."},discussion:{description:"Open-ended research/decision conversation — no code changes expected.",initialPromptTemplate:"You are in an open-ended discussion. The goal is a decision or shared understanding, not a code change — do not start editing files unless the human explicitly asks you to after the discussion lands somewhere."},build:{description:"Prepares and publishes a release build to this project's configured registry.",initialPromptTemplate:"You are preparing a release build. Treat the goal below as the full objective — verify the project's build target configuration before publishing."},"project-home-builder":{description:"Reads this project and writes one self-contained overview page (home.html) for Project Home.",initialPromptTemplate:"You are generating this project's Project Home page. Read the real project first — its manifest, README/docs, directory structure, key scripts, and recent git history. Then write ONE self-contained HTML overview page (inline CSS only, no external scripts, fonts, or images) covering what the project is, who it is for, its structure, how to run it, and its key commands. Never fabricate a claim — an omitted section beats an invented one. Save it by calling the `project_home_write` MCP tool exactly once with the full HTML. If `project_home_write` is unavailable or errors, report that plainly and STOP — never build infrastructure in this project as a workaround."},"bilko-host-publisher":{description:"Publishes this project's Project Home page (home.html) to bilko.run as a static-path listing via the bilko-host MCP's gated publish pipeline.",initialPromptTemplate:"You are publishing this project to bilko.run. Read `session-manager-operations/architecture/bilko-host-integration.md` first — it is the source of truth for the pipeline, the bundle path, and the non-negotiables (ship the Project Home page verbatim; never bypass a failing gate on your own initiative). Call `bilko-host__get_host_contract` and read `~/Projects/Bilko/mcp-host-server/src/gates/*.ts` live before publishing — never assume a cached understanding of the gates, they can change independently of this app's release cycle. Then follow `.claude/agents/bilko-host-publisher.md` as your operating protocol."}},lP=["feature","bug","discussion","project-home-builder"];function IC(i){return AC[i]}function yf(i){return{path:i,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function w_(i,e,t){const n={...i,diskRaw:e.raw,diskData:e.data,exists:e.exists,parseError:e.parseError,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.raw,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}function x_(i,e,t){const n={...i,diskRaw:e.text,diskData:null,exists:e.exists,parseError:null,loadError:e.error,mtimeMs:e.mtimeMs,busy:!1};return!t||!i.dirty?(n.draftRaw=e.text,n.dirty=!1):n.dirty=n.draftRaw!==n.diskRaw,n}const Of=Un((i,e)=>({files:{},watchRefs:{},loadJson:async t=>{const n=e().files[t];i({files:{...e().files,[t]:{...n??yf(t),busy:!0}}});const r=await window.api.config.readJson(t),l=e().files[t]??yf(t);i({files:{...e().files,[t]:w_(l,r,!1)}})},loadText:async(t,n=!1)=>{const r=e().files[t];i({files:{...e().files,[t]:{...r??yf(t),busy:!0}}});const l=await window.api.config.readText(t),p=e().files[t]??yf(t);i({files:{...e().files,[t]:x_(p,l,n)}})},setDraft:(t,n)=>{const r=e().files[t]??yf(t),l=n!==r.diskRaw;i({files:{...e().files,[t]:{...r,draftRaw:n,dirty:l}}})},revert:t=>{const n=e().files[t];n&&i({files:{...e().files,[t]:{...n,draftRaw:n.diskRaw,dirty:!1}}})},saveJson:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};let r;try{r=n.draftRaw.trim()===""?{}:JSON.parse(n.draftRaw)}catch(d){return{ok:!1,error:`invalid JSON: ${d.message}`}}i({files:{...e().files,[t]:{...n,busy:!0}}});const l=await window.api.config.writeJson(t,r);if(!l.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:l.error};const p=await window.api.config.readJson(t),a=w_({...n,busy:!1},p,!1);return i({files:{...e().files,[t]:{...a,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async t=>{const n=e().files[t];if(!n)return{ok:!1,error:"not loaded"};i({files:{...e().files,[t]:{...n,busy:!0}}});const r=await window.api.config.writeText(t,n.draftRaw);if(!r.ok)return i({files:{...e().files,[t]:{...n,busy:!1}}}),{ok:!1,error:r.error};const l=await window.api.config.readText(t),p=x_({...n,busy:!1},l,!1);return i({files:{...e().files,[t]:{...p,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:t=>{const n={...e().watchRefs};n[t]=(n[t]??0)+1,i({watchRefs:n}),n[t]===1&&window.api.config.watch([t])},unwatchFile:t=>{const n={...e().watchRefs};n[t]&&(n[t]--,n[t]<=0&&(delete n[t],window.api.config.unwatch([t])),i({watchRefs:n}))},onExternalChange:t=>{e().files[t]&&(t.endsWith(".json")?window.api.config.readJson(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:w_(l,r,!0)}})}):window.api.config.readText(t).then(r=>{const l=e().files[t];l&&i({files:{...e().files,[t]:x_(l,r,!0)}})}))}}));function cP(){return window.api.config.onChanged(({path:i})=>{Of.getState().onExternalChange(i)})}function _h(...i){return i.filter(Boolean).map((e,t)=>t===0?e.replace(/\/+$/,""):e.replace(/^\/+|\/+$/g,"")).join("/")}const im={scopes:["user","project","local"],resolve:(i,e,t)=>i==="user"?_h(e,".claude","settings.json"):t?i==="project"?_h(t,".claude","settings.json"):_h(t,".claude","settings.local.json"):null},S_={scopes:["user","project","local"],resolve:(i,e,t)=>i==="user"?_h(e,".claude","CLAUDE.md"):t?i==="project"?_h(t,"CLAUDE.md"):_h(t,"CLAUDE.local.md"):null},qB=im,KB={user:{label:"User",hint:"~/.claude/ — applies to all projects"},project:{label:"Project",hint:"<cwd>/.claude/ — checked into git"},local:{label:"Local",hint:"<cwd>/.claude/…local — gitignored, per-machine"}},dP=[];function Ng(i){return Array.isArray(i)?"array":i!==null&&typeof i=="object"?"object":"scalar"}function uP(i){const e=i.filter(t=>t.data!==void 0);return e.length===0?{kind:"object",children:{}}:PC(e,[])}function PC(i,e){const t=dP.includes(e.join(".")),n=i.every(g=>Ng(g.data)==="object"),r=i.every(g=>Ng(g.data)==="array");if(n){const g=new Set;for(const b of i)for(const T of Object.keys(b.data))g.add(T);const m={};for(const b of g){const T=i.filter(E=>b in E.data).map(E=>({scope:E.scope,data:E.data[b]}));m[b]=PC(T,[...e,b])}return{kind:"object",children:m}}if(r&&!t){const g=[];for(const m of[...i].reverse())for(const b of m.data)g.push({value:b,fromScope:m.scope,index:g.length});return{kind:"array",items:g}}const l=[...i].reverse(),p=l[0],a=l.slice(1).map(g=>({scope:g.scope,value:g.data})),d=Ng(p.data),f=a.some(g=>Ng(g.value)!==d);return{kind:"leaf",value:p.data,winner:p.scope,shadowed:a,...f?{typeMismatch:!0}:{}}}function RC(i,e){if(e.length===0)return i;if(i.kind!=="object")return null;const[t,...n]=e,r=i.children[t];return r?RC(r,n):null}function hP(i,e,t){if(e.length===0)return t;const[n,...r]=e,l=i&&typeof i=="object"&&!Array.isArray(i)?{...i}:{};return l[n]=hP(l[n],r,t),l}const pP=["user","project","local"];function fP(i,e){const t=[];for(const n of pP){const r=e[n];if(!r)continue;const l=i[r];if(!l||!l.exists)continue;const p=l.draftRaw??"";if(p.trim())try{t.push({scope:n,data:JSON.parse(p)})}catch{}}return t}const mP=3e4;function OC(i){const e=Ab(),t=B.useMemo(()=>{if(!e)return{};const a={};for(const d of im.scopes){const f=im.resolve(d,e,i);f&&(a[d]=f)}return a},[e,i]),n=Of(a=>a.files),r=Of(a=>a.loadJson),l=Of(a=>a.watchFile),p=Of(a=>a.unwatchFile);return B.useEffect(()=>{const a=Object.values(t).filter(Boolean);a.forEach(f=>{n[f]||r(f),l(f)});const d=window.setInterval(()=>{a.forEach(f=>r(f))},mP);return()=>{clearInterval(d),a.forEach(f=>p(f))}},[JSON.stringify(t)]),B.useMemo(()=>uP(fP(n,t)),[n,t])}function LC(i,e){const t=RC(i,e);return!t||t.kind!=="leaf"?{value:null,source:null}:{value:typeof t.value=="string"?t.value:null,source:t.winner}}function $C(i,e){return!i||!e?"effort — (model default)":e==="epic"?`effort ${i} (this session)`:e==="persona"?`effort ${i} (persona)`:e==="persona-overlay"?`effort ${i} (project persona)`:`effort ${i} (${e} settings.json)`}function gP(i){return i==="epic"?"Effort was chosen for this session only and is passed to the CLI as --effort, overriding the agent persona and settings.json.":i==="persona"||i==="persona-overlay"?"Effort comes from the agent persona and is passed to the CLI as --effort, overriding settings.json.":i?"The persona sets no effort, so the settings.json effortLevel applies.":"No effort is set by the persona or settings.json, so the model default applies."}function vP(i,e,t={}){const n=t.model&&t.model!=="inherit"?t.model:null,r=t.effort&&t.effort!=="inherit"&&t.effort!=="auto"?t.effort:null;if(r)return{...i,epicModel:n,effortLevel:r,effortSource:"epic"};if(i.personaEffort&&(i.personaEffortSource==="persona"||i.personaEffortSource==="persona-overlay"))return{...i,epicModel:n,effortLevel:i.personaEffort,effortSource:i.personaEffortSource};const{value:l,source:p}=LC(e,["effortLevel"]);return{...i,epicModel:n,effortLevel:l,effortSource:p}}function NC(i,e,t){const n=OC(i),[r,l]=B.useState(null);return B.useEffect(()=>{if(!i||!e){l(null);return}let p=!1;return l(null),window.api.agents.resolveModelInfo({cwd:i,agentType:e}).then(a=>{p||l(a)},()=>{p||l(null)}),()=>{p=!0}},[i,e]),!i||!e||!r?null:vP(r,n,t)}const MC=[{id:"project",label:"Project & Tab",realm:"machine",blurb:"A PROJECT is a cwd; a TAB is one open project.",tone:{chip:"bg-bg-elev text-fg-dim",border:"border-line",dot:"bg-fg-faint"}},{id:"epic",label:"Epic (PromptSession)",realm:"project",blurb:"The central aggregate root — one unit of work, one claude session.",tone:{chip:"bg-accent-muted text-accent-dark",border:"border-accent",dot:"bg-accent"}},{id:"scheduler",label:"Scheduler",realm:"project",blurb:"PRDs + the headless jobs that execute them.",tone:{chip:"bg-butter/30 text-honey-dark",border:"border-honey",dot:"bg-honey"}},{id:"agents",label:"Agents & Taxonomy",realm:"machine",blurb:"The ACTOR and MISSION halves of AIM.",tone:{chip:"bg-sage/20 text-sage-dark",border:"border-sage",dot:"bg-sage"}},{id:"memory",label:"Memory",realm:"machine",blurb:"Workspace, cross-project, and per-agent memory.",tone:{chip:"bg-hive-teal/20 text-hive-teal",border:"border-hive-teal",dot:"bg-hive-teal"}},{id:"transcript",label:"Transcript & Usage",realm:"machine",blurb:"The Claude CLI's own JSONL, classified events, and billing.",tone:{chip:"bg-bg-hi text-fg-dim",border:"border-rule",dot:"bg-fg-dim"}},{id:"brief",label:"Project Home & Publishing",realm:"project",blurb:"The synthesized Brief, generated pages, and bilko.run publish state.",tone:{chip:"bg-accent-muted/60 text-accent-dark",border:"border-accent-muted",dot:"bg-accent-muted"}},{id:"config",label:"Machine Config",realm:"machine",blurb:"Settings, layout, and the single-writer ownership map.",tone:{chip:"bg-line text-fg-faint",border:"border-rule",dot:"bg-fg-faint"}}];function XB(i){const e=MC.find(t=>t.id===i);if(!e)throw new Error(`unknown ErdGroupId: ${i}`);return e}const Rb=[{id:"project",name:"Project",aka:"cwd — Main Project",group:"project",store:{path:"identity only, no record of its own — folded at read time from ~/.claude/projects/<encoded>",format:"in-memory",definedIn:"src/renderer/lib/knownProjectAggregate.ts (aggregateProjectsByCwd) "},summary:"A folder whose cwd never resolved from transcript content is DROPPED, never guessed — the naive decode once reported 2044 phantom projects.",fields:[{name:"cwd",type:"string",key:"pk",note:"resolved working directory — the project's identity"},{name:"name",type:"string",note:"display name: the cwd's last path segment"},{name:"encoded",type:"string",note:"representative transcript folder (most recently active)"},{name:"encodedIds",type:"string[]",note:"every ~/.claude/projects/<encoded> folder that resolved to this cwd"},{name:"sessionCount",type:"number"},{name:"sizeBytes",type:"number"},{name:"lastSession",type:"number"}]},{id:"tab",name:"PersistedTab",aka:"TAB",group:"project",store:{path:"~/.config/session-manager/tabs.json",format:"json",definedIn:"src/main/sessionsStore.cjs "},summary:"One TAB per project — extra sessions within a project are Epics, not tabs.",fields:[{name:"id",type:"string",key:"pk"},{name:"sessionId",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"label",type:"string"},{name:"presetId",type:"string | null"}]},{id:"epic",name:"PromptSession",aka:"EPIC",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> sessions[id]",format:"json",writer:"epics",definedIn:"src/main/lib/epicMint.cjs (ensureEpic) + src/renderer/state/promptSessions.ts "},summary:"The central aggregate root — created in exactly ONE place, a human pressing New Epic.",fields:[{name:"id",type:"string",key:"pk"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"goalText",type:"string",note:"the original top-level prompt text that started this goal"},{name:"claudeSessionId",type:"string",note:"independently minted — never shared with any tab.sessionId"},{name:"status",type:"'proposed' | 'active' | 'completed'"},{name:"createdAt",type:"string"},{name:"completedAt",type:"string | null"},{name:"resumedFromId",type:"string",optional:!0,key:"fk",ref:"epic.id"},{name:"tag",type:"TicketTag",optional:!0,key:"fk",ref:"tag.tag"},{name:"openingPrompt",type:"string | null",optional:!0},{name:"source",type:"EpicSource",optional:!0,note:"{ producer, prdSlug?, runId?, sourceTabId?, fromCwd?, fromEpicId? }"},{name:"agentType",type:"string",optional:!0,key:"fk",ref:"agentPersona.name"},{name:"sections",type:"EpicIntakeSection[]",optional:!0},{name:"worktree",type:"{ dir, branch, baseCwd, status, conflictReason? }",optional:!0,note:"own git worktree on branch 'sm-epic/<id>' when Active"}],notes:["SINGLE-CREATOR LAW, fail-closed in epicMint.cjs — the New Epic IPC handler and crossProjectFeedback.cjs are the only mint authorities.","Every Epic is born proposed; nothing is created directly as active.","EPIC : claude-session is 1:1 — Chat and Terminal are two VIEWS over one session.","Title + objective are fixed for the life of the session — iterate in follow-up messages, don't repurpose."]},{id:"epicEvent",name:"PromptSessionEvent",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/active-index.json -> events[]",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts + src/main/lib/activeIndexMerge.cjs "},summary:"One step in an Epic's Prompt → PRD → Response → ... → Closed chain.",fields:[{name:"id",type:"string",key:"pk"},{name:"promptSessionId",type:"string",key:"fk",ref:"epic.id"},{name:"kind",type:"'prompt' | 'prd_created' | 'response' | 'closed'"},{name:"causedByEventId",type:"string | null",key:"fk",ref:"epicEvent.id",note:"must be the session's current tail event — a chain, not a tree"},{name:"at",type:"string"},{name:"prdSlug",type:"string",optional:!0,key:"fk",ref:"prd.slug"},{name:"text",type:"string",optional:!0},{name:"outcome",type:"'completed' | 'failed' | 'needs_review'",optional:!0},{name:"validation",type:"'unvalidated' | 'validating' | 'verified' | 'refuted'",optional:!0}]},{id:"epicTranscriptTurn",name:"PromptSessionTranscriptTurn",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/transcripts/<epicId>.jsonl",format:"jsonl",writer:"epics",definedIn:"src/main/promptSessionTranscript.cjs "},summary:"The durable per-Epic transcript store, kept alongside the CLI's own JSONL as a fallback source of turns.",fields:[{name:"v",type:"1"},{name:"epicId",type:"string",key:"fk",ref:"epic.id"},{name:"eventId",type:"string | null",key:"fk",ref:"epicEvent.id"},{name:"role",type:"'user' | 'assistant'"},{name:"at",type:"string"},{name:"text",type:"string"}]},{id:"epicArchive",name:"PromptSessionArchive",group:"epic",store:{path:"<cwd>/session-manager-operations/prompt-sessions/<epicId>.json",format:"json",writer:"epics",definedIn:"src/renderer/state/promptSessions.ts (promptSessionArchivePath) "},summary:"On-disk archive written once at completion — freezes the Epic, its events, and its transcript.",fields:[{name:"session",type:"PromptSession"},{name:"events",type:"PromptSessionEvent[]"},{name:"transcript",type:"string"},{name:"archivedAt",type:"string"},{name:"durableTurns",type:"Array<{ role, text, at }>",optional:!0}]},{id:"prd",name:"PRD",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/epics/<epicId>/prds/<slug>.md",format:"markdown",writer:"scheduler",definedIn:"src/main/lib/prdLocations.cjs + scheduler_create_prd MCP tool "},summary:"PRD authoring is API-only via the scheduler_create_prd MCP tool — a PRD joins an EXISTING Epic and never conjures one.",fields:[{name:"slug",type:"string",key:"pk",note:"<nn>-<kebab-title>.md filename stem"},{name:"title",type:"string"},{name:"cwd",type:"string",key:"fk",ref:"project.cwd"},{name:"epicId",type:"string | null",key:"fk",ref:"epic.id",note:"derived from the PRD's DIRECTORY — fact on disk"},{name:"sourcePromptId",type:"string",optional:!0,key:"fk",ref:"epic.id",note:"frontmatter intent — can disagree with epicId"},{name:"sourceTabId",type:"string",optional:!0},{name:"estimateMinutes",type:"number"},{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'bilko-host-publisher'",optional:!0,key:"fk",ref:"tag.tag"},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug",note:"the SOLE ordering primitive"},{name:"goal",type:"string"},{name:"acceptanceCriteria",type:"string[]"},{name:"implementationNotes",type:"string"},{name:"outOfScope",type:"string[]",optional:!0},{name:"createdVia",type:"string",optional:!0},{name:"issuedAt",type:"string",optional:!0}],notes:["Flat scheduler/prds/ is RETIRED — auto-consolidated into prds-archived/ on every reconcile() pass.","epicId is derived from the DIRECTORY (fact on disk) while sourcePromptId is frontmatter intent and can disagree."]},{id:"scheduleJob",name:"ScheduleJob",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/queueStore.cjs + src/main/lib/scheduleJobSchema.cjs "},summary:"dependsOn is the SOLE ordering primitive — parallelGroup is a display hint, never a barrier.",fields:[{name:"slug",type:"string",key:"pk",note:"shared identity with the PRD it executes"},{name:"title",type:"string"},{name:"cwd",type:"string | null",key:"fk",ref:"project.cwd"},{name:"parallelGroup",type:"number"},{name:"estimateMinutes",type:"number | null"},{name:"bodyPreview",type:"string"},{name:"status",type:"'pending' | 'running' | 'investigating' | 'completed' | 'failed' | 'needs_review' | 'quarantined'"},{name:"runId",type:"string | null",key:"fk",ref:"runLog.runId"},{name:"startedAt",type:"string | null"},{name:"finishedAt",type:"string | null"},{name:"exitCode",type:"number | null"},{name:"error",type:"string | null"},{name:"sessionId",type:"string",optional:!0},{name:"runtime",type:"ScheduleJobRuntime",optional:!0,note:"{ pid, runId, startedAt, sessionId?, cwd? }"},{name:"verifierVerdict",type:"string",optional:!0},{name:"dependsOn",type:"string[]",optional:!0,key:"fk",ref:"prd.slug"},{name:"originSessionId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"sourceTabId",type:"string | null",optional:!0},{name:"sourcePromptId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id",note:"authoritative — derived from the PRD directory"},{name:"statusHistory",type:"ScheduleJobStatusHistoryEntry[]",optional:!0}],notes:["Every launch must take a slot from lib/sessionSlots.cjs — the single machine-wide concurrency limit.","--model is always pinned on every claude -p call site.","A job in needs_review is a QUESTION routed back to the authoring Epic and never creates work on its own."]},{id:"scheduleJobStatusHistory",name:"ScheduleJobStatusHistoryEntry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> jobs[].statusHistory[]",format:"json",writer:"scheduler",definedIn:"src/main/lib/scheduleJobTransitions.cjs "},summary:"Bounded trail (~20 entries) of accepted status transitions for one ScheduleJob.",fields:[{name:"from",type:"string | null"},{name:"to",type:"string"},{name:"reason",type:"string | null"},{name:"source",type:"string | null"},{name:"at",type:"string"}]},{id:"scheduleHistoryEntry",name:"Schedule history entry",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/history.jsonl",format:"jsonl",writer:"scheduler",definedIn:"src/main/lib/queueStore.cjs "},summary:"Terminal jobs aged out of queue.json land here, one JSON object per line.",fields:[{name:"slug",type:"string",key:"fk",ref:"prd.slug"},{name:"status",type:"ScheduleJobStatus"},{name:"finishedAt",type:"string | null"},{name:"epicId",type:"string | null",optional:!0,key:"fk",ref:"epic.id"},{name:"runId",type:"string | null",optional:!0,key:"fk",ref:"runLog.runId"}]},{id:"scheduleConfig",name:"ScheduleConfig",group:"scheduler",store:{path:"<cwd>/session-manager-operations/scheduler/state/queue.json -> config",format:"json",writer:"scheduler",definedIn:"src/main/lib/schedulerConfig.cjs "},summary:"Per-project auto-fire policy and utilization gate.",fields:[{name:"enabled",type:"boolean",note:"legacy on/off, kept for v0.4 backwards compat"},{name:"offsetMinutes",type:"number"},{name:"defaultCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"firePolicy",type:"'manual' | 'on-reset' | 'when-available'"},{name:"utilizationThreshold",type:"number"},{name:"schemaVersion",type:"1"}]},{id:"runLog",name:"Run log",group:"scheduler",store:{path:"~/.claude/session-manager/scheduled-plans/runs/<runId>/",format:"directory",definedIn:"src/main/scheduler.cjs (RUNS_DIR) "},summary:"One directory per headless claude -p invocation — stdout/stderr/exit capture for a ScheduleJob's run.",fields:[{name:"runId",type:"string",key:"pk"}]},{id:"agentPersona",name:"AgentPersona",aka:"ACTOR — also an ACTION when scoped",group:"agents",store:{path:"~/.claude/agents/<name>.md",format:"markdown",definedIn:"src/main/agentLibrary.cjs + src/main/lib/agentPersonaSchema.cjs "},summary:"One global persona — an ACTION is this same persona given a project scope, not a fourth concept.",fields:[{name:"name",type:"string",key:"pk"},{name:"description",type:"string | null"},{name:"tools",type:"string[]"},{name:"model",type:"string | null",note:"wins over the Settings default for this Epic"},{name:"color",type:"string | null"},{name:"tags",type:"AgentPersonaTag[]",key:"fk",ref:"tag.tag"},{name:"projects",type:"string[]",key:"fk",ref:"project.cwd",note:"'*' means every project"},{name:"action",type:"string | null"},{name:"actionLabel",type:"string | null"},{name:"title",type:"string | null",optional:!0},{name:"path",type:"string"},{name:"body",type:"string"},{name:"overridingProjects",type:"string[]"}]},{id:"tag",name:"Tag",aka:"MISSION — EpicTag",group:"agents",store:{path:"src/renderer/lib/tagLibrary.ts (TAG_LIBRARY)",format:"code",definedIn:"src/renderer/lib/tagLibrary.ts + src/renderer/lib/agentTagDefs.ts "},summary:"The closed 5-taxonomy union — Epic creation is agentType (who) + tag (what), two independent selections.",fields:[{name:"tag",type:"'feature' | 'bug' | 'discussion' | 'build' | 'project-home-builder' | 'bilko-host-publisher'",key:"pk"},{name:"label",type:"string"},{name:"description",type:"string"},{name:"developEagerness",type:"'expected-default' | 'available-not-assumed'"},{name:"developsVia",type:"string"}]},{id:"memoryEntry",name:"MemoryEntry",group:"memory",store:{path:"~/.claude/projects/<encodedCwd>/memory/<name>.md",format:"markdown",definedIn:"src/main/memoryTool.cjs "},summary:"One workspace memory file, semantically organized by topic.",fields:[{name:"name",type:"string",key:"pk"},{name:"path",type:"string"},{name:"mtimeMs",type:"number"},{name:"bytes",type:"number"},{name:"workspace",type:"string",key:"fk",ref:"project.cwd",note:"carried on MemoryListResult, denormalized here — the directory this entry lives under"}]},{id:"memoryCluster",name:"MemoryCluster",group:"memory",store:{path:"~/.claude/session-manager/memory-clusters/<encodedCwd>.json",format:"json",definedIn:"src/main/memoryAggregate.cjs "},summary:"Derived grouping of related MemoryEntry files, computed and cached per workspace.",fields:[{name:"id",type:"string",key:"pk"},{name:"name",type:"string"},{name:"summary",type:"string"},{name:"memberSlugs",type:"string[]",key:"fk",ref:"memoryEntry.name"},{name:"links",type:"MemoryClusterLink[]",note:"{ from, to, label? }"}]},{id:"agentMemoryEntry",name:"AgentMemoryEntry",group:"memory",store:{path:"~/.claude/session-manager/agent-memory/<agentId>/",format:"directory",definedIn:"src/renderer/state/agentMemory.ts "},summary:"Per-subagent memory, keyed by agent name rather than workspace cwd.",fields:[{name:"id",type:"string",key:"pk"},{name:"body",type:"string"},{name:"category",type:"'command' | 'preference' | 'pattern' | 'failure' | 'workflow' | null"},{name:"createdAt",type:"number"},{name:"updatedAt",type:"number"},{name:"bytes",type:"number"},{name:"agentId",type:"string",key:"fk",ref:"agentPersona.name",note:"carried on AgentMemoryListResult, denormalized here — the directory this entry lives under"}]},{id:"claudeTranscript",name:"Claude transcript",group:"transcript",store:{path:"~/.claude/projects/<encodedCwd>/<sessionUuid>.jsonl",format:"jsonl",definedIn:"written by the Claude Code CLI; tailed by src/main/transcripts.cjs "},summary:"The CLI's own append-only transcript — Session Manager only tails and classifies it, never writes it.",fields:[{name:"sessionUuid",type:"string",key:"pk"},{name:"encodedCwd",type:"string",key:"fk",ref:"project.cwd"}]},{id:"transcriptEvent",name:"TranscriptEvent",group:"transcript",store:{path:"in-memory ring buffer, broadcast as transcript:event:<tabId>",format:"in-memory",definedIn:"src/main/transcripts.cjs -> src/renderer/state/live.ts "},summary:"Classified, bounded-preview view over one raw transcript line — never the source of truth.",fields:[{name:"kind",type:"TranscriptEventKind"},{name:"data",type:"unknown"},{name:"raw",type:"unknown"},{name:"previewText",type:"string"},{name:"ref",type:"TranscriptEventRef | null",note:"{ filePath, byteOffset, byteLength }"},{name:"tabId",type:"string",key:"fk",ref:"tab.id"}]},{id:"historyRollupDay",name:"History rollup day",group:"transcript",store:{path:"~/.claude/session-manager/history-rollup.jsonl",format:"jsonl",definedIn:"src/main/lib/historyRollup.cjs "},summary:"One finalized day-per-project analytics row (History tab is analytics/cost/charts only).",fields:[{name:"date",type:"string",key:"pk"},{name:"projectCwd",type:"string",key:"fk",ref:"project.cwd"},{name:"promptCount",type:"number"},{name:"inputTokens",type:"number"},{name:"outputTokens",type:"number"},{name:"estimatedCostUsd",type:"number"}]},{id:"billingUsage",name:"UsageSnapshot",group:"transcript",store:{path:"~/.claude/session-manager/billing-cache.json",format:"json",definedIn:"src/main/usage.cjs (CACHE_PATH) "},summary:"Cached rolling-window utilization percentages from the account's billing API.",fields:[{name:"five_hour",type:"UsageWindow | null"},{name:"seven_day",type:"UsageWindow | null"},{name:"seven_day_sonnet",type:"UsageWindow | null"},{name:"seven_day_opus",type:"UsageWindow | null"},{name:"seven_day_oauth_apps",type:"UsageWindow | null"},{name:"extra_usage",type:"{ is_enabled, monthly_limit, used_credits, utilization, currency } | null"}]},{id:"projectBrief",name:"ProjectBrief",group:"brief",store:{path:"<cwd>/session-manager-operations/project-brief/brief.json",format:"json",writer:"project-home",definedIn:"src/main/projectBrief.cjs "},summary:"The synthesized project Brief — generated, with a hand-edit escape hatch.",fields:[{name:"version",type:"number"},{name:"synthesizedAt",type:"string"},{name:"editedAt",type:"string | null"},{name:"model",type:"string"},{name:"purpose",type:"string"},{name:"what",type:"string[]"},{name:"areas",type:"ProjectBriefArea[]",note:"{ name, files, note, epic, heat }"},{name:"scope",type:"ProjectBriefScopeEntry[]",note:"{ when, kind, text, src }"},{name:"conventions",type:"string[]"},{name:"pins",type:"{ what: boolean; conventions: boolean }"},{name:"pinned",type:"{ what: string[] | null; conventions: string[] | null }"}]},{id:"projectPages",name:"ProjectPagesOutput",group:"brief",store:{path:"<cwd>/session-manager-operations/project-pages/ (home.html)",format:"directory",writer:"project-home",definedIn:"project_home_write MCP tool (src/main/lib/projectHomeAdminRoutes.cjs)"},summary:"One self-contained overview page, written only via project_home_write.",fields:[{name:"html",type:"string | null"},{name:"mtimeMs",type:"number | null"}]},{id:"bilkoPublishState",name:"BilkoHostPublishState",group:"brief",store:{path:"<cwd>/session-manager-operations/bilko-host/publish-state.json",format:"json",writer:"bilko-host",definedIn:"src/renderer/lib/bilkoHost.ts + bilko-host MCP "},summary:"The bilko.run relay is intentionally still live — never delete or decommission it.",fields:[{name:"status",type:"'not-published' | 'bundle-ready' | 'publishing' | 'published' | 'publish-failed'"},{name:"slug",type:"string"},{name:"url",type:"string",optional:!0},{name:"lastAttemptAt",type:"string",optional:!0},{name:"lastError",type:"string",optional:!0}]},{id:"settingsScope",name:"Settings (scoped)",group:"config",store:{path:"~/.claude/settings.json + <cwd>/.claude/settings.json + <cwd>/.claude/settings.local.json",format:"json",definedIn:"src/main/config.cjs + src/renderer/state/config.ts + src/renderer/lib/mergeScopes.ts "},summary:"Substrate, not per-Epic curation — model is the one field carved out per-Epic (persona wins over Settings).",fields:[{name:"scope",type:"'system' | 'project' | 'local'",key:"pk"},{name:"cwd",type:"string",optional:!0,key:"fk",ref:"project.cwd"},{name:"model",type:"string",optional:!0}]},{id:"layoutEnvelope",name:"LayoutEnvelope",group:"config",store:{path:"~/.claude/session-manager/workbench-layout.json",format:"json",definedIn:"src/main/layoutStore.cjs + src/renderer/state/layout.ts "},summary:"Persisted dockview panel layout, pruned against the live panel registry on hydrate.",fields:[{name:"version",type:"number"},{name:"panels",type:"string[]",key:"fk",ref:"tab.id"},{name:"dockview",type:"Record<string, unknown>",note:"opaque SerializedDockview blob"}]},{id:"opsNamespace",name:"Ops namespace ownership",aka:"the SINGLE-WRITER LAW",group:"config",store:{path:"src/main/lib/opsOwnership.cjs (OWNERS)",format:"code",definedIn:"src/main/lib/opsOwnership.cjs (assertOpsWrite) "},summary:"Fail-closed — a new top-level ops folder must land in OWNERS (or the deliberately-unowned list) in the same PR that creates it.",fields:[{name:"namespace",type:"string",key:"pk",note:"e.g. 'prompt-sessions', 'scheduler', 'project-brief', 'bilko-host'"},{name:"writer",type:"string",note:"e.g. 'epics', 'scheduler', 'project-home', 'bilko-host'"}]}];function YB(i){const e=Rb.find(t=>t.id===i);if(!e)throw new Error(`unknown ErdEntity id: ${i}`);return e}const jC=[{from:"tab",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"project",cardinality:"N-1",label:"belongs to"},{from:"epic",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"epic",to:"agentPersona",cardinality:"N-1",label:"actor",optional:!0},{from:"epic",to:"epic",cardinality:"N-1",label:"resumed from",optional:!0},{from:"epic",to:"claudeTranscript",cardinality:"1-1",label:"1:1 session"},{from:"epicEvent",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicEvent",to:"epicEvent",cardinality:"N-1",label:"caused by",optional:!0},{from:"epicEvent",to:"prd",cardinality:"N-1",label:"about",optional:!0},{from:"epicTranscriptTurn",to:"epic",cardinality:"N-1",label:"belongs to"},{from:"epicTranscriptTurn",to:"epicEvent",cardinality:"N-1",label:"labeled by",optional:!0},{from:"epicArchive",to:"epic",cardinality:"1-1",label:"freezes"},{from:"prd",to:"epic",cardinality:"N-1",label:"joins (directory fact)"},{from:"prd",to:"epic",cardinality:"N-1",via:"sourcePromptId",label:"authored from (frontmatter intent)",optional:!0},{from:"prd",to:"project",cardinality:"N-1",label:"belongs to"},{from:"prd",to:"tag",cardinality:"N-1",label:"mission",optional:!0},{from:"scheduleJob",to:"prd",cardinality:"1-1",label:"executes"},{from:"scheduleJob",to:"prd",cardinality:"N-N",via:"dependsOn",label:"depends on",optional:!0},{from:"scheduleJob",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleJob",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleJob",to:"scheduleJob",cardinality:"N-N",via:"dependsOn",label:"depends on (self)",optional:!0},{from:"scheduleJobStatusHistory",to:"scheduleJob",cardinality:"N-1",label:"transitions of"},{from:"scheduleHistoryEntry",to:"prd",cardinality:"N-1",label:"archives"},{from:"scheduleHistoryEntry",to:"epic",cardinality:"N-1",label:"belongs to",optional:!0},{from:"scheduleHistoryEntry",to:"runLog",cardinality:"N-1",label:"ran as",optional:!0},{from:"scheduleConfig",to:"project",cardinality:"1-1",label:"configures"},{from:"agentPersona",to:"tag",cardinality:"N-N",label:"tagged with"},{from:"agentPersona",to:"project",cardinality:"N-N",label:"action button in"},{from:"memoryEntry",to:"project",cardinality:"N-1",label:"workspace"},{from:"memoryCluster",to:"memoryEntry",cardinality:"1-N",label:"clusters"},{from:"agentMemoryEntry",to:"agentPersona",cardinality:"N-1",label:"belongs to"},{from:"transcriptEvent",to:"tab",cardinality:"N-1",label:"classified for"},{from:"transcriptEvent",to:"claudeTranscript",cardinality:"N-1",label:"classified from"},{from:"claudeTranscript",to:"project",cardinality:"N-1",label:"belongs to"},{from:"historyRollupDay",to:"project",cardinality:"N-N",label:"aggregates"},{from:"billingUsage",to:"scheduleConfig",cardinality:"1-N",label:"gates when-available firing"},{from:"projectBrief",to:"project",cardinality:"1-1",label:"describes"},{from:"projectBrief",to:"epic",cardinality:"N-1",via:"areas[].epic",label:"traces to",optional:!0},{from:"projectPages",to:"project",cardinality:"1-1",label:"generated for"},{from:"bilkoPublishState",to:"project",cardinality:"1-1",label:"publishes"},{from:"settingsScope",to:"project",cardinality:"N-1",label:"scoped to",optional:!0},{from:"layoutEnvelope",to:"tab",cardinality:"1-N",label:"panels for"},{from:"opsNamespace",to:"epic",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"prd",cardinality:"1-N",label:"governs writes"},{from:"opsNamespace",to:"projectBrief",cardinality:"1-N",label:"governs writes"}];function _P(i){return jC.filter(e=>e.from===i||e.to===i)}function JB(i){const e=new Set;for(const t of _P(i)){const n=t.from===i?t.to:t.from;n!==i&&e.add(n)}return[...e]}function ZB(i){switch(i){case"1-1":return"1—1";case"1-N":return"1—N";case"N-1":return"N—1";case"N-N":return"N—N"}}const Zx=220,Qx=7,yP=44,bP=16,wP=10,xP=96,SP=28,Mg=24;function CP(i){const e=Math.min(i,Qx)+(i>Qx?1:0);return yP+e*bP+wP}function EP(i){const e=i.x+i.w,t=i.y+i.h*.35,n=i.y+i.h*.65,r=e+48;return{d:`M ${e} ${t} C ${r} ${t}, ${r} ${n}, ${e} ${n}`,mx:r,my:(t+n)/2}}function QB(i=Rb,e=jC){const t=MC.map(f=>f.id).filter(f=>i.some(g=>g.group===f)),n=[],r=new Map;t.forEach((f,g)=>{const m=Mg+g*(Zx+xP);let b=Mg;for(const T of i){if(T.group!==f)continue;const E=CP(T.fields.length),k={id:T.id,group:f,x:m,y:b,w:Zx,h:E};n.push(k),r.set(T.id,k),b+=E+SP}});const l=new Set(i.map(f=>f.id)),p=[];for(const f of e){if(!l.has(f.from)||!l.has(f.to))continue;const g=r.get(f.from),m=r.get(f.to);if(!g||!m)continue;if(f.from===f.to){const O=EP(g);p.push({relation:f,...O});continue}const b=g.x<m.x,T=b?g.x+g.w:g.x,E=g.y+g.h/2,k=b?m.x:m.x+m.w,y=m.y+m.h/2,S=Math.max(40,Math.abs(k-T)/2),w=T+(b?S:-S),x=k+(b?-S:S),A=`M ${T} ${E} C ${w} ${E}, ${x} ${y}, ${k} ${y}`;p.push({relation:f,d:A,mx:(T+k)/2,my:(E+y)/2})}const a=n.reduce((f,g)=>Math.max(f,g.x+g.w),0),d=n.reduce((f,g)=>Math.max(f,g.y+g.h),0);return{boxes:n,edges:p,width:a+Mg,height:d+Mg}}const Ob=[];function kP({onNavigate:i}){const e=B.useMemo(()=>{const g=new Date().getHours();return g<5?"Up late":g<12?"Good morning":g<18?"Good afternoon":"Good evening"},[]);UP();const t=AP(),n=DP(),r=St(g=>g.tabs),l=St(g=>g.addTab),p=St(g=>g.setActive),[a,d]=B.useState(!1),f=g=>{EC(g,r,l,p),i==null||i("terminal")};return c.jsxs("div",{className:"h-full overflow-auto",children:[c.jsxs("div",{className:"mx-auto max-w-[1080px] px-[34px] py-[26px] text-fg",children:[c.jsx(RP,{greeting:e,projectCount:n.length,needsCount:t.length,onNavigate:i,onOpenNewEpic:()=>d(!0)}),c.jsxs("div",{className:"grid gap-[18px] mb-7",style:{gridTemplateColumns:"minmax(0,1fr) minmax(0,1fr) 220px"},children:[c.jsx(zP,{}),c.jsx(BP,{projectRows:n}),c.jsx(MP,{onNavigate:i})]}),c.jsx(NP,{rows:t,onNavigate:i}),c.jsx(WP,{onNavigate:i}),c.jsx(FP,{onNavigate:i}),c.jsx(eP,{}),c.jsx(IP,{}),c.jsx(PP,{onNavigate:i}),c.jsx(XI,{})]}),c.jsx(FI,{open:a,onClose:()=>d(!1),projects:n,onConfirm:f})]})}const TP=B.memo(kP);function DP(){const{projects:i}=vd(),e=Mv(),t=ti(n=>n.sessions);return B.useMemo(()=>LI(i,e,t),[i,e,t])}function AP(){const i=ti(n=>n.sessions),e=Mv(),t=Nr(n=>{var r;return(r=n.snapshot)==null?void 0:r.jobs})??Ob;return B.useMemo(()=>{const n={};for(const r of Object.keys(i)){const l=i[r];l.status==="proposed"&&(n[r]={id:r,cwd:l.cwd,goalText:l.goalText,tag:l.tag})}return jI(n,e,t)},[i,e,t])}function IP(){const i=OC(null),{value:e,source:t}=LC(i,["effortLevel"]),n=$C(e,t);return c.jsxs("section",{className:"mb-6",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Agents"}),c.jsxs("span",{className:"font-mono text-[12px] text-fg-faint","data-testid":"home-agents-effort",title:"Machine-wide effective reasoning effort — the settings.json scope chain's current winner, independent of any one project.",children:["1 tag per session · ",n]})]}),c.jsx("div",{className:"grid gap-2",children:lP.map(r=>{const l=AC[r],p=t1(r);return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[13px] px-4 py-[13px]",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("span",{className:`font-mono text-[10.5px] font-semibold uppercase tracking-[0.06em] px-1.5 py-0.5 rounded ${p.bg} ${p.text}`,children:p.label}),c.jsx("span",{className:"text-[12px] text-fg-faint",children:l.description})]}),c.jsx("p",{className:"m-0 text-[12.5px] text-fg-dim leading-[1.5] font-mono whitespace-pre-wrap",children:l.initialPromptTemplate})]},r)})})]})}function PP({onNavigate:i}){return c.jsx("section",{className:"mb-6",children:c.jsxs("button",{type:"button","data-testid":"home-data-model-card",onClick:()=>i==null?void 0:i("data-model"),className:"w-full text-left bg-bg-hi border border-line rounded-[14px] px-4 py-[14px] flex items-center justify-between hover:bg-bg-elev/40 transition-colors",children:[c.jsxs("span",{children:[c.jsx("span",{className:"block font-serif text-[16px] font-medium text-fg",children:"Data Model"}),c.jsxs("span",{className:"block text-[12.5px] text-fg-dim",children:[Rb.length," entities — what Session Manager persists, and how it joins"]})]}),c.jsx("span",{className:"font-mono text-[11px] text-accent shrink-0",children:"Open →"})]})})}function RP({greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r}){const[l,p]=B.useState(!1);return c.jsxs(c.Fragment,{children:[c.jsx(OP,{greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r,legendOpen:l,onToggleLegend:()=>p(a=>!a)}),l&&c.jsx($P,{})]})}function OP({greeting:i,projectCount:e,needsCount:t,onNavigate:n,onOpenNewEpic:r,legendOpen:l,onToggleLegend:p}){const a=_b(),d=(a==null?void 0:a.total)??5,f=(a==null?void 0:a.inUse)??0,g=()=>{var m;(m=document.getElementById("home-needs-you"))==null||m.scrollIntoView({behavior:"smooth",block:"start"})};return c.jsxs("header",{className:"mb-[18px] flex items-end gap-4",children:[c.jsxs("div",{children:[c.jsxs("div",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-1.5",children:["This machine · ",e," project",e===1?"":"s"]}),c.jsxs("h1",{className:"m-0 font-serif text-[30px] font-semibold leading-[1.1] text-fg tracking-[-0.01em]",children:[i,". ",c.jsxs("span",{className:"text-accent",children:[f," of ",d]})," slots busy,"," ",t>0?c.jsxs("button",{onClick:g,className:"underline decoration-dotted underline-offset-4 text-honey-dark hover:text-honey",children:[t," thing",t>1?"s":""]}):c.jsx("span",{className:"text-sage",children:"nothing"})," ","need",t===1?"s":""," you."]})]}),c.jsxs("div",{className:"ml-auto flex gap-2 shrink-0",children:[c.jsx(C_,{onClick:p,children:l?"Hide interactions":"Interactions"}),c.jsx(C_,{onClick:()=>n==null?void 0:n("history"),children:"All history"}),c.jsx(C_,{primary:!0,onClick:r,children:"New epic"})]})]})}const LP=[{term:"Usage card",description:"Read-only — shows the live 5-hour and weekly billing windows. Not clickable."},{term:"Queued job",description:`Click a job row to open a popover with its real details (project, estimate, status) and actions — Open in Scheduler, plus Nudge scheduler now while it's pending. Use "Open Scheduler →" in the card header to jump straight to the Scheduler tab.`},{term:"Needs-you row",description:"Click a row to expand it inline, then Approve & start / Discard a proposed session, Open a session waiting on input, Retry / view a failed job, or Adopt / view a quarantined PRD."},{term:"Active session row",description:"Click Open to jump to the Scheduler tab (job) or the session's Terminal view."},{term:"Recent row",description:"Click resume to open a new Terminal tab that resumes that transcript session."},{term:"Project row",description:"Click a project to activate its open Terminal tab, or open a new dormant one."},{term:"New session",description:"Opens a project picker; confirming activates-or-opens that project's tab and lands you in its Sessions workspace to start the session."}];function $P(){return c.jsxs("div",{className:"mb-7 bg-bg-hi border border-line rounded-[13px] px-4 py-[13px]",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2.5",children:"Interactions"}),c.jsx("div",{className:"grid gap-2",style:{gridTemplateColumns:"minmax(0,140px) minmax(0,1fr)"},children:LP.map(i=>c.jsxs("div",{className:"contents",children:[c.jsx("div",{className:"text-[12.5px] font-semibold text-fg underline decoration-dotted underline-offset-4",children:i.term}),c.jsx("div",{className:"text-[12.5px] text-fg-dim leading-[1.5]",children:i.description})]},i.term))})]})}function C_({children:i,onClick:e,primary:t}){return c.jsx("button",{onClick:e,className:t?"rounded-lg bg-accent text-bg-hi px-4 py-2 text-[12.5px] font-semibold hover:bg-accent-dark":"rounded-lg border border-line bg-bg-hi px-4 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:i})}function NP({rows:i,onNavigate:e}){const[t,n]=B.useState(null),[r,l]=B.useState(null),p=m=>{if(!(!m.epicId||r)){l(m.id);try{const b=ti.getState().approveProposed(m.epicId,"Home needs-you");if(!b){nt.error("This session is no longer awaiting approval.");return}pi.getState().send({tabId:b.id,sessionId:b.claudeSessionId,cwd:b.cwd,prompt:b.openingPrompt||b.goalText}),nt.info("Session approved and started.")}finally{l(null),n(null)}}},a=m=>{!m.epicId||r||(l(m.id),ti.getState().markCompleted(m.epicId,"Home needs-you discard").catch(()=>{}).finally(()=>{l(null),n(null)}))},d=m=>{m.epicId&&(jv(m.epicId),e==null||e("terminal"))},f=m=>{!m.jobSlug||r||(l(m.id),window.api.schedule.resetJob(m.jobSlug).then(b=>{b.ok?nt.info(`${m.jobSlug} reset to pending.`):nt.error(b.error??"Could not reset job.")}).catch(b=>nt.error(b instanceof Error?b.message:String(b))).finally(()=>{l(null),n(null)}))},g=m=>{!m.jobSlug||r||(l(m.id),window.api.schedule.adoptPrd(m.jobSlug).then(b=>{b.ok?nt.info(`${m.jobSlug} adopted — will run on the next tick.`):nt.error(b.message??"Could not adopt PRD.")}).catch(b=>nt.error(b instanceof Error?b.message:String(b))).finally(()=>{l(null),n(null)}))};return c.jsxs("section",{id:"home-needs-you",className:"mb-6 scroll-mt-4",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Needs you"}),c.jsx("span",{className:"font-mono text-[12px] text-fg-faint",children:i.length?`${i.length} open`:"all clear"})]}),i.length===0&&c.jsx("div",{className:"bg-bg-hi border border-line rounded-[11px] px-4 py-[18px] text-center text-[13px] text-fg-faint",children:"Nothing waiting on you. Proposed Epics, mid-run questions, and failed jobs will surface here."}),c.jsx("div",{className:"grid gap-[7px]",children:i.map(m=>{const b=t===m.id,T=m.kind==="job-failed"?"bg-accent":m.kind==="job-quarantined"?m.escalated?"bg-accent":"bg-honey":m.kind==="needs-input"?"bg-honey":"bg-sage";return c.jsxs("div",{className:`border rounded-[11px] overflow-hidden ${b?"bg-bg-hi border-line":"bg-bg border-line/60"}`,children:[c.jsxs("button",{onClick:()=>n(b?null:m.id),className:"w-full grid items-center gap-2.5 px-[13px] py-[10px] text-left",style:{gridTemplateColumns:"6px minmax(0,1fr) auto"},children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T}`}),c.jsxs("span",{className:"min-w-0",children:[c.jsx("span",{className:"block text-[12.5px] font-semibold text-fg",children:m.label}),c.jsxs("span",{className:"block text-[11.5px] text-fg-faint truncate",children:[m.project?`${m.project} · `:"",m.detail]})]}),c.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:b?"▴":"▾"})]}),b&&c.jsxs("div",{className:"border-t border-line px-[13px] pt-[11px] pb-3 grid gap-2.5",children:[c.jsx("div",{className:"text-[12.5px] text-fg-dim leading-relaxed",children:m.meta}),c.jsxs("div",{className:"flex gap-2",children:[m.kind==="proposed-epic"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>p(m),disabled:r===m.id,children:"Approve & start"}),c.jsx(nd,{quiet:!0,onClick:()=>a(m),disabled:r===m.id,children:"Discard"})]}),m.kind==="needs-input"&&c.jsx(nd,{onClick:()=>d(m),children:"Open session"}),m.kind==="job-failed"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>f(m),disabled:r===m.id,children:"Retry now"}),c.jsx(nd,{quiet:!0,onClick:()=>e==null?void 0:e("scheduler"),children:"View in Scheduler"})]}),m.kind==="job-quarantined"&&c.jsxs(c.Fragment,{children:[c.jsx(nd,{onClick:()=>g(m),disabled:r===m.id,children:"Adopt PRD"}),c.jsx(nd,{quiet:!0,onClick:()=>e==null?void 0:e("scheduler"),children:"View in Scheduler"})]})]})]})]},m.id)})})]})}function nd({children:i,onClick:e,disabled:t,quiet:n}){return c.jsx("button",{onClick:e,disabled:t,className:n?"rounded-md border border-line bg-bg px-3 py-[5px] text-[11.5px] font-semibold text-fg-dim hover:bg-bg-elev disabled:opacity-50":"rounded-md bg-accent text-bg-hi px-3 py-[5px] text-[11.5px] font-semibold hover:bg-accent-dark disabled:opacity-50",children:i})}function MP({onNavigate:i}){const e=Nr(p=>{var a;return(a=p.snapshot)==null?void 0:a.jobs})??Ob,t=B.useMemo(()=>e.filter(p=>p.status==="pending").slice(0,4),[e]),[n,r]=B.useState(null),l=()=>{window.api.schedule.runNow().catch(p=>nt.error(p instanceof Error?p.message:String(p))),r(null)};return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[14px] px-4 py-[14px]",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2.5",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint",children:"Queued"}),c.jsx("button",{onClick:()=>i==null?void 0:i("scheduler"),className:"font-mono text-[10.5px] text-accent hover:underline",children:"Open Scheduler →"})]}),t.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-1",children:"Nothing pending."}):c.jsx("div",{className:"space-y-2.5",children:t.map(p=>c.jsxs("div",{className:"relative",children:[c.jsxs("button",{onClick:()=>r(n===p.slug?null:p.slug),className:"w-full text-left hover:bg-bg/40 rounded-md -mx-1 px-1 py-0.5 transition-colors",children:[c.jsx("div",{className:"font-mono text-[11.5px] font-semibold text-fg truncate",children:p.title||p.slug}),c.jsxs("div",{className:"text-[11px] text-fg-faint truncate",children:[p.cwd?Lo(p.cwd):"—",p.estimateMinutes!=null?` · ~${p.estimateMinutes}m`:""]})]}),n===p.slug&&c.jsx(WI,{job:p,onClose:()=>r(null),onOpenScheduler:()=>{r(null),i==null||i("scheduler")},onRunNow:p.status==="pending"?l:void 0})]},p.slug))})]})}function jP({slots:i}){const e=(i==null?void 0:i.min)??0,t=(i==null?void 0:i.max)??10,n=(i==null?void 0:i.total)??5,r=(i==null?void 0:i.envOverride)??!1,[l,p]=B.useState(null),[a,d]=B.useState(!1),f=l??n,g=m=>{p(m),d(!0),window.api.schedule.setSessionSlots(m).catch(()=>{}).finally(()=>{d(!1),p(null)})};return c.jsxs("span",{className:"flex items-center gap-2.5 shrink-0",title:r?"Pinned by SM_SESSION_SLOTS env var":"Max concurrent claude -p sessions on this machine (0 pauses new launches)",children:[c.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:"Max slots"}),c.jsx("input",{type:"range",min:e,max:t,step:1,value:f,disabled:r||a,onChange:m=>g(Number(m.target.value)),className:"w-24 accent-accent disabled:opacity-40 disabled:cursor-not-allowed"}),c.jsx("span",{className:"font-mono text-[12px] font-semibold text-fg w-4 text-right",children:f})]})}function zP(){const i=Jf(t=>t.data),e=L1(i);return c.jsxs("div",{className:"space-y-3",children:[i&&i.kind!=="ok"&&i.kind!=="ok-stale"&&c.jsx(aP,{result:i,onRetry:jD}),!i&&c.jsx("div",{className:"text-xs text-fg-faint",children:"loading usage…"}),e&&c.jsx(HI,{data:e,updatedAt:e.fetchedAt})]})}function BP({projectRows:i}){const e=St(l=>l.tabs),t=St(l=>l.addTab),n=St(l=>l.setActive),r=l=>{EC(l,e,t,n),Ii.getState().setEpicsWorkspaceOpen(!1)};return c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[14px] px-4 py-[14px]",children:[c.jsx("div",{className:"font-mono text-[11px] uppercase tracking-[0.08em] text-fg-faint mb-2.5",children:"Projects"}),i.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-2",children:"No known projects yet."}):c.jsx("div",{className:"space-y-1",children:i.map(l=>c.jsxs("button",{onClick:()=>r(l.cwd),className:"w-full flex items-center gap-2.5 text-left px-2 py-1.5 rounded-lg hover:bg-bg/60 transition-colors",title:l.cwd,children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:CC(l.dotSeed)}}),c.jsx("span",{className:"flex-1 min-w-0 text-[13px] text-fg truncate",children:l.name}),l.liveCount>0?c.jsxs("span",{className:"font-mono text-[11px] text-accent whitespace-nowrap",children:[l.liveCount," live"]}):c.jsx("span",{className:"font-mono text-[11px] text-fg-faint whitespace-nowrap",children:nm(l.lastActivityMs)})]},l.encoded))})]})}function UP(){const{projects:i}=vd(),e=B.useMemo(()=>i.map(t=>t.cwd).join(`
2924
2924
  `),[i]);B.useEffect(()=>{for(const t of e?e.split(`
2925
2925
  `):[])ti.getState().hydrate(t),ti.getState().hydrateArchived(t)},[e])}function GP(i=4){const e=Ab(),[t,n]=B.useState([]),[r,l]=B.useState(!0);return B.useEffect(()=>{if(!e)return;let p=!1;return(async()=>{l(!0);try{const a=await window.api.config.listDir(`${e}/.claude/projects`,{dirsOnly:!0}),d=[];for(const f of a.entries){if(p)return;const g=await window.api.config.listDir(f.path,{filesOnly:!0});for(const m of g.entries)m.name.endsWith(".jsonl")&&d.push({sessionId:m.name.replace(/\.jsonl$/,""),projectEncoded:f.name,path:m.path,mtimeMs:m.mtimeMs,sizeBytes:m.size})}d.sort((f,g)=>g.mtimeMs-f.mtimeMs),p||n(d.slice(0,i))}catch(a){console.error("[Home] recent-sessions scan failed:",a)}finally{p||l(!1)}})(),()=>{p=!0}},[e,i]),{rows:t,loading:r}}const HP="92px minmax(0,1.2fr) minmax(0,1fr) 80px 74px 78px";function FP({onNavigate:i}){const{rows:e,loading:t}=GP(5),{projects:n}=vd(),r=St(T=>T.addTab),l=ti(T=>T.sessions),[p,a]=B.useState(null),d=B.useMemo(()=>{const T={};for(const E of n)for(const k of E.encodedIds)T[k]=E.cwd;return T},[n]),f=T=>d[T]??xC(T),g=T=>{const E=f(T.projectEncoded);r({cwd:E,startupCommand:`claude --resume ${fr(T.sessionId)}`,presetId:"history-resume"})},m=p?Xx(p.sessionId,l):null,b=p?[{label:"Session",value:p.sessionId},{label:"Project",value:f(p.projectEncoded)},{label:"Epic",value:m??"—"},{label:"Last activity",value:`${zC(p.mtimeMs)} (${nm(p.mtimeMs)})`},{label:"Size",value:`${Math.round(p.sizeBytes/1024)}k`}]:[];return c.jsxs("section",{className:"mb-6",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Recent sessions"}),c.jsx("button",{onClick:()=>i==null?void 0:i("history"),className:"text-[13px] text-accent font-medium hover:underline",children:"See all history →"})]}),c.jsxs("div",{className:"bg-bg-hi border border-line rounded-[14px] overflow-hidden",children:[t&&e.length===0&&c.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint text-center",children:"Reading transcripts…"}),!t&&e.length===0&&c.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint text-center",children:"No sessions yet — hit “Start a session” to begin."}),e.map((T,E)=>{const k=Xx(T.sessionId,l);return c.jsxs("button",{onClick:()=>a(T),className:"w-full grid items-center gap-3.5 px-[18px] py-[11px] text-left hover:bg-bg/40 transition-colors",style:{gridTemplateColumns:HP,borderTop:E?"1px solid #d9c9a8":"none"},children:[c.jsx("span",{className:"text-[11.5px] text-fg-faint font-mono truncate",children:T.sessionId.slice(0,8)}),c.jsx("span",{className:"text-[12.5px] font-semibold text-fg truncate",title:T.projectEncoded,children:Lo(f(T.projectEncoded))}),c.jsx("span",{className:"text-[12.5px] text-fg-dim truncate",children:k??"—"}),c.jsxs("span",{className:"text-[11.5px] text-fg-faint font-mono text-right",children:[Math.round(T.sizeBytes/1024),"k"]}),c.jsx("span",{className:"text-[11px] text-fg-faint font-mono text-right",children:nm(T.mtimeMs)}),c.jsx("span",{className:"justify-self-end text-[12px] font-semibold px-[11px] py-[5px] rounded-lg text-sage bg-[#e5ecd8]",title:`Open ${T.sessionId.slice(0,8)}…`,children:"details"})]},T.path)})]}),c.jsx(Ib,{open:p!=null,onClose:()=>a(null),title:m??(p?Lo(f(p.projectEncoded)):""),sub:p?`Recent session · ${p.sessionId.slice(0,8)}…`:null,keyVals:b,footer:p&&c.jsx("button",{onClick:()=>{g(p),a(null)},className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg text-sage bg-[#e5ecd8] hover:brightness-95 transition-[filter]",children:"Resume"})})]})}function zC(i){return new Date(i).toLocaleString()}function nm(i){const e=Date.now()-i;return e<6e4?"just now":e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}function WP({onNavigate:i}){var y;const e=_b(),t=Nr(S=>{var w;return(w=S.snapshot)==null?void 0:w.jobs})??Ob,n=Mv(),r=ti(S=>S.sessions),[l,p]=B.useState(null),a=(e==null?void 0:e.total)??5,d=(e==null?void 0:e.inUse)??0,f=B.useMemo(()=>t.filter(S=>S.status==="running"),[t]),g=Nr(S=>{var w;return(w=S.snapshot)==null?void 0:w.lastTick}),m=B.useMemo(()=>{var w;if(!g||g.fired)return null;const S=t.filter(x=>x.status==="pending").length;if(S===0)return null;switch(g.reason){case"memory-deferred":return`memory gate: ${g.availableMb} MB free, need ${g.threshold} MB`;case"slots-exhausted":return`all ${a} slots busy — ${g.deferredCount??S} pending`;case"held":{const x=((w=g.holds)==null?void 0:w.length)??0;return x>0?`${x} pending held behind dependencies`:g.detail??"held"}case"paused":return"scheduler paused";default:return null}},[g,t,a]),b=B.useMemo(()=>$I((e==null?void 0:e.holders)??[],f,n,r),[e,f,n,r]),T=S=>{if(S.openTarget==="scheduler"){i==null||i("scheduler");return}S.openTarget==="terminal"&&S.epicId&&(jv(S.epicId),i==null||i("terminal"))},E=(l==null?void 0:l.kind)==="chat run"&&l.epicId?(y=n[l.epicId])==null?void 0:y.turns.slice(-4).map(S=>({id:S.id,role:S.role,text:S.text})):void 0,k=l?[{label:"Owner",value:l.owner},{label:"Kind",value:l.kind},{label:"Epic",value:l.epicTitle??"—"},{label:"Project",value:l.project??"—"},{label:"Started",value:`${zC(new Date(l.at).getTime())} (${nm(new Date(l.at).getTime())})`}]:[];return c.jsxs("section",{className:"mb-6",children:[c.jsxs("div",{className:"flex items-baseline justify-between mb-3",children:[c.jsx("h2",{className:"m-0 font-serif text-[22px] font-medium",children:"Active sessions"}),c.jsxs("span",{className:"flex items-center gap-4",children:[c.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[d," of ",a," slots in use",m&&c.jsxs("span",{className:"ml-2 text-amber-400/90",children:["· ",m]})]}),c.jsx(jP,{slots:e})]})]}),b.length===0?c.jsx("div",{className:"text-[13px] text-fg-faint py-1",children:"No headless Claude sessions running."}):c.jsx("div",{className:"grid gap-2",children:b.map(S=>c.jsxs("button",{onClick:()=>p(S),className:"w-full text-left bg-bg-hi border border-line rounded-[13px] px-4 py-[13px] grid items-center gap-3.5 hover:bg-bg-elev/40 transition-colors",style:{gridTemplateColumns:"minmax(0,1fr) auto"},children:[c.jsxs("span",{className:"min-w-0",children:[c.jsxs("span",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent shrink-0"}),c.jsx("span",{className:"font-mono text-[12.5px] font-semibold text-fg truncate",children:S.owner}),c.jsx("span",{className:"font-mono text-[10.5px] text-fg-faint shrink-0",children:S.kind})]}),(S.project||S.epicTitle)&&c.jsx("span",{className:"block text-[12px] text-fg-faint truncate",children:[S.project,S.epicTitle?`Epic · ${S.epicTitle}`:null].filter(Boolean).join(" · ")})]}),c.jsxs("span",{className:"flex items-center gap-3.5 shrink-0",children:[c.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:nm(new Date(S.at).getTime())}),S.openTarget&&c.jsx("span",{onClick:w=>{w.stopPropagation(),T(S)},className:"border border-line bg-bg rounded-lg px-[11px] py-[5px] text-[12px] font-semibold text-fg-dim hover:bg-bg/60 transition-colors",children:"Open"})]})]},S.owner))}),c.jsx(Ib,{open:l!=null,onClose:()=>p(null),title:(l==null?void 0:l.epicTitle)??(l==null?void 0:l.owner)??"",sub:l?`Active session · ${l.kind}`:null,keyVals:k,tail:E,footer:(l==null?void 0:l.openTarget)&&c.jsx("button",{onClick:()=>{T(l),p(null)},className:"text-[12px] font-semibold px-[13px] py-[7px] rounded-lg bg-accent text-bg-hi hover:bg-accent-dark",children:"Open"})})]})}function e0(i){return i.html===null?null:{html:i.html,mtimeMs:i.mtimeMs}}function VP(i){const[e,t]=B.useState(null),[n,r]=B.useState(!1);return B.useEffect(()=>{if(!i)return;let l=!1;return r(!1),window.api.projectPages.get(i).then(p=>{l||(t(e0(p)),r(!0))}).catch(p=>{l||(r(!0),nt.error(`Could not load Project Pages: ${p instanceof Error?p.message:String(p)}`))}),()=>{l=!0}},[i]),B.useEffect(()=>{if(!i)return;window.api.projectPages.watch(i);const l=window.api.projectPages.onChanged(p=>{p.cwd===i&&(t(e0(p)),r(!0))});return()=>{l(),window.api.projectPages.unwatch(i)}},[i]),{output:e,loaded:n}}const bv={"general-behavior":{key:"general-behavior",label:"General behaviour",description:"Universal working-style rules for every Epic, independent of which Agent persona or Mission tag is chosen — the floor every session stands on, including Epics created before any persona resolved.",text:`Work concisely: lead with the answer or the result, skip preamble, and don't recap what you just did unless asked. Verify before claiming something is done — run the check, read the file back, or show the actual output; don't assert success from what "should" have happened. Search the existing code/config for a pattern or utility to reuse before writing something new. Ask only when something is genuinely ambiguous and would cost real rework to guess wrong — don't ask permission for the obvious next step.`},"delegate-implementation":{key:"delegate-implementation",label:"Delegate implementation",description:"Keeps this interactive session in a planning-and-deciding role and pushes actual implementation to the headless scheduler, independent of which Agent persona is chosen — the same floor as General behaviour, on by default for feature/bug work.",text:"This interactive session plans and decides; it does not implement. Once scope is clear, queue the implementation as scheduled PRDs via the /develop skill and let it run headless — do not edit application source inline in this conversation. If the scheduler tools are unavailable, say so explicitly rather than falling back to implementing the work yourself."}},BC=Object.keys(bv);function cd(i){return i.replace(/\r?\n/g," ")}function qP(i,e){const t=e.map(n=>`Reference: ${cd(n)}`);return t.length?`${i}
2926
2926
 
@@ -2936,7 +2936,7 @@ ${t.join(`
2936
2936
 
2937
2937
  ${m}`:m,T=g?`Goal: ${g}
2938
2938
 
2939
- ${m}`:m,E=[];if(r&&l&&E.push({kind:"actor",label:"Actor",text:`You are acting as the "${cd(r)}" agent: ${cd(l)}`,source:r}),p){const k=XP(p,a);k&&E.push({kind:"persona-body",label:"Persona notes",text:k,source:r})}for(const k of Object.keys(bv)){if(!(f!=null&&f[k]))continue;const y=bv[k];E.push({kind:"injection",label:y.label,text:y.text,source:k})}d&&E.push({kind:"input",label:"Input",text:cd(d)}),n&&E.push({kind:"mission",label:"Mission",text:IC(n).initialPromptTemplate,source:n}),E.push({kind:"goal",label:"Goal",text:T});for(const k of t)E.push({kind:"reference",label:"Reference",text:`Reference: ${cd(k)}`,source:k});return{goalText:qP(b,t),openingPrompt:YP(E),sections:E}}const Ly="project-home-builder",t0="project-home-builder",JP="Generate this project's Project Home page (one self-contained home.html).";function ZP(i,e){for(const t of Object.values(i))if(t.cwd===e&&t.tag===Ly&&t.status==="active")return t;return null}function i0(i){jv(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function QP(i){const e=ti(d=>d.sessions),t=ti(d=>d.createPromptSession),n=ti(d=>d.approveProposed),[r,l]=B.useState(null);B.useEffect(()=>{let d=!1;return window.api.agents.listPersonas().then(f=>{if(d)return;const g=f.find(m=>m.name===t0);l(g?{name:g.name,description:g.description}:null)}).catch(()=>{d||l(null)}),()=>{d=!0}},[]);const p=B.useMemo(()=>i?ZP(e,i):null,[e,i]),a=B.useCallback(async()=>{if(!i)return;if(p){i0(p.id);return}if(!r){$o.getState().show("error",`Cannot generate Project Home — the "${t0}" persona is not installed. Add it in the Agent Library (or re-run the seed step), then try again.`);return}let d;try{d=await window.api.app.delegationReadiness(i)}catch(b){$o.getState().show("error",`Cannot generate Project Home — could not check delegation readiness: ${b instanceof Error?b.message:String(b)}`);return}if(!d.ok){const b=d.checks.filter(T=>!T.ok).map(T=>T.label).join("; ");$o.getState().show("error",`Cannot generate Project Home — delegation isn't ready (${b||"unknown reason"}). Fix this in the New Epic readiness banner, then try again.`);return}const{goalText:f,openingPrompt:g}=Bv({title:"",goal:JP,tag:Ly,agentName:r.name,agentDescription:r.description??void 0}),m=await t(i,f,Ly,"ProjectHome",r.name);n(m.id,"ProjectHome"),pi.getState().send({tabId:m.id,sessionId:m.claudeSessionId,cwd:i,prompt:g}),i0(m.id)},[p,t,n,i,r]);return{existingBuilderEpic:p,generate:a}}function xh({title:i,hint:e}){return c.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:c.jsxs("div",{className:"text-center max-w-md",children:[c.jsx("div",{className:"mb-2 text-fg-dim",children:i}),e&&c.jsx("div",{className:"text-fg-faint",children:e})]})})}function eR(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);return t<60?`${t}m${(e%60).toString().padStart(2,"0")}s`:`${Math.floor(t/60)}h${(t%60).toString().padStart(2,"0")}m`}function UC(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60);return n<24?`${n}h${t%60?` ${t%60}m`:""}`:`${Math.floor(n/24)}d`}function QB(i){return new Date(i).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function rl(i,e){if(i===null)return"never";const t=e-i;return t<0?"soon":t<5e3?"just now":`${UC(t)} ago`}function e5(i){if(!i)return"";const e=Math.max(0,Date.now()-i);return e<6e4?`saved ${Math.round(e/1e3)}s ago`:e<36e5?`saved ${Math.round(e/6e4)}m ago`:`saved ${Math.round(e/36e5)}h ago`}function t5(i){if(!i)return"";const e=Date.now()-i;return e<5e3?"just now":`${UC(e)} ago`}function tR(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}h ${r}m`:`${n}h`}function iR({title:i,html:e}){return c.jsx("iframe",{title:i,sandbox:"allow-same-origin",srcDoc:e,style:{width:"100%",height:"100%",border:"none",display:"block"}})}const nR="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3.5 py-2 text-xs font-semibold text-bg-hi cursor-pointer hover:bg-accent-dark";function n0({label:i,onGenerate:e}){return c.jsxs("button",{type:"button",onClick:e,className:nR,children:[c.jsx("span",{className:"inline-flex",children:c.jsx(Vs,{name:"sparkle",size:14})}),i]})}function sR({output:i,loaded:e,onGenerate:t}){return e?i?c.jsxs("div",{children:[c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2.5",children:[c.jsxs("span",{className:"font-mono text-[10.5px] text-fg-faint",children:["generated ",rl(i.mtimeMs,Date.now())]}),c.jsx(n0,{label:"Regenerate",onGenerate:t})]}),c.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-bg-hi",style:{height:"calc(100vh - 200px)",minHeight:520},children:c.jsx(iR,{title:"Project Home",html:i.html})})]}):c.jsx("div",{className:"flex justify-center py-16",children:c.jsx(n0,{label:"Generate Project Home",onGenerate:t})}):null}function rR(){const i=St(d=>d.tabs),e=St(d=>d.activeTabId),t=i.find(d=>d.id===e),n=(t==null?void 0:t.cwd)??null,{output:r,loaded:l}=VP(n),{generate:p}=QP(n),a=()=>{p().catch(d=>{nt.error(d instanceof Error?d.message:String(d))})};return t?c.jsx("div",{className:"h-full overflow-auto",children:c.jsx("div",{className:"mx-auto max-w-[1080px] px-[34px] py-[26px] text-fg",children:c.jsx(sR,{output:r,loaded:l,onGenerate:a})})}):c.jsx(xh,{title:"Open a project to see its brief"})}const oR=B.memo(rR);function s0(i){return i.split("/").filter(Boolean).pop()||i}function aR(i,e){var r;const t=i.findIndex(l=>l.path===e);if(t===-1)return((r=i[0])==null?void 0:r.path)??null;const n=i.filter(l=>l.path!==e);return n.length===0?null:(n[t]??n[t-1]??n[0]).path}function sh(i,e){if(!(e in i))return i;const t={...i};return delete t[e],t}function jg(i,e,t){if(!(e in i))return i;const n={...i};return n[t]=n[e],delete n[e],n}const Oi=Un((i,e)=>({openFiles:[],activeFilePath:null,buffers:{},baselines:{},dirty:{},viewMode:{},pendingReveal:null,openFile:(t,n)=>{const{openFiles:r}=e(),l=r.some(p=>p.path===t);i({openFiles:l?r:[...r,{path:t,name:s0(t)}],activeFilePath:t,pendingReveal:(n==null?void 0:n.line)!=null?{path:t,line:n.line,col:n.col}:e().pendingReveal})},closeFile:t=>{const{openFiles:n,activeFilePath:r}=e(),l=r===t?aR(n,t):r;i({openFiles:n.filter(p=>p.path!==t),activeFilePath:l,dirty:sh(e().dirty,t),viewMode:sh(e().viewMode,t),buffers:sh(e().buffers,t),baselines:sh(e().baselines,t)})},closeOthers:t=>{const n=e().openFiles.find(l=>l.path===t),r=l=>n&&t in l?{[t]:l[t]}:{};i({openFiles:n?[n]:[],activeFilePath:n?t:null,dirty:r(e().dirty),viewMode:r(e().viewMode),buffers:r(e().buffers),baselines:r(e().baselines)})},closeToTheRight:t=>{const{openFiles:n,activeFilePath:r}=e(),l=n.findIndex(f=>f.path===t);if(l===-1)return;const p=n.slice(0,l+1),a=new Set(p.map(f=>f.path)),d=f=>Object.fromEntries(Object.entries(f).filter(([g])=>a.has(g)));i({openFiles:p,activeFilePath:r&&a.has(r)?r:t,dirty:d(e().dirty),viewMode:d(e().viewMode),buffers:d(e().buffers),baselines:d(e().baselines)})},closeAll:()=>i({openFiles:[],activeFilePath:null,dirty:{},viewMode:{},buffers:{},baselines:{}}),setActive:t=>i({activeFilePath:t}),loadBuffer:(t,n)=>i(r=>({buffers:{...r.buffers,[t]:n},baselines:{...r.baselines,[t]:n},dirty:r.dirty[t]?sh(r.dirty,t):r.dirty})),setBuffer:(t,n)=>i(r=>{const l=n!==(r.baselines[t]??n);return{buffers:{...r.buffers,[t]:n},dirty:r.dirty[t]===l?r.dirty:{...r.dirty,[t]:l}}}),markSaved:t=>i(n=>({baselines:{...n.baselines,[t]:n.buffers[t]??""},dirty:sh(n.dirty,t)})),hasBuffer:t=>t in e().buffers,setViewMode:(t,n)=>i(r=>({viewMode:{...r.viewMode,[t]:n}})),consumeReveal:t=>{const n=e().pendingReveal;return n&&n.path===t?(i({pendingReveal:null}),n):null},renameOpenFile:(t,n)=>{const{openFiles:r,activeFilePath:l}=e(),p=r.findIndex(d=>d.path===t);if(p===-1)return;const a=[...r];a[p]={path:n,name:s0(n)},i({openFiles:a,activeFilePath:l===t?n:l,buffers:jg(e().buffers,t,n),baselines:jg(e().baselines,t,n),dirty:jg(e().dirty,t,n),viewMode:jg(e().viewMode,t,n)})}})),lR=new Set(["md","mdx","markdown"]),cR=new Set(["html","htm"]),dR=new Set(["csv","tsv"]),uR=new Set(["jsonl","ndjson"]),GC=new Set(["png","jpg","jpeg","gif","svg","webp","ico","avif","bmp"]);function Mr(i){return i.toLowerCase().split(".").pop()||""}function Ja(i){return lR.has(Mr(i))}function HC(i){return cR.has(Mr(i))}function FC(i){return GC.has(Mr(i))}function WC(i){return Mr(i)==="pdf"}function VC(i){return dR.has(Mr(i))}function qC(i){return uR.has(Mr(i))}function KC(i){return Ja(i)||HC(i)||VC(i)||qC(i)}function hR(i){return Ja(i)}function pR(i){return KC(i)?"preview":"edit"}function Uv(i){const e=i.split("/").map(encodeURIComponent).join("/");return`smfile://local${e.startsWith("/")?"":"/"}${e}`}typeof window<"u"&&(window.__editor=Oi);const sv={fontSize:13,wordWrap:!1,minimap:!1,theme:"paper",autosave:!0,wideMeasure:!1,assistantRail:!0},XC="sm.editorPrefs.v1",r0=9,o0=28;function fR(){try{const i=localStorage.getItem(XC);if(!i)return sv;const e=JSON.parse(i);return{...sv,...e}}catch{return sv}}function mR(i){try{localStorage.setItem(XC,JSON.stringify(i))}catch{}}const dh=Un((i,e)=>{const t=n=>{const r={fontSize:e().fontSize,wordWrap:e().wordWrap,minimap:e().minimap,theme:e().theme,autosave:e().autosave,wideMeasure:e().wideMeasure,assistantRail:e().assistantRail,...n};mR(r),i(n)};return{...fR(),setFontSize:n=>t({fontSize:Math.max(r0,Math.min(o0,Math.round(n)))}),bumpFontSize:n=>t({fontSize:Math.max(r0,Math.min(o0,e().fontSize+n))}),resetFontSize:()=>t({fontSize:sv.fontSize}),toggleWordWrap:()=>t({wordWrap:!e().wordWrap}),toggleMinimap:()=>t({minimap:!e().minimap}),setTheme:n=>t({theme:n}),toggleAutosave:()=>t({autosave:!e().autosave}),toggleWideMeasure:()=>t({wideMeasure:!e().wideMeasure}),toggleAssistantRail:()=>t({assistantRail:!e().assistantRail})}});function gR({openFiles:i,activeFilePath:e,dirty:t,onSelectFile:n,onCloseFile:r,onCloseOthers:l,onCloseToTheRight:p,onCloseAll:a}){const[d,f]=B.useState(null),g=B.useRef(null),m=vb();B.useEffect(()=>{if(!d)return;const E=y=>{g.current&&!g.current.contains(y.target)&&f(null)},k=y=>{m.current&&y.key==="Escape"&&f(null)};return document.addEventListener("mousedown",E),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",E),document.removeEventListener("keydown",k)}},[d]);const b=B.useCallback((E,k)=>{E.preventDefault(),f({x:E.clientX,y:E.clientY,path:k})},[]),T=B.useCallback((E,k)=>{E.button===1&&(E.preventDefault(),r(k))},[r]);return i.length===0?null:c.jsxs("div",{className:"relative shrink-0",children:[c.jsx("div",{className:"flex items-center gap-0.5 px-2 py-1 bg-bg-elev border-b border-line overflow-x-auto",children:i.map(E=>{const k=E.path===e;return c.jsxs("div",{onClick:()=>n(E.path),onMouseDown:y=>T(y,E.path),onContextMenu:y=>b(y,E.path),className:`
2939
+ ${m}`:m,E=[];if(r&&l&&E.push({kind:"actor",label:"Actor",text:`You are acting as the "${cd(r)}" agent: ${cd(l)}`,source:r}),p){const k=XP(p,a);k&&E.push({kind:"persona-body",label:"Persona notes",text:k,source:r})}for(const k of Object.keys(bv)){if(!(f!=null&&f[k]))continue;const y=bv[k];E.push({kind:"injection",label:y.label,text:y.text,source:k})}d&&E.push({kind:"input",label:"Input",text:cd(d)}),n&&E.push({kind:"mission",label:"Mission",text:IC(n).initialPromptTemplate,source:n}),E.push({kind:"goal",label:"Goal",text:T});for(const k of t)E.push({kind:"reference",label:"Reference",text:`Reference: ${cd(k)}`,source:k});return{goalText:qP(b,t),openingPrompt:YP(E),sections:E}}const Ly="project-home-builder",t0="project-home-builder",JP="Generate this project's Project Home page (one self-contained home.html).";function ZP(i,e){for(const t of Object.values(i))if(t.cwd===e&&t.tag===Ly&&t.status==="active")return t;return null}function i0(i){jv(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function QP(i){const e=ti(d=>d.sessions),t=ti(d=>d.createPromptSession),n=ti(d=>d.approveProposed),[r,l]=B.useState(null);B.useEffect(()=>{let d=!1;return window.api.agents.listPersonas().then(f=>{if(d)return;const g=f.find(m=>m.name===t0);l(g?{name:g.name,description:g.description}:null)}).catch(()=>{d||l(null)}),()=>{d=!0}},[]);const p=B.useMemo(()=>i?ZP(e,i):null,[e,i]),a=B.useCallback(async()=>{if(!i)return;if(p){i0(p.id);return}if(!r){$o.getState().show("error",`Cannot generate Project Home — the "${t0}" persona is not installed. Add it in the Agent Library (or re-run the seed step), then try again.`);return}let d;try{d=await window.api.app.delegationReadiness(i)}catch(b){$o.getState().show("error",`Cannot generate Project Home — could not check delegation readiness: ${b instanceof Error?b.message:String(b)}`);return}if(!d.ok){const b=d.checks.filter(T=>!T.ok).map(T=>T.label).join("; ");$o.getState().show("error",`Cannot generate Project Home — delegation isn't ready (${b||"unknown reason"}). Fix this in the New Epic readiness banner, then try again.`);return}const{goalText:f,openingPrompt:g}=Bv({title:"",goal:JP,tag:Ly,agentName:r.name,agentDescription:r.description??void 0}),m=await t(i,f,Ly,"ProjectHome",r.name);n(m.id,"ProjectHome"),pi.getState().send({tabId:m.id,sessionId:m.claudeSessionId,cwd:i,prompt:g}),i0(m.id)},[p,t,n,i,r]);return{existingBuilderEpic:p,generate:a}}function xh({title:i,hint:e}){return c.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:c.jsxs("div",{className:"text-center max-w-md",children:[c.jsx("div",{className:"mb-2 text-fg-dim",children:i}),e&&c.jsx("div",{className:"text-fg-faint",children:e})]})})}function eR(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);return t<60?`${t}m${(e%60).toString().padStart(2,"0")}s`:`${Math.floor(t/60)}h${(t%60).toString().padStart(2,"0")}m`}function UC(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60);return n<24?`${n}h${t%60?` ${t%60}m`:""}`:`${Math.floor(n/24)}d`}function e5(i){return new Date(i).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function rl(i,e){if(i===null)return"never";const t=e-i;return t<0?"soon":t<5e3?"just now":`${UC(t)} ago`}function t5(i){if(!i)return"";const e=Math.max(0,Date.now()-i);return e<6e4?`saved ${Math.round(e/1e3)}s ago`:e<36e5?`saved ${Math.round(e/6e4)}m ago`:`saved ${Math.round(e/36e5)}h ago`}function i5(i){if(!i)return"";const e=Date.now()-i;return e<5e3?"just now":`${UC(e)} ago`}function tR(i){i<0&&(i=0);const e=Math.floor(i/1e3);if(e<60)return`${e}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),r=t%60;return r>0?`${n}h ${r}m`:`${n}h`}function iR({title:i,html:e}){return c.jsx("iframe",{title:i,sandbox:"allow-same-origin",srcDoc:e,style:{width:"100%",height:"100%",border:"none",display:"block"}})}const nR="inline-flex items-center gap-1.5 rounded-lg bg-accent px-3.5 py-2 text-xs font-semibold text-bg-hi cursor-pointer hover:bg-accent-dark";function n0({label:i,onGenerate:e}){return c.jsxs("button",{type:"button",onClick:e,className:nR,children:[c.jsx("span",{className:"inline-flex",children:c.jsx(Vs,{name:"sparkle",size:14})}),i]})}function sR({output:i,loaded:e,onGenerate:t}){return e?i?c.jsxs("div",{children:[c.jsxs("div",{className:"mb-2 flex items-center justify-end gap-2.5",children:[c.jsxs("span",{className:"font-mono text-[10.5px] text-fg-faint",children:["generated ",rl(i.mtimeMs,Date.now())]}),c.jsx(n0,{label:"Regenerate",onGenerate:t})]}),c.jsx("div",{className:"overflow-hidden rounded-xl border border-line bg-bg-hi",style:{height:"calc(100vh - 200px)",minHeight:520},children:c.jsx(iR,{title:"Project Home",html:i.html})})]}):c.jsx("div",{className:"flex justify-center py-16",children:c.jsx(n0,{label:"Generate Project Home",onGenerate:t})}):null}function rR(){const i=St(d=>d.tabs),e=St(d=>d.activeTabId),t=i.find(d=>d.id===e),n=(t==null?void 0:t.cwd)??null,{output:r,loaded:l}=VP(n),{generate:p}=QP(n),a=()=>{p().catch(d=>{nt.error(d instanceof Error?d.message:String(d))})};return t?c.jsx("div",{className:"h-full overflow-auto",children:c.jsx("div",{className:"mx-auto max-w-[1080px] px-[34px] py-[26px] text-fg",children:c.jsx(sR,{output:r,loaded:l,onGenerate:a})})}):c.jsx(xh,{title:"Open a project to see its brief"})}const oR=B.memo(rR);function s0(i){return i.split("/").filter(Boolean).pop()||i}function aR(i,e){var r;const t=i.findIndex(l=>l.path===e);if(t===-1)return((r=i[0])==null?void 0:r.path)??null;const n=i.filter(l=>l.path!==e);return n.length===0?null:(n[t]??n[t-1]??n[0]).path}function sh(i,e){if(!(e in i))return i;const t={...i};return delete t[e],t}function jg(i,e,t){if(!(e in i))return i;const n={...i};return n[t]=n[e],delete n[e],n}const Oi=Un((i,e)=>({openFiles:[],activeFilePath:null,buffers:{},baselines:{},dirty:{},viewMode:{},pendingReveal:null,openFile:(t,n)=>{const{openFiles:r}=e(),l=r.some(p=>p.path===t);i({openFiles:l?r:[...r,{path:t,name:s0(t)}],activeFilePath:t,pendingReveal:(n==null?void 0:n.line)!=null?{path:t,line:n.line,col:n.col}:e().pendingReveal})},closeFile:t=>{const{openFiles:n,activeFilePath:r}=e(),l=r===t?aR(n,t):r;i({openFiles:n.filter(p=>p.path!==t),activeFilePath:l,dirty:sh(e().dirty,t),viewMode:sh(e().viewMode,t),buffers:sh(e().buffers,t),baselines:sh(e().baselines,t)})},closeOthers:t=>{const n=e().openFiles.find(l=>l.path===t),r=l=>n&&t in l?{[t]:l[t]}:{};i({openFiles:n?[n]:[],activeFilePath:n?t:null,dirty:r(e().dirty),viewMode:r(e().viewMode),buffers:r(e().buffers),baselines:r(e().baselines)})},closeToTheRight:t=>{const{openFiles:n,activeFilePath:r}=e(),l=n.findIndex(f=>f.path===t);if(l===-1)return;const p=n.slice(0,l+1),a=new Set(p.map(f=>f.path)),d=f=>Object.fromEntries(Object.entries(f).filter(([g])=>a.has(g)));i({openFiles:p,activeFilePath:r&&a.has(r)?r:t,dirty:d(e().dirty),viewMode:d(e().viewMode),buffers:d(e().buffers),baselines:d(e().baselines)})},closeAll:()=>i({openFiles:[],activeFilePath:null,dirty:{},viewMode:{},buffers:{},baselines:{}}),setActive:t=>i({activeFilePath:t}),loadBuffer:(t,n)=>i(r=>({buffers:{...r.buffers,[t]:n},baselines:{...r.baselines,[t]:n},dirty:r.dirty[t]?sh(r.dirty,t):r.dirty})),setBuffer:(t,n)=>i(r=>{const l=n!==(r.baselines[t]??n);return{buffers:{...r.buffers,[t]:n},dirty:r.dirty[t]===l?r.dirty:{...r.dirty,[t]:l}}}),markSaved:t=>i(n=>({baselines:{...n.baselines,[t]:n.buffers[t]??""},dirty:sh(n.dirty,t)})),hasBuffer:t=>t in e().buffers,setViewMode:(t,n)=>i(r=>({viewMode:{...r.viewMode,[t]:n}})),consumeReveal:t=>{const n=e().pendingReveal;return n&&n.path===t?(i({pendingReveal:null}),n):null},renameOpenFile:(t,n)=>{const{openFiles:r,activeFilePath:l}=e(),p=r.findIndex(d=>d.path===t);if(p===-1)return;const a=[...r];a[p]={path:n,name:s0(n)},i({openFiles:a,activeFilePath:l===t?n:l,buffers:jg(e().buffers,t,n),baselines:jg(e().baselines,t,n),dirty:jg(e().dirty,t,n),viewMode:jg(e().viewMode,t,n)})}})),lR=new Set(["md","mdx","markdown"]),cR=new Set(["html","htm"]),dR=new Set(["csv","tsv"]),uR=new Set(["jsonl","ndjson"]),GC=new Set(["png","jpg","jpeg","gif","svg","webp","ico","avif","bmp"]);function Mr(i){return i.toLowerCase().split(".").pop()||""}function Ja(i){return lR.has(Mr(i))}function HC(i){return cR.has(Mr(i))}function FC(i){return GC.has(Mr(i))}function WC(i){return Mr(i)==="pdf"}function VC(i){return dR.has(Mr(i))}function qC(i){return uR.has(Mr(i))}function KC(i){return Ja(i)||HC(i)||VC(i)||qC(i)}function hR(i){return Ja(i)}function pR(i){return KC(i)?"preview":"edit"}function Uv(i){const e=i.split("/").map(encodeURIComponent).join("/");return`smfile://local${e.startsWith("/")?"":"/"}${e}`}typeof window<"u"&&(window.__editor=Oi);const sv={fontSize:13,wordWrap:!1,minimap:!1,theme:"paper",autosave:!0,wideMeasure:!1,assistantRail:!0},XC="sm.editorPrefs.v1",r0=9,o0=28;function fR(){try{const i=localStorage.getItem(XC);if(!i)return sv;const e=JSON.parse(i);return{...sv,...e}}catch{return sv}}function mR(i){try{localStorage.setItem(XC,JSON.stringify(i))}catch{}}const dh=Un((i,e)=>{const t=n=>{const r={fontSize:e().fontSize,wordWrap:e().wordWrap,minimap:e().minimap,theme:e().theme,autosave:e().autosave,wideMeasure:e().wideMeasure,assistantRail:e().assistantRail,...n};mR(r),i(n)};return{...fR(),setFontSize:n=>t({fontSize:Math.max(r0,Math.min(o0,Math.round(n)))}),bumpFontSize:n=>t({fontSize:Math.max(r0,Math.min(o0,e().fontSize+n))}),resetFontSize:()=>t({fontSize:sv.fontSize}),toggleWordWrap:()=>t({wordWrap:!e().wordWrap}),toggleMinimap:()=>t({minimap:!e().minimap}),setTheme:n=>t({theme:n}),toggleAutosave:()=>t({autosave:!e().autosave}),toggleWideMeasure:()=>t({wideMeasure:!e().wideMeasure}),toggleAssistantRail:()=>t({assistantRail:!e().assistantRail})}});function gR({openFiles:i,activeFilePath:e,dirty:t,onSelectFile:n,onCloseFile:r,onCloseOthers:l,onCloseToTheRight:p,onCloseAll:a}){const[d,f]=B.useState(null),g=B.useRef(null),m=vb();B.useEffect(()=>{if(!d)return;const E=y=>{g.current&&!g.current.contains(y.target)&&f(null)},k=y=>{m.current&&y.key==="Escape"&&f(null)};return document.addEventListener("mousedown",E),document.addEventListener("keydown",k),()=>{document.removeEventListener("mousedown",E),document.removeEventListener("keydown",k)}},[d]);const b=B.useCallback((E,k)=>{E.preventDefault(),f({x:E.clientX,y:E.clientY,path:k})},[]),T=B.useCallback((E,k)=>{E.button===1&&(E.preventDefault(),r(k))},[r]);return i.length===0?null:c.jsxs("div",{className:"relative shrink-0",children:[c.jsx("div",{className:"flex items-center gap-0.5 px-2 py-1 bg-bg-elev border-b border-line overflow-x-auto",children:i.map(E=>{const k=E.path===e;return c.jsxs("div",{onClick:()=>n(E.path),onMouseDown:y=>T(y,E.path),onContextMenu:y=>b(y,E.path),className:`
2940
2940
  group flex items-center gap-2 px-2 py-1 rounded text-xs cursor-pointer select-none shrink-0 max-w-[200px]
2941
2941
  ${k?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi/60"}
2942
2942
  `,children:[c.jsx("span",{className:"truncate",children:E.name}),c.jsx("button",{onClick:y=>{y.stopPropagation(),r(E.path)},className:`
@@ -3024,7 +3024,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
3024
3024
 
3025
3025
  ${t}`}const Nf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},c$=["popover","review","diff"],_E=["popover","review"];function d$(i,e){switch(e.type){case"SELECT":return{...Nf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Nf,editCount:i.editCount};case"LISTEN":return _E.includes(i.phase)?{...i,phase:"listening",transcript:"",modelStatus:null}:i;case"HEARD":return i.phase!=="listening"?i:{...i,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return c$.includes(i.phase)?{...i,phase:"thinking",instruction:e.recordInstruction?e.instruction:i.instruction}:i;case"RUN_OK":return i.phase!=="thinking"?i:{...i,phase:"diff",diff:e.diff};case"RUN_ERR":return i.phase!=="thinking"?i:{...i,phase:"popover",transcript:"",diff:null};case"ACCEPT":return i.phase!=="diff"?i:{...Nf,editCount:i.editCount+1};case"RESET_FILE":return{...Nf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function u$(i,e){let t=null;for(const n of e){const r=n.cwd;!r||!(i===r||i.startsWith(r.endsWith("/")?r:`${r}/`))||(t===null||r.length>t.length)&&(t=r)}return t}function h$(i,e,t){var l;let n=null,r=-1/0;for(const p of e){if(p.cwd!==i||p.status!=="dormant")continue;const a=((l=t[p.id])==null?void 0:l.lastEventAt)??0;(n===null||a>r)&&(n=p,r=a)}return n}const p$="sonnet";function f$(i,e){const[t,n]=B.useReducer(d$,Nf),r=B.useRef(0),l=B.useRef(null),p=B.useRef(i),a=B.useRef(new Map);B.useEffect(()=>window.api.docEdit.onSessionResult(x=>{const A=a.current.get(x.requestId);A&&(a.current.delete(x.requestId),A(x))}),[]),B.useEffect(()=>{p.current!==i&&(p.current=i,r.current+=1,d(),n({type:"RESET_FILE"}))},[i]);function d(){const x=l.current;x&&(l.current=null,x.stop().catch(()=>{}),x.destroy(),Ct.setState({externalRecording:!1}))}const f=B.useCallback(x=>{r.current+=1,d(),n({type:"SELECT",selection:x})},[]),g=B.useCallback(()=>{r.current+=1,d(),n({type:"CANCEL"})},[]),m=B.useCallback(()=>{if(!_E.includes(t.phase))return;if(Ct.getState().isRecording){nt.error("Microphone is already in use");return}if(!Rv()){nt.error("Microphone or Web Worker not available");return}const x=++r.current;n({type:"LISTEN"}),Ct.setState({externalRecording:!0});const A=()=>{l.current===O&&(l.current=null),Ct.setState({externalRecording:!1})},O=I1({onFinal:$=>{if(r.current!==x)return;O.stop().catch(()=>{}),O.destroy(),A();const j=$.trim();if(!j){n({type:"CANCEL"});return}n({type:"HEARD",transcript:j})},onError:$=>{r.current===x&&(O.destroy(),A(),nt.error(`Microphone error: ${$}`),n({type:"CANCEL"}))},onModelStatus:($,j)=>{r.current===x&&n({type:"MODEL_STATUS",status:$,message:j})},onProgress:$=>{r.current===x&&n({type:"MODEL_STATUS",status:"loading",message:`${$}%`})}});l.current=O,O.start().catch($=>{r.current===x&&(O.destroy(),A(),nt.error(`Could not start mic: ${$ instanceof Error?$.message:String($)}`),n({type:"CANCEL"}))})},[t.phase]),b=B.useCallback(()=>{const x=u$(i,St.getState().tabs);if(!x)return null;const A=h$(x,St.getState().tabs,nv.getState().tabs);return!A||pi.getState().get(A.id).running?null:A},[i]),T=B.useCallback((x,A,O,$,j,L)=>{const G=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(W=>{a.current.set(G,W),window.api.docEdit.runInSession({tabId:x,sessionId:A,cwd:O,before:$,instruction:j,documentText:L,requestId:G})})},[]),E=B.useCallback(async(x,A)=>{const O=t.selection;if(!O)return;const $=++r.current;n({type:"RUN",instruction:x,recordInstruction:A});const j=l$(e);try{const L=b(),G=L?await T(L.id,L.sessionId,L.cwd,O.text,x,j):await window.api.docEdit.run({path:i,before:O.text,instruction:x,documentText:j});if(r.current!==$)return;if(!G.ok){nt.error(G.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:O.text,after:G.after??""}})}catch(L){if(r.current!==$)return;nt.error(L instanceof Error?L.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,b,T]),k=B.useCallback(x=>{E(x,!0)},[E]),y=B.useCallback(()=>{t.phase==="review"&&E(t.transcript,!0)},[E,t.phase,t.transcript]),S=B.useCallback(()=>{const x=t.instruction;x&&E(`${x}
3026
3026
 
3027
- (Give a different rewrite than the last one.)`,!1)},[E,t.instruction]),w=B.useCallback(x=>{const A=t.diff;if(!A)return{ok:!1,reason:"not-found"};const O=o$(x,A.before,A.after);return O.ok?(r.current+=1,n({type:"ACCEPT"})):nt.error(O.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),O},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:y,run:k,retry:S,accept:w}}const m$=[{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."}],j0=320,Ef=8;function g$(){return c.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function v$(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Ef),Math.max(Ef,e-j0-Ef)),n=Math.max(i.top-Ef,Ef);return{position:"fixed",left:t,top:n,width:j0,transform:"translateY(-100%)",zIndex:XD.dialog}}function _$({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:g,onReject:m,onRetry:b}){const[T,E]=B.useState(""),k=()=>{const y=T.trim();y&&(p(y),E(""))};return c.jsxs("div",{"data-doc-edit-popover":!0,style:v$(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&c.jsxs("div",{className:"p-2",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2",children:[c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{onClick:a,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),m$.map(y=>c.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),c.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),c.jsx("input",{autoFocus:!0,value:T,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?k():y.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&c.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[c.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(g$,{}),"Listening…"]}),r&&c.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),c.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&c.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[c.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),c.jsxs("div",{className:"flex justify-end gap-1.5",children:[c.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),c.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&c.jsxs("div",{className:"p-3 flex items-center justify-between",children:[c.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),c.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&c.jsxs("div",{className:"p-3",children:[c.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[c.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),c.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),c.jsxs("div",{className:"flex justify-end gap-1.5",children:[c.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),c.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),c.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function y$(){return c.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function z0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:g}){return c.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[c.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),c.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zf(p$)})]}),c.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&c.jsxs("div",{className:"text-fg-faint",children:[c.jsx("p",{children:"Select text in the doc…"}),c.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&c.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&c.jsxs("div",{children:[c.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[c.jsx(y$,{}),"Listening…"]}),r&&c.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),c.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&c.jsxs("div",{children:[c.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),c.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&c.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&c.jsxs("div",{children:[c.jsxs("div",{className:"mb-3 space-y-2",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),c.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),c.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),c.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),c.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function b$(){const i=St(t=>t.tabs),e=St(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function B0(i){return i.split("/").filter(Boolean).pop()||i}function w$({path:i,onRenamed:e,onDeleted:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(!1),[a,d]=B.useState(""),[f,g]=B.useState(!1),m=Oi(W=>W.buffers[i]),b=Oi(W=>W.openFile),T=Oi(W=>W.renameOpenFile),E=Oi(W=>W.closeFile),k=b$(),y=B0(i),S=()=>r(!1),w=()=>{d(y),p(!0),S()},x=async()=>{const W=a.trim();if(!W||W===y){p(!1);return}try{const re=await window.api.files.rename(i,W);if(re.ok){const ae=i.slice(0,i.lastIndexOf("/")),Z=re.newPath??`${ae}/${W}`;T(i,Z),e==null||e(i,Z),nt.info(`Renamed to ${W}`)}else nt.error(re.error??`Couldn't rename ${y}`)}catch(re){nt.error(re instanceof Error?re.message:`Couldn't rename ${y}`)}p(!1)},A=async()=>{S();try{const W=await window.api.files.duplicate(i);W.ok&&W.path?(b(W.path),nt.info(`Duplicated as ${B0(W.path)}`)):nt.error(W.error??`Couldn't duplicate ${y}`)}catch(W){nt.error(W instanceof Error?W.message:`Couldn't duplicate ${y}`)}},O=async()=>{try{const W=await window.api.files.delete(i);W.ok?(E(i),t==null||t(i),nt.info(`Deleted ${y}`)):nt.error(W.error??`Couldn't delete ${y}`)}catch(W){nt.error(W instanceof Error?W.message:`Couldn't delete ${y}`)}g(!1)},$=async()=>{S();const W=m??"";try{await navigator.clipboard.writeText(W),nt.info(`Copied ${W.length} chars`)}catch(re){nt.error(re instanceof Error?re.message:`Couldn't copy ${y}`)}},j=()=>{if(S(),!k){nt.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${i} `}),nt.info(`Added ${y} to Claude context`)},L=()=>{S(),window.api.shell.open({as:"openPath",path:i}).then(W=>{W.ok||nt.error(W.error??`Couldn't open ${y}`)}).catch(W=>nt.error(W instanceof Error?W.message:`Couldn't open ${y}`))},G=()=>{S(),window.api.shell.open({as:"revealPath",path:i}).then(W=>{W.ok||nt.error(W.error??`Couldn't reveal ${y}`)}).catch(W=>nt.error(W instanceof Error?W.message:`Couldn't reveal ${y}`))};return c.jsxs("div",{className:"relative inline-block mr-1",children:[c.jsx("button",{onClick:()=>r(W=>!W),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:S}),c.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[c.jsx(L_,{children:"Edit"}),c.jsx(rd,{label:"Rename",onClick:w}),c.jsx(rd,{label:"Duplicate",onClick:A}),c.jsx(rd,{label:"Delete document",danger:!0,onClick:()=>{S(),g(!0)}}),c.jsx(U0,{}),c.jsx(L_,{children:"Open"}),c.jsx(rd,{label:"Open in default app",onClick:L}),c.jsx(rd,{label:"Reveal in OS",onClick:G}),c.jsx(U0,{}),c.jsx(L_,{children:"Export"}),c.jsx(rd,{label:"Copy as Markdown",onClick:$}),c.jsx(rd,{label:"Add to Claude context",onClick:j,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),l&&c.jsx(x$,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&c.jsx(S$,{name:y,onCancel:()=>g(!1),onConfirm:()=>void O()})]})}function L_({children:i}){return c.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function rd({label:i,onClick:e,danger:t,disabled:n,title:r}){return c.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function U0(){return c.jsx("div",{className:"my-1 border-t border-line"})}function x$({value:i,onChange:e,onCancel:t,onConfirm:n}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),c.jsx("input",{autoFocus:!0,value:i,onChange:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function S$({name:i,onCancel:e,onConfirm:t}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function C$(){const[i,e]=B.useState(!1),t=dh();return c.jsxs("div",{className:"relative inline-block mr-1",children:[c.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),c.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[c.jsx(oh,{label:"Text size",children:c.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[c.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−"}),c.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),c.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+"})]})}),c.jsx(oh,{label:"Word wrap",children:c.jsx(Hg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),c.jsx(oh,{label:"Minimap",children:c.jsx(Hg,{on:t.minimap,onClick:t.toggleMinimap})}),c.jsx(oh,{label:"Theme",children:c.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"})}),c.jsx(oh,{label:"Autosave",children:c.jsx(Hg,{on:t.autosave,onClick:t.toggleAutosave})}),c.jsx(oh,{label:"Wide measure",children:c.jsx(Hg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function oh({label:i,children:e}){return c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Hg({on:i,onClick:e}){return c.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const E$=B.lazy(()=>Bn(()=>import("./TiptapBody-DGzSg3BO.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Fg(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Vg(i){return FC(i)||WC(i)}function k$(){const i=vb(),e=Oi(Ye=>Ye.openFiles),t=Oi(Ye=>Ye.activeFilePath),n=Oi(Ye=>Ye.dirty),r=Oi(Ye=>Ye.viewMode),l=Oi(Ye=>Ye.buffers),p=Oi(Ye=>Ye.setActive),a=Oi(Ye=>Ye.closeFile),d=Oi(Ye=>Ye.closeOthers),f=Oi(Ye=>Ye.closeToTheRight),g=Oi(Ye=>Ye.closeAll),m=Oi(Ye=>Ye.loadBuffer),b=Oi(Ye=>Ye.setBuffer),T=Oi(Ye=>Ye.markSaved),E=Oi(Ye=>Ye.setViewMode),k=dh(),[y,S]=B.useState({}),[w,x]=B.useState({}),[A,O]=B.useState(null),[$,j]=B.useState(null),[L,G]=B.useState(!1),[W,re]=B.useState(!1),[ae,Z]=B.useState(!0),pe=B.useRef(null),oe=B.useRef(null),me=B.useRef(void 0),we=B.useRef(null),ve=B.useRef(null),F=f$(t??"",l[t??""]??""),J=B.useCallback(Ye=>{pe.current=Ye},[]),V=B.useCallback(()=>pe.current,[]);B.useEffect(()=>{const Ye=t;if(!Ye||Vg(Ye))return;if(Oi.getState().hasBuffer(Ye)){S(ht=>ht[Ye]==="ready"?ht:{...ht,[Ye]:"ready"});return}let yt=!1;return S(ht=>({...ht,[Ye]:"loading"})),window.api.files.read(Ye).then(ht=>{yt||(ht.binary?S(ke=>({...ke,[Ye]:{binary:!0,size:ht.size??0,mime:ht.mime??"application/octet-stream",reason:ht.error??"Binary file"}})):ht.ok?(m(Ye,ht.text),S(ke=>({...ke,[Ye]:"ready"}))):S(ke=>({...ke,[Ye]:{error:ht.error??"failed to read"}})))}),()=>{yt=!0}},[t,m]),B.useEffect(()=>{j(null)},[t]);const se=B.useCallback(async(Ye,yt=!1)=>{const ht=Oi.getState().buffers[Ye];if(ht==null)return;yt&&G(!0);const ke=await window.api.files.write(Ye,ht);ke.ok?(T(Ye),x(tt=>({...tt,[Ye]:(tt[Ye]??0)+1})),yt||nt.info(`Saved ${Fg(Ye)}`)):nt.error(ke.error??`Couldn't save ${Fg(Ye)}`),yt&&G(!1)},[T]);B.useEffect(()=>{if(!k.autosave)return;const Ye=t;if(!(!Ye||Vg(Ye)||!n[Ye]))return window.clearTimeout(me.current),me.current=window.setTimeout(()=>{se(Ye,!0)},1200),()=>window.clearTimeout(me.current)},[k.autosave,t,n,l,se]);const ge=B.useCallback(Ye=>{Ye.length&&(S(yt=>Wg(yt,Ye)),x(yt=>Wg(yt,Ye)))},[]),Te=B.useCallback((Ye,yt)=>{S(ht=>Ye in ht?{...Wg(ht,[Ye]),[yt]:ht[Ye]}:ht),x(ht=>Ye in ht?{...Wg(ht,[Ye]),[yt]:ht[Ye]}:ht)},[]),je=B.useCallback(Ye=>{n[Ye]?O({kind:"one",path:Ye}):(a(Ye),ge([Ye]))},[n,a,ge]),Ze=B.useCallback(Ye=>{e.some(ht=>ht.path!==Ye&&n[ht.path])?O({kind:"others",path:Ye}):(d(Ye),ge(e.filter(ht=>ht.path!==Ye).map(ht=>ht.path)))},[e,n,d,ge]),ye=B.useCallback(Ye=>{const yt=e.findIndex(ke=>ke.path===Ye);yt!==-1&&e.slice(yt+1).some(ke=>n[ke.path])?O({kind:"right",path:Ye}):(f(Ye),ge(yt!==-1?e.slice(yt+1).map(ke=>ke.path):[]))},[e,n,f,ge]);B.useEffect(()=>{const Ye=yt=>{if(i.current)if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const ht=Oi.getState().activeFilePath;ht&&!Vg(ht)&&(yt.preventDefault(),se(ht))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),re(ht=>!ht);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const ht=Oi.getState().activeFilePath;ht&&Oi.getState().openFiles.length>1&&(yt.preventDefault(),Ze(ht))}else yt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():yt.key==="Escape"&&W&&re(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[se,W,Ze,F.state.phase,F.cancel]),B.useEffect(()=>{if(F.state.phase==="idle")return;const Ye=yt=>{var ke,tt;const ht=yt.target;(ke=ve.current)!=null&&ke.contains(ht)||(tt=we.current)!=null&&tt.contains(ht)||F.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[F.state.phase,F.cancel]),B.useEffect(()=>{F.cancel()},[t,F.cancel]);const Y=B.useCallback(()=>{e.some(yt=>n[yt.path])?O({kind:"all",path:""}):(g(),S({}),x({}))},[e,n,g]),_e=()=>{if(A){if(A.kind==="one")a(A.path),ge([A.path]);else if(A.kind==="others"){const Ye=e.filter(yt=>yt.path!==A.path).map(yt=>yt.path);d(A.path),ge(Ye)}else if(A.kind==="right"){const Ye=e.findIndex(ht=>ht.path===A.path),yt=Ye!==-1?e.slice(Ye+1).map(ht=>ht.path):[];f(A.path),ge(yt)}else g(),S({}),x({});O(null)}};if(e.length===0)return c.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:"mb-2",children:"no file open"}),c.jsxs("div",{children:["open the ",c.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const ue=t,Re=ue?Fg(ue):"",He=ue?y[ue]:void 0,lt=ue?KC(ue):!1,It=ue?hR(ue):!1,ct=ue&&lt?r[ue]??pR(ue):"edit",qt=!!ue&&!Vg(ue)&&He==="ready",qe=qt,Rt=It?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],_t=ue&&c.jsx(DO,{path:ue,name:Re,value:l[ue]??"",onChange:Ye=>b(ue,Ye),onSave:()=>void se(ue),onReady:J,onCursor:j}),ni=L?"Saving…":ue&&n[ue]?k.autosave?"Editing…":"Unsaved":"All changes saved";return c.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!W&&c.jsx(gR,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:je,onCloseOthers:Ze,onCloseToTheRight:ye,onCloseAll:Y}),ue&&!W&&c.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[c.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Re}),c.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ue}),qt&&c.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ni]}),Ja(ue)&&(ct==="preview"||ct==="split")&&c.jsx("button",{onClick:()=>Z(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${ae?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ja(ue)&&(ct==="preview"||ct==="split")&&c.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Rt.length>0&&c.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Rt.map(Ye=>c.jsx("button",{onClick:()=>E(ue,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ct===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),c.jsx("div",{className:"flex-1"}),c.jsx(w$,{path:ue,onRenamed:Te,onDeleted:Ye=>ge([Ye])}),qt&&c.jsx(C$,{}),c.jsx("button",{onClick:()=>re(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),W&&c.jsx("button",{onClick:()=>re(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),c.jsx("div",{className:"flex-1 min-h-0",children:ue?FC(ue)?c.jsx(JL,{path:ue,name:Re}):WC(ue)?c.jsx(ZL,{path:ue}):He&&typeof He=="object"&&"binary"in He?c.jsx(r$,{path:ue,name:Re,size:He.size,mime:He.mime,reason:He.reason}):He&&typeof He=="object"&&"error"in He?c.jsx("div",{className:"p-6 text-xs text-red-400",children:He.error}):He!=="ready"?c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ct==="wysiwyg"&&Ja(ue)?c.jsx(B.Suspense,{fallback:c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:c.jsx(E$,{value:l[ue]??"",onChange:Ye=>b(ue,Ye)},ue)}):ct==="split"&&Ja(ue)?c.jsxs("div",{className:"flex h-full",children:[ae&&c.jsx($0,{text:l[ue]??"",scrollRef:oe}),c.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[c.jsx(L0,{getEditor:V}),c.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),c.jsx("div",{ref:we,className:"flex-1 min-w-0",children:c.jsx(jy,{ref:oe,text:l[ue]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!W&&k.assistantRail&&c.jsx(z0,{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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)},onReject:F.cancel,onRetry:F.retry})]}):ct==="preview"&&Ja(ue)?c.jsxs("div",{className:"flex h-full",children:[ae&&c.jsx($0,{text:l[ue]??"",scrollRef:oe}),c.jsx("div",{ref:we,className:"flex-1 min-w-0",children:c.jsx(jy,{ref:oe,text:l[ue]??"",wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!W&&k.assistantRail&&c.jsx(z0,{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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)},onReject:F.cancel,onRetry:F.retry})]}):ct==="preview"&&HC(ue)?c.jsx(XL,{path:ue,dirty:!!n[ue],reloadToken:w[ue]??0}):ct==="preview"&&VC(ue)?c.jsx(e$,{path:ue,text:l[ue]??""}):ct==="preview"&&qC(ue)?c.jsx(n$,{path:ue,text:l[ue]??""}):Ja(ue)?c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsx(L0,{getEditor:V}),c.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),qe&&c.jsx(KL,{text:l[ue]??"",cursor:$,language:Mr(ue)||void 0}),ue&&Ja(ue)&&(ct==="preview"||ct==="split")&&F.state.phase!=="idle"&&F.state.selection&&c.jsx("div",{ref:ve,children:c.jsx(_$,{phase:F.state.phase,rect:F.state.selection.rect,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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)}})}),A&&c.jsx(T$,{message:A.kind==="one"?`Discard unsaved changes to ${Fg(A.path)}?`:A.kind==="others"?"Discard unsaved changes in the other open files?":A.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>O(null),onConfirm:_e})]})}const Uy=B.memo(k$);function T$({message:i,onCancel:e,onConfirm:t}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const D$={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},G0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Hb({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?c.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&c.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),c.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=B.useRef(null),f=B.useRef(null),g=B.useRef(e);if(g.current=e,B.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const E=setTimeout(()=>{const y=d.current;if(!y)return;const S=y.querySelector(G0);S?S.focus():y.focus()},0),k=y=>{if(y.key==="Escape"){y.stopPropagation(),g.current();return}if(y.key==="Tab"){const S=d.current;if(!S)return;const w=Array.from(S.querySelectorAll(G0)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(w.length===0){y.preventDefault(),S.focus();return}const x=w[0],A=w[w.length-1],O=document.activeElement;y.shiftKey?(O===x||!S.contains(O))&&(y.preventDefault(),A.focus()):(O===A||!S.contains(O))&&(y.preventDefault(),x.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(E),document.removeEventListener("keydown",k);const y=f.current;if(y&&y instanceof HTMLElement)try{y.focus()}catch{}f.current=null}},[i]),!i)return null;const m=T=>{T.target===T.currentTarget&&e()},b=c.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:c.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":n??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${D$[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?c.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?c.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?dm.createPortal(b,document.body):b}class yE extends B.Component{constructor(){super(...arguments);Ni(this,"state",{error:null});Ni(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):c.jsxs("div",{className:"p-6 text-xs",children:[c.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),c.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),c.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function A$({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return c.jsxs(Hb,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&c.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),c.jsx("button",{type:"button",onClick:e,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsx(yE,{children:n})})]})}function bE(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const H0=i=>Symbol.iterator in i,F0=i=>"entries"in i,W0=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},I$=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function P$(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:H0(i)&&H0(e)?F0(i)&&F0(e)?W0(i,e):I$(i,e):W0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Fb(i){const e=Ot.useRef(void 0);return t=>{const n=i(t);return P$(e.current,n)?e.current:e.current=n}}let V0=0;const R$=1e3;function O$(i){const e=performance.now();e-V0<R$||(V0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function L$(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(Fb(gv)),r=()=>{const f=Ct.getState(),{canRecord:g,reason:m}=gv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return O$(m);const b=St.getState().activeTabId;b&&f.startRecording(b)},l=bE(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,d=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return c.jsx("button",{onClick:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${d}`,children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),c.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),c.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),c.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function $$(){const i=Ct(t=>t.ttsEnabled),e=Ct(t=>t.toggleTTS);return c.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?c.jsxs(c.Fragment,{children:[c.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),c.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),c.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),c.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function N$(i){return/^monitor of /i.test(i.trim())}function q0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function K0(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=q0(e),l=t.filter(p=>p.label&&q0(p.label)===r);return l.length===1?l[0]:null}async function X0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&N$(n.label))):[]}const Y0=!1;function wE(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=B.useState([]),[n,r]=B.useState(null),[l,p]=B.useState(null);B.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await X0(Y0);if(f)return;t(m),p(g.selectedLabel);const b=K0(g.selectedDeviceId,g.selectedLabel,m);b?(r(b.deviceId),g.selectedDeviceId&&b.deviceId!==g.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){pt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=B.useCallback(async()=>{try{const f=await X0(Y0);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=K0(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);B.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var T;const g=f.target.value,m=g===""?null:g,b=m?((T=e.find(E=>E.deviceId===m))==null?void 0:T.label)??null:null;r(m),p(b);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:b}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(E){pt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(i)try{await Ct.getState().restartWithDevice()}catch(E){pt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return c.jsxs("select",{value:n??"",onChange:d,onFocus:()=>{a()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[c.jsx("option",{value:"",children:"Default"}),e.map(f=>c.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function M$(){const i=Ct(T=>T.isRecording),e=Ct(T=>T.levelMeterEnabled),[t,n]=B.useState(0),[r,l]=B.useState(0),p=B.useRef(0);p.current=r;const[a,d]=B.useState(0),[f,g]=B.useState(!1),m=B.useRef(null);if(B.useEffect(()=>{if(!i||!e){n(0),l(0);return}let T=0,E=!1,k=null,y=null;const S=()=>{if(E)return;const x=y??O1();if(!x){T=requestAnimationFrame(S);return}y!==x&&(y=x,k=new Uint8Array(new ArrayBuffer(x.fftSize)));const A=k;x.getByteTimeDomainData(A);let O=0;for(let G=0;G<A.length;G++){const W=A[G]-128;O+=W*W}const $=Math.sqrt(O/A.length)/128,j=$>0?20*Math.log10($):-60,L=Math.max(0,Math.min(1,(j+60)/60));l($),n(L),$>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),T=requestAnimationFrame(S)};T=requestAnimationFrame(S);const w=setInterval(()=>{E||d(Math.round(p.current*100))},250);return()=>{E=!0,cancelAnimationFrame(T),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const b=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return c.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${f?"ring-1 ring-red-500":""}`,children:c.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function xE(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=B.useState(()=>performance.now());if(B.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,d=Ct.getState().cancelSubmit;return c.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:c.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:c.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function j$({open:i,onClose:e,variant:t="overlay"}){return c.jsx(A$,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:c.jsxs("div",{className:"p-4 space-y-4",children:[c.jsx(G$,{}),c.jsx(xE,{}),c.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[c.jsx(L$,{}),c.jsx(wE,{}),c.jsx($$,{})]}),c.jsx(z$,{}),c.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[c.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),c.jsx(U$,{})]}),c.jsx(M$,{})]})})}function z$(){const i=Ct(l=>l.isRecording),[e,t]=B.useState(null);if(B.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(a=>{l||t(a)}).catch(()=>{});const p=window.api.voice.onHotkeyConfigChanged(a=>t(a));return()=>{l=!0,p()}},[]),i||!e)return null;const n=e.mode==="hold"?"Hold":"Press",r=B$(e.accelerator);return c.jsxs("div",{className:"text-[11px] text-fg-faint",children:[c.jsxs("span",{children:[n," "]}),c.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),c.jsx("span",{children:" to record"})]})}function B$(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function U$(){const[i,e]=B.useState(null);if(B.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return c.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[c.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[c.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),c.jsx("span",{children:"Tap on/off"})]}),c.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[c.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),c.jsx("span",{children:"Hold to talk"})]})]})}function G$(){const i=Ct(l=>l.isRecording),e=Ct(l=>l.lastTranscript),t=Ct(l=>l.error),n=Ct(l=>l.modelStatus),r=Ct(l=>l.loadingProgress);return t?c.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?c.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[c.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),c.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?c.jsxs("div",{className:"text-[11px] text-fg-faint",children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("span",{children:"Loading speech model"}),c.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),c.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const SE="~/.claude/session-manager/projects-prefs.json",H$={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Wl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(SE,t).catch(()=>{})}const J0=Un((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(SE);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Wl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":H$[t];i({sort:{col:t,dir:r}}),Wl(e)},setRecentFilter:t=>{i({recentFilter:t}),Wl(e)},setHasRemote:t=>{i({hasRemote:t}),Wl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Wl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Wl(e)},setSearch:t=>{i({search:t}),Wl(e)},setEditor:t=>{i({editor:t}),Wl(e)}})),CE=i=>`sm.fileTree.expanded:${i}`;function F$(i){try{const e=localStorage.getItem(CE(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function W$(i,e){try{localStorage.setItem(CE(i),JSON.stringify([...e].slice(0,500)))}catch{}}const EE="sm.fileTree.showHidden";function V$(){try{const i=localStorage.getItem(EE);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function q$(i){try{localStorage.setItem(EE,JSON.stringify(i))}catch{}}function $_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const N_={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},K$=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 X$(i){const e=Mr(i);return K$.has(e)||GC.has(e)||e==="pdf"}function Y$(i,e){if(e)return"#d97757";switch(Mr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function kf(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}function J$({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=vb(),l=Ov(),[p,a]=B.useState([]),[d,f]=B.useState(new Set),g=B.useRef(d);g.current=d;const[m,b]=B.useState(""),[T,E]=B.useState(V$),k=B.useCallback(qe=>{E(Rt=>{const _t=typeof qe=="function"?qe(Rt):qe;return q$(_t),_t})},[]),[y,S]=B.useState(!1),[w,x]=B.useState(null),[A,O]=B.useState({}),[$,j]=B.useState(null),[L,G]=B.useState(null),[W,re]=B.useState(""),[ae,Z]=B.useState(null),[pe,oe]=B.useState(""),[me,we]=B.useState(null),ve=B.useRef(null),F=B.useRef(null),J=B.useRef(0),V=B.useCallback(async()=>{if(!i)return;const qe=++J.current;S(!0),x(null);const Rt=await window.api.files.list(i,T);J.current===qe&&(Rt.ok?a(Rt.entries.map(_t=>({..._t}))):(x(Rt.error??"failed to list"),a([])),S(!1))},[i,T]),se=B.useCallback(async qe=>{const Rt=J.current,_t=new Map;for(const Ye of qe){const yt=Ye.split("/").length,ht=_t.get(yt);ht?ht.push(Ye):_t.set(yt,[Ye])}const ni=[];for(const Ye of[..._t.keys()].sort((yt,ht)=>yt-ht)){const yt=_t.get(Ye),ht=await Promise.all(yt.map(async ke=>({p:ke,result:await window.api.files.list(ke,T)})));if(J.current!==Rt)return ni;for(const{p:ke,result:tt}of ht)tt.ok?a(Wt=>rv(Wt,ke,tt.entries.map(ci=>({...ci})))):ni.push(ke)}return ni},[T]),ge=B.useCallback(async qe=>(await V(),qe.length?se(qe):[]),[V,se]);B.useEffect(()=>{b(""),G(null),j(null),Z(null),we(null),O({});const qe=F$(i),Rt=new Set(qe);g.current=Rt,f(Rt);let _t=!1;return(async()=>{const ni=await ge(qe);_t||!ni.length||je(Ye=>{const yt=new Set;let ht=!1;for(const ke of Ye){if(ni.some(tt=>ke===tt||ke.startsWith(tt+"/"))){ht=!0;continue}yt.add(ke)}return ht?yt:Ye})})(),kf(i).then(ni=>{_t||O(ni)}),()=>{_t=!0}},[i]);const Te=B.useRef(!0);B.useEffect(()=>{if(Te.current){Te.current=!1;return}ge([...g.current])},[T]),B.useEffect(()=>{if(!i||!l)return;kf(i).then(O);const qe=window.setInterval(()=>{kf(i).then(O)},5e3);return()=>window.clearInterval(qe)},[i,l]),B.useEffect(()=>{if(!$)return;const qe=()=>j(null),Rt=_t=>{r.current&&_t.key==="Escape"&&j(null)};return window.addEventListener("mousedown",qe),window.addEventListener("keydown",Rt),()=>{window.removeEventListener("mousedown",qe),window.removeEventListener("keydown",Rt)}},[$]),B.useEffect(()=>{L&&setTimeout(()=>{var qe;return(qe=ve.current)==null?void 0:qe.select()},30)},[L]),B.useEffect(()=>{ae&&setTimeout(()=>{var qe;return(qe=F.current)==null?void 0:qe.focus()},30)},[ae]);const je=B.useCallback(qe=>{const Rt=g.current,_t=qe(Rt);_t!==Rt&&(g.current=_t,f(_t),W$(i,_t))},[i]),Ze=B.useCallback(async qe=>{if(d.has(qe.path)){je(_t=>$_(_t,qe.path));return}if(je(_t=>new Set(_t).add(qe.path)),qe.children)return;const Rt=await window.api.files.list(qe.path,T);Rt.ok&&a(_t=>rv(_t,qe.path,Rt.entries.map(ni=>({...ni}))))},[d,T,je]),ye=B.useCallback(async qe=>{if(qe===i){await V();return}const Rt=await window.api.files.list(qe,T);Rt.ok&&a(_t=>rv(_t,qe,Rt.entries.map(ni=>({...ni}))))},[i,V,T]),Y=B.useCallback(qe=>{if(qe.isDirectory){Ze(qe);return}X$(qe.name)&&e?e(qe.path):window.api.shell.open({as:"openPath",path:qe.path})},[Ze,e]),_e=B.useCallback(qe=>{if(t){t(qe);return}if(n){const Rt=qe.startsWith(i+"/")?qe.slice(i.length+1):qe;window.api.pty.write({tabId:n,data:`@${Rt} `})}},[t,n,i]),ue=B.useCallback((qe,Rt)=>{qe.preventDefault(),qe.stopPropagation(),j({x:qe.clientX,y:qe.clientY,node:Rt})},[]),Re=qe=>{G(qe.path),re(qe.name)},He=async()=>{if(!L)return;const qe=W.trim();if(!qe){G(null);return}const Rt=await window.api.files.rename(L,qe);if(G(null),Rt.ok){const _t=L.slice(0,L.lastIndexOf("/"));je(ni=>$_(ni,L)),await ye(_t||i),kf(i).then(O)}else{const _t=Rt.error??"rename failed";x(_t),nt.error(_t)}},lt=async()=>{if(!ae)return;const qe=pe.trim();if(!qe){Z(null),oe("");return}const Rt=await window.api.files.create(ae.parent,qe,ae.kind);if(Z(null),oe(""),Rt.ok)await ye(ae.parent),ae.kind==="folder"&&je(_t=>new Set(_t).add(ae.parent));else{const _t=Rt.error??"create failed";x(_t),nt.error(_t)}},It=async()=>{if(!me)return;const qe=await window.api.files.delete(me.path),Rt=me.path.slice(0,me.path.lastIndexOf("/"));if(we(null),qe.ok)je(_t=>$_(_t,me.path)),await ye(Rt||i),kf(i).then(O);else{const _t=qe.error??"delete failed";x(_t),nt.error(_t)}},ct=B.useMemo(()=>{if(!m.trim())return p;const qe=m.toLowerCase();return p.filter(Rt=>Rt.name.toLowerCase().includes(qe))},[p,m]),qt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return c.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[c.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[c.jsx(TE,{size:14,className:"shrink-0 text-accent"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"text-xs font-medium text-fg truncate",children:qt}),c.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),c.jsx("button",{onClick:V,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:y,children:c.jsx(nN,{size:12,className:y?"animate-spin":""})})]}),c.jsx("div",{className:"relative",children:c.jsx("input",{value:m,onChange:qe=>b(qe.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"})})]}),c.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[c.jsx("button",{onClick:()=>Z({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:c.jsx(sN,{size:12})}),c.jsx("button",{onClick:()=>Z({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:c.jsx(rN,{size:12})}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:()=>k(qe=>!qe),className:`p-1.5 rounded transition-colors ${T?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:T?"Hide hidden files":"Show hidden files",children:T?c.jsx(oN,{size:12}):c.jsx(aN,{size:12})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&c.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&ct.length===0&&!y&&c.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&c.jsx(kE,{nodes:ct,depth:0,expanded:d,gitStatus:A,renaming:L,renameValue:W,renameInputRef:ve,onRenameChange:re,onRenameCommit:He,onRenameCancel:()=>G(null),onToggleDir:Ze,onFileClick:Y,onSendToChat:_e,onContextMenu:ue})]}),c.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"}),$&&c.jsx(Z$,{x:$.x,y:$.y,node:$.node,onClose:()=>j(null),onRename:()=>{Re($.node),j(null)},onDelete:()=>{we($.node),j(null)},onNewFile:()=>{Z({parent:$.node.path,kind:"file"}),j(null)},onNewFolder:()=>{Z({parent:$.node.path,kind:"folder"}),j(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:$.node.path}),j(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:$.node.path}),j(null)},onCopyPath:()=>{var qe;(qe=navigator.clipboard)==null||qe.writeText($.node.path),j(null)},onSendToChat:()=>{_e($.node.path),j(null)}}),ae&&c.jsx(Z0,{title:`New ${ae.kind}`,subtitle:`in ${Q$(ae.parent)}`,onCancel:()=>{Z(null),oe("")},onConfirm:lt,confirmLabel:"Create",confirmDisabled:!pe.trim(),children:c.jsx("input",{ref:F,value:pe,onChange:qe=>oe(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&lt(),qe.key==="Escape"&&(Z(null),oe(""))},placeholder:ae.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),me&&c.jsx(Z0,{title:`Delete ${me.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>we(null),onConfirm:It,confirmLabel:"Delete",danger:!0,children:c.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",c.jsxs("span",{className:"text-fg font-medium",children:['"',me.name,'"']})," to the trash?",me.isDirectory&&c.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function kE(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return c.jsx(c.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,g=r[a.path],m=Y$(a.name,a.isDirectory);return c.jsxs("div",{children:[c.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:b=>p(b,a),children:[a.isDirectory?c.jsx(iN,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):c.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?c.jsx(eN,{size:12,color:m}):c.jsx(TE,{size:12,color:m}):c.jsx(tN,{size:12,color:m}),f?c.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:b=>i.onRenameChange(b.target.value),onClick:b=>b.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:b=>{b.key==="Enter"&&i.onRenameCommit(),b.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):c.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),g&&c.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:N_[g].color,backgroundColor:`${N_[g].color}20`},title:g,children:N_[g].label}),!a.isDirectory&&c.jsx("button",{onClick:b=>{b.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:c.jsx(lN,{size:10})})]}),a.isDirectory&&d&&a.children&&c.jsx(kE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function Z$(i){const{x:e,y:t,node:n}=i;return c.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&c.jsx(Vl,{label:"Send to chat",onClick:i.onSendToChat}),c.jsx(Vl,{label:"Open in default app",onClick:i.onOpenExternal}),c.jsx(Vl,{label:"Reveal in OS",onClick:i.onShowInFinder}),c.jsx(M_,{}),c.jsx(Vl,{label:"Copy path",onClick:i.onCopyPath}),c.jsx(Vl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&c.jsxs(c.Fragment,{children:[c.jsx(M_,{}),c.jsx(Vl,{label:"New file",onClick:i.onNewFile}),c.jsx(Vl,{label:"New folder",onClick:i.onNewFolder})]}),c.jsx(M_,{}),c.jsx(Vl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Vl({label:i,onClick:e,danger:t}){return c.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function M_(){return c.jsx("div",{className:"my-1 border-t border-line"})}function Z0(i){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&c.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),c.jsx("div",{className:"mb-4",children:i.children}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),c.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function Q$(i){return i.split("/").filter(Boolean).pop()||i}function rv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:rv(n.children,e,t)}:n)}function ba({size:i,children:e,className:t,color:n}){return c.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function TE({size:i,className:e,color:t}){return c.jsx(ba,{size:i,className:e,color:t,children:c.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 eN({size:i,className:e,color:t}){return c.jsx(ba,{size:i,className:e,color:t,children:c.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 tN({size:i,className:e,color:t}){return c.jsxs(ba,{size:i,className:e,color:t,children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function iN({size:i,className:e}){return c.jsx(ba,{size:i,className:e,children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}function nN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.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 sN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"}),c.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),c.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function rN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.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"}),c.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),c.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function oN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function aN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.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"}),c.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function lN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function DE({content:i,children:e,align:t="bottom-right"}){const[n,r]=B.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return c.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&c.jsx("span",{role:"tooltip",className:`absolute ${Cn.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function qf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Gy="sm.projects.splitPct",Hy=33,AE=20,IE=60,PE="sm.projects.fileTreeCollapsed",cN=32;function dN(){try{const i=parseFloat(localStorage.getItem(Gy)??"");if(Number.isFinite(i))return Math.min(IE,Math.max(AE,i))}catch{}return Hy}function uN(){try{return localStorage.getItem(PE)==="1"}catch{return!1}}function hN(){const i=St(W=>W.tabs),e=St(W=>W.activeTabId),t=i.find(W=>W.id===e)??null,n=Ii(W=>W.navFace),[r,l]=B.useState(null);B.useEffect(()=>{if(n!=="home"||r)return;let W=!1;return window.api.app.homeDir().then(re=>{W||l(re)}).catch(()=>{}),()=>{W=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=B.useState(()=>dN()),[f,g]=B.useState(()=>uN()),[m,b]=B.useState(!1),T=B.useRef(a);T.current=a;const E=B.useRef(null),k=B.useRef(null),{projects:y,openProject:S,archiveProjectByCwd:w}=vd(),x=J0(W=>W.pinned),A=J0(W=>W.togglePin),O=[...y].sort((W,re)=>(x[re.cwd]?1:0)-(x[W.cwd]?1:0));B.useEffect(()=>{if(!m)return;const W=re=>{k.current&&!k.current.contains(re.target)&&b(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const $=B.useCallback(W=>{Oi.getState().openFile(W)},[]),j=B.useCallback(W=>{W.preventDefault();const re=W.clientX,ae=T.current;let Z=ae;const pe=me=>{const we=E.current;if(!we)return;const ve=we.getBoundingClientRect(),F=me.clientX-re;Z=Math.min(IE,Math.max(AE,ae+F/ve.width*100)),d(Z)},oe=()=>{window.removeEventListener("pointermove",pe),window.removeEventListener("pointerup",oe),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gy,String(Z))}catch{}};window.addEventListener("pointermove",pe),window.addEventListener("pointerup",oe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=B.useCallback(()=>{d(Hy);try{localStorage.setItem(Gy,String(Hy))}catch{}},[]),G=B.useCallback(()=>{g(W=>{const re=!W;try{localStorage.setItem(PE,re?"1":"0")}catch{}return re})},[]);return f?c.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[c.jsxs("button",{onClick:G,"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:cN},children:[c.jsx("span",{className:"text-[11px]",children:"▸"}),c.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),c.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:c.jsx(Uy,{})})]}):c.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[c.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[c.jsxs("div",{ref:k,className:"relative shrink-0 flex items-stretch border-b border-line",children:[c.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(W=>!W),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:[c.jsx("span",{className:"flex-1 truncate text-left",children:p?qf(p):"Projects"}),c.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),c.jsx("button",{onClick:G,"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&&c.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Cn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:O.length===0?c.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):O.map(W=>{const re=qf(W.cwd);return c.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[c.jsx(DE,{content:x[W.cwd]?"Unpin":"Pin to top",children:c.jsx("button",{onClick:()=>A(W.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[W.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[W.cwd]?"★":"☆"})}),c.jsx("button",{onClick:()=>{S(W.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),c.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await w(W)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},W.cwd)})})]}),p?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:p,children:qf(p)}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsx(J$,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:$})})]}):c.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),c.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:j,onDoubleClick:L,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),c.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:c.jsx(Uy,{})})]})}const pN=B.memo(hN),fN={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a Whisper model that loads the first time you record (a progress bar shows the download). A press-to-record hotkey starts and stops the mic; what you say is typed into the active terminal, and an auto-submit timer fires it for you a moment after you stop speaking. A one-time mic check confirms your microphone works.",sections:[{title:"Recording controls",items:[{term:"Hotkey",body:"Press your mic hotkey to record. The default is Ctrl+Shift+Space (Cmd+Option+V on Mac); the panel shows the live binding. Two behaviours: 'Hold to talk' records only while the key is held (push-to-talk), 'Tap on/off' starts on one press and stops on the next. The default is hold-to-talk; switch with the radio buttons."},{term:"Mic button & device",body:"The mic button toggles recording with the mouse. The device picker chooses which microphone to use, and a live level meter shows that audio is coming through."},{term:"Run mic check",body:"Opens a short wizard that confirms your mic is picking up sound. It runs automatically once after a settings-format change, or any time you click 'Run mic check'."}]},{title:"Speaking & hearing back",items:[{term:"Live transcript",body:"While recording, a pulsing red dot and the latest transcribed words appear so you can see what was heard. Errors (e.g. mic blocked) surface inline in red."},{term:"TTS (read replies aloud)",body:"The speaker button toggles text-to-speech. When on, Claude's replies are read back to you out loud."}]}],tips:["The speech model downloads on first use only, then stays cached — later recordings start instantly.","Hold-to-talk is best for quick interjections; Tap on/off is better for longer dictation where you don't want to hold a key."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},"tag-library":{headline:"Tag Library — the Epic intent-tag taxonomy",intro:"Every Epic carries an initial intent tag — feature, bug, discussion, or build — chosen at creation. The tag sets how eagerly /develop should fire inside that Epic's session: feature/bug/build treat PRD decomposition as the expected next step, discussion keeps /develop available but never assumed until whether-to-build is settled.",sections:[{title:"What it shows",items:[{term:"Tag",body:"The four intent tags an Epic can be created with."},{term:"/develop eagerness",body:"Whether PRD decomposition is the expected default for that tag, or available-but-not-assumed."},{term:"Agents carrying this tag",body:"Which Agent Library personas have this tag in their `tags:` frontmatter — the same relationship Agent Library edits from the agent side. Assign or remove an agent here to update that persona's file directly."}]}],tips:["Home face only — the taxonomy is machine-wide, not scoped to one project.","The tag taxonomy itself is read-only here — change an existing Epic's tag from its queue row menu, not from this page. The agent↔tag assignment, though, is editable from either Tag Library or Agent Library."]},"bilko-host":{headline:"Host on Bilko.run — publish this project's Project Home page",intro:"Turns this project's already-generated Project Home page (home.html) into a live static-path listing on bilko.run, using the bilko-host MCP's existing gated publish pipeline (manifest/budget/golden/a11y/audit checks) — never a second, competing hosting mechanism.",sections:[{title:"What it shows",items:[{term:"Status",body:"not-published → bundle-ready → publishing → published/publish-failed, mirroring the on-disk publish-state.json a bilko-host-publisher Epic writes."},{term:"Slug",body:"The bilko.run/projects/<slug>/ path this project would publish to — defaults from package.json's name."},{term:"Bundle",body:"Size, build time, and git sha of the dist/ bundle Prepare Bundle last wrote."}]}],tips:["Project face only — publishing is always scoped to the active project's tab.",`Requires a generated Project Home page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}},Wb="sm.learningPanel.collapsed";function Q0(){try{const i=localStorage.getItem(Wb);if(i===null)return!1;if(i.startsWith("{")){const e=JSON.parse(i);return!!(e&&typeof e=="object"&&Object.values(e).some(Boolean))}return i==="1"||i==="true"}catch{return!1}}function eS(i){try{localStorage.setItem(Wb,i?"1":"0")}catch{}}function mN({content:i}){return c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>c.jsxs("div",{className:"mb-3 last:mb-0",children:[c.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),c.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>c.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&c.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",c.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&c.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[c.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),c.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>c.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function gN({active:i}){const[e,t]=B.useState(()=>!Q0()),n=B.useRef(null),r=B.useCallback(()=>{t(a=>{const d=!a;return eS(!d),d})},[]);B.useEffect(()=>{const a=d=>{d.key===Wb&&t(!Q0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),B.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),eS(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=B.useRef(!1);B.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=fN[i];return p?c.jsxs("span",{ref:n,className:"relative inline-block",children:[c.jsx("button",{type:"button",onClick:r,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":e,title:e?"Close learning panel":"What is this?",children:"Learn"}),e&&c.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:c.jsx(mN,{content:p})})]}):null}function vN({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return c.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&c.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"max-w-[820px]",children:[i&&c.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&c.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&c.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&c.jsx(gN,{active:r})]}),c.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const _N=B.lazy(()=>Bn(()=>import("./Skills-BQDqp-EN.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,1,2]),import.meta.url).then(i=>({default:i.Skills}))),yN=B.lazy(()=>Bn(()=>import("./History-C685Kytt.js"),__vite__mapDeps([12,1,2]),import.meta.url).then(i=>({default:i.History}))),bN=B.lazy(()=>Bn(()=>import("./Scheduler-D488ebKm.js"),__vite__mapDeps([13,10,7,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),wN=B.lazy(()=>Bn(()=>import("./Settings-D5Lhj7ga.js"),__vite__mapDeps([14,6,5,15,7,1,2]),import.meta.url).then(i=>({default:i.Settings}))),xN=B.lazy(()=>Bn(()=>import("./Permissions-3pGLJmxQ.js"),__vite__mapDeps([16,6,5,9,15,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),SN=B.lazy(()=>Bn(()=>import("./SystemPrompt-tFr19Od6.js"),__vite__mapDeps([17,5,9,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),CN=B.lazy(()=>Bn(()=>import("./Memory-DAP1t8bA.js"),__vite__mapDeps([18,4,1,2]),import.meta.url).then(i=>({default:i.Memory}))),EN=B.lazy(()=>Bn(()=>import("./Plugins-Q1KoLEzn.js"),__vite__mapDeps([19,8,9,11,1,2,4]),import.meta.url).then(i=>({default:i.Plugins}))),kN=B.lazy(()=>Bn(()=>import("./McpServers-BLM3ftzP.js"),__vite__mapDeps([20,5,6,8,9,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),TN=B.lazy(()=>Bn(()=>import("./Hooks-CwLnp0Z_.js"),__vite__mapDeps([21,5,6,8,9,15,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),DN=B.lazy(()=>Bn(()=>Promise.resolve().then(()=>Lz),void 0,import.meta.url).then(i=>({default:i.AgentLibrary}))),AN=B.lazy(()=>Bn(()=>import("./TagLibrary-BjyrnaRE.js"),__vite__mapDeps([22,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),IN=B.lazy(()=>Bn(()=>import("./HostBilko-CwEHEKYk.js"),__vite__mapDeps([23,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),PN=B.lazy(()=>Bn(()=>import("./DataModel-B0LDnnSL.js"),__vite__mapDeps([24,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),RN=c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function hr({children:i}){return c.jsx(B.Suspense,{fallback:RN,children:i})}const ON={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"Every session, ever",intro:"Resumable transcripts across every project you have opened. Pick a row to reattach Claude to the same conversation."},plugins:{title:"Plugins",intro:"Extensions for Claude Code. Install, enable, or remove plugins per-scope."},mcp:{title:"MCP Servers",intro:"External tools and integrations the agent can call. Add a new server or test an existing connection."},hooks:{title:"Hooks",intro:"Run scripts on session events. Tail logs, format files, post to Slack — anything that responds to a shell command."},memory:{title:"Memory",intro:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},"bilko-host":{title:"Host on Bilko.run",intro:"Publish this project's generated Marketing page to bilko.run as a static-path listing, via the bilko-host MCP's gated publish pipeline."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},LN=()=>{},tS=new Map;function $N(i,e){const t=tS.get(i);if(t&&t.ctx===e)return t.node;const n=NN(i,e);return tS.set(i,{ctx:e,node:n}),n}function NN(i,e){switch(i){case"overview":return c.jsx(TP,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return c.jsx(oR,{});case"editor":return c.jsx(Uy,{});case"projects":return c.jsx(pN,{})}const t=ON[i],n=(()=>{switch(i){case"skills":return c.jsx(hr,{children:c.jsx(_N,{})});case"history":return c.jsx(hr,{children:c.jsx(yN,{})});case"scheduler":return c.jsx(hr,{children:c.jsx(bN,{navigate:e.onNavigate})});case"plugins":return c.jsx(hr,{children:c.jsx(EN,{})});case"mcp":return c.jsx(hr,{children:c.jsx(kN,{})});case"hooks":return c.jsx(hr,{children:c.jsx(TN,{})});case"memory":return c.jsx(hr,{children:c.jsx(CN,{})});case"system-prompt":return c.jsx(hr,{children:c.jsx(SN,{})});case"permissions":return c.jsx(hr,{children:c.jsx(xN,{})});case"settings":return c.jsx(hr,{children:c.jsx(wN,{})});case"agent-library":return c.jsx(hr,{children:c.jsx(DN,{})});case"tag-library":return c.jsx(hr,{children:c.jsx(AN,{})});case"bilko-host":return c.jsx(hr,{children:c.jsx(IN,{})});case"data-model":return c.jsx(hr,{children:c.jsx(PN,{})});case"voice":return c.jsx(j$,{open:!0,onClose:LN,variant:"page"});default:return null}})();if(!n)return null;const r=jT[i];return t&&r?c.jsx(vN,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var j_={exports:{}},iS;function MN(){return iS||(iS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(w,x,A,O){var $,j=arguments.length,L=j<3?x:O===null?O=Object.getOwnPropertyDescriptor(x,A):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(w,x,A,O);else for(var G=w.length-1;G>=0;G--)($=w[G])&&(L=(j<3?$(L):j>3?$(x,A,L):$(x,A))||L);return j>3&&L&&Object.defineProperty(x,A,L),L},g=this&&this.__param||function(w,x){return function(A,O){x(A,O,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),b=d(9924),T=d(844),E=d(4725),k=d(2585),y=d(3656);let S=a.AccessibilityManager=class extends T.Disposable{constructor(w,x,A,O){super(),this._terminal=w,this._coreBrowserService=A,this._renderService=O,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 $=0;$<this._terminal.rows;$++)this._rowElements[$]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[$]);if(this._topBoundaryFocusListener=$=>this._handleBoundaryFocus($,0),this._bottomBoundaryFocusListener=$=>this._handleBoundaryFocus($,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(($=>this._handleResize($.rows)))),this.register(this._terminal.onRender(($=>this._refreshRows($.start,$.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar(($=>this._handleChar($)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
3027
+ (Give a different rewrite than the last one.)`,!1)},[E,t.instruction]),w=B.useCallback(x=>{const A=t.diff;if(!A)return{ok:!1,reason:"not-found"};const O=o$(x,A.before,A.after);return O.ok?(r.current+=1,n({type:"ACCEPT"})):nt.error(O.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),O},[t.diff]);return{state:t,select:f,cancel:g,listen:m,sendHeard:y,run:k,retry:S,accept:w}}const m$=[{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."}],j0=320,Ef=8;function g$(){return c.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function v$(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,Ef),Math.max(Ef,e-j0-Ef)),n=Math.max(i.top-Ef,Ef);return{position:"fixed",left:t,top:n,width:j0,transform:"translateY(-100%)",zIndex:XD.dialog}}function _$({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:g,onReject:m,onRetry:b}){const[T,E]=B.useState(""),k=()=>{const y=T.trim();y&&(p(y),E(""))};return c.jsxs("div",{"data-doc-edit-popover":!0,style:v$(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&c.jsxs("div",{className:"p-2",children:[c.jsxs("div",{className:"flex items-center justify-between mb-2",children:[c.jsxs("div",{className:"flex flex-wrap gap-1",children:[c.jsx("button",{onClick:a,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),m$.map(y=>c.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),c.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),c.jsx("input",{autoFocus:!0,value:T,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?k():y.key==="Escape"&&f()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),i==="listening"&&c.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[c.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[c.jsxs("span",{className:"flex items-center gap-2",children:[c.jsx(g$,{}),"Listening…"]}),r&&c.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),c.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&c.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[c.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),c.jsxs("div",{className:"flex justify-end gap-1.5",children:[c.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),c.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&c.jsxs("div",{className:"p-3 flex items-center justify-between",children:[c.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),c.jsx("button",{onClick:f,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="diff"&&t&&c.jsxs("div",{className:"p-3",children:[c.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[c.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),c.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),c.jsxs("div",{className:"flex justify-end gap-1.5",children:[c.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),c.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),c.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function y$(){return c.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),c.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function z0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:g}){return c.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[c.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),c.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zf(p$)})]}),c.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&c.jsxs("div",{className:"text-fg-faint",children:[c.jsx("p",{children:"Select text in the doc…"}),c.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&c.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&c.jsxs("div",{children:[c.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[c.jsx(y$,{}),"Listening…"]}),r&&c.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),c.jsx("button",{onClick:a,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),i==="review"&&c.jsxs("div",{children:[c.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),c.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&c.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&c.jsxs("div",{children:[c.jsxs("div",{className:"mb-3 space-y-2",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),c.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),c.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),c.jsxs("div",{className:"flex gap-1.5",children:[c.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),c.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),c.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function b$(){const i=St(t=>t.tabs),e=St(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function B0(i){return i.split("/").filter(Boolean).pop()||i}function w$({path:i,onRenamed:e,onDeleted:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(!1),[a,d]=B.useState(""),[f,g]=B.useState(!1),m=Oi(W=>W.buffers[i]),b=Oi(W=>W.openFile),T=Oi(W=>W.renameOpenFile),E=Oi(W=>W.closeFile),k=b$(),y=B0(i),S=()=>r(!1),w=()=>{d(y),p(!0),S()},x=async()=>{const W=a.trim();if(!W||W===y){p(!1);return}try{const re=await window.api.files.rename(i,W);if(re.ok){const ae=i.slice(0,i.lastIndexOf("/")),Z=re.newPath??`${ae}/${W}`;T(i,Z),e==null||e(i,Z),nt.info(`Renamed to ${W}`)}else nt.error(re.error??`Couldn't rename ${y}`)}catch(re){nt.error(re instanceof Error?re.message:`Couldn't rename ${y}`)}p(!1)},A=async()=>{S();try{const W=await window.api.files.duplicate(i);W.ok&&W.path?(b(W.path),nt.info(`Duplicated as ${B0(W.path)}`)):nt.error(W.error??`Couldn't duplicate ${y}`)}catch(W){nt.error(W instanceof Error?W.message:`Couldn't duplicate ${y}`)}},O=async()=>{try{const W=await window.api.files.delete(i);W.ok?(E(i),t==null||t(i),nt.info(`Deleted ${y}`)):nt.error(W.error??`Couldn't delete ${y}`)}catch(W){nt.error(W instanceof Error?W.message:`Couldn't delete ${y}`)}g(!1)},$=async()=>{S();const W=m??"";try{await navigator.clipboard.writeText(W),nt.info(`Copied ${W.length} chars`)}catch(re){nt.error(re instanceof Error?re.message:`Couldn't copy ${y}`)}},j=()=>{if(S(),!k){nt.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${i} `}),nt.info(`Added ${y} to Claude context`)},L=()=>{S(),window.api.shell.open({as:"openPath",path:i}).then(W=>{W.ok||nt.error(W.error??`Couldn't open ${y}`)}).catch(W=>nt.error(W instanceof Error?W.message:`Couldn't open ${y}`))},G=()=>{S(),window.api.shell.open({as:"revealPath",path:i}).then(W=>{W.ok||nt.error(W.error??`Couldn't reveal ${y}`)}).catch(W=>nt.error(W instanceof Error?W.message:`Couldn't reveal ${y}`))};return c.jsxs("div",{className:"relative inline-block mr-1",children:[c.jsx("button",{onClick:()=>r(W=>!W),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),n&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:S}),c.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,children:[c.jsx(L_,{children:"Edit"}),c.jsx(rd,{label:"Rename",onClick:w}),c.jsx(rd,{label:"Duplicate",onClick:A}),c.jsx(rd,{label:"Delete document",danger:!0,onClick:()=>{S(),g(!0)}}),c.jsx(U0,{}),c.jsx(L_,{children:"Open"}),c.jsx(rd,{label:"Open in default app",onClick:L}),c.jsx(rd,{label:"Reveal in OS",onClick:G}),c.jsx(U0,{}),c.jsx(L_,{children:"Export"}),c.jsx(rd,{label:"Copy as Markdown",onClick:$}),c.jsx(rd,{label:"Add to Claude context",onClick:j,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),l&&c.jsx(x$,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&c.jsx(S$,{name:y,onCancel:()=>g(!1),onConfirm:()=>void O()})]})}function L_({children:i}){return c.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function rd({label:i,onClick:e,danger:t,disabled:n,title:r}){return c.jsx("button",{onClick:e,disabled:n,title:r,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${t?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:i})}function U0(){return c.jsx("div",{className:"my-1 border-t border-line"})}function x$({value:i,onChange:e,onCancel:t,onConfirm:n}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),c.jsx("input",{autoFocus:!0,value:i,onChange:r=>e(r.target.value),onKeyDown:r=>{r.key==="Enter"?n():r.key==="Escape"&&t()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function S$({name:i,onCancel:e,onConfirm:t}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function C$(){const[i,e]=B.useState(!1),t=dh();return c.jsxs("div",{className:"relative inline-block mr-1",children:[c.jsx("button",{onClick:()=>e(n=>!n),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),i&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),c.jsxs("div",{className:`absolute right-0 top-full mt-1 ${Cn.contextMenu} w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5`,children:[c.jsx(oh,{label:"Text size",children:c.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[c.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−"}),c.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),c.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+"})]})}),c.jsx(oh,{label:"Word wrap",children:c.jsx(Hg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),c.jsx(oh,{label:"Minimap",children:c.jsx(Hg,{on:t.minimap,onClick:t.toggleMinimap})}),c.jsx(oh,{label:"Theme",children:c.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"})}),c.jsx(oh,{label:"Autosave",children:c.jsx(Hg,{on:t.autosave,onClick:t.toggleAutosave})}),c.jsx(oh,{label:"Wide measure",children:c.jsx(Hg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function oh({label:i,children:e}){return c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Hg({on:i,onClick:e}){return c.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:i?"On":"Off"})}const E$=B.lazy(()=>Bn(()=>import("./TiptapBody-BbcJL9az.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Fg(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e){if(!e.length)return i;const t=new Set(e),n={};for(const[r,l]of Object.entries(i))t.has(r)||(n[r]=l);return n}function Vg(i){return FC(i)||WC(i)}function k$(){const i=vb(),e=Oi(Ye=>Ye.openFiles),t=Oi(Ye=>Ye.activeFilePath),n=Oi(Ye=>Ye.dirty),r=Oi(Ye=>Ye.viewMode),l=Oi(Ye=>Ye.buffers),p=Oi(Ye=>Ye.setActive),a=Oi(Ye=>Ye.closeFile),d=Oi(Ye=>Ye.closeOthers),f=Oi(Ye=>Ye.closeToTheRight),g=Oi(Ye=>Ye.closeAll),m=Oi(Ye=>Ye.loadBuffer),b=Oi(Ye=>Ye.setBuffer),T=Oi(Ye=>Ye.markSaved),E=Oi(Ye=>Ye.setViewMode),k=dh(),[y,S]=B.useState({}),[w,x]=B.useState({}),[A,O]=B.useState(null),[$,j]=B.useState(null),[L,G]=B.useState(!1),[W,re]=B.useState(!1),[ae,Z]=B.useState(!0),pe=B.useRef(null),oe=B.useRef(null),me=B.useRef(void 0),we=B.useRef(null),ve=B.useRef(null),F=f$(t??"",l[t??""]??""),J=B.useCallback(Ye=>{pe.current=Ye},[]),V=B.useCallback(()=>pe.current,[]);B.useEffect(()=>{const Ye=t;if(!Ye||Vg(Ye))return;if(Oi.getState().hasBuffer(Ye)){S(ht=>ht[Ye]==="ready"?ht:{...ht,[Ye]:"ready"});return}let yt=!1;return S(ht=>({...ht,[Ye]:"loading"})),window.api.files.read(Ye).then(ht=>{yt||(ht.binary?S(ke=>({...ke,[Ye]:{binary:!0,size:ht.size??0,mime:ht.mime??"application/octet-stream",reason:ht.error??"Binary file"}})):ht.ok?(m(Ye,ht.text),S(ke=>({...ke,[Ye]:"ready"}))):S(ke=>({...ke,[Ye]:{error:ht.error??"failed to read"}})))}),()=>{yt=!0}},[t,m]),B.useEffect(()=>{j(null)},[t]);const se=B.useCallback(async(Ye,yt=!1)=>{const ht=Oi.getState().buffers[Ye];if(ht==null)return;yt&&G(!0);const ke=await window.api.files.write(Ye,ht);ke.ok?(T(Ye),x(tt=>({...tt,[Ye]:(tt[Ye]??0)+1})),yt||nt.info(`Saved ${Fg(Ye)}`)):nt.error(ke.error??`Couldn't save ${Fg(Ye)}`),yt&&G(!1)},[T]);B.useEffect(()=>{if(!k.autosave)return;const Ye=t;if(!(!Ye||Vg(Ye)||!n[Ye]))return window.clearTimeout(me.current),me.current=window.setTimeout(()=>{se(Ye,!0)},1200),()=>window.clearTimeout(me.current)},[k.autosave,t,n,l,se]);const ge=B.useCallback(Ye=>{Ye.length&&(S(yt=>Wg(yt,Ye)),x(yt=>Wg(yt,Ye)))},[]),Te=B.useCallback((Ye,yt)=>{S(ht=>Ye in ht?{...Wg(ht,[Ye]),[yt]:ht[Ye]}:ht),x(ht=>Ye in ht?{...Wg(ht,[Ye]),[yt]:ht[Ye]}:ht)},[]),je=B.useCallback(Ye=>{n[Ye]?O({kind:"one",path:Ye}):(a(Ye),ge([Ye]))},[n,a,ge]),Ze=B.useCallback(Ye=>{e.some(ht=>ht.path!==Ye&&n[ht.path])?O({kind:"others",path:Ye}):(d(Ye),ge(e.filter(ht=>ht.path!==Ye).map(ht=>ht.path)))},[e,n,d,ge]),ye=B.useCallback(Ye=>{const yt=e.findIndex(ke=>ke.path===Ye);yt!==-1&&e.slice(yt+1).some(ke=>n[ke.path])?O({kind:"right",path:Ye}):(f(Ye),ge(yt!==-1?e.slice(yt+1).map(ke=>ke.path):[]))},[e,n,f,ge]);B.useEffect(()=>{const Ye=yt=>{if(i.current)if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const ht=Oi.getState().activeFilePath;ht&&!Vg(ht)&&(yt.preventDefault(),se(ht))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),re(ht=>!ht);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const ht=Oi.getState().activeFilePath;ht&&Oi.getState().openFiles.length>1&&(yt.preventDefault(),Ze(ht))}else yt.key==="Escape"&&F.state.phase!=="idle"?F.cancel():yt.key==="Escape"&&W&&re(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[se,W,Ze,F.state.phase,F.cancel]),B.useEffect(()=>{if(F.state.phase==="idle")return;const Ye=yt=>{var ke,tt;const ht=yt.target;(ke=ve.current)!=null&&ke.contains(ht)||(tt=we.current)!=null&&tt.contains(ht)||F.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[F.state.phase,F.cancel]),B.useEffect(()=>{F.cancel()},[t,F.cancel]);const Y=B.useCallback(()=>{e.some(yt=>n[yt.path])?O({kind:"all",path:""}):(g(),S({}),x({}))},[e,n,g]),_e=()=>{if(A){if(A.kind==="one")a(A.path),ge([A.path]);else if(A.kind==="others"){const Ye=e.filter(yt=>yt.path!==A.path).map(yt=>yt.path);d(A.path),ge(Ye)}else if(A.kind==="right"){const Ye=e.findIndex(ht=>ht.path===A.path),yt=Ye!==-1?e.slice(Ye+1).map(ht=>ht.path):[];f(A.path),ge(yt)}else g(),S({}),x({});O(null)}};if(e.length===0)return c.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:c.jsxs("div",{className:"text-center",children:[c.jsx("div",{className:"mb-2",children:"no file open"}),c.jsxs("div",{children:["open the ",c.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const ue=t,Re=ue?Fg(ue):"",He=ue?y[ue]:void 0,lt=ue?KC(ue):!1,It=ue?hR(ue):!1,ct=ue&&lt?r[ue]??pR(ue):"edit",qt=!!ue&&!Vg(ue)&&He==="ready",qe=qt,Rt=It?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],_t=ue&&c.jsx(DO,{path:ue,name:Re,value:l[ue]??"",onChange:Ye=>b(ue,Ye),onSave:()=>void se(ue),onReady:J,onCursor:j}),ni=L?"Saving…":ue&&n[ue]?k.autosave?"Editing…":"Unsaved":"All changes saved";return c.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!W&&c.jsx(gR,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:je,onCloseOthers:Ze,onCloseToTheRight:ye,onCloseAll:Y}),ue&&!W&&c.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[c.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Re}),c.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:ue}),qt&&c.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ni]}),Ja(ue)&&(ct==="preview"||ct==="split")&&c.jsx("button",{onClick:()=>Z(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${ae?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ja(ue)&&(ct==="preview"||ct==="split")&&c.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Rt.length>0&&c.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Rt.map(Ye=>c.jsx("button",{onClick:()=>E(ue,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${ct===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),c.jsx("div",{className:"flex-1"}),c.jsx(w$,{path:ue,onRenamed:Te,onDeleted:Ye=>ge([Ye])}),qt&&c.jsx(C$,{}),c.jsx("button",{onClick:()=>re(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),W&&c.jsx("button",{onClick:()=>re(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),c.jsx("div",{className:"flex-1 min-h-0",children:ue?FC(ue)?c.jsx(JL,{path:ue,name:Re}):WC(ue)?c.jsx(ZL,{path:ue}):He&&typeof He=="object"&&"binary"in He?c.jsx(r$,{path:ue,name:Re,size:He.size,mime:He.mime,reason:He.reason}):He&&typeof He=="object"&&"error"in He?c.jsx("div",{className:"p-6 text-xs text-red-400",children:He.error}):He!=="ready"?c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):ct==="wysiwyg"&&Ja(ue)?c.jsx(B.Suspense,{fallback:c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:c.jsx(E$,{value:l[ue]??"",onChange:Ye=>b(ue,Ye)},ue)}):ct==="split"&&Ja(ue)?c.jsxs("div",{className:"flex h-full",children:[ae&&c.jsx($0,{text:l[ue]??"",scrollRef:oe}),c.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[c.jsx(L0,{getEditor:V}),c.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),c.jsx("div",{ref:we,className:"flex-1 min-w-0",children:c.jsx(jy,{ref:oe,text:l[ue]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!W&&k.assistantRail&&c.jsx(z0,{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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)},onReject:F.cancel,onRetry:F.retry})]}):ct==="preview"&&Ja(ue)?c.jsxs("div",{className:"flex h-full",children:[ae&&c.jsx($0,{text:l[ue]??"",scrollRef:oe}),c.jsx("div",{ref:we,className:"flex-1 min-w-0",children:c.jsx(jy,{ref:oe,text:l[ue]??"",wideMeasure:k.wideMeasure,onSelect:F.select,onDismissSelection:F.cancel})}),!W&&k.assistantRail&&c.jsx(z0,{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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)},onReject:F.cancel,onRetry:F.retry})]}):ct==="preview"&&HC(ue)?c.jsx(XL,{path:ue,dirty:!!n[ue],reloadToken:w[ue]??0}):ct==="preview"&&VC(ue)?c.jsx(e$,{path:ue,text:l[ue]??""}):ct==="preview"&&qC(ue)?c.jsx(n$,{path:ue,text:l[ue]??""}):Ja(ue)?c.jsxs("div",{className:"flex flex-col h-full",children:[c.jsx(L0,{getEditor:V}),c.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),qe&&c.jsx(KL,{text:l[ue]??"",cursor:$,language:Mr(ue)||void 0}),ue&&Ja(ue)&&(ct==="preview"||ct==="split")&&F.state.phase!=="idle"&&F.state.selection&&c.jsx("div",{ref:ve,children:c.jsx(_$,{phase:F.state.phase,rect:F.state.selection.rect,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 Ye=F.accept(l[ue]??"");Ye.ok&&b(ue,Ye.next)}})}),A&&c.jsx(T$,{message:A.kind==="one"?`Discard unsaved changes to ${Fg(A.path)}?`:A.kind==="others"?"Discard unsaved changes in the other open files?":A.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>O(null),onConfirm:_e})]})}const Uy=B.memo(k$);function T$({message:i,onCancel:e,onConfirm:t}){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),c.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const D$={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},G0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function Hb({open:i,onClose:e,children:t,title:n,size:r="sm",fillHeight:l=!1,noPadding:p=!1,variant:a="overlay"}){if(a==="page")return i?c.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&c.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),c.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=B.useRef(null),f=B.useRef(null),g=B.useRef(e);if(g.current=e,B.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const E=setTimeout(()=>{const y=d.current;if(!y)return;const S=y.querySelector(G0);S?S.focus():y.focus()},0),k=y=>{if(y.key==="Escape"){y.stopPropagation(),g.current();return}if(y.key==="Tab"){const S=d.current;if(!S)return;const w=Array.from(S.querySelectorAll(G0)).filter($=>!$.hasAttribute("disabled")&&$.tabIndex!==-1);if(w.length===0){y.preventDefault(),S.focus();return}const x=w[0],A=w[w.length-1],O=document.activeElement;y.shiftKey?(O===x||!S.contains(O))&&(y.preventDefault(),A.focus()):(O===A||!S.contains(O))&&(y.preventDefault(),x.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(E),document.removeEventListener("keydown",k);const y=f.current;if(y&&y instanceof HTMLElement)try{y.focus()}catch{}f.current=null}},[i]),!i)return null;const m=T=>{T.target===T.currentTarget&&e()},b=c.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:c.jsxs("div",{ref:d,role:"dialog","aria-modal":"true","aria-label":n??"Dialog",tabIndex:-1,className:`bg-bg-elev border border-line rounded-lg shadow-xl w-full mx-4 outline-none flex flex-col break-words ${D$[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?c.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?c.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?dm.createPortal(b,document.body):b}class yE extends B.Component{constructor(){super(...arguments);Ni(this,"state",{error:null});Ni(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t,n){console.error("[ErrorBoundary]",t,n)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):c.jsxs("div",{className:"p-6 text-xs",children:[c.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),c.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),c.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function A$({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return c.jsxs(Hb,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&c.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[c.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),c.jsx("button",{type:"button",onClick:e,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsx(yE,{children:n})})]})}function bE(i,e={}){switch(i){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const H0=i=>Symbol.iterator in i,F0=i=>"entries"in i,W0=(i,e)=>{const t=i instanceof Map?i:new Map(i.entries()),n=e instanceof Map?e:new Map(e.entries());if(t.size!==n.size)return!1;for(const[r,l]of t)if(!n.has(r)||!Object.is(l,n.get(r)))return!1;return!0},I$=(i,e)=>{const t=i[Symbol.iterator](),n=e[Symbol.iterator]();let r=t.next(),l=n.next();for(;!r.done&&!l.done;){if(!Object.is(r.value,l.value))return!1;r=t.next(),l=n.next()}return!!r.done&&!!l.done};function P$(i,e){return Object.is(i,e)?!0:typeof i!="object"||i===null||typeof e!="object"||e===null||Object.getPrototypeOf(i)!==Object.getPrototypeOf(e)?!1:H0(i)&&H0(e)?F0(i)&&F0(e)?W0(i,e):I$(i,e):W0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function Fb(i){const e=Ot.useRef(void 0);return t=>{const n=i(t);return P$(e.current,n)?e.current:e.current=n}}let V0=0;const R$=1e3;function O$(i){const e=performance.now();e-V0<R$||(V0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function L$(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(Fb(gv)),r=()=>{const f=Ct.getState(),{canRecord:g,reason:m}=gv(f);if(f.isRecording)return f.stopRecording();if(f.wizardArmed&&!f.wizardOpen){f.openWizard();return}if(m==="error"||m==="load-timeout"){f.resetAndRetryModel();return}if(!g)return O$(m);const b=St.getState().activeTabId;b&&f.startRecording(b)},l=bE(n.reason,{loadingPct:t,errorMessage:e,isRecording:i}),p=n.reason==="unsupported",a=!n.canRecord,d=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":i?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return c.jsx("button",{onClick:r,disabled:p,"aria-disabled":a,"aria-label":l,title:l,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${d}`,children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),c.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),c.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),c.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function $$(){const i=Ct(t=>t.ttsEnabled),e=Ct(t=>t.toggleTTS);return c.jsxs("button",{onClick:e,title:i?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${i?"text-accent":"text-fg-dim hover:text-fg"}`,children:[c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?c.jsxs(c.Fragment,{children:[c.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),c.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):c.jsxs(c.Fragment,{children:[c.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),c.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),c.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function N$(i){return/^monitor of /i.test(i.trim())}function q0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function K0(i,e,t){if(i){const p=t.find(a=>a.deviceId===i);if(p)return p}if(!e)return null;const n=t.filter(p=>p.label===e);if(n.length===1)return n[0];if(n.length>1)return null;const r=q0(e),l=t.filter(p=>p.label&&q0(p.label)===r);return l.length===1?l[0]:null}async function X0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&N$(n.label))):[]}const Y0=!1;function wE(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=B.useState([]),[n,r]=B.useState(null),[l,p]=B.useState(null);B.useEffect(()=>{let f=!1;return(async()=>{try{const g=await window.api.voice.getDevicePref();if(f)return;const m=await X0(Y0);if(f)return;t(m),p(g.selectedLabel);const b=K0(g.selectedDeviceId,g.selectedLabel,m);b?(r(b.deviceId),g.selectedDeviceId&&b.deviceId!==g.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:g.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||g.selectedLabel}).catch(()=>{}))):((g.selectedDeviceId||g.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:g.selectedLabel,hadId:!!g.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!g.selectedDeviceId})),r(null))}catch(g){pt.warn("voice","device-picker init failed",{error:g instanceof Error?g.message:String(g)})}})(),()=>{f=!0}},[]);const a=B.useCallback(async()=>{try{const f=await X0(Y0);if(t(f),n&&!f.some(g=>g.deviceId===n)){const g=K0(null,l,f);g?(r(g.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:g.deviceId,selectedLabel:g.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);B.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var T;const g=f.target.value,m=g===""?null:g,b=m?((T=e.find(E=>E.deviceId===m))==null?void 0:T.label)??null:null;r(m),p(b);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:b}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(E){pt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(i)try{await Ct.getState().restartWithDevice()}catch(E){pt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return c.jsxs("select",{value:n??"",onChange:d,onFocus:()=>{a()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[c.jsx("option",{value:"",children:"Default"}),e.map(f=>c.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function M$(){const i=Ct(T=>T.isRecording),e=Ct(T=>T.levelMeterEnabled),[t,n]=B.useState(0),[r,l]=B.useState(0),p=B.useRef(0);p.current=r;const[a,d]=B.useState(0),[f,g]=B.useState(!1),m=B.useRef(null);if(B.useEffect(()=>{if(!i||!e){n(0),l(0);return}let T=0,E=!1,k=null,y=null;const S=()=>{if(E)return;const x=y??O1();if(!x){T=requestAnimationFrame(S);return}y!==x&&(y=x,k=new Uint8Array(new ArrayBuffer(x.fftSize)));const A=k;x.getByteTimeDomainData(A);let O=0;for(let G=0;G<A.length;G++){const W=A[G]-128;O+=W*W}const $=Math.sqrt(O/A.length)/128,j=$>0?20*Math.log10($):-60,L=Math.max(0,Math.min(1,(j+60)/60));l($),n(L),$>=.95&&(g(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(!1),150)),T=requestAnimationFrame(S)};T=requestAnimationFrame(S);const w=setInterval(()=>{E||d(Math.round(p.current*100))},250);return()=>{E=!0,cancelAnimationFrame(T),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const b=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return c.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":a,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${f?"ring-1 ring-red-500":""}`,children:c.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function xE(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=B.useState(()=>performance.now());if(B.useEffect(()=>{if(i===null)return;let f;const g=()=>{n(performance.now()),f=requestAnimationFrame(g)};return f=requestAnimationFrame(g),()=>cancelAnimationFrame(f)},[i]),i===null)return null;const r=t-i,l=Math.max(0,e-r),p=Math.max(0,Math.min(100,l/e*100)),a=l<500,d=Ct.getState().cancelSubmit;return c.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:c.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:c.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function j$({open:i,onClose:e,variant:t="overlay"}){return c.jsx(A$,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:c.jsxs("div",{className:"p-4 space-y-4",children:[c.jsx(G$,{}),c.jsx(xE,{}),c.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[c.jsx(L$,{}),c.jsx(wE,{}),c.jsx($$,{})]}),c.jsx(z$,{}),c.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[c.jsx("button",{type:"button",onClick:()=>Ct.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),c.jsx(U$,{})]}),c.jsx(M$,{})]})})}function z$(){const i=Ct(l=>l.isRecording),[e,t]=B.useState(null);if(B.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(a=>{l||t(a)}).catch(()=>{});const p=window.api.voice.onHotkeyConfigChanged(a=>t(a));return()=>{l=!0,p()}},[]),i||!e)return null;const n=e.mode==="hold"?"Hold":"Press",r=B$(e.accelerator);return c.jsxs("div",{className:"text-[11px] text-fg-faint",children:[c.jsxs("span",{children:[n," "]}),c.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),c.jsx("span",{children:" to record"})]})}function B$(i){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return i.replace(/CommandOrControl/g,e?"⌘":"Ctrl").replace(/CmdOrCtrl/g,e?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,e?"⌥":"Alt").replace(/Shift/g,e?"⇧":"Shift")}function U$(){const[i,e]=B.useState(null);if(B.useEffect(()=>{let n=!1;window.api.voice.getHotkeyConfig().then(l=>{n||e(l)}).catch(l=>pt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const r=window.api.voice.onHotkeyConfigChanged(l=>{e(l)});return()=>{n=!0,r()}},[]),!i)return null;const t=async n=>{if(i.mode===n)return;const r={...i,mode:n};e(r);try{await window.api.voice.setHotkeyConfig(r)}catch(l){pt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return c.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[c.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[c.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),c.jsx("span",{children:"Tap on/off"})]}),c.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[c.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),c.jsx("span",{children:"Hold to talk"})]})]})}function G$(){const i=Ct(l=>l.isRecording),e=Ct(l=>l.lastTranscript),t=Ct(l=>l.error),n=Ct(l=>l.modelStatus),r=Ct(l=>l.loadingProgress);return t?c.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?c.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[c.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),c.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?c.jsxs("div",{className:"text-[11px] text-fg-faint",children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("span",{children:"Loading speech model"}),c.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),c.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const SE="~/.claude/session-manager/projects-prefs.json",H$={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Wl(i){const e=i(),t={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(SE,t).catch(()=>{})}const J0=Un((i,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const t=await window.api.config.readJson(SE);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data;i({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}i({hydrated:!0})},togglePin:t=>{const n={...e().pinned,[t]:!e().pinned[t]};i({pinned:n}),Wl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":H$[t];i({sort:{col:t,dir:r}}),Wl(e)},setRecentFilter:t=>{i({recentFilter:t}),Wl(e)},setHasRemote:t=>{i({hasRemote:t}),Wl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),Wl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),Wl(e)},setSearch:t=>{i({search:t}),Wl(e)},setEditor:t=>{i({editor:t}),Wl(e)}})),CE=i=>`sm.fileTree.expanded:${i}`;function F$(i){try{const e=localStorage.getItem(CE(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function W$(i,e){try{localStorage.setItem(CE(i),JSON.stringify([...e].slice(0,500)))}catch{}}const EE="sm.fileTree.showHidden";function V$(){try{const i=localStorage.getItem(EE);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function q$(i){try{localStorage.setItem(EE,JSON.stringify(i))}catch{}}function $_(i,e){const t=e+"/";let n=!1;const r=new Set;for(const l of i){if(l===e||l.startsWith(t)){n=!0;continue}r.add(l)}return n?r:i}const N_={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},K$=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 X$(i){const e=Mr(i);return K$.has(e)||GC.has(e)||e==="pdf"}function Y$(i,e){if(e)return"#d97757";switch(Mr(i)){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function kf(i){try{return await window.api.git.fileStatus(i)}catch{return{}}}function J$({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=vb(),l=Ov(),[p,a]=B.useState([]),[d,f]=B.useState(new Set),g=B.useRef(d);g.current=d;const[m,b]=B.useState(""),[T,E]=B.useState(V$),k=B.useCallback(qe=>{E(Rt=>{const _t=typeof qe=="function"?qe(Rt):qe;return q$(_t),_t})},[]),[y,S]=B.useState(!1),[w,x]=B.useState(null),[A,O]=B.useState({}),[$,j]=B.useState(null),[L,G]=B.useState(null),[W,re]=B.useState(""),[ae,Z]=B.useState(null),[pe,oe]=B.useState(""),[me,we]=B.useState(null),ve=B.useRef(null),F=B.useRef(null),J=B.useRef(0),V=B.useCallback(async()=>{if(!i)return;const qe=++J.current;S(!0),x(null);const Rt=await window.api.files.list(i,T);J.current===qe&&(Rt.ok?a(Rt.entries.map(_t=>({..._t}))):(x(Rt.error??"failed to list"),a([])),S(!1))},[i,T]),se=B.useCallback(async qe=>{const Rt=J.current,_t=new Map;for(const Ye of qe){const yt=Ye.split("/").length,ht=_t.get(yt);ht?ht.push(Ye):_t.set(yt,[Ye])}const ni=[];for(const Ye of[..._t.keys()].sort((yt,ht)=>yt-ht)){const yt=_t.get(Ye),ht=await Promise.all(yt.map(async ke=>({p:ke,result:await window.api.files.list(ke,T)})));if(J.current!==Rt)return ni;for(const{p:ke,result:tt}of ht)tt.ok?a(Wt=>rv(Wt,ke,tt.entries.map(ci=>({...ci})))):ni.push(ke)}return ni},[T]),ge=B.useCallback(async qe=>(await V(),qe.length?se(qe):[]),[V,se]);B.useEffect(()=>{b(""),G(null),j(null),Z(null),we(null),O({});const qe=F$(i),Rt=new Set(qe);g.current=Rt,f(Rt);let _t=!1;return(async()=>{const ni=await ge(qe);_t||!ni.length||je(Ye=>{const yt=new Set;let ht=!1;for(const ke of Ye){if(ni.some(tt=>ke===tt||ke.startsWith(tt+"/"))){ht=!0;continue}yt.add(ke)}return ht?yt:Ye})})(),kf(i).then(ni=>{_t||O(ni)}),()=>{_t=!0}},[i]);const Te=B.useRef(!0);B.useEffect(()=>{if(Te.current){Te.current=!1;return}ge([...g.current])},[T]),B.useEffect(()=>{if(!i||!l)return;kf(i).then(O);const qe=window.setInterval(()=>{kf(i).then(O)},5e3);return()=>window.clearInterval(qe)},[i,l]),B.useEffect(()=>{if(!$)return;const qe=()=>j(null),Rt=_t=>{r.current&&_t.key==="Escape"&&j(null)};return window.addEventListener("mousedown",qe),window.addEventListener("keydown",Rt),()=>{window.removeEventListener("mousedown",qe),window.removeEventListener("keydown",Rt)}},[$]),B.useEffect(()=>{L&&setTimeout(()=>{var qe;return(qe=ve.current)==null?void 0:qe.select()},30)},[L]),B.useEffect(()=>{ae&&setTimeout(()=>{var qe;return(qe=F.current)==null?void 0:qe.focus()},30)},[ae]);const je=B.useCallback(qe=>{const Rt=g.current,_t=qe(Rt);_t!==Rt&&(g.current=_t,f(_t),W$(i,_t))},[i]),Ze=B.useCallback(async qe=>{if(d.has(qe.path)){je(_t=>$_(_t,qe.path));return}if(je(_t=>new Set(_t).add(qe.path)),qe.children)return;const Rt=await window.api.files.list(qe.path,T);Rt.ok&&a(_t=>rv(_t,qe.path,Rt.entries.map(ni=>({...ni}))))},[d,T,je]),ye=B.useCallback(async qe=>{if(qe===i){await V();return}const Rt=await window.api.files.list(qe,T);Rt.ok&&a(_t=>rv(_t,qe,Rt.entries.map(ni=>({...ni}))))},[i,V,T]),Y=B.useCallback(qe=>{if(qe.isDirectory){Ze(qe);return}X$(qe.name)&&e?e(qe.path):window.api.shell.open({as:"openPath",path:qe.path})},[Ze,e]),_e=B.useCallback(qe=>{if(t){t(qe);return}if(n){const Rt=qe.startsWith(i+"/")?qe.slice(i.length+1):qe;window.api.pty.write({tabId:n,data:`@${Rt} `})}},[t,n,i]),ue=B.useCallback((qe,Rt)=>{qe.preventDefault(),qe.stopPropagation(),j({x:qe.clientX,y:qe.clientY,node:Rt})},[]),Re=qe=>{G(qe.path),re(qe.name)},He=async()=>{if(!L)return;const qe=W.trim();if(!qe){G(null);return}const Rt=await window.api.files.rename(L,qe);if(G(null),Rt.ok){const _t=L.slice(0,L.lastIndexOf("/"));je(ni=>$_(ni,L)),await ye(_t||i),kf(i).then(O)}else{const _t=Rt.error??"rename failed";x(_t),nt.error(_t)}},lt=async()=>{if(!ae)return;const qe=pe.trim();if(!qe){Z(null),oe("");return}const Rt=await window.api.files.create(ae.parent,qe,ae.kind);if(Z(null),oe(""),Rt.ok)await ye(ae.parent),ae.kind==="folder"&&je(_t=>new Set(_t).add(ae.parent));else{const _t=Rt.error??"create failed";x(_t),nt.error(_t)}},It=async()=>{if(!me)return;const qe=await window.api.files.delete(me.path),Rt=me.path.slice(0,me.path.lastIndexOf("/"));if(we(null),qe.ok)je(_t=>$_(_t,me.path)),await ye(Rt||i),kf(i).then(O);else{const _t=qe.error??"delete failed";x(_t),nt.error(_t)}},ct=B.useMemo(()=>{if(!m.trim())return p;const qe=m.toLowerCase();return p.filter(Rt=>Rt.name.toLowerCase().includes(qe))},[p,m]),qt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return c.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[c.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[c.jsx(TE,{size:14,className:"shrink-0 text-accent"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("p",{className:"text-xs font-medium text-fg truncate",children:qt}),c.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),c.jsx("button",{onClick:V,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:y,children:c.jsx(nN,{size:12,className:y?"animate-spin":""})})]}),c.jsx("div",{className:"relative",children:c.jsx("input",{value:m,onChange:qe=>b(qe.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"})})]}),c.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[c.jsx("button",{onClick:()=>Z({parent:i,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:c.jsx(sN,{size:12})}),c.jsx("button",{onClick:()=>Z({parent:i,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:c.jsx(rN,{size:12})}),c.jsx("div",{className:"flex-1"}),c.jsx("button",{onClick:()=>k(qe=>!qe),className:`p-1.5 rounded transition-colors ${T?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:T?"Hide hidden files":"Show hidden files",children:T?c.jsx(oN,{size:12}):c.jsx(aN,{size:12})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&c.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&ct.length===0&&!y&&c.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&c.jsx(kE,{nodes:ct,depth:0,expanded:d,gitStatus:A,renaming:L,renameValue:W,renameInputRef:ve,onRenameChange:re,onRenameCommit:He,onRenameCancel:()=>G(null),onToggleDir:Ze,onFileClick:Y,onSendToChat:_e,onContextMenu:ue})]}),c.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"}),$&&c.jsx(Z$,{x:$.x,y:$.y,node:$.node,onClose:()=>j(null),onRename:()=>{Re($.node),j(null)},onDelete:()=>{we($.node),j(null)},onNewFile:()=>{Z({parent:$.node.path,kind:"file"}),j(null)},onNewFolder:()=>{Z({parent:$.node.path,kind:"folder"}),j(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:$.node.path}),j(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:$.node.path}),j(null)},onCopyPath:()=>{var qe;(qe=navigator.clipboard)==null||qe.writeText($.node.path),j(null)},onSendToChat:()=>{_e($.node.path),j(null)}}),ae&&c.jsx(Z0,{title:`New ${ae.kind}`,subtitle:`in ${Q$(ae.parent)}`,onCancel:()=>{Z(null),oe("")},onConfirm:lt,confirmLabel:"Create",confirmDisabled:!pe.trim(),children:c.jsx("input",{ref:F,value:pe,onChange:qe=>oe(qe.target.value),onKeyDown:qe=>{qe.key==="Enter"&&lt(),qe.key==="Escape"&&(Z(null),oe(""))},placeholder:ae.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),me&&c.jsx(Z0,{title:`Delete ${me.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>we(null),onConfirm:It,confirmLabel:"Delete",danger:!0,children:c.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",c.jsxs("span",{className:"text-fg font-medium",children:['"',me.name,'"']})," to the trash?",me.isDirectory&&c.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function kE(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return c.jsx(c.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,g=r[a.path],m=Y$(a.name,a.isDirectory);return c.jsxs("div",{children:[c.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+t*14}px`},onClick:()=>{f||(a.isDirectory?i.onToggleDir(a):i.onFileClick(a))},onDoubleClick:()=>{a.isDirectory||window.api.shell.open({as:"openPath",path:a.path})},onContextMenu:b=>p(b,a),children:[a.isDirectory?c.jsx(iN,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):c.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?c.jsx(eN,{size:12,color:m}):c.jsx(TE,{size:12,color:m}):c.jsx(tN,{size:12,color:m}),f?c.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:b=>i.onRenameChange(b.target.value),onClick:b=>b.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:b=>{b.key==="Enter"&&i.onRenameCommit(),b.key==="Escape"&&i.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):c.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),g&&c.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:N_[g].color,backgroundColor:`${N_[g].color}20`},title:g,children:N_[g].label}),!a.isDirectory&&c.jsx("button",{onClick:b=>{b.stopPropagation(),i.onSendToChat(a.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:c.jsx(lN,{size:10})})]}),a.isDirectory&&d&&a.children&&c.jsx(kE,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function Z$(i){const{x:e,y:t,node:n}=i;return c.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:`fixed ${Cn.contextMenu} w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1`,style:{left:e,top:t},children:[!n.isDirectory&&c.jsx(Vl,{label:"Send to chat",onClick:i.onSendToChat}),c.jsx(Vl,{label:"Open in default app",onClick:i.onOpenExternal}),c.jsx(Vl,{label:"Reveal in OS",onClick:i.onShowInFinder}),c.jsx(M_,{}),c.jsx(Vl,{label:"Copy path",onClick:i.onCopyPath}),c.jsx(Vl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&c.jsxs(c.Fragment,{children:[c.jsx(M_,{}),c.jsx(Vl,{label:"New file",onClick:i.onNewFile}),c.jsx(Vl,{label:"New folder",onClick:i.onNewFolder})]}),c.jsx(M_,{}),c.jsx(Vl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Vl({label:i,onClick:e,danger:t}){return c.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${t?"text-red-400":"text-fg-dim hover:text-fg"}`,children:i})}function M_(){return c.jsx("div",{className:"my-1 border-t border-line"})}function Z0(i){return c.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:e=>{e.target===e.currentTarget&&i.onCancel()},children:c.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[c.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&c.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),c.jsx("div",{className:"mb-4",children:i.children}),c.jsxs("div",{className:"flex justify-end gap-2",children:[c.jsx("button",{onClick:i.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),c.jsx("button",{onClick:i.onConfirm,disabled:!!i.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:i.confirmLabel??"OK"})]})]})})}function Q$(i){return i.split("/").filter(Boolean).pop()||i}function rv(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:rv(n.children,e,t)}:n)}function ba({size:i,children:e,className:t,color:n}){return c.jsx("svg",{width:i,height:i,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:t,children:e})}function TE({size:i,className:e,color:t}){return c.jsx(ba,{size:i,className:e,color:t,children:c.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 eN({size:i,className:e,color:t}){return c.jsx(ba,{size:i,className:e,color:t,children:c.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 tN({size:i,className:e,color:t}){return c.jsxs(ba,{size:i,className:e,color:t,children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function iN({size:i,className:e}){return c.jsx(ba,{size:i,className:e,children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})}function nN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("polyline",{points:"1 20 1 14 7 14"}),c.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 sN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),c.jsx("polyline",{points:"14 2 14 8 20 8"}),c.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),c.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function rN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.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"}),c.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),c.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function oN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function aN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.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"}),c.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function lN({size:i,className:e}){return c.jsxs(ba,{size:i,className:e,children:[c.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),c.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function DE({content:i,children:e,align:t="bottom-right"}){const[n,r]=B.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return c.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&c.jsx("span",{role:"tooltip",className:`absolute ${Cn.dialog} ${l} px-2 py-1 text-[10px] leading-snug text-fg bg-bg-elev border border-line rounded shadow-lg max-w-[18rem] whitespace-normal pointer-events-none`,children:i})]})}function qf(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const Gy="sm.projects.splitPct",Hy=33,AE=20,IE=60,PE="sm.projects.fileTreeCollapsed",cN=32;function dN(){try{const i=parseFloat(localStorage.getItem(Gy)??"");if(Number.isFinite(i))return Math.min(IE,Math.max(AE,i))}catch{}return Hy}function uN(){try{return localStorage.getItem(PE)==="1"}catch{return!1}}function hN(){const i=St(W=>W.tabs),e=St(W=>W.activeTabId),t=i.find(W=>W.id===e)??null,n=Ii(W=>W.navFace),[r,l]=B.useState(null);B.useEffect(()=>{if(n!=="home"||r)return;let W=!1;return window.api.app.homeDir().then(re=>{W||l(re)}).catch(()=>{}),()=>{W=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=B.useState(()=>dN()),[f,g]=B.useState(()=>uN()),[m,b]=B.useState(!1),T=B.useRef(a);T.current=a;const E=B.useRef(null),k=B.useRef(null),{projects:y,openProject:S,archiveProjectByCwd:w}=vd(),x=J0(W=>W.pinned),A=J0(W=>W.togglePin),O=[...y].sort((W,re)=>(x[re.cwd]?1:0)-(x[W.cwd]?1:0));B.useEffect(()=>{if(!m)return;const W=re=>{k.current&&!k.current.contains(re.target)&&b(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[m]);const $=B.useCallback(W=>{Oi.getState().openFile(W)},[]),j=B.useCallback(W=>{W.preventDefault();const re=W.clientX,ae=T.current;let Z=ae;const pe=me=>{const we=E.current;if(!we)return;const ve=we.getBoundingClientRect(),F=me.clientX-re;Z=Math.min(IE,Math.max(AE,ae+F/ve.width*100)),d(Z)},oe=()=>{window.removeEventListener("pointermove",pe),window.removeEventListener("pointerup",oe),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gy,String(Z))}catch{}};window.addEventListener("pointermove",pe),window.addEventListener("pointerup",oe),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=B.useCallback(()=>{d(Hy);try{localStorage.setItem(Gy,String(Hy))}catch{}},[]),G=B.useCallback(()=>{g(W=>{const re=!W;try{localStorage.setItem(PE,re?"1":"0")}catch{}return re})},[]);return f?c.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[c.jsxs("button",{onClick:G,"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:cN},children:[c.jsx("span",{className:"text-[11px]",children:"▸"}),c.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),c.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:c.jsx(Uy,{})})]}):c.jsxs("div",{ref:E,className:"flex h-full w-full","data-testid":"projects-workspace",children:[c.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[c.jsxs("div",{ref:k,className:"relative shrink-0 flex items-stretch border-b border-line",children:[c.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>b(W=>!W),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:[c.jsx("span",{className:"flex-1 truncate text-left",children:p?qf(p):"Projects"}),c.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),c.jsx("button",{onClick:G,"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&&c.jsx("div",{"data-testid":"projects-launcher-list",className:`absolute left-0 right-0 top-full ${Cn.dialog} bg-bg-elev border border-line shadow-lg max-h-60 overflow-auto`,children:O.length===0?c.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):O.map(W=>{const re=qf(W.cwd);return c.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[c.jsx(DE,{content:x[W.cwd]?"Unpin":"Pin to top",children:c.jsx("button",{onClick:()=>A(W.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[W.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[W.cwd]?"★":"☆"})}),c.jsx("button",{onClick:()=>{S(W.cwd),b(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:re}),c.jsx("button",{onClick:async()=>{window.confirm(`Archive ${re}?`)&&await w(W)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},W.cwd)})})]}),p?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 border-b border-line text-[11.5px] text-fg-faint font-mono truncate shrink-0",title:p,children:qf(p)}),c.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:c.jsx(J$,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:$})})]}):c.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),c.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:j,onDoubleClick:L,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),c.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:c.jsx(Uy,{})})]})}const pN=B.memo(hN),fN={"project-home":{headline:"The Brief — what this project is, and what is in flight",intro:"Home for a project tab is a synthesized brief: what the project is for, how it is structured, and what is currently in flight across its Epics. Content is scaffolded for now — the synthesis pipeline lands in a later update.",sections:[{title:"What you see",items:[{body:"A header naming the active project, resolved from the active tab's working directory."}]}]},overview:{headline:"Your home base — a calm landing page for your local Claude Code cockpit",intro:"Overview is the first screen you see. It greets you by time of day and frames Session Manager as a local cockpit that wraps the Claude CLI alongside skills, hooks, MCP servers, and a scheduler. Nothing here phones home. The page is a launchpad, not a settings screen: a live 5-hour usage card, a few quick-start buttons, your most-recent sessions, and a peek at what is queued in the scheduler. Click any of them to jump straight into the relevant tab.",sections:[{title:"What you see",items:[{term:"Billing meters",body:"A live read of your subscription usage — plan chip, the current 5-hour rolling window, and the weekly windows — each with percent used, a color bar, and the reset time. Same data the CLI /usage command reads."},{term:"Quick start",body:"Four buttons — Start a session, Resume last (opens History), Draft a PRD (opens Scheduler), and Add a project (opens Projects) — plus a microphone button that opens voice input."},{term:"Recent sessions",body:"Your four most-recently-touched transcripts, scanned from ~/.claude/projects. Each row shows the project, the short session id, the transcript size, and how long ago it was active. Click a row to reopen that session with claude --resume."},{term:"In the scheduler",body:"A peek at the first three jobs in the scheduler queue, each tagged running or queued with a rough time estimate. “Open scheduler →” jumps to the full Scheduler tab."}]},{title:"Behaviors this affects",items:[{body:"Overview is read-only and click-through. It never edits anything; every button just navigates you to the tab that does the work (History, Scheduler, Projects, Voice) or starts a new session."},{body:"The 5-hour countdown refreshes on a timer. If the usage card shows a dash, billing data is not loaded yet (or the Claude login has expired — re-authenticate with the CLI)."}]}]},terminal:{headline:"A real Claude Code CLI running inside the app, kept alive across tab switches",intro:"The Terminal tab is a genuine terminal running the claude CLI for you. It behaves like running claude in your own shell, but Session Manager keeps the process alive when you switch to other tabs, makes file paths and URLs clickable, smooths over copy/paste, and lets you broadcast a prompt to several tabs or attach background watchers. Each tab is one Claude session — the tab id IS the session id, so the tab maps directly to its transcript on disk.",sections:[{title:"In the terminal pane",items:[{term:"Settings gear (top-right)",body:"A small gear opens a popover to change the terminal theme (Dark / Light / Paper) and font size (10–22px, with a reset). Changes apply instantly to every open terminal and persist between launches."},{term:"Clickable file paths",body:"Paths like src/main/index.cjs:42 are detected and underlined. Clicking one opens that file in the in-app editor at the right line. URLs are also clickable and open in your system browser."},{term:"Paste images",body:"Ctrl+V pastes clipboard text as usual, but if the clipboard holds an image it is saved to a temp PNG and its path is typed in — so you can paste a screenshot and let Claude read it."},{term:"Smart Ctrl+C",body:"With text selected, Ctrl+C copies it; with nothing selected, Ctrl+C passes through to interrupt Claude (same as a normal terminal). Ctrl+Shift+C always copies."}]},{title:"Session commands (Command Palette / shortcuts)",items:[{term:"Restart session",body:"Ctrl+Shift+R kills this tab's claude process and spawns a fresh one in the same directory. Use it after editing settings, hooks, or skills so Claude reloads them."},{term:"Reboot app",body:"Relaunches Session Manager; your tabs come back automatically. Use when something feels stuck."},{term:"Broadcast",body:"Ctrl+Shift+B opens a bar to send the same prompt to several tabs at once. You tick which tabs to include; each row shows sent or skipped (a dead session is skipped)."},{term:"Watchers",body:"Ctrl+Shift+W attaches a long-running shell command (e.g. npm test --watch, tail -f log) to this tab. Each new line of its output pops up as a toast. Watchers survive tab switches and stop when you remove them."}]},{title:"Things that are easy to miss",items:[{body:"Open the Command Palette (Cmd-K / Ctrl-K) to reach the session commands above, plus copy-cwd, copy-transcript path, and open-transcript."},{body:"Switching to another tab does NOT kill the terminal — the claude process keeps running in the background and the screen is just hidden."},{body:"Voice input (the microphone in the sidebar) types into whichever terminal tab is focused — there is no separate voice tab."}]}],tips:["Press Ctrl+C with nothing selected to interrupt Claude mid-response — same as the standalone CLI.","If the prompt looks frozen, scroll up: Claude often produced output but the cursor is below the visible window."]},"system-prompt":{headline:"Edit ~/.claude/CLAUDE.md — the house rules every session on this machine starts with",intro:"CLAUDE.md is a plain-text file Claude reads at the start of every session. Whatever you write here is added to its instructions — so it's where you put coding standards, communication preferences, and “always do X / never do Y” rules. This tab edits exactly ONE of them: the User file at ~/.claude/CLAUDE.md, which applies everywhere, in every project. A project can also carry its own <repo>/CLAUDE.md and <repo>/CLAUDE.local.md — those are contextual to that project and are read by the CLI from the session's own directory when it launches there, so they are edited with the project's files, not from this machine-wide screen.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the real ~/.claude/CLAUDE.md. Save writes it to disk; Claude picks it up on its next session start."},{term:"Presets",body:"Browse a library of starter prompts. Use one as a starting point, then refine it in the editor."}]},{title:"What this file reaches — and what it doesn't",items:[{term:"User (edited here)",body:"Lives at ~/.claude/CLAUDE.md. Applies to every session you start, in every repo. Best for personal style: communication tone, default tooling preferences, things you always want."},{term:"Project (not edited here)",body:"Lives at <repo>/CLAUDE.md, checked into git — shared team context: stack, architecture, do/don't lists. It only means anything relative to a project directory, so it is picked up when a session launches in that repo; open it from the project's own files."},{term:"Local (not edited here)",body:"Lives at <repo>/CLAUDE.local.md, gitignored — personal overrides that shouldn't reach teammates. Same story as Project: contextual to one repo, applied at session launch."},{body:"At runtime every file that is present combines; more-specific wins: Local > Project > User. This screen only owns the base layer."}]},{title:"What's shown in the header",items:[{term:"chars / tokens",body:"A rough size estimate (~4 chars per token). The bigger the file, the more of Claude's context window it consumes before your real prompt — keep it tight."},{term:"unsaved edits",body:"Save and Revert live in the bottom bar; navigating away does NOT auto-save."},{body:"If the file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets here (“be concise”, “use Python type hints”, “always run tests after changes”). That alone changes Claude's behavior noticeably.","Don't write essays. Claude reads CLAUDE.md before every reply, so every word costs tokens. One-line rules beat paragraphs.","Rule of thumb for what belongs here: if it would still be true in a repo you haven't created yet, it is a User rule. If it names this stack, this architecture, or this team, it belongs in that project's own CLAUDE.md."]},settings:{headline:"The settings.json files that control Claude Code's behavior",intro:"Claude Code is configured by JSON files named settings.json. This tab shows up to three of them combined: User (~/.claude/settings.json), Project (<repo>/.claude/settings.json, shared with the repo), and Local (<repo>/.claude/settings.local.json, your private overrides). The Guided view is a friendly card editor; Tree shows the merged values as a JSON tree; Raw lets you hand-edit the file. A bundled schema (from schemastore.org) gives you autocomplete and validation as you type.",sections:[{title:"Views",items:[{term:"Guided",body:"A card-based editor over the merged settings. Each setting shows which scope currently provides it; editing a card writes the change into the scope you've selected."},{term:"Tree",body:"The same merged config as an expandable JSON tree. Useful for nested settings like permissions and hooks; you can override a value into the active scope from here too."},{term:"Raw",body:"The JSON file at the active scope, edited directly. Save validates before writing; a parse error blocks the save and is shown in the bottom bar."},{term:"Telemetry",body:"Opt-in OpenTelemetry export of Session Manager's own classified transcript events (tool names, todo counts, usage tokens). Off by default, stored separately from Claude's settings, and excludes prompt/plan content unless you turn on “Include content”."}]},{title:"Common settings to know",items:[{term:"model",body:"Default model used when you start a session (e.g. “opus”, “sonnet”, “haiku”). Override per-session with /model in the terminal."},{term:"permissions",body:"Allow / Ask / Deny lists for Bash commands, file edits, MCP tools, web fetches. The dedicated Permissions tab is a friendlier UI for this same key."},{term:"hooks",body:"Shell commands the CLI runs in response to events (pre/post tool use, session start, etc.). See the Hooks tab."},{term:"env",body:"Environment variables injected into every claude process — handy for API keys or DEBUG flags."},{term:"mcpServers",body:"External tool servers Claude can call. Edit via the MCP Servers tab for a structured form."}]},{title:"Scope precedence",items:[{body:"Local overrides Project overrides User. A Project-scoped setting beats a User-scoped one when you work in that repo, and your personal Local file beats both. Project and Local require an open project tab — with no working directory, only User is editable."},{body:"Lists merge (allow + allow), but objects do not — a Project-scoped { permissions: { allow: [...] } } REPLACES the user-scoped object wholesale unless you copy the entries you want to keep."}]}],tips:["When in doubt, edit at User scope. Project-scoped settings get committed to git; teammates inherit them.","After changing settings.json, restart any open sessions (Restart session, Ctrl+Shift+R) so Claude reloads."]},permissions:{headline:"Decide which tools Claude can run automatically and which need your OK",intro:"Every action Claude takes — running a Bash command, editing a file, calling an MCP tool — passes a permission check. This tab is a structured editor for the permissions block inside settings.json (there is no separate permissions file). You build three lists — Allow / Deny / Ask — of rules; get them right and you barely see prompts, get them wrong and you're either hammered with confirmations or Claude runs something you didn't want.",sections:[{title:"Views",items:[{term:"Effective",body:"The merged permissions Claude actually sees, as a tree, with which scope each value came from. Read-and-override here."},{term:"Rules",body:"The structured editor: a Default Mode picker, the Allow / Deny / Ask lists (type a rule and press Enter or click add; × to remove), and Additional Directories. Edits write into the scope you've selected."},{term:"Presets",body:"A starter library of common permission sets to copy from."}]},{title:"The three lists",items:[{term:"Allow",body:"Claude runs matching actions silently — no confirmation. Use for safe, repetitive things: Bash(ls:*), Read(~/.claude/**), Edit(src/**)."},{term:"Deny",body:"Claude refuses outright, even if you'd say yes interactively. Use for genuinely dangerous things: Bash(rm -rf:*), Write(/etc/**)."},{term:"Ask",body:"Claude pauses and asks before running. Sits between Allow and Deny for things you want to eyeball each time."}]},{title:"Rule shape",items:[{term:"Tool(pattern)",body:"Format is <ToolName>(<pattern>). Examples: Bash(git push:*), Edit(src/**/*.ts), WebFetch(domain:*.example.com)."},{term:":*",body:"A trailing colon-star means “any arguments”. Bash(npm:*) allows every npm invocation; Bash(npm test) only the literal “npm test”."},{body:"Deny wins ties. If a request matches both Allow and Deny, Deny takes effect. (See the “rule syntax” link in the toolbar for the full grammar.)"}]},{title:"Default Mode",items:[{term:"default",body:"Out-of-the-box behavior: ask for risky operations, allow harmless reads."},{term:"acceptEdits",body:"Auto-approve file edits within the session's working tree. Speeds up iterative coding; avoid for prod repos."},{term:"plan",body:"Read-only mode. Claude can explore and propose, but cannot edit or run shell commands. Good for review sessions."},{term:"bypassPermissions",body:"Skip ALL prompts. Equivalent to --dangerously-skip-permissions. Use only in throwaway sandboxes."}]}],tips:["Start permissive at User scope (your common safe commands), then tighten at Project scope for repos with secrets.","Additional Directories lets Claude read files outside the cwd — add reference repos here as absolute paths instead of cd’ing into each one."]},skills:{headline:"Reusable instructions Claude loads on demand for specific tasks",intro:`A skill is a markdown file that teaches Claude how to do one specific thing — "write Playwright tests", "review SQL migrations", "format an OpenAPI doc". Each skill has frontmatter describing when to trigger it and a body with the actual instructions. Claude doesn't load all skills up front; it scans titles and pulls the body in only when a relevant request arrives, keeping your context tight.`,sections:[{title:"List + Detail",items:[{term:"Scope switch",body:"Toggle User vs Project at the top. User skills live in ~/.claude/skills/ and apply everywhere; Project skills live in <repo>/.claude/skills/ and only when a tab is open in that repo. The toolbar shows the item count and the file path of the selected skill."},{term:"Sidebar",body:"Two groups — Skills and Slash Commands — with a filter box that matches on name. Click an entry to open its markdown in the editor."},{term:"Enable toggle",body:"Each skill has an on/off switch. Turning it off writes disable-model-invocation into the skill's frontmatter, so Claude stops auto-invoking it; the file stays on disk and the name shows struck-through. Slash commands have no toggle."},{term:"Remove (✕)",body:"Deletes a skill's folder to the trash (recoverable). It comes out of your active set entirely — reinstall any time from the Library. This is different from the toggle, which only stops auto-invocation."},{term:"Editor",body:"Standard markdown with a Save/Revert bar at the bottom. The frontmatter (the --- block at the top) controls discovery; the body is what Claude reads when the skill fires."},{term:"Library view",body:'Switch to Library to browse a curated catalog of skills. Each row gives a "source" link and a "copy install" button (a git-clone command you paste into a terminal) — there is no one-click install for skills.'}]},{title:"Skill anatomy",items:[{term:"name",body:"Used in transcripts and the Library. Should be unique within a scope."},{term:"description",body:'Critical — Claude scans descriptions to decide when to load this skill. Be specific about WHEN to use it ("when writing E2E tests with Playwright"), not just what it does.'},{term:"allowed-tools",body:"Optional. Restricts which tools Claude can use while the skill is active. Adds an extra layer of safety on top of permissions."},{term:"Body",body:"Plain markdown. Procedures, code examples, do/don't lists. This is what Claude actually reads."}]},{title:"Slash commands",items:[{body:'Commands (in ~/.claude/commands/ or .claude/commands/) are skills you invoke explicitly with /name — they show with a leading "/" in the sidebar. Skills proper are auto-loaded; commands are user-triggered.'},{body:"This tab lists both at the active scope — same markdown shape on disk, different folders."}]}],tips:["A bad description is worse than no skill — Claude either won't load it when needed, or will load it constantly and waste tokens.","When refining a skill, use Restart Session in the terminal so Claude reloads it."]},plugins:{headline:"Bundled collections of skills, subagents, and hooks that ship together",intro:'A plugin is a directory under ~/.claude/plugins/<name>/ that packages multiple Claude Code primitives (skills, subagents, hooks, MCP servers, LSPs, monitors) under one name. Installing a plugin adds all of them at once; uninstalling removes them cleanly. Use plugins when you want to share a coherent toolkit — "react-frontend-pack", "data-pipeline-helpers" — instead of asking teammates to copy ten files into the right places.',sections:[{title:"Three views",items:[{term:"Installed",body:"A read-only inspector for every plugin folder on disk, shown as a table: name, origin, version, whether it has a manifest, and a contents summary (counts of agents · skills · hooks · monitors · bin · lsp · mcp). Click a row to drill into a full-page view: a header with name/version/description, a meta strip (author, license, homepage, and the full path), and a section index (skills, agents, MCP server, hooks, monitors, LSP, bin) beside the component listing. To edit a plugin's pieces, use the dedicated Skills / Hooks tabs — they point at the same files."},{term:"Discover",body:"A built-in list of official add-ons (LSP servers, MCP integrations). The Install button runs claude plugin install <slug> in a hidden terminal and streams its output below the row; on success the row flips to installed."},{term:"Library",body:'Browse the curated plugin catalog. Each row has a "source" link, a "copy" button for the /plugin install command, and an Install button that wires up the marketplace and installs for you.'}]},{title:"Plugin layout on disk",items:[{term:"plugin.json",body:"The manifest — name, version, description, what the plugin includes. The canonical location is .claude-plugin/plugin.json; older installs keep it at the folder root. Both are detected."},{term:"skills/",body:"Same shape as ~/.claude/skills/. Show up in the Skills tab."},{term:"agents/",body:"Markdown subagents (same shape as ~/.claude/agents/), available to the main Claude to delegate to."},{term:"hooks/hooks.json",body:"Hooks contributed by the plugin (mirrors settings.json's hooks shape, keyed by event), merged into your effective hook set."},{term:".mcp.json / .lsp.json / monitors/",body:"Optional — MCP servers, language servers, and monitors the plugin bundles. Their presence shows up in the contents summary."}]}],tips:["The Installed view is inspect-only here — it will not let you edit or delete plugin files. Edit a plugin's contents through the Skills/Hooks tabs instead.","Editing plugin contents directly is fine but be aware: an upgrade may overwrite your changes. Fork the plugin if you need persistent customizations."]},mcp:{headline:"Connect Claude to external tools — databases, APIs, filesystems — via MCP servers",intro:"MCP (Model Context Protocol) is the open spec for letting Claude call out to external tools. An MCP server is a small process (or HTTP endpoint) that exposes a set of functions; once you register it, Claude treats those functions as first-class tools. Common examples: a Postgres server that lets Claude run SELECTs, a Slack server that posts messages, a filesystem server that exposes a specific directory tree.",sections:[{title:"Where servers are stored",items:[{term:"User scope",body:"~/.claude.json under mcpServers. Available in every session, every repo."},{term:"Project scope",body:"<repo>/.mcp.json. Available only when working in this repo. Commit it so teammates pick up the same servers."},{term:"Editing",body:'Use "+ new server" to add one, click a row to edit it, rename via the name field, and Save/Revert at the bottom. A filter box narrows the list; the Library view installs catalog servers for you.'}]},{title:"Server types",items:[{term:"stdio",body:"Local process — Claude spawns the command and talks to it via stdin/stdout. Most common for tools you ship as a CLI. Fields: command, args, env."},{term:"http / streamable-http",body:"Remote endpoint with JSON-RPC. Field: url, plus headers for auth."},{term:"sse",body:"Server-Sent Events transport — deprecated; the editor flags it and suggests streamable-http instead."},{term:"ws",body:"WebSocket transport. Same url + headers fields as the other remote types."}]},{title:"Per-server controls",items:[{term:"env / headers",body:"Secrets like API keys go here (env for stdio, headers for remote types). Project-scope values get committed to git — be careful; prefer User scope for anything sensitive."},{term:"args",body:"Command-line arguments passed to a stdio server's command. Often used to point at a specific config file or directory."},{term:"alwaysLoad",body:"Bypass tool-search deferral and always load this server's tools up front (rather than only when searched for)."},{term:"enabled",body:"Uncheck to stop loading this server in new sessions without deleting its config."},{term:"disabledTools",body:"A comma-separated denylist of individual tool names to hide from this server."},{term:"permissions",body:"Per-server tool gating: inherit (default), allow all, deny all, or an explicit allowlist of tool names."}]}],tips:['The name "workspace" is reserved — the editor warns that Claude Code will refuse to load a server with that name. Names like "ide" and "tasks" get a softer caution because they collide with commonly-bundled servers.',"After adding/editing a server, restart the affected sessions so Claude reconnects and rediscovers tools."]},hooks:{headline:"Run scripts when Claude does something — pre/post-tool, session start/end, more",intro:"Hooks let you run a shell command, HTTP request, prompt, subagent, or MCP tool in response to events Claude Code emits. Want to log every Bash command Claude runs to a file? PreToolUse hook. Want a subagent to review every edit before it sticks? PostToolUse hook. Want a Slack ping when a long session ends? Stop hook. Hooks are stored in settings.json and can gate, log, or transform actions.",sections:[{title:"Two ways to view",items:[{term:"Effective",body:"The merged result of all scopes (User / Project / Local) — what actually fires. Editing here writes an override into the scope you have selected."},{term:"Events",body:"A per-event editor. The left list shows every supported event with a count of hooks attached; pick one, then add groups (with an optional matcher) and hooks under it."},{term:"Library",body:"Browse catalog hooks. Each event row links to the official hook reference."}]},{title:"The five hook types",items:[{term:"command",body:"Run a shell string (with an optional args array for the no-shell exec form). The script receives the event as JSON on stdin and can return a JSON decision. Only command hooks support the Test fire button."},{term:"http",body:"POST the event JSON to a URL. The response becomes the decision."},{term:"prompt",body:'Send a templated prompt to Claude itself for a quick gut-check. Useful for "should I really run this command?" guards.'},{term:"agent",body:"Spawn a subagent (a markdown file under ~/.claude/agents/) with the event as input. The agent's output is the decision."},{term:"mcp_tool",body:"Invoke a named MCP tool (e.g. mcp__server__tool) in response to the event."}]},{title:"Common events",items:[{term:"PreToolUse / PostToolUse",body:"Before / after Claude calls any tool. Most-used hooks live here — gating, logging, transforming. A matcher (tool-name regex or exact match) scopes a group to specific tools."},{term:"UserPromptSubmit",body:"Fires when you press Enter on a prompt. Good for prepending context (current branch, recent errors) before Claude sees the prompt."},{term:"SessionStart / SessionEnd",body:"Boot/teardown housekeeping — refresh tokens, save transcripts, post a summary."},{term:"Stop / SubagentStop",body:'When the main loop or a subagent finishes. Good for "ping me when done" notifications.'},{term:"PreCompact / PostCompact",body:"Around the auto-compaction step. Useful for archiving the full transcript before it's shrunk."},{body:"Many more are supported — permissions, tasks, worktrees, config/file changes, notifications. Hover any event in the list for its trigger and payload shape. Hooks saved under names Claude Code no longer recognizes are flagged in a warning banner."}]}],tips:['Test new hooks with the "test fire" button next to a command hook — it runs the command against an editable fake event payload (and shows whether your matcher would match) so you can debug without waiting for a real session.',"Each hook can set a timeout (ms) and command hooks can emit a terminalSequence (e.g. a bell). Slow synchronous hooks are noticeable — use http or fire-and-forget for work you don't need to wait on."]},memory:{headline:"Memories Claude can read and write across sessions — by project or by subagent",intro:`Two scopes share one tab, toggled by the Workspace / Subagent switch up top (your choice is remembered). Workspace is a cwd-scoped notebook at ~/.claude/projects/<workspace>/memory/ — plain markdown files with an optional description. Subagent is keyed by agent at ~/.claude/session-manager/agent-memory/<agentId>.json — facts about a specific agent (e.g. the "code-reviewer" agent's preferred test runner) that survive across projects. You can hand-edit either here; Claude writes to them during sessions when you ask it to remember things across context resets.`,sections:[{title:"Workspace memories",items:[{term:"Scope",body:"Auto-selected from the active terminal tab's directory. Switching to a tab in a different folder shows a different memory set. A watcher refreshes the list when Claude writes to these files mid-session."},{term:"New memory",body:"Names are lowercase letters/digits/dashes/underscores and become the .md filename. You can add an optional one-line description. Edit the body in the markdown editor, then Save (or Delete)."},{term:"Natural panel",body:'A chat-style console for the workspace. Type plain commands — list, show <name>, search <text>, remember <text>, forget <name>, help. It never writes on its own: free-form text offers two buttons — "Send to Claude in terminal" (pastes a prompt you still press Enter on) or "Add as new memory" (writes directly).'}]},{title:"Subagent memories",items:[{term:"Agent",body:"Pick an agent from the dropdown — scanned from ~/.claude/agents and <cwd>/.claude/agents (project agents shadow same-named user ones)."},{term:"Entries",body:'Each entry has an id, a body, and an optional category: Commands, Preferences, Patterns, Avoid, or Workflow. Newest entries sort first. Add via "+ New entry"; edit the body and Save, or Delete.'},{term:"Caps",body:"1 MiB per entry body. Writes above the cap are refused."}]}]},projects:{headline:"Every directory you've ever run Claude Code in, with quick-resume and bulk tools",intro:"Whenever you start a Claude session in a new directory, Claude Code remembers it by writing transcripts under ~/.claude/projects/<encoded-cwd>/. This tab lists those directories — how many sessions each has, when you last worked there, total transcript size — plus git and CLAUDE.md details it fills in as it reads each folder. Search, filter, pin your favorites, open a folder four different ways, or archive ones you're done with.",sections:[{title:"Columns",items:[{term:"Project",body:"The directory path (with its detected project name). Hover to peek at the start of its CLAUDE.md if it has one."},{term:"Sessions",body:"How many session transcripts exist for this folder. High numbers mean you work here often."},{term:"Last active",body:"When the most recent transcript was touched. The default sort — most recent first."},{term:"Size",body:"Disk usage of all transcripts for this project. Old projects can balloon; archiving is safe if you don't need the history."},{term:"Branch / Remote",body:"The last git branch and git remote, shown once Session Manager finishes reading the folder."}]},{title:"Per-row actions",items:[{term:"Open in session",body:"Spawns a new terminal tab running claude in this directory."},{term:"Open externally",body:"Three more openers: your editor (VS Code / Cursor / Sublime / nano — pick a default up top, or Auto), your file manager, or a system terminal."},{term:"CLAUDE.md",body:"A side drawer that previews this project's CLAUDE.md read-only (no in-drawer editing)."},{term:"Pin / Archive",body:"Star a project to keep it at the top; archive moves it to ~/.claude/projects-archive/ after a confirm."}]},{title:"Finding projects",items:[{term:"Search",body:"Matches path, project name, git remote, and the CLAUDE.md preview."},{term:"Sort & filter",body:"Sort by project, sessions, last active, or size (toggle direction). Filter chips narrow by recency (≤7d / ≤30d), git remote, CLAUDE.md presence, or pinned-only."},{term:"Stats header",body:"Totals up top: project count, how many were active in 7 days, total sessions, total on-disk size, and clickable pills for your most-active projects."}]}],tips:["Tick the checkboxes to select several projects, then archive them all or open them all in your editor at once.","Sort by size to find runaway transcript folders — a multi-hundred-MB project usually means many long sessions, safe to archive if you don't need them."]},history:{headline:"Every individual Claude session you've ever run, ready to resume",intro:"Where the Projects tab shows directories, the History tab shows individual sessions — one row per .jsonl transcript under ~/.claude/projects/. Two views share the tab: Log is a flat, searchable list you can resume from; Dashboard rolls the same transcripts up into prompt, token, and cost charts. Your view choice is remembered.",sections:[{title:"Log view",items:[{term:"Session id",body:"The UUID identifying the session (shown short). The same id appears in --session-id flags and Claude's own logs."},{term:"Project",body:"The folder this session belongs to (the encoded directory name, decoded back to a path)."},{term:"Last active / Size",body:"When the transcript was last touched (sorted newest first) and its size — a big transcript means a long conversation."},{term:"Resume",body:"Click Resume, pick the directory to run in, and a new tab opens running claude --resume <sessionId>. Claude reads the full transcript and continues; the tab id matches the session id."},{term:"Filter",body:"The search box matches session id and project name (case-insensitive substring); it does not search message text."}]},{title:"Dashboard view",items:[{term:"Summary",body:"Cards for total prompts, input tokens, output tokens, sessions, and estimated cost across the selected range."},{term:"Charts",body:"A daily trend line (switch between prompts, tokens, sessions, errors, or cost) and a per-day input-vs-output token stack, plus a sortable per-project table with each project's top tool and estimated cost."},{term:"Range & refresh",body:'Narrow by from/to date and by project name. Auto-refreshes every 30 seconds, with a manual refresh button and an "updated X ago" stamp. A yellow banner warns if a scan timed out and the numbers are partial.'}]}],tips:["Resume lets you pick any directory — handy when you've moved or renamed the original project folder since the session ran."]},scheduler:{headline:"Author PRDs and run them as claude -p jobs against your 5-hour window",intro:"One home for the headless-batch workflow, split into three tabs. The Queue tab combines global Options (session pool, fire policy, on-disk paths) with monitoring this project's jobs; the PRDs tab is where you author the markdown files those jobs execute; the History tab lists recent completed and failed jobs. PRDs live in each active project's own <cwd>/session-manager-operations/scheduler/prds/. A status strip across the top shows when the window resets, how many jobs are pending / running / completed today, and how much of the 5-hour window you have used. Jobs auto-pause on rate-limit and auto-resume on the next 5-hour reset.",sections:[{title:"Queue — when jobs start",items:[{term:"when available",body:'Default. The scheduler polls your billing usage every ~10 minutes and fires the next batch whenever your 5-hour utilization is below the "Pause above" percent (90% by default).'},{term:"only on reset",body:"Fire queued jobs shortly after each 5-hour window resets, instead of polling."},{term:"manually",body:'Nothing fires on its own — you start work yourself with "Fire next batch now".'}]},{title:"Queue — controls",items:[{term:"Up to N at once",body:"How many jobs in the same group may run in parallel. Defaults to 3 — raising it runs more node processes at once, which can exhaust memory on a small machine."},{term:"Fire next batch now",body:"Launches the next batch immediately, bypassing the billing-usage poll. Useful when the usage meter is itself rate-limited or you just want progress now."},{term:"Resume",body:"When the queue is paused (rate-limit, expired sign-in, network, or a manual pause), a banner explains why and offers Resume."}]},{title:"PRDs — authoring",items:[{body:"Each file is one task — frontmatter (title, cwd, estimateMinutes, parallelGroup) plus a self-contained body Claude can act on without conversation context."},{term:"parallelGroup",body:'The group number. Jobs in the same group run together (up to the concurrency cap); lower groups run before higher ones. If you omit it, the leading "NN-" number in the filename is used, else 99.'},{term:"estimateMinutes",body:"Roughly how long you expect the job to take. The scheduler uses this to pick jobs that fit in your remaining 5-hour budget."}]},{title:"Options — the session pool (global, not per-project)",items:[{term:"One pool, every consumer",body:"Session-Manager owns a machine-wide pool of concurrent Claude sessions (3 by default). Scheduler jobs and Epic chat runs each request a slot before launching and release it when they finish — no subsystem has a private cap that can stack with another's."},{term:"Guardrails",body:"Beyond the slot cap, a memory gate defers new jobs when free RAM drops below a per-job budget, and each job gets an OOM-score bias so the kernel prefers killing a restartable job over the app itself."}]}],tips:["Use the /prd skill to create a fresh PRD with the right structure — manually-written ones often miss the cwd or estimate fields.","Read PRD_AUTHORING.md before queueing a new job — it codifies two real stuck-job incidents (the fizzpop poll-hang and the etch-engine post-AC overrun).","SM_SESSION_SLOTS (1–3) overrides the pool size for one launch; the default is sized to keep three 1 GB+ jobs from starving the app."]},editor:{headline:"View and edit files in-app",intro:"Opens when you click a file in the File Explorer sidebar or a file link in the terminal. Text files open in Monaco (syntax highlighting, font zoom, word wrap, minimap, Dark/Paper theme); Markdown adds Edit / Wysiwyg / Preview / Split, HTML adds Edit / Preview. Images, PDFs, CSV/TSV tables, and JSONL records each get their own viewer; binary or oversized files show a summary instead. URLs still open in your browser.",sections:[{title:"Editing",items:[{term:"Cmd/Ctrl-S",body:'Save the active file. With Autosave on (the "Auto" toggle), edits also save automatically ~1.2 s after you stop typing.'},{term:"Cmd/Ctrl-Shift-F",body:"Toggle Focus mode — hides the tabs and header for distraction-free editing. Esc exits."},{term:"Close guard",body:"Closing a tab with unsaved changes asks before discarding."}]},{title:"Markdown",items:[{term:"Wysiwyg",body:"A rich-text mode built on Tiptap with a floating formatting toolbar (bold, italic, headings, lists, code, blockquote, links) — edit the rendered document directly instead of raw markdown. YAML frontmatter is split off, kept read-only, and rejoined on save; switch to Edit for surgical edits to PRDs and agent files, since Wysiwyg normalizes list markers and heading style."},{term:"Outline",body:"In Preview or Split mode, a document outline lists headings; click to jump. Toggle it with the Outline button."},{term:"Toolbar",body:"A formatting toolbar sits above the editor for Markdown files."}]}],tips:["Use the view toggle (Edit / Wysiwyg / Preview / Split) for Markdown, or Edit / Preview for HTML. HTML previews are sandboxed — page scripts run with no access to your files or session.","Open and Reveal buttons hand the file to your OS default app or file manager."]},voice:{headline:"Voice & microphone",intro:"Talk to Claude instead of typing. Speech is transcribed on-device with a Whisper model that loads the first time you record (a progress bar shows the download). A press-to-record hotkey starts and stops the mic; what you say is typed into the active terminal, and an auto-submit timer fires it for you a moment after you stop speaking. A one-time mic check confirms your microphone works.",sections:[{title:"Recording controls",items:[{term:"Hotkey",body:"Press your mic hotkey to record. The default is Ctrl+Shift+Space (Cmd+Option+V on Mac); the panel shows the live binding. Two behaviours: 'Hold to talk' records only while the key is held (push-to-talk), 'Tap on/off' starts on one press and stops on the next. The default is hold-to-talk; switch with the radio buttons."},{term:"Mic button & device",body:"The mic button toggles recording with the mouse. The device picker chooses which microphone to use, and a live level meter shows that audio is coming through."},{term:"Run mic check",body:"Opens a short wizard that confirms your mic is picking up sound. It runs automatically once after a settings-format change, or any time you click 'Run mic check'."}]},{title:"Speaking & hearing back",items:[{term:"Live transcript",body:"While recording, a pulsing red dot and the latest transcribed words appear so you can see what was heard. Errors (e.g. mic blocked) surface inline in red."},{term:"TTS (read replies aloud)",body:"The speaker button toggles text-to-speech. When on, Claude's replies are read back to you out loud."}]}],tips:["The speech model downloads on first use only, then stays cached — later recordings start instantly.","Hold-to-talk is best for quick interjections; Tap on/off is better for longer dictation where you don't want to hold a key."]},"agent-library":{headline:"Agent Library — every persona available to this machine",intro:"Global agent definitions live at ~/.claude/agents/*.md. A project can overlay a same-named agent at <project>/.claude/agents/<name>.md, which Claude Code prefers over the global definition whenever both exist. New / Duplicate / Save / Delete here write the matching global .md file directly.",sections:[{title:"What it shows",items:[{term:"Global personas",body:"Every agent .md file under ~/.claude/agents, with its frontmatter (name, description, model, color, tools) and body."},{term:"Overriding projects",body:"For each agent, which of your currently-open project tabs has a local overlay of the same name — that overlay is what actually runs in that project. Dropping one here deletes that project's local .md file."}]}],tips:["Home face only — this is machine-wide data, not scoped to one project.","Only the global definition is editable here — a project overlay is created by Claude Code convention (a same-named file under <project>/.claude/agents/), not from this page."]},"tag-library":{headline:"Tag Library — the Epic intent-tag taxonomy",intro:"Every Epic carries an initial intent tag — feature, bug, discussion, or build — chosen at creation. The tag sets how eagerly /develop should fire inside that Epic's session: feature/bug/build treat PRD decomposition as the expected next step, discussion keeps /develop available but never assumed until whether-to-build is settled.",sections:[{title:"What it shows",items:[{term:"Tag",body:"The four intent tags an Epic can be created with."},{term:"/develop eagerness",body:"Whether PRD decomposition is the expected default for that tag, or available-but-not-assumed."},{term:"Agents carrying this tag",body:"Which Agent Library personas have this tag in their `tags:` frontmatter — the same relationship Agent Library edits from the agent side. Assign or remove an agent here to update that persona's file directly."}]}],tips:["Home face only — the taxonomy is machine-wide, not scoped to one project.","The tag taxonomy itself is read-only here — change an existing Epic's tag from its queue row menu, not from this page. The agent↔tag assignment, though, is editable from either Tag Library or Agent Library."]},"bilko-host":{headline:"Host on Bilko.run — publish this project's Project Home page",intro:"Turns this project's already-generated Project Home page (home.html) into a live static-path listing on bilko.run, using the bilko-host MCP's existing gated publish pipeline (manifest/budget/golden/a11y/audit checks) — never a second, competing hosting mechanism.",sections:[{title:"What it shows",items:[{term:"Status",body:"not-published → bundle-ready → publishing → published/publish-failed, mirroring the on-disk publish-state.json a bilko-host-publisher Epic writes."},{term:"Slug",body:"The bilko.run/projects/<slug>/ path this project would publish to — defaults from package.json's name."},{term:"Bundle",body:"Size, build time, and git sha of the dist/ bundle Prepare Bundle last wrote."}]}],tips:["Project face only — publishing is always scoped to the active project's tab.",`Requires a generated Project Home page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]},"data-model":{headline:"Data Model — an ERD of what Session Manager actually persists",intro:"A hand-maintained diagram of the app's own storage: entities, their on-disk path/format, the single-writer owner if one is declared, their fields, and how they relate. It is a mirror of the real shapes in code (lib/dataModelErd.ts), not a live scanner — it can drift if a shape changes without an update.",sections:[{title:"What it shows",items:[{term:"Diagram",body:"Boxes grouped by realm (project/machine/both), with relation lines. Click a box for its storage path, fields, and relations; toggle a group in the legend to hide it."},{term:"Tables",body:"The same entities as a flat, grouped list of tables — useful for scanning every field at once."}]}],tips:["Home face only — this diagrams the application's own data model, which is identical for every project.","Read-only reference material, not live data — nothing here reflects the currently-open project's actual on-disk state."]}},Wb="sm.learningPanel.collapsed";function Q0(){try{const i=localStorage.getItem(Wb);if(i===null)return!1;if(i.startsWith("{")){const e=JSON.parse(i);return!!(e&&typeof e=="object"&&Object.values(e).some(Boolean))}return i==="1"||i==="true"}catch{return!1}}function eS(i){try{localStorage.setItem(Wb,i?"1":"0")}catch{}}function mN({content:i}){return c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:i.intro}),i.sections.map(e=>c.jsxs("div",{className:"mb-3 last:mb-0",children:[c.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:e.title}),c.jsx("ul",{className:"space-y-1",children:e.items.map((t,n)=>c.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[t.term&&c.jsx("span",{className:"text-fg font-medium",children:t.term}),t.term&&" — ",c.jsx("span",{children:t.body})]},n))})]},e.title)),i.tips&&i.tips.length>0&&c.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[c.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),c.jsx("ul",{className:"space-y-1",children:i.tips.map((e,t)=>c.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",e]},t))})]})]})}function gN({active:i}){const[e,t]=B.useState(()=>!Q0()),n=B.useRef(null),r=B.useCallback(()=>{t(a=>{const d=!a;return eS(!d),d})},[]);B.useEffect(()=>{const a=d=>{d.key===Wb&&t(!Q0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),B.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),eS(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=B.useRef(!1);B.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=fN[i];return p?c.jsxs("span",{ref:n,className:"relative inline-block",children:[c.jsx("button",{type:"button",onClick:r,className:"text-[10px] uppercase tracking-wider text-accent font-medium hover:opacity-80 transition-opacity","aria-expanded":e,title:e?"Close learning panel":"What is this?",children:"Learn"}),e&&c.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:c.jsx(mN,{content:p})})]}):null}function vN({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return c.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&c.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[c.jsxs("div",{className:"max-w-[820px]",children:[i&&c.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&c.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&c.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&c.jsx(gN,{active:r})]}),c.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const _N=B.lazy(()=>Bn(()=>import("./Skills-D522Zfol.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,1,2]),import.meta.url).then(i=>({default:i.Skills}))),yN=B.lazy(()=>Bn(()=>import("./History-BDyJUGtR.js"),__vite__mapDeps([12,1,2]),import.meta.url).then(i=>({default:i.History}))),bN=B.lazy(()=>Bn(()=>import("./Scheduler--rn1QBYc.js"),__vite__mapDeps([13,10,7,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),wN=B.lazy(()=>Bn(()=>import("./Settings-Dsx6XZP5.js"),__vite__mapDeps([14,6,5,15,7,1,2]),import.meta.url).then(i=>({default:i.Settings}))),xN=B.lazy(()=>Bn(()=>import("./Permissions-DhMMp27n.js"),__vite__mapDeps([16,6,5,9,15,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),SN=B.lazy(()=>Bn(()=>import("./SystemPrompt-DKj-q39J.js"),__vite__mapDeps([17,5,9,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),CN=B.lazy(()=>Bn(()=>import("./Memory-B-9GlHqe.js"),__vite__mapDeps([18,4,1,2]),import.meta.url).then(i=>({default:i.Memory}))),EN=B.lazy(()=>Bn(()=>import("./Plugins-DKfAlmMY.js"),__vite__mapDeps([19,8,9,11,1,2,4]),import.meta.url).then(i=>({default:i.Plugins}))),kN=B.lazy(()=>Bn(()=>import("./McpServers-B_rvIYDs.js"),__vite__mapDeps([20,5,6,8,9,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),TN=B.lazy(()=>Bn(()=>import("./Hooks-CmK6l0uf.js"),__vite__mapDeps([21,5,6,8,9,15,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),DN=B.lazy(()=>Bn(()=>Promise.resolve().then(()=>Lz),void 0,import.meta.url).then(i=>({default:i.AgentLibrary}))),AN=B.lazy(()=>Bn(()=>import("./TagLibrary-BH7CG7-6.js"),__vite__mapDeps([22,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),IN=B.lazy(()=>Bn(()=>import("./HostBilko-D8TIx-Bx.js"),__vite__mapDeps([23,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),PN=B.lazy(()=>Bn(()=>import("./DataModel-DZK9QZpV.js"),__vite__mapDeps([24,1,2]),import.meta.url).then(i=>({default:i.DataModel}))),RN=c.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function hr({children:i}){return c.jsx(B.Suspense,{fallback:RN,children:i})}const ON={skills:{title:"Reusable instructions",intro:"Skills are scoped pieces of context that Claude loads on demand. Add new ones, audit what is live, or disable a skill that is misbehaving."},history:{title:"Every session, ever",intro:"Resumable transcripts across every project you have opened. Pick a row to reattach Claude to the same conversation."},plugins:{title:"Plugins",intro:"Extensions for Claude Code. Install, enable, or remove plugins per-scope."},mcp:{title:"MCP Servers",intro:"External tools and integrations the agent can call. Add a new server or test an existing connection."},hooks:{title:"Hooks",intro:"Run scripts on session events. Tail logs, format files, post to Slack — anything that responds to a shell command."},memory:{title:"Memory",intro:"Memories that persist across conversations — Workspace scope (keyed by project) or Subagent scope (keyed by agent). Stored locally, nothing leaves your machine."},"system-prompt":{title:"System prompt",intro:"The personality and behavior contract for this app. Edits here apply to every new session you spawn."},permissions:{title:"Permissions",intro:"Allow and deny rules per scope. Adjust which tools Claude can call without prompting."},settings:{title:"Settings",intro:"Theme, voice input, billing window, density. Per-scope JSON with schema validation."},"agent-library":{title:"Agent Library",intro:'Agents are the ACTOR of the AIM framework every session opens with — "you are acting as …". Every persona on this machine lives here: global definitions in ~/.claude/agents, plus which currently-open projects override them locally. Give a persona a project scope and an opening instruction and it also becomes an Action — a one-click button in that project’s Sessions toolbar that starts a session already grounded on it. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk.'},"tag-library":{title:"Tag Library",intro:"Every session intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},"bilko-host":{title:"Host on Bilko.run",intro:"Publish this project's generated Marketing page to bilko.run as a static-path listing, via the bilko-host MCP's gated publish pipeline."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},"data-model":{title:"Data Model",intro:"A hand-maintained ERD of what Session Manager actually persists — storage paths, single-writer owners, and how entities relate."}},LN=()=>{},tS=new Map;function $N(i,e){const t=tS.get(i);if(t&&t.ctx===e)return t.node;const n=NN(i,e);return tS.set(i,{ctx:e,node:n}),n}function NN(i,e){switch(i){case"overview":return c.jsx(TP,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return c.jsx(oR,{});case"editor":return c.jsx(Uy,{});case"projects":return c.jsx(pN,{})}const t=ON[i],n=(()=>{switch(i){case"skills":return c.jsx(hr,{children:c.jsx(_N,{})});case"history":return c.jsx(hr,{children:c.jsx(yN,{})});case"scheduler":return c.jsx(hr,{children:c.jsx(bN,{navigate:e.onNavigate})});case"plugins":return c.jsx(hr,{children:c.jsx(EN,{})});case"mcp":return c.jsx(hr,{children:c.jsx(kN,{})});case"hooks":return c.jsx(hr,{children:c.jsx(TN,{})});case"memory":return c.jsx(hr,{children:c.jsx(CN,{})});case"system-prompt":return c.jsx(hr,{children:c.jsx(SN,{})});case"permissions":return c.jsx(hr,{children:c.jsx(xN,{})});case"settings":return c.jsx(hr,{children:c.jsx(wN,{})});case"agent-library":return c.jsx(hr,{children:c.jsx(DN,{})});case"tag-library":return c.jsx(hr,{children:c.jsx(AN,{})});case"bilko-host":return c.jsx(hr,{children:c.jsx(IN,{})});case"data-model":return c.jsx(hr,{children:c.jsx(PN,{})});case"voice":return c.jsx(j$,{open:!0,onClose:LN,variant:"page"});default:return null}})();if(!n)return null;const r=jT[i];return t&&r?c.jsx(vN,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var j_={exports:{}},iS;function MN(){return iS||(iS=1,(function(i,e){(function(t,n){i.exports=n()})(globalThis,(()=>(()=>{var t={4567:function(p,a,d){var f=this&&this.__decorate||function(w,x,A,O){var $,j=arguments.length,L=j<3?x:O===null?O=Object.getOwnPropertyDescriptor(x,A):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(w,x,A,O);else for(var G=w.length-1;G>=0;G--)($=w[G])&&(L=(j<3?$(L):j>3?$(x,A,L):$(x,A))||L);return j>3&&L&&Object.defineProperty(x,A,L),L},g=this&&this.__param||function(w,x){return function(A,O){x(A,O,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),b=d(9924),T=d(844),E=d(4725),k=d(2585),y=d(3656);let S=a.AccessibilityManager=class extends T.Disposable{constructor(w,x,A,O){super(),this._terminal=w,this._coreBrowserService=A,this._renderService=O,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 $=0;$<this._terminal.rows;$++)this._rowElements[$]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[$]);if(this._topBoundaryFocusListener=$=>this._handleBoundaryFocus($,0),this._bottomBoundaryFocusListener=$=>this._handleBoundaryFocus($,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(($=>this._handleResize($.rows)))),this.register(this._terminal.onRender(($=>this._refreshRows($.start,$.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar(($=>this._handleChar($)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
3028
3028
  `)))),this.register(this._terminal.onA11yTab(($=>this._handleTab($)))),this.register(this._terminal.onKey(($=>this._handleKey($.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,T.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(w){for(let x=0;x<w;x++)this._handleChar(" ")}_handleChar(w){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==w&&(this._charsToAnnounce+=w):this._charsToAnnounce+=w,w===`
3029
3029
  `&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=m.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(w){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(w)||this._charsToConsume.push(w)}_refreshRows(w,x){this._liveRegionDebouncer.refresh(w,x,this._terminal.rows)}_renderRows(w,x){const A=this._terminal.buffer,O=A.lines.length.toString();for(let $=w;$<=x;$++){const j=A.lines.get(A.ydisp+$),L=[],G=(j==null?void 0:j.translateToString(!0,void 0,void 0,L))||"",W=(A.ydisp+$+1).toString(),re=this._rowElements[$];re&&(G.length===0?(re.innerText=" ",this._rowColumns.set(re,[0,1])):(re.textContent=G,this._rowColumns.set(re,L)),re.setAttribute("aria-posinset",W),re.setAttribute("aria-setsize",O))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(w,x){const A=w.target,O=this._rowElements[x===0?1:this._rowElements.length-2];if(A.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||w.relatedTarget!==O)return;let $,j;if(x===0?($=A,j=this._rowElements.pop(),this._rowContainer.removeChild(j)):($=this._rowElements.shift(),j=A,this._rowContainer.removeChild($)),$.removeEventListener("focus",this._topBoundaryFocusListener),j.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const L=this._createAccessibilityTreeNode();this._rowElements.unshift(L),this._rowContainer.insertAdjacentElement("afterbegin",L)}else{const L=this._createAccessibilityTreeNode();this._rowElements.push(L),this._rowContainer.appendChild(L)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),w.preventDefault(),w.stopImmediatePropagation()}_handleSelectionChange(){var G;if(this._rowElements.length===0)return;const w=document.getSelection();if(!w)return;if(w.isCollapsed)return void(this._rowContainer.contains(w.anchorNode)&&this._terminal.clearSelection());if(!w.anchorNode||!w.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:w.anchorNode,offset:w.anchorOffset},A={node:w.focusNode,offset:w.focusOffset};if((x.node.compareDocumentPosition(A.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===A.node&&x.offset>A.offset)&&([x,A]=[A,x]),x.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(x={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(x.node))return;const O=this._rowElements.slice(-1)[0];if(A.node.compareDocumentPosition(O)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(A={node:O,offset:((G=O.textContent)==null?void 0:G.length)??0}),!this._rowContainer.contains(A.node))return;const $=({node:W,offset:re})=>{const ae=W instanceof Text?W.parentNode:W;let Z=parseInt(ae==null?void 0:ae.getAttribute("aria-posinset"),10)-1;if(isNaN(Z))return console.warn("row is invalid. Race condition?"),null;const pe=this._rowColumns.get(ae);if(!pe)return console.warn("columns is null. Race condition?"),null;let oe=re<pe.length?pe[re]:pe.slice(-1)[0]+1;return oe>=this._terminal.cols&&(++Z,oe=0),{row:Z,column:oe}},j=$(x),L=$(A);if(j&&L){if(j.row>L.row||j.row===L.row&&j.column>=L.column)throw new Error("invalid range");this._terminal.select(j.column,j.row,(L.row-j.row)*this._terminal.cols-j.column+L.column)}}_handleResize(w){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let x=this._rowContainer.children.length;x<this._terminal.rows;x++)this._rowElements[x]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[x]);for(;this._rowElements.length>w;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const w=this._coreBrowserService.mainDocument.createElement("div");return w.setAttribute("role","listitem"),w.tabIndex=-1,this._refreshRowDimensions(w),w}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let w=0;w<this._terminal.rows;w++)this._refreshRowDimensions(this._rowElements[w])}}_refreshRowDimensions(w){w.style.height=`${this._renderService.dimensions.css.cell.height}px`}};a.AccessibilityManager=S=f([g(1,k.IInstantiationService),g(2,E.ICoreBrowserService),g(3,E.IRenderService)],S)},3614:(p,a)=>{function d(b){return b.replace(/\r?\n/g,"\r")}function f(b,T){return T?"\x1B[200~"+b+"\x1B[201~":b}function g(b,T,E,k){b=f(b=d(b),E.decPrivateModes.bracketedPasteMode&&k.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(b,!0),T.value=""}function m(b,T,E){const k=E.getBoundingClientRect(),y=b.clientX-k.left-10,S=b.clientY-k.top-10;T.style.width="20px",T.style.height="20px",T.style.left=`${y}px`,T.style.top=`${S}px`,T.style.zIndex="1000",T.focus()}Object.defineProperty(a,"__esModule",{value:!0}),a.rightClickHandler=a.moveTextAreaUnderMouseCursor=a.paste=a.handlePasteEvent=a.copyHandler=a.bracketTextForPaste=a.prepareTextForTerminal=void 0,a.prepareTextForTerminal=d,a.bracketTextForPaste=f,a.copyHandler=function(b,T){b.clipboardData&&b.clipboardData.setData("text/plain",T.selectionText),b.preventDefault()},a.handlePasteEvent=function(b,T,E,k){b.stopPropagation(),b.clipboardData&&g(b.clipboardData.getData("text/plain"),T,E,k)},a.paste=g,a.moveTextAreaUnderMouseCursor=m,a.rightClickHandler=function(b,T,E,k,y){m(b,T,E),y&&k.rightClickSelect(b),T.value=k.selectionText,T.select()}},7239:(p,a,d)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.ColorContrastCache=void 0;const f=d(1505);a.ColorContrastCache=class{constructor(){this._color=new f.TwoKeyMap,this._css=new f.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:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.addDisposableDomListener=void 0,a.addDisposableDomListener=function(d,f,g,m){d.addEventListener(f,g,m);let b=!1;return{dispose:()=>{b||(b=!0,d.removeEventListener(f,g,m))}}}},3551:function(p,a,d){var f=this&&this.__decorate||function(S,w,x,A){var O,$=arguments.length,j=$<3?w:A===null?A=Object.getOwnPropertyDescriptor(w,x):A;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(S,w,x,A);else for(var L=S.length-1;L>=0;L--)(O=S[L])&&(j=($<3?O(j):$>3?O(w,x,j):O(w,x))||j);return $>3&&j&&Object.defineProperty(w,x,j),j},g=this&&this.__param||function(S,w){return function(x,A){w(x,A,S)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const m=d(3656),b=d(8460),T=d(844),E=d(2585),k=d(4725);let y=a.Linkifier=class extends T.Disposable{get currentLink(){return this._currentLink}constructor(S,w,x,A,O){super(),this._element=S,this._mouseService=w,this._renderService=x,this._bufferService=A,this._linkProviderService=O,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,T.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,T.toDisposable)((()=>{var $;this._lastMouseEvent=void 0,($=this._activeProviderReplies)==null||$.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(S){this._lastMouseEvent=S;const w=this._positionFromMouseEvent(S,this._element,this._mouseService);if(!w)return;this._isMouseOut=!1;const x=S.composedPath();for(let A=0;A<x.length;A++){const O=x[A];if(O.classList.contains("xterm"))break;if(O.classList.contains("xterm-hover"))return}this._lastBufferCell&&w.x===this._lastBufferCell.x&&w.y===this._lastBufferCell.y||(this._handleHover(w),this._lastBufferCell=w)}_handleHover(S){if(this._activeLine!==S.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(S,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,S)||(this._clearCurrentLink(),this._askForLink(S,!0))}_askForLink(S,w){var A,O;this._activeProviderReplies&&w||((A=this._activeProviderReplies)==null||A.forEach(($=>{$==null||$.forEach((j=>{j.link.dispose&&j.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=S.y);let x=!1;for(const[$,j]of this._linkProviderService.linkProviders.entries())w?(O=this._activeProviderReplies)!=null&&O.get($)&&(x=this._checkLinkProviderResult($,S,x)):j.provideLinks(S.y,(L=>{var W,re;if(this._isMouseOut)return;const G=L==null?void 0:L.map((ae=>({link:ae})));(W=this._activeProviderReplies)==null||W.set($,G),x=this._checkLinkProviderResult($,S,x),((re=this._activeProviderReplies)==null?void 0:re.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(S.y,this._activeProviderReplies)}))}_removeIntersectingLinks(S,w){const x=new Set;for(let A=0;A<w.size;A++){const O=w.get(A);if(O)for(let $=0;$<O.length;$++){const j=O[$],L=j.link.range.start.y<S?0:j.link.range.start.x,G=j.link.range.end.y>S?this._bufferService.cols:j.link.range.end.x;for(let W=L;W<=G;W++){if(x.has(W)){O.splice($--,1);break}x.add(W)}}}}_checkLinkProviderResult(S,w,x){var $;if(!this._activeProviderReplies)return x;const A=this._activeProviderReplies.get(S);let O=!1;for(let j=0;j<S;j++)this._activeProviderReplies.has(j)&&!this._activeProviderReplies.get(j)||(O=!0);if(!O&&A){const j=A.find((L=>this._linkAtPosition(L.link,w)));j&&(x=!0,this._handleNewLink(j))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let j=0;j<this._activeProviderReplies.size;j++){const L=($=this._activeProviderReplies.get(j))==null?void 0:$.find((G=>this._linkAtPosition(G.link,w)));if(L){x=!0,this._handleNewLink(L);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(S){if(!this._currentLink)return;const w=this._positionFromMouseEvent(S,this._element,this._mouseService);w&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,w)&&this._currentLink.link.activate(S,this._currentLink.link.text)}_clearCurrentLink(S,w){this._currentLink&&this._lastMouseEvent&&(!S||!w||this._currentLink.link.range.start.y>=S&&this._currentLink.link.range.end.y<=w)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,T.disposeArray)(this._linkCacheDisposables))}_handleNewLink(S){if(!this._lastMouseEvent)return;const w=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);w&&this._linkAtPosition(S.link,w)&&(this._currentLink=S,this._currentLink.state={decorations:{underline:S.link.decorations===void 0||S.link.decorations.underline,pointerCursor:S.link.decorations===void 0||S.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,S.link,this._lastMouseEvent),S.link.decorations={},Object.defineProperties(S.link.decorations,{pointerCursor:{get:()=>{var x,A;return(A=(x=this._currentLink)==null?void 0:x.state)==null?void 0:A.decorations.pointerCursor},set:x=>{var A;(A=this._currentLink)!=null&&A.state&&this._currentLink.state.decorations.pointerCursor!==x&&(this._currentLink.state.decorations.pointerCursor=x,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",x))}},underline:{get:()=>{var x,A;return(A=(x=this._currentLink)==null?void 0:x.state)==null?void 0:A.decorations.underline},set:x=>{var A,O,$;(A=this._currentLink)!=null&&A.state&&(($=(O=this._currentLink)==null?void 0:O.state)==null?void 0:$.decorations.underline)!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(S.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const A=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,O=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=A&&this._currentLink.link.range.end.y<=O&&(this._clearCurrentLink(A,O),this._lastMouseEvent)){const $=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);$&&this._askForLink($,!1)}}))))}_linkHover(S,w,x){var A;(A=this._currentLink)!=null&&A.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!0),this._currentLink.state.decorations.pointerCursor&&S.classList.add("xterm-cursor-pointer")),w.hover&&w.hover(x,w.text)}_fireUnderlineEvent(S,w){const x=S.range,A=this._bufferService.buffer.ydisp,O=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-A-1,x.end.x,x.end.y-A-1,void 0);(w?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(O)}_linkLeave(S,w,x){var A;(A=this._currentLink)!=null&&A.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!1),this._currentLink.state.decorations.pointerCursor&&S.classList.remove("xterm-cursor-pointer")),w.leave&&w.leave(x,w.text)}_linkAtPosition(S,w){const x=S.range.start.y*this._bufferService.cols+S.range.start.x,A=S.range.end.y*this._bufferService.cols+S.range.end.x,O=w.y*this._bufferService.cols+w.x;return x<=O&&O<=A}_positionFromMouseEvent(S,w,x){const A=x.getCoords(S,w,this._bufferService.cols,this._bufferService.rows);if(A)return{x:A[0],y:A[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(S,w,x,A,O){return{x1:S,y1:w,x2:x,y2:A,cols:this._bufferService.cols,fg:O}}};a.Linkifier=y=f([g(1,k.IMouseService),g(2,k.IRenderService),g(3,E.IBufferService),g(4,k.ILinkProviderService)],y)},9042:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(p,a,d){var f=this&&this.__decorate||function(k,y,S,w){var x,A=arguments.length,O=A<3?y:w===null?w=Object.getOwnPropertyDescriptor(y,S):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(k,y,S,w);else for(var $=k.length-1;$>=0;$--)(x=k[$])&&(O=(A<3?x(O):A>3?x(y,S,O):x(y,S))||O);return A>3&&O&&Object.defineProperty(y,S,O),O},g=this&&this.__param||function(k,y){return function(S,w){y(S,w,k)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const m=d(511),b=d(2585);let T=a.OscLinkProvider=class{constructor(k,y,S){this._bufferService=k,this._optionsService=y,this._oscLinkService=S}provideLinks(k,y){var G;const S=this._bufferService.buffer.lines.get(k-1);if(!S)return void y(void 0);const w=[],x=this._optionsService.rawOptions.linkHandler,A=new m.CellData,O=S.getTrimmedLength();let $=-1,j=-1,L=!1;for(let W=0;W<O;W++)if(j!==-1||S.hasContent(W)){if(S.loadCell(W,A),A.hasExtendedAttrs()&&A.extended.urlId){if(j===-1){j=W,$=A.extended.urlId;continue}L=A.extended.urlId!==$}else j!==-1&&(L=!0);if(L||j!==-1&&W===O-1){const re=(G=this._oscLinkService.getLinkData($))==null?void 0:G.uri;if(re){const ae={start:{x:j+1,y:k},end:{x:W+(L||W!==O-1?0:1),y:k}};let Z=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const pe=new URL(re);["http:","https:"].includes(pe.protocol)||(Z=!0)}catch{Z=!0}Z||w.push({text:re,range:ae,activate:(pe,oe)=>x?x.activate(pe,oe,ae):E(0,oe),hover:(pe,oe)=>{var me;return(me=x==null?void 0:x.hover)==null?void 0:me.call(x,pe,oe,ae)},leave:(pe,oe)=>{var me;return(me=x==null?void 0:x.leave)==null?void 0:me.call(x,pe,oe,ae)}})}L=!1,A.hasExtendedAttrs()&&A.extended.urlId?(j=W,$=A.extended.urlId):(j=-1,$=-1)}}y(w)}};function E(k,y){if(confirm(`Do you want to navigate to ${y}?
3030
3030
 
@@ -3051,7 +3051,7 @@ Check git vs the published package for this project, decide the right version bu
3051
3051
  \x1B[38;5;240m[session exited code=${O}]\x1B[0m\r
3052
3052
  `),f(i,!1),d({code:O??null})});m.onData(O=>el(t,O)),m.onResize(({cols:O,rows:$})=>window.api.pty.resize({tabId:t,cols:O,rows:$})),window.api.pty.spawn({tabId:t,cwd:e,cols:k,rows:y}).then(async({reattached:O})=>{if(O)return;const $=await Iv(e,t).catch(()=>!0),j=await Jj(e,t),L=await Zj(e,t),W=`claude --dangerously-skip-permissions ${$?`--resume ${fr(t)}`:`--session-id ${fr(t)}`}${ob(j)}${Gk(L)}\r`;setTimeout(()=>el(t,W),1500)}).catch(O=>{const $=O instanceof Error?O.message:String(O);m.write(`\r
3053
3053
  \x1B[31mfailed to start terminal: ${$}\x1B[0m\r
3054
- `),nt.error(`Terminal failed to start: ${$}`)});const x=()=>T();window.addEventListener("resize",x);const A=new ResizeObserver(()=>T());return A.observe(r.current),()=>{window.removeEventListener("resize",x),A.disconnect(),S(),w(),E(),m.dispose()}},[t,e,i,f]),a?c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-sm text-fg-faint","data-testid":"epic-terminal-exited",children:[c.jsxs("p",{children:["Terminal session exited",a.code!==null?` (code ${a.code})`:"","."]}),c.jsx("button",{type:"button",onClick:n,"data-testid":"epic-terminal-back-to-chat",className:"rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-white hover:bg-accent/90",children:"Back to Chat"})]}):c.jsx("div",{ref:r,"data-testid":"epic-terminal-host",onMouseDown:()=>{var g;return(g=l.current)==null?void 0:g.focus()},className:"h-full w-full bg-bg"})}const e3={default:"bg-bg-hi text-fg-dim border-line",accent:"bg-accent/15 text-accent-dark border-accent/30",warn:"bg-honey/15 text-honey-dark border-honey/30",dim:"bg-bg-elev text-fg-dim border-line",good:"bg-sage/15 text-sage-dark border-sage/30"};function _a({children:i,tone:e="default",className:t="",title:n}){return c.jsx("span",{title:n,className:`inline-flex items-center gap-1 text-[10px] leading-none px-1.5 py-0.5 rounded border uppercase tracking-wide ${e3[e]} ${t}`,children:i})}function JE(i){if(!i)return null;const e=i.replace(/\/+$/,"").split("/");return e[e.length-1]||i}function t3(i,e){const t=i?JE(i)??"":e??"";return CC(t)}const i3={running:"bg-accent text-white",investigating:"bg-accent text-white",pending:"bg-bg text-fg-dim border border-line",completed:"bg-sage/20 text-sage",skipped:"bg-fg-dim/10 text-fg-dim border border-line",needs_review:"bg-butter/25 text-fg-dim",failed:"bg-accent/15 text-accent",quarantined:"bg-fuchsia-500/20 text-fuchsia-300 border border-fuchsia-500/40"},n3={pending:"○",completed:"✓",skipped:"⊘",needs_review:"!",failed:"✕",quarantined:"⚑"};function s3({status:i}){const e=n3[i];return c.jsxs("span",{className:`inline-flex items-center gap-1.5 shrink-0 px-2.5 py-1 rounded-lg min-w-[104px] justify-center text-xs font-semibold tracking-wide ${i3[i]}`,role:"status","aria-label":`Status: ${i.replace("_"," ")}`,children:[i==="running"||i==="investigating"?c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):e&&c.jsx("span",{"aria-hidden":"true",children:e}),i.replace("_"," ")]})}function r3(i){return i.map(e=>`${e.comm} (pid ${e.pid})`).join(", ")}function i5({leaked:i}){return!i||i.length===0?null:c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`Leaked ${i.length} descendant process${i.length===1?"":"es"} — swept after exit: ${r3(i)}`,children:c.jsxs("span",{"data-testid":"leak-badge",children:["⚠ ",i.length]})})}function n5({count:i,truncated:e,salvagePatch:t}){if(!i||i<=0)return null;const n=`left ${i}${e?"+":""} file${i===1?"":"s"} uncommitted`,r=t?` — recoverable from salvage patch ${t}`:"";return c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`${n}${r}`,children:c.jsx("span",{"data-testid":"leftover-badge",children:n})})}function s5({status:i,overrun:e}){if(i!=="running"||!e)return null;const t=`${e.ratio.toFixed(1)}x over ${e.estimateMinutes}m est`;return c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`Running ${Math.round(e.ranMs/6e4)}m against a ${e.estimateMinutes}m estimate — check the run log, then let it finish or cancel it via scheduler_cancel_job`,children:c.jsx("span",{"data-testid":"overrun-badge",children:t})})}function o3({cwd:i,name:e}){const t=e??(i?JE(i)??i:"—"),n=t3(i,e);return c.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:n},"aria-hidden":"true"}),t]})}function r5({epicId:i,label:e,onOpen:t,testId:n="epic-tag",className:r=""}){if(!i)return null;const l=e!=null,p=l?e:lT(i),a=l?`Session · ${e}`:`Session ${i} is not currently loaded`,d=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide opacity-70 shrink-0",children:"epic"}),c.jsx("span",{className:"truncate",children:p})]}),f=`inline-flex items-center gap-1.5 font-mono text-[11.5px] max-w-full min-w-0 ${r}`;return!t||!l?c.jsx("span",{"data-testid":n,"data-epic-id":i,title:a,className:`${f} text-fg-faint`,children:d}):c.jsx("span",{role:"button",tabIndex:0,"data-testid":n,"data-epic-id":i,title:a,onClick:g=>{g.stopPropagation(),g.preventDefault(),t(i)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.stopPropagation(),g.preventDefault(),t(i))},className:`${f} text-accent hover:text-accent/80 cursor-pointer`,children:d})}function o5({label:i,children:e}){return c.jsxs("div",{children:[c.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:i}),c.jsx("div",{className:"grid gap-1.5",children:e})]})}function a5({k:i,v:e,wrap:t}){return c.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[c.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:i}),c.jsx("span",{className:`text-fg ${t?"break-all":""}`,children:e})]})}const a3={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",abandoned_background_task:"abandoned auto-backgrounded task",pass_no_commit:"PASS sentinel but no commit landed",silent_no_op:"no commit, clean tree — no evidence of work",blocked_by_foreign_wip_streak:"blocked by a sibling job's foreign WIP 3x in a row"};function l3(i){return a3[i]??i}function l5(i){const e=i.match(/^(\d+)-/);return e?e[1]:null}function c5({n:i}){return c.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",i]})}const ew={running:{bg:"bg-accent",text:"text-white",border:!1,label:"running"},investigating:{bg:"bg-accent",text:"text-white",border:!1,label:"investigating"},queued:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"queued"},ready:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"ready to run"},draft:{bg:"bg-bg",text:"text-fg-faint",border:!0,label:"draft"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},skipped:{bg:"bg-fg-dim/10",text:"text-fg-dim",border:!0,label:"skipped"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"},needs_input:{bg:"bg-[#8e641a]/10",text:"text-[#7a5416]",border:!0,label:"needs your answer"},claimed:{bg:"bg-muteband/60",text:"text-fg-dim",border:!0,label:"claimed — not yet verified"},verified:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"verified"},refuted:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"refuted"},validating:{bg:"bg-accent",text:"text-white",border:!1,label:"validating"}};function ZE(i,e){return i==="failed"||i==="needs_review"?i:e==="verified"?"verified":e==="refuted"?"refuted":e==="validating"?"validating":e==="unvalidated"&&i==="completed"?"claimed":i}function c3(i,e){if(!i)return"ready";const t=i.status==="pending"?"queued":i.status;return ZE(t,e)}function QE({status:i}){const e=ew[i];return c.jsx("span",{role:"status","aria-label":`Status: ${e.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${e.bg} ${e.text}${e.border?" ring-1 ring-inset ring-line":""}`,children:e.label})}function d5({children:i,height:e,className:t="",testId:n}){return c.jsx("div",{"data-testid":n,style:e?{height:e}:void 0,className:`flex items-center border-b border-rule-structural ${t}`,children:i})}const gS="inline-flex items-center justify-center w-[13px] h-[13px] rounded-full border border-fg-faint text-[9px] leading-none text-fg-faint normal-case tracking-normal";function d3({title:i,testId:e,children:t,popoverTestId:n,alignRight:r,glyph:l="i",widthCls:p="w-96"}){const[a,d]=B.useState(!1),f=B.useRef(null);return B.useEffect(()=>{if(!a)return;const g=b=>{var T;(T=f.current)!=null&&T.contains(b.target)||d(!1)},m=b=>{b.key==="Escape"&&d(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",m)}},[a]),t?c.jsxs("span",{ref:f,className:"relative inline-flex normal-case tracking-normal font-normal",children:[c.jsx("button",{type:"button","data-testid":e,title:i,"aria-label":i,"aria-haspopup":"dialog","aria-expanded":a,onClick:()=>d(g=>!g),className:`${gS} cursor-pointer hover:text-fg hover:border-fg`,children:l}),a&&c.jsx("div",{role:"dialog","data-testid":n,className:`absolute ${r?"right-0":"left-0"} top-full mt-1 ${Cn.dialog} ${p} max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-3 py-2 text-left text-[12px] text-fg-dim`,children:t})]}):c.jsx("span",{"data-testid":e,title:i,"aria-label":i,className:`${gS} cursor-help`,children:"i"})}function u5({value:i,min:e,max:t,onCommit:n,testId:r,title:l}){const[p,a]=B.useState(!1);return p?c.jsx("input",{type:"number",autoFocus:!0,min:e,max:t,"data-testid":r,title:l,defaultValue:i,onChange:d=>n(Math.max(e,Math.min(t,Number(d.target.value)))),onBlur:()=>a(!1),onKeyDown:d=>{(d.key==="Enter"||d.key==="Escape")&&a(!1)},className:"w-9 text-center border border-line bg-bg-hi rounded py-0 font-mono text-[11.5px] text-fg"}):c.jsxs("button",{type:"button","data-testid":r?`${r}-text`:void 0,title:l,onClick:()=>a(!0),className:"bg-transparent border-0 p-0 font-mono text-[11.5px] text-fg-faint hover:text-fg hover:underline cursor-text",children:[i,"%"]})}function h5({label:i,info:e,infoContent:t,infoTestId:n,infoAlignRight:r,labelExtra:l,value:p,sub:a,third:d,testId:f}){return c.jsxs("div",{"data-testid":f,className:"flex-1 basis-0 min-w-0 px-3 py-1 border-l border-rule-structural first:border-l-0 flex flex-col justify-center gap-0.5",children:[c.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint leading-none",children:[c.jsx("span",{children:i}),e&&c.jsx(d3,{title:e,testId:n,alignRight:r,children:t}),l&&c.jsx("span",{className:"ml-auto normal-case tracking-normal",children:l})]}),c.jsxs("div",{className:"flex items-baseline gap-1.5 min-w-0 leading-tight",children:[c.jsx("span",{className:"text-[21px] font-semibold text-fg leading-none",children:p}),a&&c.jsx("span",{className:"text-[12px] text-fg-dim truncate",children:a})]}),c.jsx("div",{className:"font-mono text-[11.5px] text-fg-faint leading-none truncate h-[13px] flex items-center",children:d})]})}function p5({pct:i,tone:e="bg-accent"}){const t=Math.max(0,Math.min(100,i));return c.jsx("span",{className:"block w-full h-[5px] bg-rule-inner rounded-sm overflow-hidden",role:"progressbar","aria-valuenow":Math.round(t),"aria-valuemin":0,"aria-valuemax":100,children:c.jsx("span",{className:`block h-full ${e}`,style:{width:`${t}%`}})})}function f5({filled:i,total:e}){const t=Math.max(0,Math.min(e,10));return c.jsx("span",{className:"flex gap-[3px] w-full","data-testid":"kpi-slot-pills",children:Array.from({length:t},(n,r)=>c.jsx("span",{className:`flex-1 h-[5px] rounded-sm ${r<i?"bg-accent":"bg-rule-inner"}`},r))})}function m5({value:i,min:e,max:t,disabled:n,onChange:r,title:l}){const p="w-[20px] h-[20px] leading-none rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed text-[13px]";return c.jsxs("span",{className:"inline-flex items-center gap-1",title:l,children:[c.jsx("button",{type:"button","aria-label":"Decrease concurrency","data-testid":"kpi-concurrency-dec",disabled:n||i<=e,onClick:()=>r(Math.max(e,i-1)),className:p,children:"−"}),c.jsx("span",{"data-testid":"kpi-concurrency-value",className:"w-[20px] text-center text-[18px] font-semibold text-fg font-mono",children:i}),c.jsx("button",{type:"button","aria-label":"Increase concurrency","data-testid":"kpi-concurrency-inc",disabled:n||i>=t,onClick:()=>r(Math.min(t,i+1)),className:p,children:"+"})]})}const u3=5,V_=80;function q_(i,e){const t=i.trim().replace(/\s+/g," ");return t.length>e?`${t.slice(0,e-1)}…`:t}function h3(i){switch(i.status){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed";case"needs-input":return"needs_input"}}function p3({chat:i}){const e=i==null?void 0:i.activeTicket,t=(i==null?void 0:i.queue)??[],n=(i==null?void 0:i.ticketHistory)??[];if(!e&&t.length===0&&n.length===0)return null;const r=(e==null?void 0:e.status)==="queued"?"classifying":"running",l=[...n].reverse().slice(0,u3);return c.jsxs("div",{className:"grid gap-2 rounded-lg border border-line bg-bg-hi/40 px-3 py-2.5 text-xs","data-testid":"epic-queue-panel",children:[e&&c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-active",children:[c.jsx("span",{className:"shrink-0 rounded-full bg-accent/15 px-2 py-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-accent",children:r}),c.jsx("span",{className:"truncate text-fg-dim",children:q_(e.text,V_)})]}),t.length>0&&c.jsx("div",{className:"grid gap-1",children:t.map((p,a)=>c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-item",children:[c.jsxs("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint",children:["#",a+1]}),c.jsx("span",{className:"truncate text-fg-dim",children:q_(p.text,V_)})]},p.id))}),l.length>0&&c.jsx("div",{className:"grid gap-1 border-t border-line pt-1.5",children:l.map(p=>c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-history-item",children:[c.jsx(QE,{status:h3(p)}),c.jsx("span",{className:"truncate text-fg-faint",children:q_(p.text,V_)})]},p.id))})]})}const f3={actor:"Actor","persona-body":"Persona notes",injection:"Injections",input:"Input",mission:"Mission",goal:"Goal",reference:"References"},m3={actor:!0,"persona-body":!1,injection:!1,input:!1,mission:!0,goal:!0,reference:!1};function g3(i){const e=[];for(const t of i){const n=e[e.length-1];n&&n.kind===t.kind?n.items.push(t):e.push({kind:t.kind,items:[t]})}return e}const vS=96,v3=400;function _3(i){return i.reduce((e,t)=>e+t.text.length,0)}function y3(i){if(i.length===1){const e=i[0].text.replace(/\s+/g," ").trim();return e.length>vS?`${e.slice(0,vS)}…`:e}return`${i.length} items`}function b3({group:i}){const e=_3(i.items)>v3,[t,n]=B.useState(m3[i.kind]&&!e),r=i.items.length;return c.jsxs("div",{className:"overflow-hidden rounded-lg border border-line","data-testid":"epic-intake-section","data-section-kind":i.kind,children:[c.jsxs("button",{type:"button",onClick:()=>n(l=>!l),"data-testid":"epic-intake-section-toggle",className:"flex w-full items-center gap-1.5 bg-elev px-2.5 py-1.5 font-mono text-[11px] font-semibold text-fg-dim hover:bg-hi",children:[c.jsx("span",{className:`inline-block shrink-0 transition-transform ${t?"rotate-90":""}`,"aria-hidden":"true",children:"▸"}),c.jsx("span",{className:"shrink-0 text-left",children:f3[i.kind]}),r>1&&c.jsxs("span",{className:"shrink-0 text-fg-faint",children:["· ",r]}),!t&&c.jsx("span",{className:"min-w-0 flex-1 truncate text-left font-normal text-fg-faint","data-testid":"epic-intake-section-summary",children:y3(i.items)})]}),t&&c.jsx("div",{className:`grid gap-2 bg-bg px-2.5 py-2 ${e?"max-h-[45vh] overflow-y-auto":""}`,"data-testid":"epic-intake-section-body",children:i.items.map((l,p)=>c.jsxs("div",{className:"min-w-0 text-sm leading-relaxed whitespace-pre-wrap text-fg",children:[i.items.length>1&&c.jsxs("div",{className:"mb-0.5 font-mono text-[10px] text-fg-faint",children:[l.label,l.source?` · ${l.source}`:""]}),l.text]},p))})]})}function w3({sections:i,at:e,openingPrompt:t}){const n=g3(i);return c.jsx(XE,{badge:c.jsx("span",{"data-testid":"epic-intake-badge",className:"rounded border border-accent/40 bg-accent/10 px-1.5 py-0.5 text-[10px] font-semibold text-accent",children:"AIM briefing"}),timestamp:e,copyText:t,testId:"epic-intake-card",children:c.jsx("div",{className:"grid gap-1.5","data-testid":"epic-intake-card-sections",children:n.map(r=>c.jsx(b3,{group:r},r.kind))})})}let Yy=null;function x3(i){Yy=i,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:i}))}function g5(){const i=Yy;return Yy=null,i}let Jy=null;function S3(i){Jy=i,window.dispatchEvent(new CustomEvent("sm:select-persona",{detail:i}))}function C3(){const i=Jy;return Jy=null,i}function ek(i){x3(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function v5(i){jv(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function E3(i){S3(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"agent-library"}))}const _S="sonnet";function k3(i){const e=Qa(i),t=e!==null&&i.startsWith("claude-");return{text:t?`${e} → ${i} (this session)`:`${i} · resolved by the CLI at launch (this session)`,title:`This session's model was chosen on the New Session card${t?` (${Zf(i)})`:""} and is passed to the CLI as --model, overriding the agent persona.`}}function T3(i){if(i.epicModel)return k3(i.epicModel);if(i.modelSource==="fallback")return{text:`${_S} · persona not found`,title:`Agent "${i.agentType}" has no matching persona file — this session would launch at the fallback model (${_S}), not a real per-persona choice.`};const e=i.modelSource==="inherit",t=e?"inherited":i.modelAlias??"inherited";if(i.resolvedModelId&&i.resolvedModelId===i.modelAlias&&!i.resolvedFrom){const r=Zf(i.resolvedModelId);return{text:`${i.resolvedModelId} → ${r} (pinned)`,title:`This persona pins the exact model ${i.resolvedModelId} (${r}) — no alias for the CLI to resolve at launch.`}}if(!i.resolvedModelId)return{text:`${t} · resolved by the CLI at launch`,title:"No session using this persona has run yet, so the concrete model is unknown — the CLI resolves this alias the moment it launches."};const n=Zf(i.resolvedModelId);return e?{text:`inherited → ${n} (settings default)`,title:`This persona sets no model override, so it runs at the settings default — last observed running as ${n}.`}:{text:`${t} → ${n}`,title:`Persona override "${t}" last observed running as ${n}.`}}function tk(i){const e=T3(i),t=$C(i.effortLevel,i.effortSource);return{text:`${e.text} · ${t}`,title:`${e.title} ${t}. ${gP(i.effortSource)}`}}function ik({info:i}){const{text:e,title:t}=tk(i);return c.jsx("span",{title:t,children:e})}function D3({options:i,active:e,onChange:t}){return c.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:i.map(({key:n,label:r})=>c.jsx("button",{onClick:()=>t(n),className:`px-2 py-0.5 text-xs ${e===n?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:r},n))})}const yS=2e3;function A3(i){return i.is_error===!0||i.error!=null&&i.error!==""||i.type==="result"&&i.subtype!=="success"&&i.subtype!=null}function I3(i){return typeof i.error=="string"&&i.error?i.error:typeof i.result=="string"&&i.result?i.result:typeof i.subtype=="string"?i.subtype:JSON.stringify(i).slice(0,200)}function P3(i){if(typeof i.text=="string")return i.text.slice(0,200);if(typeof i.content=="string")return i.content.slice(0,200);if(Array.isArray(i.content)){for(const t of i.content)if(t&&typeof t=="object"&&"text"in t&&typeof t.text=="string")return t.text.slice(0,200)}const e=i.message;if(e&&typeof e=="object"){const t=e;if(typeof t.content=="string")return t.content.slice(0,200);if(Array.isArray(t.content)){for(const n of t.content)if(n&&typeof n=="object"&&"text"in n&&typeof n.text=="string")return n.text.slice(0,200)}}return typeof i.result=="string"&&i.result?i.result.slice(0,200):typeof i.subtype=="string"?i.subtype:JSON.stringify(i).slice(0,200)}function R3(i){if(!i||!i.trim())return{events:[],errors:{count:0,firstMessage:null},rawLineCount:0,truncated:!1};const t=i.split(`
3054
+ `),nt.error(`Terminal failed to start: ${$}`)});const x=()=>T();window.addEventListener("resize",x);const A=new ResizeObserver(()=>T());return A.observe(r.current),()=>{window.removeEventListener("resize",x),A.disconnect(),S(),w(),E(),m.dispose()}},[t,e,i,f]),a?c.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-sm text-fg-faint","data-testid":"epic-terminal-exited",children:[c.jsxs("p",{children:["Terminal session exited",a.code!==null?` (code ${a.code})`:"","."]}),c.jsx("button",{type:"button",onClick:n,"data-testid":"epic-terminal-back-to-chat",className:"rounded-md bg-accent px-3 py-1.5 text-xs font-semibold text-white hover:bg-accent/90",children:"Back to Chat"})]}):c.jsx("div",{ref:r,"data-testid":"epic-terminal-host",onMouseDown:()=>{var g;return(g=l.current)==null?void 0:g.focus()},className:"h-full w-full bg-bg"})}const e3={default:"bg-bg-hi text-fg-dim border-line",accent:"bg-accent/15 text-accent-dark border-accent/30",warn:"bg-honey/15 text-honey-dark border-honey/30",dim:"bg-bg-elev text-fg-dim border-line",good:"bg-sage/15 text-sage-dark border-sage/30"};function _a({children:i,tone:e="default",className:t="",title:n}){return c.jsx("span",{title:n,className:`inline-flex items-center gap-1 text-[10px] leading-none px-1.5 py-0.5 rounded border uppercase tracking-wide ${e3[e]} ${t}`,children:i})}function JE(i){if(!i)return null;const e=i.replace(/\/+$/,"").split("/");return e[e.length-1]||i}function t3(i,e){const t=i?JE(i)??"":e??"";return CC(t)}const i3={running:"bg-accent text-white",investigating:"bg-accent text-white",pending:"bg-bg text-fg-dim border border-line",completed:"bg-sage/20 text-sage",skipped:"bg-fg-dim/10 text-fg-dim border border-line",needs_review:"bg-butter/25 text-fg-dim",failed:"bg-accent/15 text-accent",quarantined:"bg-fuchsia-500/20 text-fuchsia-300 border border-fuchsia-500/40"},n3={pending:"○",completed:"✓",skipped:"⊘",needs_review:"!",failed:"✕",quarantined:"⚑"};function s3({status:i}){const e=n3[i];return c.jsxs("span",{className:`inline-flex items-center gap-1.5 shrink-0 px-2.5 py-1 rounded-lg min-w-[104px] justify-center text-xs font-semibold tracking-wide ${i3[i]}`,role:"status","aria-label":`Status: ${i.replace("_"," ")}`,children:[i==="running"||i==="investigating"?c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):e&&c.jsx("span",{"aria-hidden":"true",children:e}),i.replace("_"," ")]})}function r3(i){return i.map(e=>`${e.comm} (pid ${e.pid})`).join(", ")}function n5({leaked:i}){return!i||i.length===0?null:c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`Leaked ${i.length} descendant process${i.length===1?"":"es"} — swept after exit: ${r3(i)}`,children:c.jsxs("span",{"data-testid":"leak-badge",children:["⚠ ",i.length]})})}function s5({count:i,truncated:e,salvagePatch:t}){if(!i||i<=0)return null;const n=`left ${i}${e?"+":""} file${i===1?"":"s"} uncommitted`,r=t?` — recoverable from salvage patch ${t}`:"";return c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`${n}${r}`,children:c.jsx("span",{"data-testid":"leftover-badge",children:n})})}function r5({status:i,overrun:e}){if(i!=="running"||!e)return null;const t=`${e.ratio.toFixed(1)}x over ${e.estimateMinutes}m est`;return c.jsx(_a,{tone:"warn",className:"shrink-0 normal-case",title:`Running ${Math.round(e.ranMs/6e4)}m against a ${e.estimateMinutes}m estimate — check the run log, then let it finish or cancel it via scheduler_cancel_job`,children:c.jsx("span",{"data-testid":"overrun-badge",children:t})})}function o3({cwd:i,name:e}){const t=e??(i?JE(i)??i:"—"),n=t3(i,e);return c.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:n},"aria-hidden":"true"}),t]})}function o5({epicId:i,label:e,onOpen:t,testId:n="epic-tag",className:r=""}){if(!i)return null;const l=e!=null,p=l?e:lT(i),a=l?`Session · ${e}`:`Session ${i} is not currently loaded`,d=c.jsxs(c.Fragment,{children:[c.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide opacity-70 shrink-0",children:"epic"}),c.jsx("span",{className:"truncate",children:p})]}),f=`inline-flex items-center gap-1.5 font-mono text-[11.5px] max-w-full min-w-0 ${r}`;return!t||!l?c.jsx("span",{"data-testid":n,"data-epic-id":i,title:a,className:`${f} text-fg-faint`,children:d}):c.jsx("span",{role:"button",tabIndex:0,"data-testid":n,"data-epic-id":i,title:a,onClick:g=>{g.stopPropagation(),g.preventDefault(),t(i)},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.stopPropagation(),g.preventDefault(),t(i))},className:`${f} text-accent hover:text-accent/80 cursor-pointer`,children:d})}function a5({label:i,children:e}){return c.jsxs("div",{children:[c.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:i}),c.jsx("div",{className:"grid gap-1.5",children:e})]})}function l5({k:i,v:e,wrap:t}){return c.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[c.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:i}),c.jsx("span",{className:`text-fg ${t?"break-all":""}`,children:e})]})}const a3={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",abandoned_background_task:"abandoned auto-backgrounded task",pass_no_commit:"PASS sentinel but no commit landed",silent_no_op:"no commit, clean tree — no evidence of work",blocked_by_foreign_wip_streak:"blocked by a sibling job's foreign WIP 3x in a row"};function l3(i){return a3[i]??i}function c5(i){const e=i.match(/^(\d+)-/);return e?e[1]:null}function d5({n:i}){return c.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",i]})}const ew={running:{bg:"bg-accent",text:"text-white",border:!1,label:"running"},investigating:{bg:"bg-accent",text:"text-white",border:!1,label:"investigating"},queued:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"queued"},ready:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"ready to run"},draft:{bg:"bg-bg",text:"text-fg-faint",border:!0,label:"draft"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},skipped:{bg:"bg-fg-dim/10",text:"text-fg-dim",border:!0,label:"skipped"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"},needs_input:{bg:"bg-[#8e641a]/10",text:"text-[#7a5416]",border:!0,label:"needs your answer"},claimed:{bg:"bg-muteband/60",text:"text-fg-dim",border:!0,label:"claimed — not yet verified"},verified:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"verified"},refuted:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"refuted"},validating:{bg:"bg-accent",text:"text-white",border:!1,label:"validating"}};function ZE(i,e){return i==="failed"||i==="needs_review"?i:e==="verified"?"verified":e==="refuted"?"refuted":e==="validating"?"validating":e==="unvalidated"&&i==="completed"?"claimed":i}function c3(i,e){if(!i)return"ready";const t=i.status==="pending"?"queued":i.status;return ZE(t,e)}function QE({status:i}){const e=ew[i];return c.jsx("span",{role:"status","aria-label":`Status: ${e.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${e.bg} ${e.text}${e.border?" ring-1 ring-inset ring-line":""}`,children:e.label})}function u5({children:i,height:e,className:t="",testId:n}){return c.jsx("div",{"data-testid":n,style:e?{height:e}:void 0,className:`flex items-center border-b border-rule-structural ${t}`,children:i})}const gS="inline-flex items-center justify-center w-[13px] h-[13px] rounded-full border border-fg-faint text-[9px] leading-none text-fg-faint normal-case tracking-normal";function d3({title:i,testId:e,children:t,popoverTestId:n,alignRight:r,glyph:l="i",widthCls:p="w-96"}){const[a,d]=B.useState(!1),f=B.useRef(null);return B.useEffect(()=>{if(!a)return;const g=b=>{var T;(T=f.current)!=null&&T.contains(b.target)||d(!1)},m=b=>{b.key==="Escape"&&d(!1)};return document.addEventListener("mousedown",g),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",g),document.removeEventListener("keydown",m)}},[a]),t?c.jsxs("span",{ref:f,className:"relative inline-flex normal-case tracking-normal font-normal",children:[c.jsx("button",{type:"button","data-testid":e,title:i,"aria-label":i,"aria-haspopup":"dialog","aria-expanded":a,onClick:()=>d(g=>!g),className:`${gS} cursor-pointer hover:text-fg hover:border-fg`,children:l}),a&&c.jsx("div",{role:"dialog","data-testid":n,className:`absolute ${r?"right-0":"left-0"} top-full mt-1 ${Cn.dialog} ${p} max-h-[70vh] overflow-y-auto rounded border border-line bg-bg-elev shadow-lg px-3 py-2 text-left text-[12px] text-fg-dim`,children:t})]}):c.jsx("span",{"data-testid":e,title:i,"aria-label":i,className:`${gS} cursor-help`,children:"i"})}function h5({value:i,min:e,max:t,onCommit:n,testId:r,title:l}){const[p,a]=B.useState(!1);return p?c.jsx("input",{type:"number",autoFocus:!0,min:e,max:t,"data-testid":r,title:l,defaultValue:i,onChange:d=>n(Math.max(e,Math.min(t,Number(d.target.value)))),onBlur:()=>a(!1),onKeyDown:d=>{(d.key==="Enter"||d.key==="Escape")&&a(!1)},className:"w-9 text-center border border-line bg-bg-hi rounded py-0 font-mono text-[11.5px] text-fg"}):c.jsxs("button",{type:"button","data-testid":r?`${r}-text`:void 0,title:l,onClick:()=>a(!0),className:"bg-transparent border-0 p-0 font-mono text-[11.5px] text-fg-faint hover:text-fg hover:underline cursor-text",children:[i,"%"]})}function p5({label:i,info:e,infoContent:t,infoTestId:n,infoAlignRight:r,labelExtra:l,value:p,sub:a,third:d,testId:f}){return c.jsxs("div",{"data-testid":f,className:"flex-1 basis-0 min-w-0 px-3 py-1 border-l border-rule-structural first:border-l-0 flex flex-col justify-center gap-0.5",children:[c.jsxs("div",{className:"flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint leading-none",children:[c.jsx("span",{children:i}),e&&c.jsx(d3,{title:e,testId:n,alignRight:r,children:t}),l&&c.jsx("span",{className:"ml-auto normal-case tracking-normal",children:l})]}),c.jsxs("div",{className:"flex items-baseline gap-1.5 min-w-0 leading-tight",children:[c.jsx("span",{className:"text-[21px] font-semibold text-fg leading-none",children:p}),a&&c.jsx("span",{className:"text-[12px] text-fg-dim truncate",children:a})]}),c.jsx("div",{className:"font-mono text-[11.5px] text-fg-faint leading-none truncate h-[13px] flex items-center",children:d})]})}function f5({pct:i,tone:e="bg-accent"}){const t=Math.max(0,Math.min(100,i));return c.jsx("span",{className:"block w-full h-[5px] bg-rule-inner rounded-sm overflow-hidden",role:"progressbar","aria-valuenow":Math.round(t),"aria-valuemin":0,"aria-valuemax":100,children:c.jsx("span",{className:`block h-full ${e}`,style:{width:`${t}%`}})})}function m5({filled:i,total:e}){const t=Math.max(0,Math.min(e,10));return c.jsx("span",{className:"flex gap-[3px] w-full","data-testid":"kpi-slot-pills",children:Array.from({length:t},(n,r)=>c.jsx("span",{className:`flex-1 h-[5px] rounded-sm ${r<i?"bg-accent":"bg-rule-inner"}`},r))})}function g5({value:i,min:e,max:t,disabled:n,onChange:r,title:l}){const p="w-[20px] h-[20px] leading-none rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed text-[13px]";return c.jsxs("span",{className:"inline-flex items-center gap-1",title:l,children:[c.jsx("button",{type:"button","aria-label":"Decrease concurrency","data-testid":"kpi-concurrency-dec",disabled:n||i<=e,onClick:()=>r(Math.max(e,i-1)),className:p,children:"−"}),c.jsx("span",{"data-testid":"kpi-concurrency-value",className:"w-[20px] text-center text-[18px] font-semibold text-fg font-mono",children:i}),c.jsx("button",{type:"button","aria-label":"Increase concurrency","data-testid":"kpi-concurrency-inc",disabled:n||i>=t,onClick:()=>r(Math.min(t,i+1)),className:p,children:"+"})]})}const u3=5,V_=80;function q_(i,e){const t=i.trim().replace(/\s+/g," ");return t.length>e?`${t.slice(0,e-1)}…`:t}function h3(i){switch(i.status){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed";case"needs-input":return"needs_input"}}function p3({chat:i}){const e=i==null?void 0:i.activeTicket,t=(i==null?void 0:i.queue)??[],n=(i==null?void 0:i.ticketHistory)??[];if(!e&&t.length===0&&n.length===0)return null;const r=(e==null?void 0:e.status)==="queued"?"classifying":"running",l=[...n].reverse().slice(0,u3);return c.jsxs("div",{className:"grid gap-2 rounded-lg border border-line bg-bg-hi/40 px-3 py-2.5 text-xs","data-testid":"epic-queue-panel",children:[e&&c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-active",children:[c.jsx("span",{className:"shrink-0 rounded-full bg-accent/15 px-2 py-0.5 text-[10.5px] font-semibold uppercase tracking-wide text-accent",children:r}),c.jsx("span",{className:"truncate text-fg-dim",children:q_(e.text,V_)})]}),t.length>0&&c.jsx("div",{className:"grid gap-1",children:t.map((p,a)=>c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-item",children:[c.jsxs("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint",children:["#",a+1]}),c.jsx("span",{className:"truncate text-fg-dim",children:q_(p.text,V_)})]},p.id))}),l.length>0&&c.jsx("div",{className:"grid gap-1 border-t border-line pt-1.5",children:l.map(p=>c.jsxs("div",{className:"flex items-center gap-2","data-testid":"epic-queue-panel-history-item",children:[c.jsx(QE,{status:h3(p)}),c.jsx("span",{className:"truncate text-fg-faint",children:q_(p.text,V_)})]},p.id))})]})}const f3={actor:"Actor","persona-body":"Persona notes",injection:"Injections",input:"Input",mission:"Mission",goal:"Goal",reference:"References"},m3={actor:!0,"persona-body":!1,injection:!1,input:!1,mission:!0,goal:!0,reference:!1};function g3(i){const e=[];for(const t of i){const n=e[e.length-1];n&&n.kind===t.kind?n.items.push(t):e.push({kind:t.kind,items:[t]})}return e}const vS=96,v3=400;function _3(i){return i.reduce((e,t)=>e+t.text.length,0)}function y3(i){if(i.length===1){const e=i[0].text.replace(/\s+/g," ").trim();return e.length>vS?`${e.slice(0,vS)}…`:e}return`${i.length} items`}function b3({group:i}){const e=_3(i.items)>v3,[t,n]=B.useState(m3[i.kind]&&!e),r=i.items.length;return c.jsxs("div",{className:"overflow-hidden rounded-lg border border-line","data-testid":"epic-intake-section","data-section-kind":i.kind,children:[c.jsxs("button",{type:"button",onClick:()=>n(l=>!l),"data-testid":"epic-intake-section-toggle",className:"flex w-full items-center gap-1.5 bg-elev px-2.5 py-1.5 font-mono text-[11px] font-semibold text-fg-dim hover:bg-hi",children:[c.jsx("span",{className:`inline-block shrink-0 transition-transform ${t?"rotate-90":""}`,"aria-hidden":"true",children:"▸"}),c.jsx("span",{className:"shrink-0 text-left",children:f3[i.kind]}),r>1&&c.jsxs("span",{className:"shrink-0 text-fg-faint",children:["· ",r]}),!t&&c.jsx("span",{className:"min-w-0 flex-1 truncate text-left font-normal text-fg-faint","data-testid":"epic-intake-section-summary",children:y3(i.items)})]}),t&&c.jsx("div",{className:`grid gap-2 bg-bg px-2.5 py-2 ${e?"max-h-[45vh] overflow-y-auto":""}`,"data-testid":"epic-intake-section-body",children:i.items.map((l,p)=>c.jsxs("div",{className:"min-w-0 text-sm leading-relaxed whitespace-pre-wrap text-fg",children:[i.items.length>1&&c.jsxs("div",{className:"mb-0.5 font-mono text-[10px] text-fg-faint",children:[l.label,l.source?` · ${l.source}`:""]}),l.text]},p))})]})}function w3({sections:i,at:e,openingPrompt:t}){const n=g3(i);return c.jsx(XE,{badge:c.jsx("span",{"data-testid":"epic-intake-badge",className:"rounded border border-accent/40 bg-accent/10 px-1.5 py-0.5 text-[10px] font-semibold text-accent",children:"AIM briefing"}),timestamp:e,copyText:t,testId:"epic-intake-card",children:c.jsx("div",{className:"grid gap-1.5","data-testid":"epic-intake-card-sections",children:n.map(r=>c.jsx(b3,{group:r},r.kind))})})}let Yy=null;function x3(i){Yy=i,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:i}))}function v5(){const i=Yy;return Yy=null,i}let Jy=null;function S3(i){Jy=i,window.dispatchEvent(new CustomEvent("sm:select-persona",{detail:i}))}function C3(){const i=Jy;return Jy=null,i}function ek(i){x3(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function _5(i){jv(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function E3(i){S3(i),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"agent-library"}))}const _S="sonnet";function k3(i){const e=Qa(i),t=e!==null&&i.startsWith("claude-");return{text:t?`${e} → ${i} (this session)`:`${i} · resolved by the CLI at launch (this session)`,title:`This session's model was chosen on the New Session card${t?` (${Zf(i)})`:""} and is passed to the CLI as --model, overriding the agent persona.`}}function T3(i){if(i.epicModel)return k3(i.epicModel);if(i.modelSource==="fallback")return{text:`${_S} · persona not found`,title:`Agent "${i.agentType}" has no matching persona file — this session would launch at the fallback model (${_S}), not a real per-persona choice.`};const e=i.modelSource==="inherit",t=e?"inherited":i.modelAlias??"inherited";if(i.resolvedModelId&&i.resolvedModelId===i.modelAlias&&!i.resolvedFrom){const r=Zf(i.resolvedModelId);return{text:`${i.resolvedModelId} → ${r} (pinned)`,title:`This persona pins the exact model ${i.resolvedModelId} (${r}) — no alias for the CLI to resolve at launch.`}}if(!i.resolvedModelId)return{text:`${t} · resolved by the CLI at launch`,title:"No session using this persona has run yet, so the concrete model is unknown — the CLI resolves this alias the moment it launches."};const n=Zf(i.resolvedModelId);return e?{text:`inherited → ${n} (settings default)`,title:`This persona sets no model override, so it runs at the settings default — last observed running as ${n}.`}:{text:`${t} → ${n}`,title:`Persona override "${t}" last observed running as ${n}.`}}function tk(i){const e=T3(i),t=$C(i.effortLevel,i.effortSource);return{text:`${e.text} · ${t}`,title:`${e.title} ${t}. ${gP(i.effortSource)}`}}function ik({info:i}){const{text:e,title:t}=tk(i);return c.jsx("span",{title:t,children:e})}function D3({options:i,active:e,onChange:t}){return c.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:i.map(({key:n,label:r})=>c.jsx("button",{onClick:()=>t(n),className:`px-2 py-0.5 text-xs ${e===n?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:r},n))})}const yS=2e3;function A3(i){return i.is_error===!0||i.error!=null&&i.error!==""||i.type==="result"&&i.subtype!=="success"&&i.subtype!=null}function I3(i){return typeof i.error=="string"&&i.error?i.error:typeof i.result=="string"&&i.result?i.result:typeof i.subtype=="string"?i.subtype:JSON.stringify(i).slice(0,200)}function P3(i){if(typeof i.text=="string")return i.text.slice(0,200);if(typeof i.content=="string")return i.content.slice(0,200);if(Array.isArray(i.content)){for(const t of i.content)if(t&&typeof t=="object"&&"text"in t&&typeof t.text=="string")return t.text.slice(0,200)}const e=i.message;if(e&&typeof e=="object"){const t=e;if(typeof t.content=="string")return t.content.slice(0,200);if(Array.isArray(t.content)){for(const n of t.content)if(n&&typeof n=="object"&&"text"in n&&typeof n.text=="string")return n.text.slice(0,200)}}return typeof i.result=="string"&&i.result?i.result.slice(0,200):typeof i.subtype=="string"?i.subtype:JSON.stringify(i).slice(0,200)}function R3(i){if(!i||!i.trim())return{events:[],errors:{count:0,firstMessage:null},rawLineCount:0,truncated:!1};const t=i.split(`
3055
3055
  `).filter(f=>f.trim().length>0),n=t.length,r=n>yS,l=r?t.slice(0,yS):t,p=[];let a=0,d=null;for(const f of l){let g=null;try{const m=JSON.parse(f);m!==null&&typeof m=="object"&&!Array.isArray(m)&&"type"in m&&(g=m)}catch{}if(g!==null){const m=typeof g.type=="string"?g.type:"unknown",b=A3(g);b&&(a++,d===null&&(d=I3(g))),p.push({type:m,raw:f,preview:P3(g),isError:b})}else p.push({type:"raw",raw:f,preview:f.slice(0,200),isError:!1})}return{events:p,errors:{count:a,firstMessage:d},rawLineCount:n,truncated:r}}const O3={assistant:"accent",user:"default",system:"dim",result:"warn",tool_use:"default",tool_result:"default",raw:"dim"};function L3(i){return O3[i]??"default"}function $3({runId:i,slug:e,title:t,onClose:n}){const[r,l]=B.useState(!0),[p,a]=B.useState(null),[d,f]=B.useState(""),[g,m]=B.useState(null),[b,T]=B.useState("parsed");return B.useEffect(()=>{l(!0),a(null),window.api.schedule.readLog(i,e).then(E=>{if(E.ok){const k=E.text??"";f(k),m(R3(k))}else{const k=E.error??"Failed to read log";a(k),nt.error(`Log read failed: ${k}`)}}).catch(E=>{const k=E instanceof Error?E.message:String(E);a(k),nt.error(`Log read failed: ${k}`)}).finally(()=>l(!1))},[i,e]),c.jsx(Hb,{open:!0,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:t,children:c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 border-b border-line",children:[c.jsx("button",{type:"button",onClick:()=>T("parsed"),className:`text-[10px] px-2 py-0.5 rounded border ${b==="parsed"?"bg-accent/20 text-accent border-accent/40":"text-fg-faint border-line hover:text-fg-dim hover:border-fg-faint"}`,children:"Parsed"}),c.jsx("button",{type:"button",onClick:()=>T("raw"),className:`text-[10px] px-2 py-0.5 rounded border ${b==="raw"?"bg-accent/20 text-accent border-accent/40":"text-fg-faint border-line hover:text-fg-dim hover:border-fg-faint"}`,children:"Raw"}),c.jsxs("span",{className:"ml-auto text-[10px] text-fg-faint font-mono",children:[e," · ",i.slice(0,8)]}),c.jsx("button",{type:"button",onClick:n,className:"text-fg-faint hover:text-fg-dim text-sm leading-none ml-1","aria-label":"Close",children:"×"})]}),c.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[r&&c.jsx("div",{className:"flex-1 flex items-center justify-center text-[11px] text-fg-faint",children:"Loading log…"}),!r&&p&&c.jsx("div",{className:"flex-1 flex items-center justify-center",children:c.jsx("div",{className:"text-[11px] text-red-300 px-6 text-center max-w-md",children:p})}),!r&&!p&&b==="raw"&&c.jsx("pre",{className:"flex-1 overflow-auto p-4 text-[10px] font-mono text-fg-dim whitespace-pre-wrap break-all leading-relaxed",children:d||c.jsx("span",{className:"text-fg-faint italic",children:"log is empty"})}),!r&&!p&&b==="parsed"&&g&&c.jsx(N3,{parsed:g,onSwitchRaw:()=>T("raw")})]})]})})}function N3({parsed:i,onSwitchRaw:e}){const{events:t,errors:n,rawLineCount:r,truncated:l}=i;return t.length===0?c.jsx("div",{className:"flex-1 flex items-center justify-center text-[11px] text-fg-faint italic",children:"log is empty"}):c.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[c.jsx("div",{className:`shrink-0 px-4 py-2 border-b border-line text-[11px] ${n.count>0?"bg-red-950/20":"bg-bg-elev/50"}`,children:n.count>0?c.jsxs("span",{className:"text-red-300",children:[c.jsxs("span",{className:"font-medium",children:[n.count," error",n.count===1?"":"s"," detected"]}),n.firstMessage&&c.jsx("span",{className:"text-red-300/70 ml-2 font-mono",children:n.firstMessage.slice(0,120)})]}):c.jsx("span",{className:"text-green-400/70",children:"no errors detected"})}),l&&c.jsxs("div",{className:"shrink-0 px-4 py-1.5 border-b border-line bg-yellow-950/20 text-[10px] text-yellow-400/80",children:["showing first ",t.length," of ",r," events —"," ",c.jsx("button",{type:"button",onClick:e,className:"underline hover:text-yellow-300",children:"open Raw for full"})]}),c.jsx("div",{className:"flex-1 overflow-y-auto",children:t.map((p,a)=>c.jsx(M3,{event:p},a))})]})}function M3({event:i}){const[e,t]=B.useState(!1),n=i.type==="raw";return c.jsxs("div",{className:`flex items-start gap-2 px-3 py-1 border-b border-line/30 cursor-pointer hover:bg-bg-hi ${i.isError?"bg-red-950/10":""}`,onClick:()=>t(r=>!r),children:[c.jsx("div",{className:"shrink-0 pt-0.5 w-16",children:n?c.jsx("span",{className:"text-[9px] text-fg-faint/50 font-mono",children:"raw"}):c.jsx(_a,{tone:L3(i.type),className:"text-[9px]",children:i.type})}),c.jsx("div",{className:"flex-1 min-w-0",children:e?c.jsx("pre",{className:"text-[10px] font-mono text-fg-dim whitespace-pre-wrap break-all",children:i.raw}):c.jsx("span",{className:`text-[10px] truncate block ${n?"text-fg-faint/60 font-mono":"text-fg-dim"}`,children:i.preview||c.jsx("span",{className:"italic text-fg-faint/40",children:"(empty)"})})})]})}function j3(i){return typeof i=="string"?i:Array.isArray(i)?i.filter(e=>e&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(`
3056
3056
  `).trim():""}function z3(i){var t,n;const e=[];for(const r of i.split(`
3057
3057
  `)){const l=r.trim();if(!l)continue;let p;try{p=JSON.parse(l)}catch{continue}const a=p.type==="user"||p.type==="assistant"?p.type:(t=p.message)==null?void 0:t.role;if(a!=="user"&&a!=="assistant")continue;const d=j3((n=p.message)==null?void 0:n.content);d&&e.push({role:a,text:d,at:p.timestamp||new Date().toISOString()})}return e}function B3(i,e){if(!e)return i;const t=Date.parse(e);return Number.isNaN(t)?i:i.filter(n=>{const r=Date.parse(n.at);return Number.isNaN(r)||r>t})}const nk="~/.claude/session-manager/chat-prefs.json",bS={verbose:"raw"};function wS(i){return rj(i)?i:typeof i=="string"&&bS[i]?bS[i]:null}function K_(i){const e=i(),t={verbosity:e.verbosity,perEpic:e.perEpic};window.api.config.writeJson(nk,t).catch(()=>{})}const Kg=Un((i,e)=>({verbosity:pS,perEpic:{},hydrated:!1,hydrate:async()=>{if(!e().hydrated){try{const t=await window.api.config.readJson(nk);if(t.exists&&t.data&&typeof t.data=="object"){const n=t.data,r={};for(const[l,p]of Object.entries(n.perEpic??{})){const a=wS(p);a&&(r[l]=a)}i({verbosity:wS(n.verbosity)??pS,perEpic:r,hydrated:!0});return}}catch{}i({hydrated:!0})}},setVerbosity:t=>{i({verbosity:t}),K_(e)},setEpicVerbosity:(t,n)=>{const{verbosity:r,perEpic:l}=e(),p={...l};n===r?delete p[t]:p[t]=n,i({perEpic:p}),K_(e)},clearEpicVerbosity:t=>{const n={...e().perEpic};delete n[t],i({perEpic:n}),K_(e)}}));function U3(i,e,t){return e[t]??i}async function xS(i,e,t){try{const[n,{turns:r}]=await Promise.all([window.api.transcripts.pathFor(i,t),window.api.promptSessionTranscript.read(i,e)]),l=r.length>0?r[r.length-1].at:null,p=await window.api.config.readText(n);if(!p.exists||!p.text)return 0;const a=z3(p.text),d=B3(a,l);for(const f of d)await window.api.promptSessionTranscript.append(i,e,{role:f.role,text:f.text,at:f.at});return d.length}catch{return 0}}const G3=[],H3=[],F3=[];function Df({label:i,value:e}){return c.jsxs("span",{className:"inline-flex items-baseline gap-1.5 text-xs","data-testid":"epic-meta-item",children:[c.jsx("span",{className:"text-fg-faint",children:i}),c.jsx("span",{className:"font-mono font-semibold text-fg-dim",children:e})]})}function W3({epicId:i,title:e,goal:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(e),[a,d]=B.useState(!1),f=B.useRef(null),g=B.useRef(!0);B.useEffect(()=>()=>{g.current=!1},[]);const m=()=>{p(e),r(!0),setTimeout(()=>{var E;return(E=f.current)==null?void 0:E.select()},0)},b=l.trim().length>0&&l.trim()!==e.trim()&&!a,T=async()=>{if(b){d(!0);try{await ti.getState().renameEpic(i,l,t),g.current&&(r(!1),d(!1))}catch(E){nt.error(E instanceof Error?E.message:String(E)),g.current&&d(!1)}}};return n?c.jsxs("div",{className:"flex items-center gap-1.5",onKeyDown:E=>{E.key==="Escape"?(E.stopPropagation(),r(!1)):(E.metaKey||E.ctrlKey)&&E.key==="Enter"&&(E.stopPropagation(),T())},children:[c.jsx("input",{ref:f,autoFocus:!0,type:"text",value:l,onChange:E=>p(E.target.value),placeholder:"Title","aria-label":"Session title","data-testid":"epic-detail-title-input",className:"w-full min-w-0 max-w-[700px] rounded-md border border-rule bg-bg-elev px-2 py-1 font-serif text-2xl font-semibold leading-tight text-fg outline-none focus:border-accent"}),c.jsx("button",{type:"button",onClick:()=>r(!1),disabled:a,"data-testid":"epic-detail-title-cancel",className:"shrink-0 rounded-md px-2.5 py-1 text-[11.5px] font-semibold text-fg-faint hover:text-fg disabled:opacity-40",children:"Cancel"}),c.jsx("button",{type:"button",onClick:()=>void T(),disabled:!b,"data-testid":"epic-detail-title-save",className:"shrink-0 rounded-md bg-accent px-2.5 py-1 text-[11.5px] font-semibold text-white disabled:opacity-40",children:"Save"})]}):c.jsxs("div",{className:"group flex items-start gap-1.5",children:[c.jsx("h1",{className:"m-0 max-h-[2.6em] overflow-y-auto overscroll-contain font-serif text-2xl font-semibold leading-tight text-fg",title:e,"data-testid":"epic-detail-title",children:e}),c.jsx("button",{type:"button",onClick:m,title:"Rename this session","aria-label":"Rename this session","data-testid":"epic-detail-title-edit",className:"mt-1 shrink-0 rounded p-0.5 text-fg-faint opacity-0 transition-opacity hover:text-fg focus:opacity-100 group-hover:opacity-100",children:c.jsx("svg",{viewBox:"0 0 16 16",width:13,height:13,"aria-hidden":"true",children:c.jsx("path",{d:"M11.5 2.5l2 2L6 12l-3 1 1-3 7.5-7.5z",fill:"none",stroke:"currentColor",strokeWidth:1.4,strokeLinecap:"round",strokeLinejoin:"round"})})})]})}function V3({event:i,cwd:e,epicId:t}){const[n,r]=B.useState(!1),[l,p]=B.useState(null),[a,d]=B.useState(!1),f=(i.text??"").endsWith("…"),g=()=>{!n&&f&&l===null&&!a&&(d(!0),window.api.promptSessionTranscript.read(e,t).then(({turns:S})=>{const w=Date.parse(i.at),x=S.filter(O=>O.role==="assistant");if(x.length===0)return;const A=x.reduce((O,$)=>{const j=Math.abs(Date.parse(O.at)-w);return Math.abs(Date.parse($.at)-w)<j?$:O});p(A.text)}).catch(()=>{}).finally(()=>d(!1))),r(S=>!S)},m=n&&l?l:i.text??"",b=B.useMemo(()=>Yb(m),[m]),T=i.outcome==="needs_review",E=i.outcome&&!T?ZE(i.outcome,i.validation):null,k=E?ew[E]:null,y=T?`Question routed back from a scheduler run${i.prdSlug?` (PRD ${i.prdSlug})`:""}: ${i.text??""}`:i.prdSlug&&k?`PRD ${i.prdSlug} — ${k.label}`:void 0;return c.jsxs("div",{"data-testid":"epic-response-event","aria-label":y,className:`break-words text-center text-[11px] ${T?`border ${Xf} ${ec} rounded-lg px-2.5 py-1.5`:k?`${k.bg} ${k.text} rounded-lg px-2 py-1`:"text-fg-faint"}`,children:[T&&c.jsxs("div",{className:`mb-1 flex items-center justify-center gap-1.5 font-mono text-[10px] font-semibold uppercase tracking-wide ${ec}`,"data-testid":"epic-response-question-marker",children:[c.jsx("span",{"aria-hidden":"true",children:"❓"}),"Question aimed at you"]}),c.jsx("span",{"aria-hidden":"true",children:"— "}),c.jsx("span",{"data-testid":"epic-response-event-text",className:"prose-chat inline [&_*]:m-0 [&_*]:inline",dangerouslySetInnerHTML:{__html:b}}),c.jsx("span",{"aria-hidden":"true",children:" —"}),f&&c.jsx("button",{type:"button",onClick:g,className:"ml-1.5 text-accent hover:underline","data-testid":"epic-response-event-toggle",children:a?"loading…":n?"show less":"show more"})]})}function SS({text:i}){return c.jsx("div",{className:"rounded-xl border border-dashed border-rule px-6 py-8 text-center text-sm leading-relaxed text-fg-faint",children:i})}function CS(i){const e=new Date(i);return Number.isNaN(e.getTime())?"—":rl(e.getTime(),Date.now())}function q3(i){return i==="pending"?"queued":i}const Xg=new Map;function K3(i){const[e,t]=B.useState(()=>Xg.get(i)??null);return B.useEffect(()=>{var l,p;const n=Xg.get(i);if(n!==void 0){t(n);return}if(typeof((p=(l=window.api)==null?void 0:l.schedule)==null?void 0:p.readPrd)!="function")return;let r=!1;return window.api.schedule.readPrd(i).then(a=>{const d=a.ok&&a.text?a.text.split(`
@@ -3076,4 +3076,4 @@ Check git vs the published package and publish anything new.`,className:"w-full
3076
3076
  `),St.getState().setTabExited(i,O)});g.onData(O=>el(i,O)),g.onResize(({cols:O,rows:$})=>window.api.pty.resize({tabId:i,cols:O,rows:$})),Qz({tabId:i,cwd:e}).then(O=>{O&&g.write(O)}).catch(()=>{}).finally(()=>{console.log("[Terminal] calling pty.spawn",{tabId:i,cwd:e,cols:k,rows:y}),window.api.pty.spawn({tabId:i,cwd:e,cols:k,rows:y}).then(({pid:O,reattached:$})=>{console.log("[Terminal] pty.spawn resolved, pid=",O,"tabId=",i,"reattached=",$),St.getState().setTabRunning(i,O);const j=St.getState().consumeRawCommand(i);if(j&&setTimeout(()=>{el(i,`${j}\r`)},$?150:1500),$)return;const{startupCommand:L}=St.getState().tabs.find(G=>G.id===i)??{};L&&setTimeout(()=>{el(i,`${L}
3077
3077
  `)},350)}).catch(O=>{console.error("[Terminal] pty.spawn rejected for tabId=",i,O),g.write(`\r
3078
3078
  \x1B[31mfailed to spawn: ${O.message}\x1B[0m\r
3079
- `),nt.error(`Terminal failed to start: ${O.message??"spawn failed"}`),St.getState().setTabExited(i,-1)})});const x=()=>b();window.addEventListener("resize",x),window.addEventListener(Av,x);const A=new ResizeObserver(()=>b());return A.observe(r.current),()=>{window.removeEventListener("resize",x),window.removeEventListener(Av,x),A.disconnect(),S(),w(),T(),g.dispose()}},[i,e]),t?n?c.jsx(pk,{cwd:e}):null:c.jsxs("div",{className:"relative h-full w-full",children:[c.jsx("button",{type:"button",onClick:()=>St.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),a&&c.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:c.jsx(eB,{path:a,onDismiss:()=>d(null)},a)}),c.jsx("div",{ref:r,onMouseDown:()=>{var f;return(f=l.current)==null?void 0:f.focus()},className:"h-full w-full bg-bg"})]})}const iB={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},nB={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function sB(){const{isRecording:i,statusPill:e,lastPartial:t,lastTranscript:n,submitCountdownStartAt:r}=Ct(Fb(RD)),l=i||!!t||!!n,[p,a]=B.useState(l);if(B.useEffect(()=>{if(l)a(!0);else{const f=setTimeout(()=>a(!1),300);return()=>clearTimeout(f)}},[l]),!p)return null;let d=t;return d.length>200&&(d="…"+d.slice(-200)),c.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${l?"opacity-100":"opacity-0"}`,children:c.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${iB[e]??"bg-fg-faint"}`}),c.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:nB[e]??e})]}),d&&c.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),r!==null&&c.jsx("div",{className:"shrink-0",children:c.jsx(xE,{})})]})})})}function rB({visible:i=!0}){const e=St(p=>p.tabs),t=St(p=>p.activeTabId),n=e.find(p=>p.id===t)??null,l=Ii(p=>p.epicsWorkspaceOpen)||!n;return c.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[l?c.jsx(pk,{}):e.map(p=>c.jsx("div",{className:"absolute inset-0",style:{visibility:p.id===t?"inherit":"hidden"},children:c.jsx(fk,{tabId:p.id,cwd:p.cwd})},`${p.id}-${p.generation}`)),c.jsx(sB,{})]})}function oB(){const i=Ii(e=>e.focusedPanelId==="terminal");return c.jsx(rB,{visible:i})}const aB=1;function lB(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:aB,panels:e,dockview:i}}function ib(i,e){const t=i.views.filter(r=>e.has(r));if(t.length===0)return null;const n=i.activeView&&t.includes(i.activeView)?i.activeView:t[0];return{...i,views:t,activeView:n}}function mk(i,e){if(i.type==="leaf"){const n=ib(i.data,e);return n?{...i,data:n}:null}const t=i.data.map(n=>mk(n,e)).filter(n=>n!==null);return t.length===0?null:{...i,data:t}}function cB(i,e){const t=Object.keys(i.panels??{}),n=new Set(t.filter(d=>e.has(d)));if(n.size===0)return null;const r=mk(i.grid.root,n);if(!r)return null;const l={};for(const d of n)l[d]=i.panels[d];const p=(i.floatingGroups??[]).map(d=>{const f=ib(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null),a=(i.popoutGroups??[]).map(d=>{const f=ib(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:r},panels:l,floatingGroups:p,popoutGroups:a,activeGroup:i.activeGroup}}function dB(i,e){if(!i||typeof i!="object")return null;const t=i;if(!Array.isArray(t.panels)||!t.dockview||typeof t.dockview!="object")return null;const n=t.dockview;if(!n.grid||!n.panels)return null;try{return cB(n,e)}catch(r){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",r),null}}const uB=500,hB=new Set(ud.map(i=>i.id));function MS(i){const e=lB(i);e&&window.api.layout.save(e).catch(t=>{console.warn("[Workbench] layout save failed:",t)})}const gk=B.createContext(null),pB=B.memo(function(e){const t=B.useContext(gk);return t?c.jsx(c.Fragment,{children:mB(e.params.id,t)}):null}),fB={screen:pB},Yg=ud[0].id;function mB(i,e){return i==="terminal"?c.jsx(oB,{}):c.jsx(e2,{panelId:i,children:c.jsx("div",{className:"h-full overflow-auto bg-bg",children:c.jsx(yE,{children:$N(i,e)})})})}function gB({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}){const r=B.useRef(null),l=Ii(A=>A.focusedPanelId)??Yg,p=Ii(A=>A.focusToken),a=Ii(A=>A.resetToken),d=Ct(A=>A.isRecording||A.externalRecording),f=B.useRef(null),[g,m]=B.useState(!1),b=B.useRef(l);b.current=l;const T=B.useRef(null),E=B.useRef(null);B.useEffect(()=>{let A=!1;return window.api.layout.load().then(O=>{A||(O&&(f.current=dB(O,hB)),m(!0))}).catch(O=>{console.warn("[Workbench] layout load failed, using default:",O),A||m(!0)}),()=>{A=!0}},[]);const k=B.useCallback(A=>{const O=r.current;if(!O)return;const $=FT(A)??ud[0],j=O.getPanel($.id);if(j)j.api.setActive();else{const L=O.addPanel({id:$.id,component:$.component,title:$.title,params:{id:$.id},renderer:"always"});$.id==="terminal"&&L.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(Av))})}},[]),y=B.useCallback(A=>{var L;r.current=A.api;const O=G=>{G.header.hidden=!0};E.current=A.api.onDidAddGroup(O),A.api.groups.forEach(O);const $=f.current;if($)try{A.api.fromJSON($);const G=(L=A.api.activePanel)==null?void 0:L.id;G&&Ii.getState().focusPanel(G)}catch(G){console.warn("[Workbench] fromJSON failed, falling back to default layout:",G),A.api.clear(),k(b.current)}else k(b.current);A.api.onDidActivePanelChange(G=>{G&&Ii.getState().focusPanel(G.id)}),T.current=A.api.onDidRemovePanel(G=>{if(G.id==="terminal"){Ii.getState().openPanel("terminal");return}A.api.totalPanels===0&&(Ii.getState().openPanel(Yg),k(Yg))});let j=null;A.api.onDidLayoutChange(()=>{j!==null&&window.clearTimeout(j),j=window.setTimeout(()=>MS(A.api.toJSON()),uB)})},[]);B.useEffect(()=>()=>{var A,O;(A=T.current)==null||A.dispose(),(O=E.current)==null||O.dispose()},[]),B.useEffect(()=>{k(l)},[p,k]);const S=B.useRef(!0);B.useEffect(()=>{if(S.current){S.current=!1;return}const A=r.current;A&&(A.clear(),f.current=null,k(Yg),MS(A.toJSON()))},[a]),B.useEffect(()=>{const A=r.current;A&&(A.layout(A.width,A.height,!0),window.dispatchEvent(new CustomEvent(Av)))},[d]);const w=B.useMemo(()=>({components:fB,onReady:y,className:"dockview-theme-sm workbench-root"}),[y]),x=B.useMemo(()=>({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}),[i,e,t,n]);return g?c.jsx(gk.Provider,{value:x,children:c.jsx(wC,{...w})}):null}function vk(){return Ct(e=>e.isRecording||e.externalRecording)?c.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:`fixed inset-x-0 top-0 ${Cn.recording} h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0`,children:[c.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),c.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const If=5e3;function Ro(i,e,t){var n,r;try{(r=(n=window.api)==null?void 0:n.logs)==null||r.write("voice-wizard",i,e,t)}catch{}}function vB({analyser:i}){const[e,t]=B.useState(0);return B.useEffect(()=>{if(!i){t(0);return}let n=0,r=!1;const l=new Uint8Array(new ArrayBuffer(i.fftSize)),p=()=>{if(r)return;i.getByteTimeDomainData(l);let a=0;for(let g=0;g<l.length;g++){const m=l[g]-128;a+=m*m}const d=Math.sqrt(a/l.length)/128,f=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));t(f),n=requestAnimationFrame(p)};return n=requestAnimationFrame(p),()=>{r=!0,cancelAnimationFrame(n)}},[i]),c.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function _B({open:i,onClose:e}){const t=Ct(Y=>Y.permissionState),n=Ct(Y=>Y.modelStatus),r=Ct(Y=>Y.loadingProgress),[l,p]=B.useState("welcome"),[a,d]=B.useState(null),[f,g]=B.useState(!1),[m,b]=B.useState(0),T=B.useRef(null),E=B.useRef(null),k=B.useRef(null),y=B.useRef(null),S=B.useRef(null),w=B.useRef(null),x=B.useRef(null),A=B.useRef(null),[O,$]=B.useState(!1),[j,L]=B.useState(Math.round(If/1e3)),[G,W]=B.useState(!1),[re,ae]=B.useState(!1),[Z,pe]=B.useState(null),[oe,me]=B.useState(0),we=B.useCallback(()=>{var Y;try{(Y=S.current)==null||Y.stop()}catch{}if(S.current=null,A.current){try{A.current.disconnect()}catch{}A.current=null}if(y.current){try{y.current.disconnect()}catch{}y.current=null}if(k.current){try{k.current.disconnect()}catch{}k.current=null}if(me(_e=>_e+1),E.current){const _e=E.current;E.current=null;try{_e.close()}catch{}}if(T.current){try{T.current.getTracks().forEach(_e=>_e.stop())}catch{}T.current=null}},[]),ve=B.useCallback(()=>{we(),w.current=null,x.current=null,$(!1),L(Math.round(If/1e3)),W(!1),ae(!1),pe(null),d(null),g(!1)},[we]);B.useEffect(()=>{i?(Ro("info","wizard.opened"),p("welcome")):ve()},[i,ve]),B.useEffect(()=>()=>we(),[we]);const F=B.useCallback(Y=>{Ro("info","wizard.step",{step:Y}),d(null),p(Y)},[]),J=B.useCallback(Y=>{if(Ro("info","wizard.skipped",{step:l,mode:Y}),we(),e(),Y==="skip-and-record"){const _e=Ct.getState();_e.setWizardArmed(!1);const ue=St.getState().activeTabId;ue&&_e.startRecording(ue)}else Ct.getState().setWizardArmed(!1)},[l,e,we]),V=B.useCallback(()=>{if(t==="denied"){F("permission");return}F("permission")},[t,F]);B.useEffect(()=>{i&&l==="permission"&&t==="granted"&&F("device")},[i,l,t,F]),B.useEffect(()=>{if(!i||l!=="device")return;let Y=!1;return(async()=>{var _e;try{if(!((_e=navigator.mediaDevices)!=null&&_e.enumerateDevices)){Y||g(!0);return}const ue=await navigator.mediaDevices.enumerateDevices();if(Y)return;const Re=ue.filter(He=>He.kind==="audioinput");g(Re.length===0)}catch(ue){if(Y)return;Ro("warn","wizard.error",{step:"device",error:ue instanceof Error?ue.message:String(ue)}),g(!0)}})(),()=>{Y=!0}},[i,l,m]);const se=B.useCallback(async()=>{d(null),$(!0),L(Math.round(If/1e3));try{let Y=null;try{const _t=await window.api.voice.getDevicePref();Y=(_t==null?void 0:_t.selectedDeviceId)??null}catch{}const _e={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Y&&(_e.deviceId={exact:Y});const ue=await navigator.mediaDevices.getUserMedia({audio:_e});T.current=ue;const Re=new AudioContext;E.current=Re;const He=Re.createMediaStreamSource(ue),lt=Re.createAnalyser();lt.fftSize=2048,lt.smoothingTimeConstant=.8,He.connect(lt),k.current=He,y.current=lt,me(_t=>_t+1);const It=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",ct=new MediaRecorder(ue,It?{mimeType:It}:void 0);S.current=ct;const qt=[];ct.ondataavailable=_t=>{_t.data&&_t.data.size>0&&qt.push(_t.data)},ct.onstop=()=>{const _t=ct.mimeType||"audio/webm";if(w.current=new Blob(qt,{type:_t}),$(!1),y.current){try{y.current.disconnect()}catch{}y.current=null}if(k.current){try{k.current.disconnect()}catch{}k.current=null}if(me(ni=>ni+1),T.current){try{T.current.getTracks().forEach(ni=>ni.stop())}catch{}T.current=null}F("playback")},ct.onerror=_t=>{var Ye;const ni=((Ye=_t.error)==null?void 0:Ye.message)??"recorder error";Ro("error","wizard.error",{step:"record",error:ni}),d(ni),$(!1),nt.error(`Mic wizard: ${ni}`)},ct.start();const qe=Date.now(),Rt=setInterval(()=>{const _t=Date.now()-qe,ni=Math.max(0,Math.ceil((If-_t)/1e3));if(L(ni),_t>=If){clearInterval(Rt);try{ct.stop()}catch{}}},250)}catch(Y){const _e=Y instanceof Error?Y.message:String(Y);Ro("error","wizard.error",{step:"record",error:_e}),d(_e),$(!1),we(),nt.error(`Mic wizard: ${_e}`)}},[F,we]),ge=B.useCallback(async()=>{d(null);const Y=w.current;if(!Y){d("No recording available");return}try{let _e=E.current;(!_e||_e.state==="closed")&&(_e=new AudioContext,E.current=_e);let ue=x.current;if(!ue){const He=await Y.arrayBuffer();ue=await _e.decodeAudioData(He.slice(0)),x.current=ue}if(A.current){try{A.current.disconnect()}catch{}A.current=null}const Re=_e.createBufferSource();Re.buffer=ue,Re.connect(_e.destination),A.current=Re,W(!0),Re.onended=()=>{W(!1);try{Re.disconnect()}catch{}A.current===Re&&(A.current=null)},Re.start()}catch(_e){const ue=_e instanceof Error?_e.message:String(_e);Ro("error","wizard.error",{step:"playback",error:ue}),d(ue),W(!1)}},[]);B.useEffect(()=>{i&&l==="playback"&&ge().catch(()=>{})},[i,l,ge]);const Te=B.useCallback(async()=>{d(null),ae(!0),pe(null);try{const Y=x.current;if(!Y)throw new Error("No decoded audio available");const _e=Y.getChannelData(0),ue=new Float32Array(_e.length);ue.set(_e);const Re=await mD(ue);pe(Re)}catch(Y){const _e=Y instanceof Error?Y.message:String(Y);Ro("error","wizard.error",{step:"verify",error:_e}),d(_e)}finally{ae(!1)}},[]);B.useEffect(()=>{i&&l==="verify"&&n==="ready"&&Z===null&&!re&&!a&&Te()},[i,l,n,Z,re,a,Te]);const je=B.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),Ro("info","wizard.complete")}catch(Y){Ro("error","wizard.error",{step:"done",error:Y instanceof Error?Y.message:String(Y)})}Ct.getState().setWizardArmed(!1),we(),e()},[e,we]),Ze=B.useCallback(()=>{Ro("info","wizard.skipped",{step:l,mode:"modal-close"}),we(),Ct.getState().setWizardArmed(!1),e()},[l,we,e]),ye=B.useMemo(()=>{switch(l){case"welcome":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),c.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:V,"data-testid":"wizard-start",children:"Start"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>J("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),c.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>J("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return t==="denied"?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),c.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",c.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",c.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),c.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",t]}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>F("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return f?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),c.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{g(!1),b(Y=>Y+1)},"data-testid":"wizard-device-retry",children:"Try again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),c.jsx(wE,{}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>F("record"),"data-testid":"wizard-device-continue",children:"Continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return c.jsxs("div",{className:"space-y-3",children:[c.jsxs("p",{className:"text-sm text-fg",children:["Say: ",c.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),c.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),O?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",j,"s"]}),c.jsx(vB,{analyser:y.current},oe)]}):c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{se()},"data-testid":"wizard-record-start",children:"Start recording"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),c.jsx("p",{className:"text-xs text-fg-dim",children:G?"Playing back…":"Playback finished."}),c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>F("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{ge()},"data-testid":"wizard-playback-replay",children:"Replay"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,F("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return n==="loading"||n==="idle"?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),c.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[c.jsx("span",{children:"Downloading"}),c.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),c.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`},"data-testid":"wizard-load-progress"})}),c.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:re?"Transcribing your sample…":Z===null?"Ready to transcribe.":"We heard:"}),Z!==null&&c.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:Z||"(no text recognized)"}),c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",disabled:re||Z===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>F("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,pe(null),F("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),c.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{je()},"data-testid":"wizard-done",children:"Done"})})]})}},[l,V,J,t,f,O,j,oe,G,re,Z,n,r,a,F,se,ge,je]);return c.jsx(Hb,{open:i,onClose:Ze,title:"Mic check",children:c.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[c.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",l]}),a?c.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:a}):null,ye]})})}const _k="sm.tour.completedAt",Jl=Un((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:t=>{e().stepCount!==t&&i({stepCount:t})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:t,stepCount:n}=e();if(t>=n-1){e().complete();return}i({currentStep:t+1})},prev:()=>{const{currentStep:t}=e();t<=0||i({currentStep:t-1})},goTo:t=>{const{stepCount:n}=e();t<0||t>=n||i({currentStep:t})},complete:()=>{try{localStorage.setItem(_k,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function yB(){try{return!!localStorage.getItem(_k)}catch{return!1}}const jS={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function bB(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app (drain first)",section:"session",run:()=>window.api.app.rebootApp()},{id:"reboot-app-force",label:"Reboot app NOW (force — kills running jobs)",section:"session",run:()=>window.api.app.rebootApp({force:!0})},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=Ct.getState(),t=St.getState().activeTabId;e.isRecording?e.stopRecording():t&&e.startRecording(t)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>Ct.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>Ct.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{nt.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-pause",label:"Scheduler — Pause (stop new dispatch)",section:"scheduler",run:async()=>{await window.api.schedule.pause()}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{nt.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Jl.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ii.getState().resetLayout()},{id:"nav:overview",label:"Go to Overview — this machine",section:"nav",emitOnly:!0},{id:"nav:project-home",label:"Go to Home",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0},{id:"nav:agent-library",label:"Go to Agent Library",section:"nav",emitOnly:!0},{id:"nav:tag-library",label:"Go to Tag Library",section:"nav",emitOnly:!0},{id:"nav:bilko-host",label:"Go to Bilko Host",section:"nav",emitOnly:!0}]}function wB(i,e){if(!e)return 0;const t=i.toLowerCase(),n=e.toLowerCase();let r=0,l=-1,p=0;for(let a=0;a<t.length&&r<n.length;a++)t[a]===n[r]&&(p+=a-l,l=a,r++);return r!==n.length?null:p}function xB(i,e){if(!e)return i.map(n=>({...n,score:0}));const t=[];for(const n of i){const r=wB(n.label,e);r!==null&&t.push({...n,score:r})}return t.sort((n,r)=>n.score-r.score),t}function SB({open:i,onClose:e,onCommand:t}){const[n,r]=B.useState(""),[l,p]=B.useState(0),a=B.useRef(null),d=B.useRef(null),f=B.useRef(null),g=B.useRef(null),m=B.useMemo(()=>bB(),[]),b=B.useMemo(()=>xB(m,n),[m,n]);if(B.useEffect(()=>{if(i){const A=document.activeElement;g.current=A instanceof HTMLElement?A:null,r(""),p(0);const O=setTimeout(()=>{var $;return($=a.current)==null?void 0:$.focus()},0);return()=>{clearTimeout(O);const $=g.current;g.current=null,$&&requestAnimationFrame(()=>{try{$.focus()}catch{}})}}},[i]),B.useEffect(()=>{l>=b.length&&p(Math.max(0,b.length-1))},[b.length,l]),B.useEffect(()=>{if(!d.current)return;const A=d.current.querySelector(`[data-cmd-idx="${l}"]`);A&&A.scrollIntoView({block:"nearest"})},[l]),!i)return null;const T=async A=>{var O;if(e(),A.emitOnly){t(A);return}try{await((O=A.run)==null?void 0:O.call(A))}catch($){console.error("[command-palette] run failed",A.id,$);const j=$ instanceof Error?$.message:String($);nt.error(`Command "${A.label}" failed: ${j}`)}t(A)},E=A=>{var O,$,j,L;if(A.key==="Escape"){A.preventDefault(),e();return}if(A.key==="ArrowDown"){A.preventDefault(),p(G=>Math.min(b.length-1,G+1));return}if(A.key==="ArrowUp"){A.preventDefault(),p(G=>Math.max(0,G-1));return}if(A.key==="Home"){A.preventDefault(),p(0);return}if(A.key==="End"){A.preventDefault(),p(Math.max(0,b.length-1));return}if(A.key==="PageDown"){A.preventDefault(),p(G=>Math.min(b.length-1,G+5));return}if(A.key==="PageUp"){A.preventDefault(),p(G=>Math.max(0,G-5));return}if(A.key==="Tab"){A.preventDefault();const G=document.activeElement;A.shiftKey?G===a.current?(O=f.current)==null||O.focus():($=a.current)==null||$.focus():G===a.current?(j=f.current)==null||j.focus():(L=a.current)==null||L.focus();return}if(A.key==="Enter"){A.preventDefault();const G=b[l];G&&T(G);return}},k=[],y=new Map;b.forEach((A,O)=>{let $=y.get(A.section);$===void 0&&($=k.length,y.set(A.section,$),k.push({section:A.section,items:[]})),k[$].items.push({cmd:A,absIdx:O})});const S=b[l],w=S?`cmdk-opt-${S.id}`:void 0,x=c.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-start justify-center bg-black/60 pt-[15vh]`,onClick:A=>{A.target===A.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:E,children:c.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[c.jsxs("div",{className:"border-b border-line flex items-center",children:[c.jsx("input",{ref:a,id:"cmdk-title",type:"text",value:n,onChange:A=>{r(A.target.value),p(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":w,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),c.jsx("button",{ref:f,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),c.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:b.length===0?c.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):k.map(A=>c.jsxs("div",{role:"group","aria-label":jS[A.section],className:"py-1",children:[c.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:jS[A.section]}),A.items.map(({cmd:O,absIdx:$})=>{const j=$===l;return c.jsxs("button",{id:`cmdk-opt-${O.id}`,type:"button",role:"option","aria-selected":j,"data-cmd-idx":$,"data-cmd-id":O.id,tabIndex:-1,onMouseEnter:()=>p($),onClick:()=>T(O),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${j?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[c.jsx("span",{className:"truncate flex-1",children:O.label}),O.hint&&c.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:O.hint})]},O.id)})]},A.section))}),c.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[c.jsx("span",{children:"↑↓ navigate"}),c.jsx("span",{children:"↵ run"}),c.jsx("span",{children:"esc close"}),c.jsxs("span",{className:"ml-auto",children:[b.length," of ",m.length]})]})]})});return typeof document<"u"&&document.body?dm.createPortal(x,document.body):x}const CB={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function yk(){const i=$o(t=>t.toasts),e=$o(t=>t.dismiss);return i.length===0?null:c.jsx("div",{"data-testid":"toast-host",className:`fixed bottom-3 right-3 ${Cn.toast} flex flex-col gap-1.5 pointer-events-none`,children:i.map(t=>{const n=CB[t.kind];return c.jsxs("div",{"data-testid":"toast","data-kind":t.kind,role:t.kind==="error"?"alert":"status","aria-live":t.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${n.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[c.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${n.text}`,children:n.label}),c.jsx("span",{className:"flex-1 text-fg-dim break-words",children:t.message}),c.jsx("button",{type:"button",onClick:()=>e(t.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},t.id)})})}function EB(){const i=St(r=>r.tabs),e=St(r=>r.activeTabId),t=i.find(r=>r.id===e)??null,n=Ct(r=>r.isRecording);return c.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${n?"pt-7":""}`,children:[c.jsx(vk,{}),c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[c.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),t&&c.jsxs("span",{className:"truncate",children:["· ",t.cwd]})]}),c.jsx("div",{className:"flex-1 min-h-0 relative",children:t?c.jsx(fk,{tabId:t.id,cwd:t.cwd},`${t.id}-${t.generation}`):c.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),c.jsx(yk,{})]})}const od=[{id:"welcome",title:"Welcome to Session Manager",body:'A 60-second tour of how this app is laid out: projects at the top, sessions inside them, PRDs underneath. Re-run it any time from ⌘K / Ctrl+K → "Restart guided tour".',position:"center"},{id:"tabs",title:"Home, and one tab per project",body:"The top bar is navigation only. The Home pill is this machine — every project, usage, history. Each tab after it is one open project, identified by its folder. Drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"The sidebar follows the tab",body:"On Home it shows machine-wide screens — Dashboard, History, Settings, Skills, Agent Library, Tag Library. On a project tab it swaps to that project: Project Home, Sessions, Scheduler, Memory.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"new-session",title:"Open / Start Project",body:"Pick a folder and it becomes a project — that path is its identity. Picking one that is already open just activates its tab: extra work inside a project is more sessions, never more tabs.",target:'[data-testid="tour-new-session"]',position:"right"},{id:"sessions",title:"Sessions are the unit of work",body:"One session = one small goal, and one Claude session behind it. Pick an Agent (who is working) and a Mission (what it is for), write the goal, then press Approve & start — nothing is spent before that. Chat and Terminal are two views of the same session, not two sessions.",target:'[data-testid="tour-sessions"]',position:"right",projectFaceOnly:!0},{id:"scheduler",title:"Scheduler runs what your sessions wrote",body:"A session decomposes its goal into numbered PRD files under the project's session-manager-operations/scheduler/. The Scheduler queues each as a claude -p job, pauses on rate-limit and resumes at your next window reset. It is per-project — there is no machine-wide queue view.",target:'[data-testid="tour-scheduler"]',position:"right",projectFaceOnly:!0},{id:"voice",title:"Push-to-talk dictation",body:"Hold Ctrl+Shift+Space (Cmd+Option+V on macOS) to dictate, or click the mic. The hotkey, mode and input device live in Voice on the Home sidebar.",target:'[data-testid="mic-button"]',position:"right"},{id:"mainpane-actions",title:"Command palette",body:"Press ⌘K / Ctrl+K to jump to any screen, restart a session, broadcast a prompt to every tab, attach a watcher command, or force a scheduler tick.",position:"center"},{id:"statusbar",title:"Status bar",body:"Connection, your session (5h) and weekly (7d) usage, the active project and its branch, live to-dos, and the app version. Click either usage pill for the full meters on Home.",target:'[data-testid="tour-statusbar"]',position:"top"}],Kl=360,ad=220,Dn=16;function ql(i,e,t){return Math.max(e,Math.min(t,i))}function kB(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const t=window.innerWidth,n=window.innerHeight;switch(e){case"top":return{position:"fixed",top:ql(i.top-ad-Dn,Dn,n-ad-Dn),left:ql(i.left+i.width/2-Kl/2,Dn,t-Kl-Dn)};case"bottom":return{position:"fixed",top:ql(i.bottom+Dn,Dn,n-ad-Dn),left:ql(i.left+i.width/2-Kl/2,Dn,t-Kl-Dn)};case"left":return{position:"fixed",top:ql(i.top+i.height/2-ad/2,Dn,n-ad-Dn),left:ql(i.left-Kl-Dn,Dn,t-Kl-Dn)};case"right":return{position:"fixed",top:ql(i.top+i.height/2-ad/2,Dn,n-ad-Dn),left:ql(i.right+Dn,Dn,t-Kl-Dn)}}}function TB(){const i=Jl(k=>k.open),e=Jl(k=>k.currentStep),t=Jl(k=>k.next),n=Jl(k=>k.prev),r=Jl(k=>k.complete),l=Jl(k=>k.setStepCount);B.useEffect(()=>{l(od.length)},[l]);const[p,a]=B.useState(null),d=B.useRef(null),f=od[e]??od[0],g=e===0,m=e===od.length-1;if(B.useLayoutEffect(()=>{if(!i)return;let k=!1;const y=()=>{if(k)return;if(!f.target){a(null);return}const w=document.querySelector(f.target);if(!w){a(null);return}a(w.getBoundingClientRect())},S=requestAnimationFrame(y);return window.addEventListener("resize",y),()=>{k=!0,cancelAnimationFrame(S),window.removeEventListener("resize",y)}},[i,f.target,e]),B.useEffect(()=>{if(!i)return;const k=y=>{if(y.key==="Escape"){y.stopPropagation(),pt.info("tour","skipped",{step:f.id}),r();return}if(y.key==="ArrowRight"||y.key==="Enter"){y.preventDefault(),t();return}y.key==="ArrowLeft"&&(y.preventDefault(),n())};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[i,t,n,r,f.id]),B.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:f.id})},[i,e,f.id]),!i)return null;const b=kB(p,f.position),T=(e+1)/od.length*100,E=c.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:`fixed inset-0 ${Cn.tour}`,children:[p?c.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:p.top-6,left:p.left-6,width:p.width+12,height:p.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):c.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),c.jsxs("div",{ref:d,style:{...b,width:Kl},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[c.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[c.jsxs("div",{children:[c.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",od.length]}),c.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:f.title})]}),c.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),c.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:f.body}),c.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":od.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${T}%`}})}),c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),c.jsxs("div",{className:"flex items-center gap-2",children:[!g&&c.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),c.jsx("button",{type:"button",onClick:t,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:m?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?dm.createPortal(E,document.body):E}let ey=null;function DB(){return ey||(ey=Bn(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(Lb.config({monaco:i}),i))),ey}function _5({value:i,onChange:e,path:t,readOnly:n}){const r=B.useRef(null),l=p=>{r.current=p};return c.jsx(nE,{path:`file://${t}`,defaultLanguage:"json",value:i,onChange:p=>e(p??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:n,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let zS=!1;async function AB(i){if(zS)return;const e=await DB(),t=await Promise.all(i.map(async r=>{let l=r.schema;if(!l){const p=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const a=new URL(r.uri).origin;if(!p.includes(a))throw new Error("untrusted origin");const d=await fetch(r.uri);d.ok&&(l=await d.json())}catch{}}return{uri:r.uri,fileMatch:r.fileMatch,schema:l}}));e.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:t.filter(r=>r.schema),enableSchemaRequest:!0}),zS=!0}async function BS(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return St.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}async function IB(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=St.getState(),t=e.tabs.find(r=>r.cwd===i);if(t)return e.setActive(t.id),t.id;const n=crypto.randomUUID();return e.addTab({id:n,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),n}function PB(i){const e=Ct(n=>n.ttsEnabled),t=Ct(n=>n.isRecording);B.useEffect(()=>{if(!i||!e)return;const n=l=>{const p=Ct.getState().lastBargeInAt;if(p!==null&&performance.now()-p<AD){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-p)});return}_D(l)};return window.api.transcripts.onEvent(i,l=>{for(const p of l){if(p.kind!=="message")continue;const a=p.data;if(typeof a!="object"||a===null)continue;const d=a;if(d.role!=="assistant"||Ct.getState().isRecording)continue;const f=d.content;if(typeof f=="string")n(f);else if(Array.isArray(f)){const g=f.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");g&&n(g)}}})},[i,e]),B.useEffect(()=>{t&&(P1(),Ct.setState({lastBargeInAt:performance.now()}))},[t])}const bk="sm.density",RB="roomy",US="density-compact";function OB(){try{const i=localStorage.getItem(bk);if(i==="compact"||i==="roomy")return i}catch{}return RB}function wk(i){typeof document>"u"||(i==="compact"?document.body.classList.add(US):document.body.classList.remove(US))}let wh=OB();const nb=new Set;wk(wh);function LB(i){if(i!==wh){wh=i;try{localStorage.setItem(bk,i)}catch{}wk(i),nb.forEach(e=>e(i))}}function $B(){const[i,e]=B.useState(wh);B.useEffect(()=>{const n=r=>e(r);return nb.add(n),wh!==i&&e(wh),()=>{nb.delete(n)}},[]);const t=B.useCallback(n=>LB(n),[]);return{density:i,setDensity:t}}let GS=!1;function NB(){$B();const i=Ii(Z=>Z.focusedPanelId)??"overview",e=Ii(Z=>Z.navFace),[t,n]=B.useState(null),[r,l]=B.useState(!1),[p,a]=B.useState(!1),[d,f]=B.useState(!1),[g,m]=B.useState(null),b=B.useCallback(Z=>{Ii.getState().setEpicsWorkspaceOpen(Z==="terminal"),Ii.getState().openPanel(Z)},[]),T=B.useCallback(()=>b("voice"),[b]),E=B.useCallback(()=>b("scheduler"),[b]);B.useCallback(Z=>{Oi.getState().openFile(Z),b("editor")},[b]),B.useEffect(()=>{Ii.getState().hydrateOpenToHomePref()},[]),B.useEffect(()=>{const Z=()=>b("editor");return window.addEventListener("sm:open-editor",Z),()=>window.removeEventListener("sm:open-editor",Z)},[b]),B.useEffect(()=>{const Z=pe=>b(pe.detail);return window.addEventListener("sm:navigate",Z),()=>window.removeEventListener("sm:navigate",Z)},[b]);const k=St(Z=>Z.activeTabId),y=St(Z=>Z.tabs),S=y.find(Z=>Z.id===k)??null,w=B.useRef(k),x=B.useRef(new Set(y.map(Z=>Z.id)));B.useEffect(()=>{const Z=w.current,pe=x.current,oe=new Set(y.map(we=>we.id));w.current=k,x.current=oe,Z!==null&&k!==null&&k!==Z&&oe.size===pe.size&&pe.has(k)&&oe.has(Z)&&Ii.getState().openProjectPanel("terminal")},[k,y]),B.useEffect(()=>{WT(i,k,e)&&Ii.getState().openPanel("overview")},[i,k,e]),B.useEffect(()=>{if(!g)return;const Z=window.setTimeout(()=>m(null),2500);return()=>window.clearTimeout(Z)},[g]),B.useEffect(()=>S?window.api.watchers.onLine(pe=>{if(pe.tabId!==S.id)return;const oe=pe.line.replace(/\x1b\[[0-9;]*m/g,"");oe.trim()&&m(oe.length>100?`${oe.slice(0,100)}…`:oe)}):void 0,[S==null?void 0:S.id]);const A=Ct(Z=>Z.isRecording),O=Ct(Z=>Z.wizardOpen),$=Ct(Z=>Z.closeWizard);PB(k);const j=B.useCallback(()=>{const{activeTabId:Z,restartTab:pe}=St.getState();Z&&pe(Z)},[]);B.useCallback(()=>{window.api.app.rebootApp()},[]);const L=B.useCallback(()=>{a(Z=>(Z||Ii.getState().openPanel("terminal"),!Z))},[]),G=B.useCallback(()=>{f(Z=>(Z||Ii.getState().openPanel("terminal"),!Z))},[]),W=B.useRef(k);W.current=k;const re=B.useRef("hold"),ae=B.useCallback(()=>{IB().catch(()=>null).finally(()=>{Ii.getState().setEpicsWorkspaceOpen(!0),Ii.getState().openProjectPanel("terminal")})},[]);return B.useEffect(()=>{var me;if(!Rv()){GS||(pt.warn("voice","mic.gate.unsupported"),GS=!0);return}Ct.getState().initModel();let Z=null,pe=!1;const oe=()=>{if(!Z)return;const we=Z.state;Ct.getState().setPermissionState(we)};return typeof navigator<"u"&&((me=navigator.permissions)!=null&&me.query)&&navigator.permissions.query({name:"microphone"}).then(we=>{pe||(Z=we,Ct.getState().setPermissionState(we.state),we.addEventListener("change",oe))}).catch(we=>{pt.warn("voice","permission query unsupported",{error:we==null?void 0:we.message})}),()=>{pe=!0,Z&&Z.removeEventListener("change",oe)}},[]),B.useEffect(()=>{var ge;const Z=XS[0],pe=Te=>{if(!Te||St.getState().tabs.length>0)return;const je=crypto.randomUUID(),Ze=JS(Z,{sessionId:je,cwd:Te});St.setState(ye=>({tabs:[...ye.tabs,{id:je,sessionId:je,label:Te.split("/").filter(Boolean).pop()||Te,cwd:Te,pid:null,status:"spawning",exitCode:null,startupCommand:Ze,presetId:Z.id,generation:0}],activeTabId:je}))},oe=Te=>{if(!Te||St.getState().tabs.length>0)return;const je=crypto.randomUUID();St.setState(Ze=>({tabs:[...Ze.tabs,{id:je,sessionId:je,label:Te.split("/").filter(Boolean).pop()||Te,cwd:Te,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:Z.id,generation:0}],activeTabId:je}))};window.api.app.launchMode().then(({simple:Te,cwd:je})=>{if(Te){n(!0),pe(je);return}n(!1),ry().then(()=>{St.getState().tabs.length>0||bw(Z).then(Ze=>oe(Ze||"")).catch(Ze=>{console.warn("[App] failed to create initial tab:",Ze),nt.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),ry().then(()=>{St.getState().tabs.length>0||bw(Z).then(Te=>oe(Te||"")).catch(()=>{})})});const me=window.api.app.onNewSession(()=>{BS().catch(Te=>{console.error("[App] new-session from menu failed:",Te),nt.error("Could not start new session. The directory picker failed.")})}),we=window.api.app.onRebootSession(()=>{const{activeTabId:Te}=St.getState();Te?St.getState().restartTab(Te):nt.error("No active tab to restart. Open a project tab first.")});jf.getState().init(),MD(),oT(),window.api.app.claudeBinStatus().then(Te=>{Te.foundOnDisk||nt.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(Te=>{Te.ok||nt.error(`Home-directory self-check failed: ${Te.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const ve=cP();AB([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]}]).catch(Te=>console.warn("[monaco] schema install failed:",Te)),window.api.voice.getHotkeyConfig().then(Te=>{re.current=Te.mode}).catch(Te=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(Te)}));const F=window.api.voice.onHotkeyConfigChanged(Te=>{re.current=Te.mode}),J=window.api.voice.onHotkey(({phase:Te,source:je})=>{Ct.getState().armHotkey({phase:Te,source:je,mode:re.current,tabId:W.current})}),V=()=>Ct.getState().destroyHotkey();window.addEventListener("beforeunload",V);const se=async()=>{var Te;window.dispatchEvent(new Event("mic-device-change"));try{if(!((Te=navigator.mediaDevices)!=null&&Te.enumerateDevices))return;const Ze=(await navigator.mediaDevices.enumerateDevices()).filter(ue=>ue.kind==="audioinput"),ye=Ct.getState();if(!ye.isRecording)return;let Y=null;try{Y=await window.api.voice.getDevicePref()}catch{}if(!Y||!Y.selectedDeviceId||Ze.some(ue=>ue.deviceId===Y.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:Y.selectedDeviceId.slice(0,8)}),ye.stopRecording(),Ct.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(je){pt.warn("voice","devicechange handler failed",{error:je instanceof Error?je.message:String(je)})}};return typeof navigator<"u"&&((ge=navigator.mediaDevices)!=null&&ge.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",se),()=>{var Te;ve(),me(),we(),F(),J(),window.removeEventListener("beforeunload",V),typeof navigator<"u"&&((Te=navigator.mediaDevices)!=null&&Te.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",se)}},[]),B.useEffect(()=>{try{window.api.voice.setRecording(A)}catch{}},[A]),B.useEffect(()=>{const Z=oe=>{var F,J;const me=oe.target,we=((F=me==null?void 0:me.tagName)==null?void 0:F.toLowerCase())??"",ve=((J=me==null?void 0:me.classList)==null?void 0:J.contains("xterm-helper-textarea"))??!1;return!!((we==="input"||we==="textarea")&&!ve||me!=null&&me.closest(".monaco-editor"))},pe=oe=>{if((oe.metaKey||oe.ctrlKey)&&(oe.key==="k"||oe.key==="K")){if(Z(oe))return;oe.preventDefault(),oe.stopPropagation(),l(me=>!me)}else if(oe.key==="Escape"&&r)l(!1);else if(oe.altKey&&!oe.ctrlKey&&!oe.metaKey&&!oe.shiftKey){const me=/^Digit([1-5])$/.exec(oe.code);if(!me||Z(oe))return;const we=parseInt(me[1],10)-1,{tabs:ve,setActive:F}=St.getState(),J=ve[we];if(!J)return;oe.preventDefault(),oe.stopPropagation(),F(J.id),Ii.getState().setEpicsWorkspaceOpen(!1)}};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[r]),B.useEffect(()=>{let Z=!1,pe=null;return(async()=>{var oe,me;try{const we=await((me=(oe=window.api.voice).getTurnDetector)==null?void 0:me.call(oe));if(Z||!we||(Ct.setState({turnDetectorMode:we.mode,turnDetectorState:"disabled"}),we.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:we.mode}),Z))return;pe=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),pe.addEventListener("message",ve=>{const F=ve.data;if(!(!F||typeof F!="object")&&F.type==="status"){const J=F.status;J==="ready"?Ct.getState().setTurnDetectorRuntimeState("ok"):(J==="load_failed"||J==="runtime_error")&&Ct.getState().setTurnDetectorRuntimeState(J)}}),pe.addEventListener("error",ve=>{pt.error("voice-turn","turn-detector worker error",{message:ve.message}),Ct.getState().setTurnDetectorRuntimeState("runtime_error")}),pe.postMessage({type:"load"})}catch(we){pt.warn("voice-turn","mount.read-settings failed",{error:we instanceof Error?we.message:String(we)})}})(),()=>{if(Z=!0,pe){try{pe.terminate()}catch{}pe=null}}},[]),B.useEffect(()=>{let Z=!1;return(async()=>{var pe,oe;try{const me=await((oe=(pe=window.api.app).isE2E)==null?void 0:oe.call(pe));if(Z||me||yB()||Ct.getState().wizardOpen)return;Jl.getState().start()}catch{}})(),()=>{Z=!0}},[]),B.useEffect(()=>{let Z=!1;return(async()=>{var pe,oe;try{const me=await((oe=(pe=window.api.app).isE2E)==null?void 0:oe.call(pe));if(Z)return;if(me){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const we=await window.api.voice.getWizardState();if(Z)return;we.completedSchema!==we.currentSchema&&(Ct.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:we.completedSchema,currentSchema:we.currentSchema}))}catch(me){pt.warn("voice-wizard","auto-arm failed",{error:me instanceof Error?me.message:String(me)})}})(),()=>{Z=!0}},[]),t===!0?c.jsx(EB,{}):c.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${A?"pt-7":""}`,children:[c.jsx(vk,{}),c.jsx(XT,{}),c.jsxs("div",{className:"flex-1 flex min-h-0",children:[c.jsx(VD,{active:i,onNavigate:b,onNewSession:ae}),c.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&p&&c.jsx(f2,{onClose:()=>a(!1),onSent:Z=>{a(!1),m(`Sent to ${Z} tab${Z===1?"":"s"}`)}}),i==="terminal"&&S&&d&&c.jsx("div",{className:"absolute top-12 right-4 z-30",children:c.jsx(m2,{tabId:S.id,cwd:S.cwd,onClose:()=>f(!1)})}),c.jsx("div",{className:"flex-1 min-h-0 relative",children:c.jsx(gB,{onNavigate:b,onNewSession:ae,onOpenVoice:T,onOpenScheduler:E})}),g&&c.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:g})]})]}),c.jsx(d2,{onNavigate:b}),c.jsx(_B,{open:O,onClose:$}),c.jsx(TB,{}),c.jsx(yk,{}),c.jsx(SB,{open:r,onClose:()=>l(!1),onCommand:Z=>{if(l(!1),Z.id.startsWith("nav:")){b(Z.id.slice(4));return}const pe=St.getState().tabs.find(oe=>oe.id===St.getState().activeTabId)??null;switch(Z.id){case"new-tab-pick":BS().catch(oe=>{console.error("[App] new tab (pick) failed:",oe),nt.error("Could not start new session. The directory picker failed.")});return;case"new-tab-here":{if(!pe)return;St.getState().addTab({cwd:pe.cwd,startupCommand:null,dormant:!0}),Ii.getState().openProjectPanel("terminal");return}case"close-tab":pe&&St.getState().closeTab(pe.id);return;case"restart-session":j();return;case"broadcast":L();return;case"watchers":G();return;case"copy-cwd":pe&&window.api.clipboard.writeText(pe.cwd).catch(()=>nt.error("Copy failed"));return;case"copy-transcript":pe&&window.api.transcripts.pathFor(pe.cwd,pe.sessionId).then(oe=>window.api.clipboard.writeText(oe)).catch(()=>nt.error("Copy failed"));return;case"open-transcript":pe&&window.api.transcripts.pathFor(pe.cwd,pe.sessionId).then(oe=>window.api.shell.open({as:"openPath",path:oe})).catch(()=>nt.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const MB=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","plugins","clipboard","memory"];function jB(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,t=[];for(const n of MB){const r=e[n];r==null?t.push({kind:"namespace-missing",name:n}):typeof r!="object"&&t.push({kind:"namespace-not-object",name:n,actualType:typeof r})}return t}function HS(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function zB(){const i=jB(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",HS(e));return setTimeout(()=>{Bn(async()=>{const{toast:e}=await Promise.resolve().then(()=>e1);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const t=i.length===1?HS(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(t)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");zB();jk.createRoot(document.getElementById("root")).render(c.jsx(NB,{}));export{JB as $,Vs as A,e3 as B,S_ as C,o5 as D,Qx as E,nE as F,$3 as G,im as H,d3 as I,_5 as J,h5 as K,fN as L,jy as M,s3 as N,s5 as O,VB as P,f5 as Q,Ot as R,qB as S,c2 as T,m5 as U,Ch as V,DE as W,D3 as X,L$ as Y,Cn as Z,IC as _,_a as a,_b as a$,Bv as a0,Un as a1,pR as a2,r1 as a3,XB as a4,KB as a5,Mr as a6,rl as a7,KM as a8,QB as a9,g1 as aA,_P as aB,rb as aC,FB as aD,hP as aE,x3 as aF,jv as aG,pd as aH,hR as aI,g5 as aJ,t1 as aK,nt as aL,b$ as aM,pi as aN,Of as aO,v1 as aP,Oi as aQ,dh as aR,Ab as aS,vd as aT,Ii as aU,tw as aV,Ov as aW,ti as aX,HB as aY,Nr as aZ,OE as a_,eR as aa,r3 as ab,t5 as ac,UC as ad,e5 as ae,tR as af,RC as ag,sb as ah,Ja as ai,KC as aj,c as ak,ZB as al,uP as am,YB as an,al as ao,v5 as ap,fP as aq,l5 as ar,c3 as as,Zf as at,CC as au,JE as av,GB as aw,yz as ax,dm as ay,B as az,d5 as b,St as b0,$o as b1,l3 as b2,n1 as b3,WB as b4,ld as c,bh as d,u5 as e,DO as f,a5 as g,$0 as h,Rb as i,MC as j,KL as k,Uy as l,xh as m,r5 as n,i5 as o,mN as p,n5 as q,cz as r,L0 as s,p5 as t,Hb as u,lz as v,c5 as w,QE as x,o3 as y,hI as z};
3079
+ `),nt.error(`Terminal failed to start: ${O.message??"spawn failed"}`),St.getState().setTabExited(i,-1)})});const x=()=>b();window.addEventListener("resize",x),window.addEventListener(Av,x);const A=new ResizeObserver(()=>b());return A.observe(r.current),()=>{window.removeEventListener("resize",x),window.removeEventListener(Av,x),A.disconnect(),S(),w(),T(),g.dispose()}},[i,e]),t?n?c.jsx(pk,{cwd:e}):null:c.jsxs("div",{className:"relative h-full w-full",children:[c.jsx("button",{type:"button",onClick:()=>St.getState().sleepTab(i),title:"Kill this session and return to chat",className:"absolute top-2 right-11 z-20 rounded border border-white/10 bg-bg-elev/80 px-2 py-1 text-xs text-fg-muted backdrop-blur-sm hover:bg-white/5 hover:text-fg",children:"← Back to chat"}),a&&c.jsx("div",{className:"absolute bottom-2 left-2 z-20",children:c.jsx(eB,{path:a,onDismiss:()=>d(null)},a)}),c.jsx("div",{ref:r,onMouseDown:()=>{var f;return(f=l.current)==null?void 0:f.focus()},className:"h-full w-full bg-bg"})]})}const iB={listening:"bg-red-400",transcribing:"bg-amber-400",restarting:"bg-blue-400"},nB={listening:"Listening",transcribing:"Transcribing…",restarting:"Restarting…",idle:"Idle",truncated:"Truncated"};function sB(){const{isRecording:i,statusPill:e,lastPartial:t,lastTranscript:n,submitCountdownStartAt:r}=Ct(Fb(RD)),l=i||!!t||!!n,[p,a]=B.useState(l);if(B.useEffect(()=>{if(l)a(!0);else{const f=setTimeout(()=>a(!1),300);return()=>clearTimeout(f)}},[l]),!p)return null;let d=t;return d.length>200&&(d="…"+d.slice(-200)),c.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"false","aria-label":"Dictation preview","data-testid":"live-transcript",className:`absolute bottom-4 left-1/2 -translate-x-1/2 max-w-[70%] min-w-[280px] pointer-events-none transition-opacity duration-300 z-30 ${l?"opacity-100":"opacity-0"}`,children:c.jsx("div",{className:"bg-bg-elev/85 backdrop-blur border border-line rounded-lg px-4 py-2 shadow-lg",children:c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsxs("div",{className:"shrink-0 flex items-center gap-1.5",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${iB[e]??"bg-fg-faint"}`}),c.jsx("span",{className:"text-[11px] uppercase tracking-wide text-fg-dim",children:nB[e]??e})]}),d&&c.jsx("p",{className:"flex-1 min-w-0 italic text-fg/85 font-mono text-sm line-clamp-2",children:d}),r!==null&&c.jsx("div",{className:"shrink-0",children:c.jsx(xE,{})})]})})})}function rB({visible:i=!0}){const e=St(p=>p.tabs),t=St(p=>p.activeTabId),n=e.find(p=>p.id===t)??null,l=Ii(p=>p.epicsWorkspaceOpen)||!n;return c.jsxs("div",{className:"absolute inset-0",style:{visibility:i?"visible":"hidden"},children:[l?c.jsx(pk,{}):e.map(p=>c.jsx("div",{className:"absolute inset-0",style:{visibility:p.id===t?"inherit":"hidden"},children:c.jsx(fk,{tabId:p.id,cwd:p.cwd})},`${p.id}-${p.generation}`)),c.jsx(sB,{})]})}function oB(){const i=Ii(e=>e.focusedPanelId==="terminal");return c.jsx(rB,{visible:i})}const aB=1;function lB(i){const e=Object.keys(i.panels??{});return e.length===0?null:{version:aB,panels:e,dockview:i}}function ib(i,e){const t=i.views.filter(r=>e.has(r));if(t.length===0)return null;const n=i.activeView&&t.includes(i.activeView)?i.activeView:t[0];return{...i,views:t,activeView:n}}function mk(i,e){if(i.type==="leaf"){const n=ib(i.data,e);return n?{...i,data:n}:null}const t=i.data.map(n=>mk(n,e)).filter(n=>n!==null);return t.length===0?null:{...i,data:t}}function cB(i,e){const t=Object.keys(i.panels??{}),n=new Set(t.filter(d=>e.has(d)));if(n.size===0)return null;const r=mk(i.grid.root,n);if(!r)return null;const l={};for(const d of n)l[d]=i.panels[d];const p=(i.floatingGroups??[]).map(d=>{const f=ib(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null),a=(i.popoutGroups??[]).map(d=>{const f=ib(d.data,n);return f?{...d,data:f}:null}).filter(d=>d!==null);return{...i,grid:{...i.grid,root:r},panels:l,floatingGroups:p,popoutGroups:a,activeGroup:i.activeGroup}}function dB(i,e){if(!i||typeof i!="object")return null;const t=i;if(!Array.isArray(t.panels)||!t.dockview||typeof t.dockview!="object")return null;const n=t.dockview;if(!n.grid||!n.panels)return null;try{return cB(n,e)}catch(r){return console.warn("[workbenchLayoutSerialize] prune failed, falling back to default:",r),null}}const uB=500,hB=new Set(ud.map(i=>i.id));function MS(i){const e=lB(i);e&&window.api.layout.save(e).catch(t=>{console.warn("[Workbench] layout save failed:",t)})}const gk=B.createContext(null),pB=B.memo(function(e){const t=B.useContext(gk);return t?c.jsx(c.Fragment,{children:mB(e.params.id,t)}):null}),fB={screen:pB},Yg=ud[0].id;function mB(i,e){return i==="terminal"?c.jsx(oB,{}):c.jsx(e2,{panelId:i,children:c.jsx("div",{className:"h-full overflow-auto bg-bg",children:c.jsx(yE,{children:$N(i,e)})})})}function gB({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}){const r=B.useRef(null),l=Ii(A=>A.focusedPanelId)??Yg,p=Ii(A=>A.focusToken),a=Ii(A=>A.resetToken),d=Ct(A=>A.isRecording||A.externalRecording),f=B.useRef(null),[g,m]=B.useState(!1),b=B.useRef(l);b.current=l;const T=B.useRef(null),E=B.useRef(null);B.useEffect(()=>{let A=!1;return window.api.layout.load().then(O=>{A||(O&&(f.current=dB(O,hB)),m(!0))}).catch(O=>{console.warn("[Workbench] layout load failed, using default:",O),A||m(!0)}),()=>{A=!0}},[]);const k=B.useCallback(A=>{const O=r.current;if(!O)return;const $=FT(A)??ud[0],j=O.getPanel($.id);if(j)j.api.setActive();else{const L=O.addPanel({id:$.id,component:$.component,title:$.title,params:{id:$.id},renderer:"always"});$.id==="terminal"&&L.api.onDidDimensionsChange(()=>{window.dispatchEvent(new CustomEvent(Av))})}},[]),y=B.useCallback(A=>{var L;r.current=A.api;const O=G=>{G.header.hidden=!0};E.current=A.api.onDidAddGroup(O),A.api.groups.forEach(O);const $=f.current;if($)try{A.api.fromJSON($);const G=(L=A.api.activePanel)==null?void 0:L.id;G&&Ii.getState().focusPanel(G)}catch(G){console.warn("[Workbench] fromJSON failed, falling back to default layout:",G),A.api.clear(),k(b.current)}else k(b.current);A.api.onDidActivePanelChange(G=>{G&&Ii.getState().focusPanel(G.id)}),T.current=A.api.onDidRemovePanel(G=>{if(G.id==="terminal"){Ii.getState().openPanel("terminal");return}A.api.totalPanels===0&&(Ii.getState().openPanel(Yg),k(Yg))});let j=null;A.api.onDidLayoutChange(()=>{j!==null&&window.clearTimeout(j),j=window.setTimeout(()=>MS(A.api.toJSON()),uB)})},[]);B.useEffect(()=>()=>{var A,O;(A=T.current)==null||A.dispose(),(O=E.current)==null||O.dispose()},[]),B.useEffect(()=>{k(l)},[p,k]);const S=B.useRef(!0);B.useEffect(()=>{if(S.current){S.current=!1;return}const A=r.current;A&&(A.clear(),f.current=null,k(Yg),MS(A.toJSON()))},[a]),B.useEffect(()=>{const A=r.current;A&&(A.layout(A.width,A.height,!0),window.dispatchEvent(new CustomEvent(Av)))},[d]);const w=B.useMemo(()=>({components:fB,onReady:y,className:"dockview-theme-sm workbench-root"}),[y]),x=B.useMemo(()=>({onNavigate:i,onNewSession:e,onOpenVoice:t,onOpenScheduler:n}),[i,e,t,n]);return g?c.jsx(gk.Provider,{value:x,children:c.jsx(wC,{...w})}):null}function vk(){return Ct(e=>e.isRecording||e.externalRecording)?c.jsxs("div",{"data-testid":"recording-status",role:"status","aria-live":"polite",className:`fixed inset-x-0 top-0 ${Cn.recording} h-7 px-3 flex items-center gap-2 bg-red-950/95 border-b border-red-800 text-red-200 text-xs shrink-0`,children:[c.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse","aria-hidden":"true"}),c.jsx("span",{children:"Recording — speech is being captured locally"})]}):null}const If=5e3;function Ro(i,e,t){var n,r;try{(r=(n=window.api)==null?void 0:n.logs)==null||r.write("voice-wizard",i,e,t)}catch{}}function vB({analyser:i}){const[e,t]=B.useState(0);return B.useEffect(()=>{if(!i){t(0);return}let n=0,r=!1;const l=new Uint8Array(new ArrayBuffer(i.fftSize)),p=()=>{if(r)return;i.getByteTimeDomainData(l);let a=0;for(let g=0;g<l.length;g++){const m=l[g]-128;a+=m*m}const d=Math.sqrt(a/l.length)/128,f=Math.min(1,Math.max(0,Math.pow(d,.4)*1.2));t(f),n=requestAnimationFrame(p)};return n=requestAnimationFrame(p),()=>{r=!0,cancelAnimationFrame(n)}},[i]),c.jsx("div",{className:"h-1.5 w-full rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-green-500 transition-[width] duration-75 ease-out",style:{width:`${e*100}%`},"data-testid":"wizard-level-bar"})})}function _B({open:i,onClose:e}){const t=Ct(Y=>Y.permissionState),n=Ct(Y=>Y.modelStatus),r=Ct(Y=>Y.loadingProgress),[l,p]=B.useState("welcome"),[a,d]=B.useState(null),[f,g]=B.useState(!1),[m,b]=B.useState(0),T=B.useRef(null),E=B.useRef(null),k=B.useRef(null),y=B.useRef(null),S=B.useRef(null),w=B.useRef(null),x=B.useRef(null),A=B.useRef(null),[O,$]=B.useState(!1),[j,L]=B.useState(Math.round(If/1e3)),[G,W]=B.useState(!1),[re,ae]=B.useState(!1),[Z,pe]=B.useState(null),[oe,me]=B.useState(0),we=B.useCallback(()=>{var Y;try{(Y=S.current)==null||Y.stop()}catch{}if(S.current=null,A.current){try{A.current.disconnect()}catch{}A.current=null}if(y.current){try{y.current.disconnect()}catch{}y.current=null}if(k.current){try{k.current.disconnect()}catch{}k.current=null}if(me(_e=>_e+1),E.current){const _e=E.current;E.current=null;try{_e.close()}catch{}}if(T.current){try{T.current.getTracks().forEach(_e=>_e.stop())}catch{}T.current=null}},[]),ve=B.useCallback(()=>{we(),w.current=null,x.current=null,$(!1),L(Math.round(If/1e3)),W(!1),ae(!1),pe(null),d(null),g(!1)},[we]);B.useEffect(()=>{i?(Ro("info","wizard.opened"),p("welcome")):ve()},[i,ve]),B.useEffect(()=>()=>we(),[we]);const F=B.useCallback(Y=>{Ro("info","wizard.step",{step:Y}),d(null),p(Y)},[]),J=B.useCallback(Y=>{if(Ro("info","wizard.skipped",{step:l,mode:Y}),we(),e(),Y==="skip-and-record"){const _e=Ct.getState();_e.setWizardArmed(!1);const ue=St.getState().activeTabId;ue&&_e.startRecording(ue)}else Ct.getState().setWizardArmed(!1)},[l,e,we]),V=B.useCallback(()=>{if(t==="denied"){F("permission");return}F("permission")},[t,F]);B.useEffect(()=>{i&&l==="permission"&&t==="granted"&&F("device")},[i,l,t,F]),B.useEffect(()=>{if(!i||l!=="device")return;let Y=!1;return(async()=>{var _e;try{if(!((_e=navigator.mediaDevices)!=null&&_e.enumerateDevices)){Y||g(!0);return}const ue=await navigator.mediaDevices.enumerateDevices();if(Y)return;const Re=ue.filter(He=>He.kind==="audioinput");g(Re.length===0)}catch(ue){if(Y)return;Ro("warn","wizard.error",{step:"device",error:ue instanceof Error?ue.message:String(ue)}),g(!0)}})(),()=>{Y=!0}},[i,l,m]);const se=B.useCallback(async()=>{d(null),$(!0),L(Math.round(If/1e3));try{let Y=null;try{const _t=await window.api.voice.getDevicePref();Y=(_t==null?void 0:_t.selectedDeviceId)??null}catch{}const _e={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Y&&(_e.deviceId={exact:Y});const ue=await navigator.mediaDevices.getUserMedia({audio:_e});T.current=ue;const Re=new AudioContext;E.current=Re;const He=Re.createMediaStreamSource(ue),lt=Re.createAnalyser();lt.fftSize=2048,lt.smoothingTimeConstant=.8,He.connect(lt),k.current=He,y.current=lt,me(_t=>_t+1);const It=MediaRecorder.isTypeSupported("audio/webm;codecs=opus")?"audio/webm;codecs=opus":"",ct=new MediaRecorder(ue,It?{mimeType:It}:void 0);S.current=ct;const qt=[];ct.ondataavailable=_t=>{_t.data&&_t.data.size>0&&qt.push(_t.data)},ct.onstop=()=>{const _t=ct.mimeType||"audio/webm";if(w.current=new Blob(qt,{type:_t}),$(!1),y.current){try{y.current.disconnect()}catch{}y.current=null}if(k.current){try{k.current.disconnect()}catch{}k.current=null}if(me(ni=>ni+1),T.current){try{T.current.getTracks().forEach(ni=>ni.stop())}catch{}T.current=null}F("playback")},ct.onerror=_t=>{var Ye;const ni=((Ye=_t.error)==null?void 0:Ye.message)??"recorder error";Ro("error","wizard.error",{step:"record",error:ni}),d(ni),$(!1),nt.error(`Mic wizard: ${ni}`)},ct.start();const qe=Date.now(),Rt=setInterval(()=>{const _t=Date.now()-qe,ni=Math.max(0,Math.ceil((If-_t)/1e3));if(L(ni),_t>=If){clearInterval(Rt);try{ct.stop()}catch{}}},250)}catch(Y){const _e=Y instanceof Error?Y.message:String(Y);Ro("error","wizard.error",{step:"record",error:_e}),d(_e),$(!1),we(),nt.error(`Mic wizard: ${_e}`)}},[F,we]),ge=B.useCallback(async()=>{d(null);const Y=w.current;if(!Y){d("No recording available");return}try{let _e=E.current;(!_e||_e.state==="closed")&&(_e=new AudioContext,E.current=_e);let ue=x.current;if(!ue){const He=await Y.arrayBuffer();ue=await _e.decodeAudioData(He.slice(0)),x.current=ue}if(A.current){try{A.current.disconnect()}catch{}A.current=null}const Re=_e.createBufferSource();Re.buffer=ue,Re.connect(_e.destination),A.current=Re,W(!0),Re.onended=()=>{W(!1);try{Re.disconnect()}catch{}A.current===Re&&(A.current=null)},Re.start()}catch(_e){const ue=_e instanceof Error?_e.message:String(_e);Ro("error","wizard.error",{step:"playback",error:ue}),d(ue),W(!1)}},[]);B.useEffect(()=>{i&&l==="playback"&&ge().catch(()=>{})},[i,l,ge]);const Te=B.useCallback(async()=>{d(null),ae(!0),pe(null);try{const Y=x.current;if(!Y)throw new Error("No decoded audio available");const _e=Y.getChannelData(0),ue=new Float32Array(_e.length);ue.set(_e);const Re=await mD(ue);pe(Re)}catch(Y){const _e=Y instanceof Error?Y.message:String(Y);Ro("error","wizard.error",{step:"verify",error:_e}),d(_e)}finally{ae(!1)}},[]);B.useEffect(()=>{i&&l==="verify"&&n==="ready"&&Z===null&&!re&&!a&&Te()},[i,l,n,Z,re,a,Te]);const je=B.useCallback(async()=>{try{await window.api.voice.markWizardComplete(),Ro("info","wizard.complete")}catch(Y){Ro("error","wizard.error",{step:"done",error:Y instanceof Error?Y.message:String(Y)})}Ct.getState().setWizardArmed(!1),we(),e()},[e,we]),Ze=B.useCallback(()=>{Ro("info","wizard.skipped",{step:l,mode:"modal-close"}),we(),Ct.getState().setWizardArmed(!1),e()},[l,we,e]),ye=B.useMemo(()=>{switch(l){case"welcome":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Set up voice input. About 30 seconds. Audio stays on your device — nothing is uploaded."}),c.jsxs("div",{className:"flex flex-col gap-2 pt-2",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:V,"data-testid":"wizard-start",children:"Start"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>J("skip-and-record"),"data-testid":"wizard-skip-and-record",children:"Skip and record now"}),c.jsx("button",{type:"button",className:"text-xs text-fg-dim hover:text-fg underline self-start",onClick:()=>J("skip"),"data-testid":"wizard-open-settings-later",children:"Open Settings later"})]})]});case"permission":return t==="denied"?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Microphone access is blocked. Open your operating system's privacy settings and grant Session Manager microphone permission, then re-run the mic check from Settings."}),c.jsxs("p",{className:"text-xs text-fg-dim",children:["macOS: System Settings → Privacy & Security → Microphone.",c.jsx("br",{}),"Windows: Settings → Privacy & security → Microphone.",c.jsx("br",{}),"Linux: depends on desktop — usually Settings → Sound or pavucontrol."]}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Session Manager needs microphone access to recognize your speech locally. Your operating system may show a prompt — click Allow."}),c.jsxs("p",{className:"text-xs text-fg-dim",children:["State: ",t]}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>F("device"),"data-testid":"wizard-permission-continue",children:"Continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"device":return f?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"No microphone detected."}),c.jsx("p",{className:"text-xs text-fg-dim",children:"Plug in or connect a mic, then click Try again. Common causes: unplugged USB, VM without audio passthrough, or an X-forwarded session."}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{g(!1),b(Y=>Y+1)},"data-testid":"wizard-device-retry",children:"Try again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Choose your microphone:"}),c.jsx(wE,{}),c.jsxs("div",{className:"flex gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>F("record"),"data-testid":"wizard-device-continue",children:"Continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"record":return c.jsxs("div",{className:"space-y-3",children:[c.jsxs("p",{className:"text-sm text-fg",children:["Say: ",c.jsx("span",{className:"text-fg font-medium",children:'"testing one two three"'})]}),c.jsx("p",{className:"text-xs text-fg-dim",children:"Audio stays on your device — nothing is uploaded."}),O?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-xs text-fg-dim font-mono","data-testid":"wizard-countdown",children:["Recording… ",j,"s"]}),c.jsx(vB,{analyser:y.current},oe)]}):c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>{se()},"data-testid":"wizard-record-start",children:"Start recording"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"playback":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Did that sound right?"}),c.jsx("p",{className:"text-xs text-fg-dim",children:G?"Playing back…":"Playback finished."}),c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90",onClick:()=>F("verify"),"data-testid":"wizard-playback-yes",children:"Yes — continue"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{ge()},"data-testid":"wizard-playback-replay",children:"Replay"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,F("record")},"data-testid":"wizard-playback-no",children:"No — try again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"verify":return n==="loading"||n==="idle"?c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"Preparing speech model…"}),c.jsxs("div",{className:"flex items-center justify-between text-[11px] text-fg-faint",children:[c.jsx("span",{children:"Downloading"}),c.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),c.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`},"data-testid":"wizard-load-progress"})}),c.jsx("p",{className:"text-xs text-fg-dim",children:"The model runs offline once it's downloaded. This only happens on first launch."}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi flex-1",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})})]}):c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:re?"Transcribing your sample…":Z===null?"Ready to transcribe.":"We heard:"}),Z!==null&&c.jsx("p",{className:"text-sm text-fg bg-bg border border-line rounded p-2 font-mono break-words","data-testid":"wizard-transcript",children:Z||"(no text recognized)"}),c.jsxs("div",{className:"flex flex-col gap-2 pt-1",children:[c.jsx("button",{type:"button",disabled:re||Z===null,className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>F("done"),"data-testid":"wizard-verify-yes",children:"Yes — that matches"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg hover:bg-bg-hi",onClick:()=>{x.current=null,w.current=null,pe(null),F("record")},"data-testid":"wizard-verify-retry",children:"Retry — record again"}),c.jsx("button",{type:"button",className:"px-3 py-2 rounded border border-line text-sm text-fg-dim hover:text-fg",onClick:()=>J("skip"),"data-testid":"wizard-skip",children:"Skip"})]})]});case"done":return c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg",children:"All set. The mic check is complete."}),c.jsx("p",{className:"text-xs text-fg-dim",children:"You can re-run this any time from the mic-controls panel."}),c.jsx("div",{className:"flex gap-2 pt-1",children:c.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-accent text-bg text-sm font-medium hover:opacity-90 flex-1",onClick:()=>{je()},"data-testid":"wizard-done",children:"Done"})})]})}},[l,V,J,t,f,O,j,oe,G,re,Z,n,r,a,F,se,ge,je]);return c.jsx(Hb,{open:i,onClose:Ze,title:"Mic check",children:c.jsxs("div",{className:"space-y-3","data-testid":"mic-wizard",children:[c.jsxs("div",{className:"text-[10px] text-fg-faint uppercase tracking-wide",children:["Step: ",l]}),a?c.jsx("p",{className:"text-xs text-red-400","data-testid":"wizard-error",children:a}):null,ye]})})}const _k="sm.tour.completedAt",Jl=Un((i,e)=>({open:!1,currentStep:0,stepCount:0,setStepCount:t=>{e().stepCount!==t&&i({stepCount:t})},start:()=>i({open:!0,currentStep:0}),next:()=>{const{currentStep:t,stepCount:n}=e();if(t>=n-1){e().complete();return}i({currentStep:t+1})},prev:()=>{const{currentStep:t}=e();t<=0||i({currentStep:t-1})},goTo:t=>{const{stepCount:n}=e();t<0||t>=n||i({currentStep:t})},complete:()=>{try{localStorage.setItem(_k,String(Date.now()))}catch{}i({open:!1,currentStep:0})},close:()=>i({open:!1})}));function yB(){try{return!!localStorage.getItem(_k)}catch{return!1}}const jS={nav:"Navigate",scheduler:"Scheduler",voice:"Voice",session:"Session",config:"Config"};function bB(){return[{id:"new-tab-pick",label:"New tab — pick directory",section:"session",emitOnly:!0},{id:"new-tab-here",label:"New tab in current cwd",section:"session",emitOnly:!0},{id:"close-tab",label:"Close active tab",section:"session",emitOnly:!0},{id:"restart-session",label:"Restart session",section:"session",emitOnly:!0},{id:"reboot-app",label:"Reboot app (drain first)",section:"session",run:()=>window.api.app.rebootApp()},{id:"reboot-app-force",label:"Reboot app NOW (force — kills running jobs)",section:"session",run:()=>window.api.app.rebootApp({force:!0})},{id:"broadcast",label:"Broadcast prompt to all tabs",section:"session",emitOnly:!0},{id:"watchers",label:"Attach a watcher",section:"session",emitOnly:!0},{id:"copy-cwd",label:"Copy active tab cwd",section:"session",emitOnly:!0},{id:"copy-transcript",label:"Copy transcript path",section:"session",emitOnly:!0},{id:"open-transcript",label:"Open transcript JSONL",section:"session",emitOnly:!0},{id:"voice-toggle",label:"Voice — toggle mic",section:"voice",run:()=>{const e=Ct.getState(),t=St.getState().activeTabId;e.isRecording?e.stopRecording():t&&e.startRecording(t)}},{id:"voice-tts",label:"Voice — toggle TTS",section:"voice",run:()=>Ct.getState().toggleTTS()},{id:"voice-cancel-submit",label:"Voice — cancel auto-submit",section:"voice",run:()=>Ct.getState().cancelSubmit()},{id:"scheduler-run-now",label:"Scheduler — Run now",section:"scheduler",run:async()=>{await window.api.schedule.runNow()}},{id:"scheduler-force-tick",label:"Scheduler — Force tick (bypass meter)",section:"scheduler",run:async()=>{nt.fromOutcome(await window.api.schedule.forceTick())}},{id:"scheduler-pause",label:"Scheduler — Pause (stop new dispatch)",section:"scheduler",run:async()=>{await window.api.schedule.pause()}},{id:"scheduler-resume",label:"Scheduler — Resume from pause",section:"scheduler",run:async()=>{await window.api.schedule.resume()}},{id:"scheduler-rescan",label:"Scheduler — Re-scan PRDs folder",section:"scheduler",run:async()=>{nt.fromOutcome(await window.api.schedule.rescan())}},{id:"scheduler-lint",label:"Scheduler — Lint queue (find unbounded loops)",section:"scheduler",emitOnly:!0},{id:"scheduler-open-folder",label:"Scheduler — Open PRDs folder",section:"scheduler",run:async()=>{await window.api.schedule.openFolder()}},{id:"scheduler-supervisor-tick",label:"Scheduler — Run supervisor probe now",section:"scheduler",run:async()=>{await window.api.supervisor.tickNow()}},{id:"add-allow-rule",label:"Permissions — Add allow rule",section:"config",emitOnly:!0},{id:"test-fire-hook",label:"Hooks — Test-fire a hook",section:"config",emitOnly:!0},{id:"devtools",label:"Toggle DevTools",section:"config",emitOnly:!0,hint:"F12"},{id:"reload-window",label:"Reload window",section:"config",emitOnly:!0,hint:"Ctrl+R"},{id:"tour:start",label:"Restart guided tour",section:"config",run:()=>Jl.getState().start()},{id:"layout-reset",label:"Reset layout",section:"config",run:()=>Ii.getState().resetLayout()},{id:"nav:overview",label:"Go to Overview — this machine",section:"nav",emitOnly:!0},{id:"nav:project-home",label:"Go to Home",section:"nav",emitOnly:!0},{id:"nav:terminal",label:"Go to Terminal",section:"nav",emitOnly:!0},{id:"nav:settings",label:"Go to Settings",section:"nav",emitOnly:!0},{id:"nav:permissions",label:"Go to Permissions",section:"nav",emitOnly:!0},{id:"nav:skills",label:"Go to Skills",section:"nav",emitOnly:!0},{id:"nav:plugins",label:"Go to Plugins",section:"nav",emitOnly:!0},{id:"nav:mcp",label:"Go to MCP Servers",section:"nav",emitOnly:!0},{id:"nav:hooks",label:"Go to Hooks",section:"nav",emitOnly:!0},{id:"nav:scheduler",label:"Go to Scheduler",section:"nav",emitOnly:!0},{id:"nav:memory",label:"Go to Memory",section:"nav",emitOnly:!0},{id:"nav:projects",label:"Go to File Explorer",section:"nav",emitOnly:!0},{id:"nav:history",label:"Go to History",section:"nav",emitOnly:!0},{id:"nav:system-prompt",label:"Go to System Prompt",section:"nav",emitOnly:!0},{id:"nav:voice",label:"Go to Voice",section:"nav",emitOnly:!0},{id:"nav:agent-library",label:"Go to Agent Library",section:"nav",emitOnly:!0},{id:"nav:tag-library",label:"Go to Tag Library",section:"nav",emitOnly:!0},{id:"nav:bilko-host",label:"Go to Bilko Host",section:"nav",emitOnly:!0}]}function wB(i,e){if(!e)return 0;const t=i.toLowerCase(),n=e.toLowerCase();let r=0,l=-1,p=0;for(let a=0;a<t.length&&r<n.length;a++)t[a]===n[r]&&(p+=a-l,l=a,r++);return r!==n.length?null:p}function xB(i,e){if(!e)return i.map(n=>({...n,score:0}));const t=[];for(const n of i){const r=wB(n.label,e);r!==null&&t.push({...n,score:r})}return t.sort((n,r)=>n.score-r.score),t}function SB({open:i,onClose:e,onCommand:t}){const[n,r]=B.useState(""),[l,p]=B.useState(0),a=B.useRef(null),d=B.useRef(null),f=B.useRef(null),g=B.useRef(null),m=B.useMemo(()=>bB(),[]),b=B.useMemo(()=>xB(m,n),[m,n]);if(B.useEffect(()=>{if(i){const A=document.activeElement;g.current=A instanceof HTMLElement?A:null,r(""),p(0);const O=setTimeout(()=>{var $;return($=a.current)==null?void 0:$.focus()},0);return()=>{clearTimeout(O);const $=g.current;g.current=null,$&&requestAnimationFrame(()=>{try{$.focus()}catch{}})}}},[i]),B.useEffect(()=>{l>=b.length&&p(Math.max(0,b.length-1))},[b.length,l]),B.useEffect(()=>{if(!d.current)return;const A=d.current.querySelector(`[data-cmd-idx="${l}"]`);A&&A.scrollIntoView({block:"nearest"})},[l]),!i)return null;const T=async A=>{var O;if(e(),A.emitOnly){t(A);return}try{await((O=A.run)==null?void 0:O.call(A))}catch($){console.error("[command-palette] run failed",A.id,$);const j=$ instanceof Error?$.message:String($);nt.error(`Command "${A.label}" failed: ${j}`)}t(A)},E=A=>{var O,$,j,L;if(A.key==="Escape"){A.preventDefault(),e();return}if(A.key==="ArrowDown"){A.preventDefault(),p(G=>Math.min(b.length-1,G+1));return}if(A.key==="ArrowUp"){A.preventDefault(),p(G=>Math.max(0,G-1));return}if(A.key==="Home"){A.preventDefault(),p(0);return}if(A.key==="End"){A.preventDefault(),p(Math.max(0,b.length-1));return}if(A.key==="PageDown"){A.preventDefault(),p(G=>Math.min(b.length-1,G+5));return}if(A.key==="PageUp"){A.preventDefault(),p(G=>Math.max(0,G-5));return}if(A.key==="Tab"){A.preventDefault();const G=document.activeElement;A.shiftKey?G===a.current?(O=f.current)==null||O.focus():($=a.current)==null||$.focus():G===a.current?(j=f.current)==null||j.focus():(L=a.current)==null||L.focus();return}if(A.key==="Enter"){A.preventDefault();const G=b[l];G&&T(G);return}},k=[],y=new Map;b.forEach((A,O)=>{let $=y.get(A.section);$===void 0&&($=k.length,y.set(A.section,$),k.push({section:A.section,items:[]})),k[$].items.push({cmd:A,absIdx:O})});const S=b[l],w=S?`cmdk-opt-${S.id}`:void 0,x=c.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-start justify-center bg-black/60 pt-[15vh]`,onClick:A=>{A.target===A.currentTarget&&e()},"data-testid":"command-palette-backdrop",onKeyDown:E,children:c.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"cmdk-title",className:"w-[600px] max-w-[90vw] bg-bg-elev border border-line rounded shadow-xl","data-testid":"command-palette",children:[c.jsxs("div",{className:"border-b border-line flex items-center",children:[c.jsx("input",{ref:a,id:"cmdk-title",type:"text",value:n,onChange:A=>{r(A.target.value),p(0)},placeholder:"Type a command…","aria-label":"Command palette search","aria-controls":"cmdk-listbox","aria-activedescendant":w,"aria-autocomplete":"list",role:"combobox","aria-expanded":"true",className:"flex-1 bg-transparent px-3 py-2.5 text-sm text-fg placeholder:text-fg-faint focus:outline-none font-mono",spellCheck:!1,autoComplete:"off"}),c.jsx("button",{ref:f,type:"button",onClick:e,"aria-label":"Close command palette",className:"shrink-0 px-2 py-1 mr-1 text-fg-faint hover:text-fg text-sm","data-testid":"command-palette-dismiss",children:"×"})]}),c.jsx("div",{ref:d,id:"cmdk-listbox",role:"listbox","aria-label":"Commands",className:"max-h-[60vh] overflow-y-auto py-1","data-testid":"command-palette-list",children:b.length===0?c.jsx("div",{className:"px-3 py-4 text-xs text-fg-faint italic",children:"No matching commands."}):k.map(A=>c.jsxs("div",{role:"group","aria-label":jS[A.section],className:"py-1",children:[c.jsx("div",{className:"px-3 py-0.5 text-[9px] uppercase tracking-wider text-fg-faint","aria-hidden":"true",children:jS[A.section]}),A.items.map(({cmd:O,absIdx:$})=>{const j=$===l;return c.jsxs("button",{id:`cmdk-opt-${O.id}`,type:"button",role:"option","aria-selected":j,"data-cmd-idx":$,"data-cmd-id":O.id,tabIndex:-1,onMouseEnter:()=>p($),onClick:()=>T(O),className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 ${j?"bg-bg-hi text-fg":"text-fg-dim hover:bg-bg-hi/50"}`,children:[c.jsx("span",{className:"truncate flex-1",children:O.label}),O.hint&&c.jsx("span",{className:"font-mono text-[10px] text-fg-faint shrink-0",children:O.hint})]},O.id)})]},A.section))}),c.jsxs("div",{className:"border-t border-line px-3 py-1.5 text-[10px] text-fg-faint flex gap-3 font-mono","aria-hidden":"true",children:[c.jsx("span",{children:"↑↓ navigate"}),c.jsx("span",{children:"↵ run"}),c.jsx("span",{children:"esc close"}),c.jsxs("span",{className:"ml-auto",children:[b.length," of ",m.length]})]})]})});return typeof document<"u"&&document.body?dm.createPortal(x,document.body):x}const CB={info:{border:"border-line",text:"text-fg",label:"Notice"},warn:{border:"border-amber-700",text:"text-amber-200",label:"Warning"},error:{border:"border-red-700",text:"text-red-200",label:"Error"}};function yk(){const i=$o(t=>t.toasts),e=$o(t=>t.dismiss);return i.length===0?null:c.jsx("div",{"data-testid":"toast-host",className:`fixed bottom-3 right-3 ${Cn.toast} flex flex-col gap-1.5 pointer-events-none`,children:i.map(t=>{const n=CB[t.kind];return c.jsxs("div",{"data-testid":"toast","data-kind":t.kind,role:t.kind==="error"?"alert":"status","aria-live":t.kind==="error"?"assertive":"polite",className:`pointer-events-auto min-w-[240px] max-w-[420px] bg-bg-elev border ${n.border} rounded shadow-lg px-3 py-2 text-xs flex items-start gap-2`,children:[c.jsx("span",{className:`font-mono text-[10px] uppercase tracking-wider shrink-0 ${n.text}`,children:n.label}),c.jsx("span",{className:"flex-1 text-fg-dim break-words",children:t.message}),c.jsx("button",{type:"button",onClick:()=>e(t.id),"aria-label":"Dismiss notification",className:"shrink-0 text-fg-faint hover:text-fg text-xs leading-none",children:"×"})]},t.id)})})}function EB(){const i=St(r=>r.tabs),e=St(r=>r.activeTabId),t=i.find(r=>r.id===e)??null,n=Ct(r=>r.isRecording);return c.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${n?"pt-7":""}`,children:[c.jsx(vk,{}),c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-white/5 text-[11px] text-fg/50 select-none",children:[c.jsx("span",{className:"font-medium text-fg/70",children:"simple mode"}),t&&c.jsxs("span",{className:"truncate",children:["· ",t.cwd]})]}),c.jsx("div",{className:"flex-1 min-h-0 relative",children:t?c.jsx(fk,{tabId:t.id,cwd:t.cwd},`${t.id}-${t.generation}`):c.jsx("div",{className:"absolute inset-0 grid place-items-center text-fg/40",children:"Starting claude…"})}),c.jsx(yk,{})]})}const od=[{id:"welcome",title:"Welcome to Session Manager",body:'A 60-second tour of how this app is laid out: projects at the top, sessions inside them, PRDs underneath. Re-run it any time from ⌘K / Ctrl+K → "Restart guided tour".',position:"center"},{id:"tabs",title:"Home, and one tab per project",body:"The top bar is navigation only. The Home pill is this machine — every project, usage, history. Each tab after it is one open project, identified by its folder. Drag to reorder.",target:'[data-testid="tour-tabbar"]',position:"bottom"},{id:"leftnav",title:"The sidebar follows the tab",body:"On Home it shows machine-wide screens — Dashboard, History, Settings, Skills, Agent Library, Tag Library. On a project tab it swaps to that project: Project Home, Sessions, Scheduler, Memory.",target:'[data-testid="tour-leftnav"]',position:"right"},{id:"new-session",title:"Open / Start Project",body:"Pick a folder and it becomes a project — that path is its identity. Picking one that is already open just activates its tab: extra work inside a project is more sessions, never more tabs.",target:'[data-testid="tour-new-session"]',position:"right"},{id:"sessions",title:"Sessions are the unit of work",body:"One session = one small goal, and one Claude session behind it. Pick an Agent (who is working) and a Mission (what it is for), write the goal, then press Approve & start — nothing is spent before that. Chat and Terminal are two views of the same session, not two sessions.",target:'[data-testid="tour-sessions"]',position:"right",projectFaceOnly:!0},{id:"scheduler",title:"Scheduler runs what your sessions wrote",body:"A session decomposes its goal into numbered PRD files under the project's session-manager-operations/scheduler/. The Scheduler queues each as a claude -p job, pauses on rate-limit and resumes at your next window reset. It is per-project — there is no machine-wide queue view.",target:'[data-testid="tour-scheduler"]',position:"right",projectFaceOnly:!0},{id:"voice",title:"Push-to-talk dictation",body:"Hold Ctrl+Shift+Space (Cmd+Option+V on macOS) to dictate, or click the mic. The hotkey, mode and input device live in Voice on the Home sidebar.",target:'[data-testid="mic-button"]',position:"right"},{id:"mainpane-actions",title:"Command palette",body:"Press ⌘K / Ctrl+K to jump to any screen, restart a session, broadcast a prompt to every tab, attach a watcher command, or force a scheduler tick.",position:"center"},{id:"statusbar",title:"Status bar",body:"Connection, your session (5h) and weekly (7d) usage, the active project and its branch, live to-dos, and the app version. Click either usage pill for the full meters on Home.",target:'[data-testid="tour-statusbar"]',position:"top"}],Kl=360,ad=220,Dn=16;function ql(i,e,t){return Math.max(e,Math.min(t,i))}function kB(i,e){if(!i||e==="center")return{position:"fixed",top:"50%",left:"50%",transform:"translate(-50%, -50%)"};const t=window.innerWidth,n=window.innerHeight;switch(e){case"top":return{position:"fixed",top:ql(i.top-ad-Dn,Dn,n-ad-Dn),left:ql(i.left+i.width/2-Kl/2,Dn,t-Kl-Dn)};case"bottom":return{position:"fixed",top:ql(i.bottom+Dn,Dn,n-ad-Dn),left:ql(i.left+i.width/2-Kl/2,Dn,t-Kl-Dn)};case"left":return{position:"fixed",top:ql(i.top+i.height/2-ad/2,Dn,n-ad-Dn),left:ql(i.left-Kl-Dn,Dn,t-Kl-Dn)};case"right":return{position:"fixed",top:ql(i.top+i.height/2-ad/2,Dn,n-ad-Dn),left:ql(i.right+Dn,Dn,t-Kl-Dn)}}}function TB(){const i=Jl(k=>k.open),e=Jl(k=>k.currentStep),t=Jl(k=>k.next),n=Jl(k=>k.prev),r=Jl(k=>k.complete),l=Jl(k=>k.setStepCount);B.useEffect(()=>{l(od.length)},[l]);const[p,a]=B.useState(null),d=B.useRef(null),f=od[e]??od[0],g=e===0,m=e===od.length-1;if(B.useLayoutEffect(()=>{if(!i)return;let k=!1;const y=()=>{if(k)return;if(!f.target){a(null);return}const w=document.querySelector(f.target);if(!w){a(null);return}a(w.getBoundingClientRect())},S=requestAnimationFrame(y);return window.addEventListener("resize",y),()=>{k=!0,cancelAnimationFrame(S),window.removeEventListener("resize",y)}},[i,f.target,e]),B.useEffect(()=>{if(!i)return;const k=y=>{if(y.key==="Escape"){y.stopPropagation(),pt.info("tour","skipped",{step:f.id}),r();return}if(y.key==="ArrowRight"||y.key==="Enter"){y.preventDefault(),t();return}y.key==="ArrowLeft"&&(y.preventDefault(),n())};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[i,t,n,r,f.id]),B.useEffect(()=>{i&&pt.info("tour","step",{index:e,id:f.id})},[i,e,f.id]),!i)return null;const b=kB(p,f.position),T=(e+1)/od.length*100,E=c.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"tour-title","aria-describedby":"tour-body","data-testid":"tour-overlay",className:`fixed inset-0 ${Cn.tour}`,children:[p?c.jsx("div",{"aria-hidden":"true",className:"absolute rounded-md pointer-events-none transition-all",style:{top:p.top-6,left:p.left-6,width:p.width+12,height:p.height+12,boxShadow:"0 0 0 4000px rgba(0, 0, 0, 0.65), 0 0 0 2px rgba(204, 120, 92, 0.55)"}}):c.jsx("div",{"aria-hidden":"true",className:"absolute inset-0 bg-black/65"}),c.jsxs("div",{ref:d,style:{...b,width:Kl},className:"bg-bg-elev border border-line rounded-lg shadow-2xl p-4 text-fg","data-testid":"tour-tooltip",children:[c.jsxs("div",{className:"flex items-start justify-between mb-2 gap-3",children:[c.jsxs("div",{children:[c.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-fg-faint mb-0.5",children:["Step ",e+1," of ",od.length]}),c.jsx("h3",{id:"tour-title",className:"text-sm font-semibold text-fg",children:f.title})]}),c.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-fg-faint hover:text-fg p-1 -m-1","aria-label":"Skip tour","data-testid":"tour-close",children:"×"})]}),c.jsx("p",{id:"tour-body",className:"text-xs text-fg-dim leading-relaxed mb-3",children:f.body}),c.jsx("div",{role:"progressbar","aria-valuemin":1,"aria-valuemax":od.length,"aria-valuenow":e+1,className:"h-1 bg-bg rounded-full overflow-hidden mb-3",children:c.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${T}%`}})}),c.jsxs("div",{className:"flex items-center justify-between gap-2",children:[c.jsx("button",{type:"button",onClick:()=>{pt.info("tour","skipped",{step:f.id}),r()},className:"text-[11px] text-fg-faint hover:text-fg-dim underline","data-testid":"tour-skip",children:"Skip tour"}),c.jsxs("div",{className:"flex items-center gap-2",children:[!g&&c.jsx("button",{type:"button",onClick:n,className:"px-3 py-1 rounded border border-line text-xs text-fg hover:bg-bg-hi","data-testid":"tour-prev",children:"Back"}),c.jsx("button",{type:"button",onClick:t,className:"px-3 py-1 rounded bg-accent text-bg text-xs font-medium hover:opacity-90","data-testid":"tour-next",children:m?"Got it":"Next"})]})]})]})]});return typeof document<"u"&&document.body?dm.createPortal(E,document.body):E}let ey=null;function DB(){return ey||(ey=Bn(()=>import("./monaco-editor-BW5C4Iv1.js").then(i=>i.b),__vite__mapDeps([1,2]),import.meta.url).then(i=>(Lb.config({monaco:i}),i))),ey}function y5({value:i,onChange:e,path:t,readOnly:n}){const r=B.useRef(null),l=p=>{r.current=p};return c.jsx(nE,{path:`file://${t}`,defaultLanguage:"json",value:i,onChange:p=>e(p??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:n,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let zS=!1;async function AB(i){if(zS)return;const e=await DB(),t=await Promise.all(i.map(async r=>{let l=r.schema;if(!l){const p=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const a=new URL(r.uri).origin;if(!p.includes(a))throw new Error("untrusted origin");const d=await fetch(r.uri);d.ok&&(l=await d.json())}catch{}}return{uri:r.uri,fileMatch:r.fileMatch,schema:l}}));e.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:t.filter(r=>r.schema),enableSchemaRequest:!0}),zS=!0}async function BS(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=crypto.randomUUID();return St.getState().addTab({id:e,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),e}async function IB(){const i=await window.api.app.pickDirectory();if(!i)return null;const e=St.getState(),t=e.tabs.find(r=>r.cwd===i);if(t)return e.setActive(t.id),t.id;const n=crypto.randomUUID();return e.addTab({id:n,cwd:i,startupCommand:null,presetId:"pick-dangerous",dormant:!0}),n}function PB(i){const e=Ct(n=>n.ttsEnabled),t=Ct(n=>n.isRecording);B.useEffect(()=>{if(!i||!e)return;const n=l=>{const p=Ct.getState().lastBargeInAt;if(p!==null&&performance.now()-p<AD){pt.debug("voice","tts.suppressed.barge-in-ttl",{ageMs:Math.round(performance.now()-p)});return}_D(l)};return window.api.transcripts.onEvent(i,l=>{for(const p of l){if(p.kind!=="message")continue;const a=p.data;if(typeof a!="object"||a===null)continue;const d=a;if(d.role!=="assistant"||Ct.getState().isRecording)continue;const f=d.content;if(typeof f=="string")n(f);else if(Array.isArray(f)){const g=f.filter(m=>typeof m=="object"&&m!==null&&m.type==="text"&&typeof m.text=="string").map(m=>m.text).join(" ");g&&n(g)}}})},[i,e]),B.useEffect(()=>{t&&(P1(),Ct.setState({lastBargeInAt:performance.now()}))},[t])}const bk="sm.density",RB="roomy",US="density-compact";function OB(){try{const i=localStorage.getItem(bk);if(i==="compact"||i==="roomy")return i}catch{}return RB}function wk(i){typeof document>"u"||(i==="compact"?document.body.classList.add(US):document.body.classList.remove(US))}let wh=OB();const nb=new Set;wk(wh);function LB(i){if(i!==wh){wh=i;try{localStorage.setItem(bk,i)}catch{}wk(i),nb.forEach(e=>e(i))}}function $B(){const[i,e]=B.useState(wh);B.useEffect(()=>{const n=r=>e(r);return nb.add(n),wh!==i&&e(wh),()=>{nb.delete(n)}},[]);const t=B.useCallback(n=>LB(n),[]);return{density:i,setDensity:t}}let GS=!1;function NB(){$B();const i=Ii(Z=>Z.focusedPanelId)??"overview",e=Ii(Z=>Z.navFace),[t,n]=B.useState(null),[r,l]=B.useState(!1),[p,a]=B.useState(!1),[d,f]=B.useState(!1),[g,m]=B.useState(null),b=B.useCallback(Z=>{Ii.getState().setEpicsWorkspaceOpen(Z==="terminal"),Ii.getState().openPanel(Z)},[]),T=B.useCallback(()=>b("voice"),[b]),E=B.useCallback(()=>b("scheduler"),[b]);B.useCallback(Z=>{Oi.getState().openFile(Z),b("editor")},[b]),B.useEffect(()=>{Ii.getState().hydrateOpenToHomePref()},[]),B.useEffect(()=>{const Z=()=>b("editor");return window.addEventListener("sm:open-editor",Z),()=>window.removeEventListener("sm:open-editor",Z)},[b]),B.useEffect(()=>{const Z=pe=>b(pe.detail);return window.addEventListener("sm:navigate",Z),()=>window.removeEventListener("sm:navigate",Z)},[b]);const k=St(Z=>Z.activeTabId),y=St(Z=>Z.tabs),S=y.find(Z=>Z.id===k)??null,w=B.useRef(k),x=B.useRef(new Set(y.map(Z=>Z.id)));B.useEffect(()=>{const Z=w.current,pe=x.current,oe=new Set(y.map(we=>we.id));w.current=k,x.current=oe,Z!==null&&k!==null&&k!==Z&&oe.size===pe.size&&pe.has(k)&&oe.has(Z)&&Ii.getState().openProjectPanel("terminal")},[k,y]),B.useEffect(()=>{WT(i,k,e)&&Ii.getState().openPanel("overview")},[i,k,e]),B.useEffect(()=>{if(!g)return;const Z=window.setTimeout(()=>m(null),2500);return()=>window.clearTimeout(Z)},[g]),B.useEffect(()=>S?window.api.watchers.onLine(pe=>{if(pe.tabId!==S.id)return;const oe=pe.line.replace(/\x1b\[[0-9;]*m/g,"");oe.trim()&&m(oe.length>100?`${oe.slice(0,100)}…`:oe)}):void 0,[S==null?void 0:S.id]);const A=Ct(Z=>Z.isRecording),O=Ct(Z=>Z.wizardOpen),$=Ct(Z=>Z.closeWizard);PB(k);const j=B.useCallback(()=>{const{activeTabId:Z,restartTab:pe}=St.getState();Z&&pe(Z)},[]);B.useCallback(()=>{window.api.app.rebootApp()},[]);const L=B.useCallback(()=>{a(Z=>(Z||Ii.getState().openPanel("terminal"),!Z))},[]),G=B.useCallback(()=>{f(Z=>(Z||Ii.getState().openPanel("terminal"),!Z))},[]),W=B.useRef(k);W.current=k;const re=B.useRef("hold"),ae=B.useCallback(()=>{IB().catch(()=>null).finally(()=>{Ii.getState().setEpicsWorkspaceOpen(!0),Ii.getState().openProjectPanel("terminal")})},[]);return B.useEffect(()=>{var me;if(!Rv()){GS||(pt.warn("voice","mic.gate.unsupported"),GS=!0);return}Ct.getState().initModel();let Z=null,pe=!1;const oe=()=>{if(!Z)return;const we=Z.state;Ct.getState().setPermissionState(we)};return typeof navigator<"u"&&((me=navigator.permissions)!=null&&me.query)&&navigator.permissions.query({name:"microphone"}).then(we=>{pe||(Z=we,Ct.getState().setPermissionState(we.state),we.addEventListener("change",oe))}).catch(we=>{pt.warn("voice","permission query unsupported",{error:we==null?void 0:we.message})}),()=>{pe=!0,Z&&Z.removeEventListener("change",oe)}},[]),B.useEffect(()=>{var ge;const Z=XS[0],pe=Te=>{if(!Te||St.getState().tabs.length>0)return;const je=crypto.randomUUID(),Ze=JS(Z,{sessionId:je,cwd:Te});St.setState(ye=>({tabs:[...ye.tabs,{id:je,sessionId:je,label:Te.split("/").filter(Boolean).pop()||Te,cwd:Te,pid:null,status:"spawning",exitCode:null,startupCommand:Ze,presetId:Z.id,generation:0}],activeTabId:je}))},oe=Te=>{if(!Te||St.getState().tabs.length>0)return;const je=crypto.randomUUID();St.setState(Ze=>({tabs:[...Ze.tabs,{id:je,sessionId:je,label:Te.split("/").filter(Boolean).pop()||Te,cwd:Te,pid:null,status:"dormant",exitCode:null,startupCommand:null,presetId:Z.id,generation:0}],activeTabId:je}))};window.api.app.launchMode().then(({simple:Te,cwd:je})=>{if(Te){n(!0),pe(je);return}n(!1),ry().then(()=>{St.getState().tabs.length>0||bw(Z).then(Ze=>oe(Ze||"")).catch(Ze=>{console.warn("[App] failed to create initial tab:",Ze),nt.error("Failed to create initial tab. Is the claude CLI on PATH?")})})}).catch(()=>{n(!1),ry().then(()=>{St.getState().tabs.length>0||bw(Z).then(Te=>oe(Te||"")).catch(()=>{})})});const me=window.api.app.onNewSession(()=>{BS().catch(Te=>{console.error("[App] new-session from menu failed:",Te),nt.error("Could not start new session. The directory picker failed.")})}),we=window.api.app.onRebootSession(()=>{const{activeTabId:Te}=St.getState();Te?St.getState().restartTab(Te):nt.error("No active tab to restart. Open a project tab first.")});jf.getState().init(),MD(),oT(),window.api.app.claudeBinStatus().then(Te=>{Te.foundOnDisk||nt.warn("Claude binary not found at any known path — sessions will rely on $PATH and may fail to spawn. Install via `npm i -g @anthropic-ai/claude-code` if spawn fails.")}).catch(()=>{}),window.api.app.homeSelfCheck().then(Te=>{Te.ok||nt.error(`Home-directory self-check failed: ${Te.error??"unknown"}. Session spawns will reject every cwd. Likely a symlinked /Users on macOS.`)}).catch(()=>{});const ve=cP();AB([{uri:"https://json.schemastore.org/claude-code-settings.json",fileMatch:["**/settings.json","**/settings.local.json"]}]).catch(Te=>console.warn("[monaco] schema install failed:",Te)),window.api.voice.getHotkeyConfig().then(Te=>{re.current=Te.mode}).catch(Te=>pt.warn("voice-hotkey","getHotkeyConfig failed",{error:String(Te)}));const F=window.api.voice.onHotkeyConfigChanged(Te=>{re.current=Te.mode}),J=window.api.voice.onHotkey(({phase:Te,source:je})=>{Ct.getState().armHotkey({phase:Te,source:je,mode:re.current,tabId:W.current})}),V=()=>Ct.getState().destroyHotkey();window.addEventListener("beforeunload",V);const se=async()=>{var Te;window.dispatchEvent(new Event("mic-device-change"));try{if(!((Te=navigator.mediaDevices)!=null&&Te.enumerateDevices))return;const Ze=(await navigator.mediaDevices.enumerateDevices()).filter(ue=>ue.kind==="audioinput"),ye=Ct.getState();if(!ye.isRecording)return;let Y=null;try{Y=await window.api.voice.getDevicePref()}catch{}if(!Y||!Y.selectedDeviceId||Ze.some(ue=>ue.deviceId===Y.selectedDeviceId))return;pt.warn("voice","device-vanished mid-recording; stopping",{deviceIdPrefix:Y.selectedDeviceId.slice(0,8)}),ye.stopRecording(),Ct.setState({error:"Microphone disconnected",errorKind:"recording"})}catch(je){pt.warn("voice","devicechange handler failed",{error:je instanceof Error?je.message:String(je)})}};return typeof navigator<"u"&&((ge=navigator.mediaDevices)!=null&&ge.addEventListener)&&navigator.mediaDevices.addEventListener("devicechange",se),()=>{var Te;ve(),me(),we(),F(),J(),window.removeEventListener("beforeunload",V),typeof navigator<"u"&&((Te=navigator.mediaDevices)!=null&&Te.removeEventListener)&&navigator.mediaDevices.removeEventListener("devicechange",se)}},[]),B.useEffect(()=>{try{window.api.voice.setRecording(A)}catch{}},[A]),B.useEffect(()=>{const Z=oe=>{var F,J;const me=oe.target,we=((F=me==null?void 0:me.tagName)==null?void 0:F.toLowerCase())??"",ve=((J=me==null?void 0:me.classList)==null?void 0:J.contains("xterm-helper-textarea"))??!1;return!!((we==="input"||we==="textarea")&&!ve||me!=null&&me.closest(".monaco-editor"))},pe=oe=>{if((oe.metaKey||oe.ctrlKey)&&(oe.key==="k"||oe.key==="K")){if(Z(oe))return;oe.preventDefault(),oe.stopPropagation(),l(me=>!me)}else if(oe.key==="Escape"&&r)l(!1);else if(oe.altKey&&!oe.ctrlKey&&!oe.metaKey&&!oe.shiftKey){const me=/^Digit([1-5])$/.exec(oe.code);if(!me||Z(oe))return;const we=parseInt(me[1],10)-1,{tabs:ve,setActive:F}=St.getState(),J=ve[we];if(!J)return;oe.preventDefault(),oe.stopPropagation(),F(J.id),Ii.getState().setEpicsWorkspaceOpen(!1)}};return window.addEventListener("keydown",pe,!0),()=>window.removeEventListener("keydown",pe,!0)},[r]),B.useEffect(()=>{let Z=!1,pe=null;return(async()=>{var oe,me;try{const we=await((me=(oe=window.api.voice).getTurnDetector)==null?void 0:me.call(oe));if(Z||!we||(Ct.setState({turnDetectorMode:we.mode,turnDetectorState:"disabled"}),we.mode==="off")||(pt.info("voice-turn","mount.opted-in",{mode:we.mode}),Z))return;pe=new Worker(new URL(""+new URL("turnDetectorWorker-ChWji_-D.js",import.meta.url).href,import.meta.url),{type:"module"}),pe.addEventListener("message",ve=>{const F=ve.data;if(!(!F||typeof F!="object")&&F.type==="status"){const J=F.status;J==="ready"?Ct.getState().setTurnDetectorRuntimeState("ok"):(J==="load_failed"||J==="runtime_error")&&Ct.getState().setTurnDetectorRuntimeState(J)}}),pe.addEventListener("error",ve=>{pt.error("voice-turn","turn-detector worker error",{message:ve.message}),Ct.getState().setTurnDetectorRuntimeState("runtime_error")}),pe.postMessage({type:"load"})}catch(we){pt.warn("voice-turn","mount.read-settings failed",{error:we instanceof Error?we.message:String(we)})}})(),()=>{if(Z=!0,pe){try{pe.terminate()}catch{}pe=null}}},[]),B.useEffect(()=>{let Z=!1;return(async()=>{var pe,oe;try{const me=await((oe=(pe=window.api.app).isE2E)==null?void 0:oe.call(pe));if(Z||me||yB()||Ct.getState().wizardOpen)return;Jl.getState().start()}catch{}})(),()=>{Z=!0}},[]),B.useEffect(()=>{let Z=!1;return(async()=>{var pe,oe;try{const me=await((oe=(pe=window.api.app).isE2E)==null?void 0:oe.call(pe));if(Z)return;if(me){pt.info("voice-wizard","auto-arm.skipped-e2e");return}const we=await window.api.voice.getWizardState();if(Z)return;we.completedSchema!==we.currentSchema&&(Ct.getState().setWizardArmed(!0),pt.info("voice-wizard","auto-arm",{completedSchema:we.completedSchema,currentSchema:we.currentSchema}))}catch(me){pt.warn("voice-wizard","auto-arm failed",{error:me instanceof Error?me.message:String(me)})}})(),()=>{Z=!0}},[]),t===!0?c.jsx(EB,{}):c.jsxs("div",{className:`h-full w-full flex flex-col bg-bg text-fg text-sm ${A?"pt-7":""}`,children:[c.jsx(vk,{}),c.jsx(XT,{}),c.jsxs("div",{className:"flex-1 flex min-h-0",children:[c.jsx(VD,{active:i,onNavigate:b,onNewSession:ae}),c.jsxs("div",{className:"relative flex-1 min-w-0 bg-bg flex flex-col",children:[i==="terminal"&&p&&c.jsx(f2,{onClose:()=>a(!1),onSent:Z=>{a(!1),m(`Sent to ${Z} tab${Z===1?"":"s"}`)}}),i==="terminal"&&S&&d&&c.jsx("div",{className:"absolute top-12 right-4 z-30",children:c.jsx(m2,{tabId:S.id,cwd:S.cwd,onClose:()=>f(!1)})}),c.jsx("div",{className:"flex-1 min-h-0 relative",children:c.jsx(gB,{onNavigate:b,onNewSession:ae,onOpenVoice:T,onOpenScheduler:E})}),g&&c.jsx("div",{role:"status",className:"pointer-events-none fixed bottom-10 right-4 z-40 bg-bg-elev border border-line text-fg text-xs px-3 py-1.5 rounded shadow-lg","data-testid":"broadcast-toast",children:g})]})]}),c.jsx(d2,{onNavigate:b}),c.jsx(_B,{open:O,onClose:$}),c.jsx(TB,{}),c.jsx(yk,{}),c.jsx(SB,{open:r,onClose:()=>l(!1),onCommand:Z=>{if(l(!1),Z.id.startsWith("nav:")){b(Z.id.slice(4));return}const pe=St.getState().tabs.find(oe=>oe.id===St.getState().activeTabId)??null;switch(Z.id){case"new-tab-pick":BS().catch(oe=>{console.error("[App] new tab (pick) failed:",oe),nt.error("Could not start new session. The directory picker failed.")});return;case"new-tab-here":{if(!pe)return;St.getState().addTab({cwd:pe.cwd,startupCommand:null,dormant:!0}),Ii.getState().openProjectPanel("terminal");return}case"close-tab":pe&&St.getState().closeTab(pe.id);return;case"restart-session":j();return;case"broadcast":L();return;case"watchers":G();return;case"copy-cwd":pe&&window.api.clipboard.writeText(pe.cwd).catch(()=>nt.error("Copy failed"));return;case"copy-transcript":pe&&window.api.transcripts.pathFor(pe.cwd,pe.sessionId).then(oe=>window.api.clipboard.writeText(oe)).catch(()=>nt.error("Copy failed"));return;case"open-transcript":pe&&window.api.transcripts.pathFor(pe.cwd,pe.sessionId).then(oe=>window.api.shell.open({as:"openPath",path:oe})).catch(()=>nt.error("Open failed"));return;case"reload-window":window.location.reload();return;default:return}}})]})}const MB=["app","pty","transcripts","sessions","billing","logs","config","voice","watchers","otel","history","schedule","supervisor","plugins","clipboard","memory"];function jB(i){if(!i||typeof i!="object")return[{kind:"api-root-missing"}];const e=i,t=[];for(const n of MB){const r=e[n];r==null?t.push({kind:"namespace-missing",name:n}):typeof r!="object"&&t.push({kind:"namespace-not-object",name:n,actualType:typeof r})}return t}function HS(i){switch(i.kind){case"api-root-missing":return"window.api is missing — preload did not load. Check src/preload/index.cjs and the main process console.";case"namespace-missing":return`window.api.${i.name} is missing — declared in src/preload/api.d.ts but not exposed in src/preload/index.cjs.`;case"namespace-not-object":return`window.api.${i.name} is ${i.actualType}, expected object — preload exposure is malformed.`}}function zB(){const i=jB(window.api);if(i.length===0)return i;for(const e of i)console.error("[apiBootCheck]",HS(e));return setTimeout(()=>{Bn(async()=>{const{toast:e}=await Promise.resolve().then(()=>e1);return{toast:e}},void 0,import.meta.url).then(({toast:e})=>{const t=i.length===1?HS(i[0]):`Renderer is out of sync with preload (${i.length} issues). See console for details.`;e.error(t)}).catch(()=>{})},1e3),i}window.addEventListener("unhandledrejection",i=>{const e=i.reason instanceof Error?i.reason.stack??i.reason.message:String(i.reason);console.error("[renderer] unhandled rejection:",e)});window.addEventListener("error",i=>{i.error&&console.error("[renderer] uncaught error:",i.error.stack??i.error.message??i.error)});typeof window.api>"u"&&console.error("[renderer] window.api is undefined — preload script failed to load. Check main/index.cjs BrowserWindow webPreferences.preload path.");zB();jk.createRoot(document.getElementById("root")).render(c.jsx(NB,{}));export{ZB as $,Vs as A,e3 as B,S_ as C,a5 as D,Qx as E,nE as F,$3 as G,im as H,d3 as I,y5 as J,p5 as K,fN as L,jy as M,s3 as N,r5 as O,qB as P,m5 as Q,Ot as R,KB as S,c2 as T,g5 as U,Ch as V,DE as W,D3 as X,L$ as Y,Cn as Z,IC as _,_a as a,_b as a$,Bv as a0,Un as a1,pR as a2,r1 as a3,YB as a4,XB as a5,Mr as a6,rl as a7,KM as a8,e5 as a9,g1 as aA,_P as aB,rb as aC,FB as aD,hP as aE,x3 as aF,jv as aG,pd as aH,hR as aI,v5 as aJ,t1 as aK,nt as aL,b$ as aM,pi as aN,Of as aO,v1 as aP,Oi as aQ,dh as aR,Ab as aS,vd as aT,Ii as aU,tw as aV,Ov as aW,ti as aX,HB as aY,Nr as aZ,OE as a_,eR as aa,r3 as ab,i5 as ac,UC as ad,t5 as ae,tR as af,RC as ag,sb as ah,Ja as ai,KC as aj,c as ak,QB as al,uP as am,JB as an,al as ao,_5 as ap,fP as aq,c5 as ar,c3 as as,Zf as at,CC as au,JE as av,GB as aw,yz as ax,dm as ay,B as az,u5 as b,St as b0,$o as b1,l3 as b2,VB as b3,n1 as b4,WB as b5,ld as c,bh as d,h5 as e,DO as f,l5 as g,$0 as h,Rb as i,MC as j,KL as k,Uy as l,xh as m,o5 as n,n5 as o,mN as p,s5 as q,cz as r,L0 as s,f5 as t,Hb as u,lz as v,d5 as w,QE as x,o3 as y,hI as z};