claude-code-session-manager 0.67.0 → 0.68.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{AgentLibrary-CiqimwWl.js → AgentLibrary-D1SHQWCQ.js} +1 -1
- package/dist/assets/{History-DbzjII2Z.js → History-BySQczDf.js} +1 -1
- package/dist/assets/{Hooks-C0PTplI_.js → Hooks-CG8jWh3-.js} +1 -1
- package/dist/assets/{HostBilko-vGc1FYLD.js → HostBilko-BxjPY1PW.js} +1 -1
- package/dist/assets/{Library-4tU4rg2h.js → Library-BA8cOckT.js} +1 -1
- package/dist/assets/{ListDetail-BGIvkCwZ.js → ListDetail-CVIhWPWb.js} +1 -1
- package/dist/assets/{MarkdownEditor-ChFdpCam.js → MarkdownEditor-DUoKh1Qr.js} +1 -1
- package/dist/assets/{McpServers-DsRWWpU3.js → McpServers-CkowlPR7.js} +1 -1
- package/dist/assets/{Memory-DmxoxxxY.js → Memory-C5Vv5Wim.js} +1 -1
- package/dist/assets/{Panel-KC-rv3jS.js → Panel-CVgA2-Y3.js} +1 -1
- package/dist/assets/{Permissions-DrDjCRFl.js → Permissions-u43I9j0-.js} +1 -1
- package/dist/assets/{Plugins-KexSQwk0.js → Plugins-DComjLBQ.js} +2 -2
- package/dist/assets/{ProvenanceBadge-Rg-jL94y.js → ProvenanceBadge-DNTnbu6f.js} +1 -1
- package/dist/assets/{SaveBar-BbEo8U2e.js → SaveBar-R1ZZ9WH5.js} +1 -1
- package/dist/assets/{Scheduler-C4Ti9TCc.js → Scheduler-D4Gzz6iD.js} +1 -1
- package/dist/assets/{ScopeSwitcher-Di9BmYze.js → ScopeSwitcher-DBcYhNZF.js} +1 -1
- package/dist/assets/{Settings-CxyhPuYQ.js → Settings-CXcfro2y.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-0q26RHrn.js → SkillReferenceGraph-DTfBzZ7O.js} +1 -1
- package/dist/assets/{Skills-BXkVyCo5.js → Skills-CVlcQjVO.js} +1 -1
- package/dist/assets/{SystemPrompt-Bwe3NTbi.js → SystemPrompt-COLmPm10.js} +1 -1
- package/dist/assets/{TagLibrary-CnwEf6EI.js → TagLibrary-BN6bvsjU.js} +1 -1
- package/dist/assets/{TiptapBody-faCtLj9L.js → TiptapBody-DxzA0zb5.js} +1 -1
- package/dist/assets/{Toggle-Bw7G_-RR.js → Toggle-CPlUEMUg.js} +1 -1
- package/dist/assets/{index-B6dJ2CsU.js → index-Ceid3k5X.js} +4 -4
- package/dist/assets/{settingsSchema-B5C9hZoS.js → settingsSchema-CgmSslES.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/builder/session-manager-operations/scheduler/state/queue.json +3 -0
- package/src/main/__tests__/health-per-project-stall.test.cjs +4 -2
- package/src/main/__tests__/scheduler-job-overrun.test.cjs +117 -0
- package/src/main/__tests__/scheduler-stall-per-project.test.cjs +6 -2
- package/src/main/lib/schedulerConfig.cjs +15 -0
- package/src/main/scheduler.cjs +73 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-DxzA0zb5.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css","./Skills-CVlcQjVO.js","./Panel-CVgA2-Y3.js","./ListDetail-CVIhWPWb.js","./MarkdownEditor-DUoKh1Qr.js","./SaveBar-R1ZZ9WH5.js","./ScopeSwitcher-DBcYhNZF.js","./Toggle-CPlUEMUg.js","./ProvenanceBadge-DNTnbu6f.js","./Library-BA8cOckT.js","./listSkills-QORduPIk.js","./skillFrontmatter-Dif5JIg7.js","./History-BySQczDf.js","./Scheduler-D4Gzz6iD.js","./Settings-CXcfro2y.js","./settingsSchema-CgmSslES.js","./Permissions-u43I9j0-.js","./SystemPrompt-COLmPm10.js","./Memory-C5Vv5Wim.js","./Plugins-DComjLBQ.js","./McpServers-CkowlPR7.js","./Hooks-CG8jWh3-.js","./AgentLibrary-D1SHQWCQ.js","./TagLibrary-BN6bvsjU.js","./HostBilko-BxjPY1PW.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var hk=Object.defineProperty;var pk=(i,e,t)=>e in i?hk(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Bi=(i,e,t)=>pk(i,typeof e!="symbol"?e+"":e,t);import{_ as os}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 Ib(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Lv={exports:{}},Vp={},zv={exports:{}},pi={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -53,7 +53,7 @@ ${r}`,d={...l,goalText:a},f={...e().sessions,[t]:d};i({sessions:f});try{await Fa
|
|
|
53
53
|
`):l();case"queued_command":return Ai(p.prompt)??l();case"skill_listing":return Ai(p.content)??l();case"edited_text_file":return Ai(p.snippet)??l();default:return l()}}default:return l()}}function Qk(i,e){var l;let t;try{t=JSON.parse(e)}catch{return null}const n=Ss((l=Ss(t))==null?void 0:l.attachment);if(!n)return null;const r=p=>Array.isArray(p)?p.filter(a=>typeof a=="string"):null;switch(i){case"deferred_tools_delta":return r(n.addedNames);case"agent_listing_delta":return r(n.addedTypes);case"command_permissions":return r(n.allowedTools);case"skill_listing":{const a=(Ai(n.content)??"").split(`
|
|
54
54
|
`).map(d=>{var f,v;return(v=(f=/^-\s*([^:]+):/.exec(d))==null?void 0:f[1])==null?void 0:v.trim()}).filter(d=>!!d);return a.length?a:null}default:return null}}function u1(i){return i==="tool_use"||i==="todo_write"||i==="plan"||i==="agent_spawn"}function Hu(i){return typeof i=="string"&&i.length>0?i:void 0}function eg(i){return i===!0?!0:void 0}function eE(i){if(!i||typeof i!="object")return;const e=i,t={},n=(r,l)=>{l!==void 0&&(t[r]=l)};return n("attributionSkill",Hu(e.attributionSkill)),n("attributionPlugin",Hu(e.attributionPlugin)),n("attributionMcpServer",Hu(e.attributionMcpServer)),n("attributionMcpTool",Hu(e.attributionMcpTool)),n("effort",Hu(e.effort)),n("gitBranch",Hu(e.gitBranch)),n("isSidechain",eg(e.isSidechain)),n("isMeta",eg(e.isMeta)),n("isApiErrorMessage",eg(e.isApiErrorMessage)),n("interruptedByShutdown",eg(e.interruptedByShutdown)),Object.keys(t).length>0?t:void 0}const h1=[{key:"stop-signal",label:"Stop-signal protocol",start:"IMPORTANT: First deliver everything you CAN answer",end:"Otherwise complete the task and end with a concise summary of what you did."},{key:"chat-mode-truth",label:"One-shot headless run",start:"IMPORTANT: This is a one-shot headless run.",end:"reply for the work to continue."}];function p1(i){const e={preamble:null,blockKeys:[],body:i};if(typeof i!="string"||!i)return e;let t=i.length-i.trimStart().length;const n=[],r=new Set;for(;;){let p=!1;for(const a of h1){if(r.has(a.key)||!i.startsWith(a.start,t))continue;const d=i.indexOf(a.end,t+a.start.length);if(d===-1)return e;let f=d+a.end.length;for(;f<i.length&&/\s/.test(i[f]);)f++;t=f,r.add(a.key),n.push(a.key),p=!0;break}if(!p)break}if(n.length===0)return e;const l=i.slice(t);return l.trim()?{preamble:i.slice(0,t).trim(),blockKeys:n,body:l}:e}function tE(i){return i.map(e=>{var t;return((t=h1.find(n=>n.key===e))==null?void 0:t.label)??e}).join(", ")}const Kl={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},ey=20;function Kg(i,e){const t=[...i,e];return t.length>ey?t.slice(t.length-ey):t}let ty=0;function ha(){return ty+=1,`t${Date.now().toString(36)}-${ty}`}const iE="Landed",iy=60;function nE(i){const e=i.trim();if(e.length<=iy)return e;const t=e.slice(0,iy),n=t.lastIndexOf(" ");return(n>0?t.slice(0,n):t).trim()}const di=In((i,e)=>({chats:{},hydratedTabs:{},get:t=>e().chats[t]??Kl,hydrate:async({tabId:t,cwd:n,sessionId:r})=>{var l,p,a;if(!e().hydratedTabs[t]&&(i({hydratedTabs:{...e().hydratedTabs,[t]:!0}}),!(typeof window>"u"||!((l=window.api)!=null&&l.exchanges))))try{const d=await window.api.exchanges.list({cwd:n,sessionId:r});if(!d.length)return;const f=[];for(const m of[...d].reverse()){const y=new Date(m.ts).getTime();f.push({id:ha(),role:"user",text:m.prompt,at:y}),f.push({id:ha(),role:"assistant",text:m.result,at:y})}const v=e().chats[t]??Kl;i({chats:{...e().chats,[t]:{...v,turns:[...f,...v.turns],started:!0}}})}catch(d){const f=d instanceof Error?d.message:String(d);(a=(p=window.api)==null?void 0:p.logs)==null||a.write("chat","warn",`exchange hydration failed for tab ${t}: ${f}`)}},send:({tabId:t,sessionId:n,cwd:r,prompt:l,tag:p,chainRootId:a,external:d})=>{const f=l.trim();if(!f)return;if(Za.getState().isAttached(t)){lt.error("Terminal mode is active for this Epic — switch back to Chat to send a message.");return}const v=e().chats[t]??Kl;if(v.running){const m={id:crypto.randomUUID(),tabId:t,sessionId:n,cwd:r,text:f,status:"queued",createdAt:Date.now(),tag:p,chainRootId:a,external:d};i({chats:{...e().chats,[t]:{...v,queue:[...v.queue,m]}}});return}sE(t),f1({tabId:t,sessionId:n,cwd:r,text:f,tag:p,chainRootId:a})},resetThread:t=>{Jg.delete(t),i({chats:{...e().chats,[t]:{...Kl}}})},pushNotice:(t,n)=>{Yg(t,"",n)},setPendingVoiceText:(t,n)=>{Ps(t,r=>({...r,pendingVoiceText:n}))},clearPendingVoiceText:t=>{Ps(t,n=>({...n,pendingVoiceText:void 0}))},dropTab:t=>{if(!(t in e().chats)&&!(t in e().hydratedTabs))return;Jg.delete(t);const n={...e().chats};delete n[t];const r={...e().hydratedTabs};delete r[t],i({chats:n,hydratedTabs:r})}}));function Ps(i,e){const t=di.getState().chats[i]??Kl;di.setState({chats:{...di.getState().chats,[i]:e(t)}})}function Ng(i,e,t={},n="done",r={}){Ps(i,l=>{const p=l.activeTicket?Kg(l.ticketHistory??[],{...l.activeTicket,status:n,completedAt:Date.now(),...r}):l.ticketHistory??[],a=g1(i)&&(e.role==="assistant"||e.role==="user")?Lb(l.turns,e.role,e.text):-1,d=a!==-1?l.turns.map((f,v)=>{var m;return v===a?{...f,outcome:e.outcome??f.outcome,toolUses:(m=f.toolUses)!=null&&m.length?f.toolUses:l.liveToolUses}:f}):[...l.turns,{...e,toolUses:l.liveToolUses}];return{...l,turns:d,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:p,...t}}),j_(i)}function sE(i){Ps(i,e=>{const t=e.ticketHistory??[];return t.some(n=>n.status==="needs-input")?{...e,ticketHistory:t.map(n=>n.status==="needs-input"?{...n,status:"done"}:n)}:e})}function f1(i){const{tabId:e,sessionId:t,cwd:n,text:r,promptId:l,tag:p,chainRootId:a}=i,d=di.getState().chats[e]??Kl,f={id:ha(),role:"user",text:r,at:Date.now()};N_(e,"user",r);const v=d.activeTicket??{id:l??crypto.randomUUID(),tabId:e,sessionId:t,cwd:n,text:r,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:p,chainRootId:a};di.setState({chats:{...di.getState().chats,[e]:{...d,turns:[...d.turns,f],running:!0,queuedPosition:0,stream:"",activeTicket:v}}}),fv(n,t).catch(m=>{var D,k;const y=m instanceof Error?m.message:String(m);return(k=(D=window.api)==null?void 0:D.logs)==null||k.write("chat","warn",`transcript-exists check failed for tab ${e}: ${y}`),d.started}).then(m=>window.api.chat.run({tabId:e,sessionId:t,prompt:r,cwd:n,resume:m,promptId:l})).catch(m=>{const y=m instanceof Error?m.message:String(m);m1(e,t,y)})}function j_(i){const e=di.getState().chats[i]??Kl;if(e.queue.length===0)return;const[t,...n]=e.queue;if(Ps(i,r=>({...r,queue:n,running:!0,queuedPosition:0,activeTicket:t})),t.external){tg(i,t);return}if(Yt.getState().sessions[i]){tg(i,t);return}if(zk(t.tag)){tg(i,t);return}Mk(t.text).then(r=>{if(r==="develop"){aE(i,t);return}tg(i,t)})}function tg(i,e){const t={...e,status:"running",startedAt:Date.now()};Ps(i,n=>({...n,activeTicket:t})),f1({tabId:t.tabId,sessionId:t.sessionId,cwd:t.cwd,text:t.text,promptId:t.id,tag:t.tag,chainRootId:t.chainRootId})}function rE(i,e){var t,n,r,l,p;try{const a=(t=Yt.getState().events[i])==null?void 0:t.slice(-1)[0];if(!a){(r=(n=window.api)==null?void 0:n.logs)==null||r.write("chat","warn",`appendPrdCreatedEvent: PromptSession ${i} has no tail event — skipping prd_created append for ${e}`);return}Yt.getState().appendPromptSessionEvent(i,{kind:"prd_created",causedByEventId:a.id,prdSlug:e})}catch(a){const d=a instanceof Error?a.message:String(a);(p=(l=window.api)==null?void 0:l.logs)==null||p.write("chat","warn",`appendPrdCreatedEvent failed for ${i}: ${d}`)}}const ny=2e3;function N_(i,e,t){var r,l,p,a;const n=Yt.getState().sessions[i];if(n)try{(l=(r=window.api)==null?void 0:r.promptSessionTranscript)==null||l.append(n.cwd,i,{role:e,text:t})}catch(d){const f=d instanceof Error?d.message:String(d);(a=(p=window.api)==null?void 0:p.logs)==null||a.write("chat","warn",`capturePromptSessionTurn failed for ${i}: ${f}`)}}function sy(i,e){var t,n,r;try{const l=(t=Yt.getState().events[i])==null?void 0:t.slice(-1)[0];if(!l)return;const p=e.length>ny?`${e.slice(0,ny)}…`:e;Yt.getState().appendPromptSessionEvent(i,{kind:"response",causedByEventId:l.id,text:p})}catch(l){const p=l instanceof Error?l.message:String(l);(r=(n=window.api)==null?void 0:n.logs)==null||r.write("chat","warn",`appendResponseEvent failed for ${i}: ${p}`)}}async function oE(i,e){var n,r,l,p;const t=a=>{var d;return!!a&&((d=Yt.getState().sessions[a])==null?void 0:d.status)==="active"};if(e.chainRootId){const d=((di.getState().chats[i]??Kl).ticketHistory??[]).find(v=>v.id===e.chainRootId),f=(d==null?void 0:d.promptSessionId)??null;if(f){const v=Yt.getState().sessions[f];if(!v||v.status==="active")return f}}return t(i)||(await Yt.getState().hydrate(e.cwd),t(i))?i:(e.chainRootId?(r=(n=window.api)==null?void 0:n.logs)==null||r.write("chat","warn",`continuation ticket ${e.id}: no resolvable PromptSession for chainRootId ${e.chainRootId} — refusing dispatch (sessions must never mint an Epic)`):(p=(l=window.api)==null?void 0:l.logs)==null||p.write("chat","warn",`ticket ${e.id}: no resolvable PromptSession for tab ${i} — refusing dispatch (sessions must never mint an Epic)`),null)}function aE(i,e){const t=n=>{Ps(i,r=>({...r,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:Kg(r.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),Yg(i,e.sessionId,n),lt.error(n),j_(i)};oE(i,e).then(n=>{if(!n){t(`→ Ticket ${e.id}: no Epic to dispatch this PRD into. Create one via the New Epic card (or approve a proposed one), then resend.`);return}window.api.chat.createPrd({title:nE(e.text),cwd:e.cwd,estimateMinutes:15,goal:e.text,acceptanceCriteria:["Implement the request described in Goal.","timeout 300 npm run typecheck passes"],implementationNotes:`Target project: ${e.cwd}`,sourcePromptId:n,sourceTabId:e.tabId,tag:e.tag}).then(r=>{if(!(r!=null&&r.ok)){t(`→ PRD authoring failed for ticket ${e.id}: ${(r==null?void 0:r.error)??"unknown error"}`);return}const l=r.filename,p=l.endsWith(".md")?l.slice(0,-3):l;rE(n,p);const a={...e,status:"dispatched-to-prd",completedAt:Date.now(),promptSessionId:n,...e.chainRootId?{}:{prdSlugs:[p]}};Yg(i,a.sessionId,`→ dispatched to PRD ${l} (ticket ${a.id})`),Ps(i,d=>{let f=Kg(d.ticketHistory??[],a);if(e.chainRootId){const v=e.chainRootId;f=f.map(m=>m.id===v?{...m,prdSlugs:[...m.prdSlugs??[],p]}:m)}return{...d,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:f}}),j_(i)}).catch(r=>{const l=r instanceof Error?r.message:String(r);t(`→ PRD authoring failed for ticket ${e.id}: ${l}`)})})}function m1(i,e,t){Ps(i,n=>n.activeTicket?{...n,activeTicket:null,ticketHistory:Kg(n.ticketHistory??[],{...n.activeTicket,status:"failed",completedAt:Date.now()})}:n),Ng(i,{id:ha(),role:"error",text:t,at:Date.now()}),lt.error(t)}function Yg(i,e,t){Ps(i,n=>({...n,turns:[...n.turns,{id:ha(),role:"notice",text:t,at:Date.now()}]}))}const lE=20,ry=1e3,Yl=new Map,Xg=new Map,Jg=new Map;function oy(i,e){const t=e.trim();return i==="user"?p1(t).body.trim():t}function Lb(i,e,t){const n=oy(e,t);if(!n)return-1;const r=Math.max(0,i.length-lE);for(let l=i.length-1;l>=r;l--)if(i[l].role===e&&oy(e,i[l].text)===n)return l;return-1}function ay(i){return i.length>ry?i.slice(i.length-ry):i}function g1(i){return Yl.has(i)}function cE(i,e,t){var v;if(t.ref){const m=Jg.get(i)??{seen:new Set,lastOffset:-1,lineIndex:-1};t.ref.byteOffset===m.lastOffset?m.lineIndex+=1:(m.lastOffset=t.ref.byteOffset,m.lineIndex=0),Jg.set(i,m);const y=`${t.ref.byteOffset}:${m.lineIndex}`;if(m.seen.has(y))return e;m.seen.add(y)}const n=t.raw??{},r=typeof n.timestamp=="string"&&Date.parse(n.timestamp)||Date.now(),l=n.isMeta===!0||n.isSidechain===!0,p=eE(n),a=t.data,d=typeof a=="string"?a:typeof((v=a==null?void 0:a.message)==null?void 0:v.content)=="string"?a.message.content:null;if((t.kind==="assistant"||t.kind==="user")&&d!==null&&!l){const m=t.kind;let y=e.stream;if(e.running&&m==="assistant"&&y){const k=y.indexOf(d);k!==-1&&(y=y.slice(0,k)+y.slice(k+d.length))}const D=Lb(e.turns,m,d);return D!==-1?e.turns[D].ref?{...e,stream:y}:{...e,stream:y,turns:e.turns.map((k,T)=>T===D?{...k,text:d,at:r,kind:t.kind,ref:t.ref,attribution:p??k.attribution}:k)}:{...e,stream:y,turns:ay([...e.turns,{id:ha(),role:m,text:d,at:r,kind:t.kind,ref:t.ref,attribution:p}])}}let f;try{f=Zk(t.kind,t.data,t.raw)}catch{f=void 0}return{...e,turns:ay([...e.turns,{id:ha(),role:"event",text:t.previewText??"",at:r,kind:t.kind,ref:t.ref,signal:f,attribution:p}])}}function ly(i,e){e.length!==0&&Ps(i,t=>e.reduce((n,r)=>cE(i,n,r),t))}function dE(i){var a;const{tabId:e,cwd:t,sessionUuid:n}=i,r=typeof window<"u"?(a=window.api)==null?void 0:a.transcripts:void 0;if(!(r!=null&&r.onEvent)||!r.subscribe||!r.buffer)return;const l=(Yl.get(e)??0)+1;if(Yl.set(e,l),l>1)return;di.setState({hydratedTabs:{...di.getState().hydratedTabs,[e]:!0}});const p=window.api.transcripts.onEvent(e,d=>ly(e,d));Xg.set(e,p),window.api.transcripts.subscribe({tabId:e,cwd:t,sessionUuid:n}).then(async d=>{if(!Yl.has(e))return;if(!d.ok){lt.error(`Chat transcript feed unavailable: ${d.error??"subscribe failed"}`),p(),Xg.delete(e),Yl.delete(e);const v={...di.getState().hydratedTabs};delete v[e],di.setState({hydratedTabs:v});return}const f=await window.api.transcripts.buffer(e);ly(e,f)}).catch(d=>{var v,m;const f=d instanceof Error?d.message:String(d);(m=(v=window.api)==null?void 0:v.logs)==null||m.write("chat","warn",`transcript feed attach failed for ${e}: ${f}`)})}function uE(i){var t,n,r;const e=Yl.get(i);if(e){if(e>1){Yl.set(i,e-1);return}Yl.delete(i),(t=Xg.get(i))==null||t(),Xg.delete(i),(r=(n=window.api)==null?void 0:n.transcripts)==null||r.unsubscribe(i)}}var t1;typeof window<"u"&&((t1=window.api)!=null&&t1.chat)&&(window.api.chat.onQueued(({tabId:i,position:e})=>{Ps(i,t=>({...t,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:i})=>{Ps(i,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:i,delta:e})=>{Ps(i,t=>({...t,stream:t.stream+e}))}),window.api.chat.onToolUse(({tabId:i,id:e,kind:t,label:n,diff:r})=>{Ps(i,l=>({...l,liveToolUses:[...l.liveToolUses,{id:e,kind:t,label:n,diff:r}]}))}),window.api.chat.onComplete(({tabId:i,finalMessage:e})=>{N_(i,"assistant",e),sy(i,e),Ng(i,{id:ha(),role:"assistant",text:e,at:Date.now(),outcome:iE})}),window.api.chat.onNeedsInput(({tabId:i,questions:e,answerBody:t})=>{const n=ha();if(t&&t.trim()){N_(i,"assistant",t),sy(i,t),Ps(i,r=>{const l=g1(i)&&Lb(r.turns,"assistant",t)!==-1;return{...r,turns:l?r.turns:[...r.turns,{id:ha(),role:"assistant",text:t,at:Date.now(),toolUses:r.liveToolUses}],liveToolUses:[]}}),Ng(i,{id:n,role:"question",text:e.join(`
|
|
55
55
|
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:n});return}Ng(i,{id:n,role:"question",text:e.join(`
|
|
56
|
-
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:n})}),window.api.chat.onError(({tabId:i,sessionId:e,message:t})=>{m1(i,e,t)}),window.api.chat.onNotice(({tabId:i,sessionId:e,message:t})=>{Yg(i,e,t)}),window.api.chat.onExternalSend(({tabId:i,prompt:e})=>{var r,l,p,a;const t=xt.getState().tabs.find(d=>d.id===i);if(t){di.getState().send({tabId:i,sessionId:t.sessionId,cwd:t.cwd,prompt:e,external:!0});return}const n=Yt.getState().sessions[i];if(n){if(n.status==="completed"){(l=(r=window.api)==null?void 0:r.logs)==null||l.write("chat","warn",`external send ignored: Epic ${i} is completed/archived — its claudeSessionId is dead`);return}di.getState().send({tabId:i,sessionId:n.claudeSessionId,cwd:n.cwd,prompt:e,external:!0});return}(a=(p=window.api)==null?void 0:p.logs)==null||a.write("chat","warn",`external send ignored: ${i} matches neither an open tab nor a known Epic`)}));function hE(i){const e=i.split("/").filter(Boolean);return e[e.length-1]||i}async function v1(i,e=!1,t=qg()){let n=!e;n&&(n=await fv(i.cwd,i.sessionId));const r=e&&!n?crypto.randomUUID():i.sessionId,l=n?`claude --dangerously-skip-permissions --resume ${Po(r)} --model ${t}`:`claude --dangerously-skip-permissions --session-id ${Po(r)} --model ${t}`;return{sessionId:r,startupCommand:l}}const xt=In((i,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(t,n)=>{i(r=>({pendingRawCommand:{...r.pendingRawCommand,[t]:n}}))},consumeRawCommand:t=>{const n=e().pendingRawCommand[t];return n===void 0?null:(i(r=>{const l={...r.pendingRawCommand};return delete l[t],{pendingRawCommand:l}}),n)},addTab:({id:t,cwd:n,startupCommand:r,presetId:l=null,label:p,dormant:a=!1})=>{const d=t??crypto.randomUUID();if(e().tabs.find(m=>m.id===d))return i({activeTabId:d}),d;a&&r&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",r);const v={id:d,sessionId:d,label:p??hE(n),cwd:n,pid:null,status:a?"dormant":"spawning",exitCode:null,startupCommand:a?null:r,presetId:l,generation:0};return i({tabs:[...e().tabs,v],activeTabId:d}),d},setTabRunning:(t,n)=>i({tabs:e().tabs.map(r=>r.id===t?{...r,pid:n,status:"running"}:r)}),setTabExited:(t,n)=>i({tabs:e().tabs.map(r=>r.id===t?{...r,status:"exited",exitCode:n}:r)}),closeTab:t=>{var l;window.api.pty.kill(t),window.api.watchers.killTab(t).catch(()=>{}),window.api.transcripts.closeTab(t).catch(()=>{}),di.getState().dropTab(t);const n=e().tabs.filter(p=>p.id!==t),r=e().activeTabId===t?((l=n[n.length-1])==null?void 0:l.id)??null:e().activeTabId;i({tabs:n,activeTabId:r})},setActive:t=>i({activeTabId:t}),restartTab:t=>{const n=e().tabs.find(p=>p.id===t);if(!n)return;window.api.pty.kill(t);const r=crypto.randomUUID(),l=p=>{i({tabs:e().tabs.map(a=>a.id===t?{...a,sessionId:r,pid:null,status:"spawning",exitCode:null,startupCommand:p,generation:a.generation+1}:a)})};n.presetId?s1(n.presetId).then(p=>{l(p?r1(p,{sessionId:r,cwd:n.cwd}):`claude --dangerously-skip-permissions --session-id ${Po(r)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Po(r)}`)},reorderTab:(t,n)=>{const r=[...e().tabs];if(t<0||t>=r.length||n<0||n>=r.length||t===n)return;const[l]=r.splice(t,1);r.splice(n,0,l),i({tabs:r})},restoreTabs:(t,n)=>i({tabs:t,activeTabId:n,hydrated:!0}),wakeTab:async(t,n)=>{var a;const r=e().tabs.find(d=>d.id===t);if(!r||r.status!=="dormant")return;(a=di.getState().chats[t])!=null&&a.running&&(await window.api.chat.cancel(t),lt.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:p}=await v1({cwd:r.cwd,sessionId:r.sessionId},!1,n??qg());i({tabs:e().tabs.map(d=>d.id===t?{...d,sessionId:l,status:"spawning",startupCommand:p,generation:d.generation+1}:d)})},sleepTab:t=>{const n=e().tabs.find(r=>r.id===t);!n||n.status==="dormant"||(window.api.pty.kill(t),i({tabs:e().tabs.map(r=>r.id===t?{...r,pid:null,status:"dormant"}:r)}))},newSession:t=>{e().tabs.find(r=>r.id===t)&&i({tabs:e().tabs.map(r=>r.id===t?{...r,sessionId:crypto.randomUUID()}:r)})},addSessionToProject:(t,n)=>e().addTab({cwd:t,startupCommand:null,dormant:!0,...n})}));async function M_(){var t;if(xt.getState().hydrated)return;try{const{tabs:n,activeTabId:r,freshStart:l}=await window.api.sessions.load();if(n.length>0){const a=(await Promise.all(n.map(async f=>{try{const{sessionId:v}=await v1(f,l);return{id:f.id,sessionId:v,cwd:f.cwd,label:f.label,presetId:f.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(v){return console.warn("[sessions] dropping malformed persisted tab:",f==null?void 0:f.id,v),null}}))).filter(f=>f!==null),d=r&&a.find(f=>f.id===r)?r:((t=a[0])==null?void 0:t.id)??null;xt.getState().restoreTabs(a,d)}else xt.setState({hydrated:!0})}catch(n){console.warn("[sessions] hydrate failed:",n),xt.setState({hydrated:!0})}const i=()=>{const{tabs:n,activeTabId:r}=xt.getState(),l=n.map(p=>({id:p.id,sessionId:p.sessionId,cwd:p.cwd,label:p.label,presetId:p.presetId}));window.api.sessions.save({tabs:l,activeTabId:r}).catch(p=>{console.warn("[sessions] save failed:",p)})};let e=null;xt.subscribe((n,r)=>{n.hydrated&&(n.tabs===r.tabs&&n.activeTabId===r.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(i,200)))}),i()}const pE=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:M_,useSessions:xt},Symbol.toStringTag,{value:"Module"})),cy=200,fE=/\x1b\[[0-9;]*m/g;function mE(i){return i.replace(fE,"")}const Tf=In((i,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(i({initialized:!0}),window.api.watchers.onLine(t=>e().ingestLine(t)),window.api.watchers.onClosed(({watcherId:t})=>e().closed(t)))},add:async({tabId:t,label:n,command:r,cwd:l})=>{try{const p=await window.api.watchers.add({tabId:t,label:n,command:r,cwd:l??null}),a={watcherId:p.watcherId,tabId:p.tabId,label:p.label,command:p.command,cwd:p.cwd,pid:p.pid,startedAt:p.startedAt,lineCount:0,lines:[],lastLineAt:null};return i({watchers:{...e().watchers,[a.watcherId]:a}}),a}catch(p){return console.error("[watchers] add failed:",p),lt.error("Failed to add watcher"),null}},remove:async t=>{try{await window.api.watchers.remove(t)}catch(r){console.error("[watchers] remove failed:",r);const l=r instanceof Error?r.message:String(r);lt.error(`Could not remove watcher: ${l}`)}const n={...e().watchers};delete n[t],i({watchers:n})},watchersForTab:t=>Object.values(e().watchers).filter(n=>n.tabId===t),ingestLine:t=>{const n=e().watchers[t.watcherId];if(!n)return;const r=mE(t.line),l=n.lines.length>=cy?[...n.lines.slice(n.lines.length-cy+1),{line:r,ts:t.ts}]:[...n.lines,{line:r,ts:t.ts}];i({watchers:{...e().watchers,[t.watcherId]:{...n,lines:l,lineCount:n.lineCount+1,lastLineAt:t.ts}}})},closed:t=>{if(!e().watchers[t])return;const n={...e().watchers};delete n[t],i({watchers:n})}})),Jr=["home"],Kp=["project"],gE=["home","project"],Kf=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Jr},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:Kp},{key:"terminal",group:"Workspace",label:"Sessions",icon:"terminal",hint:"Independent goal-scoped sessions for this project",faces:Kp},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit — starts at your home folder from Home, the active project from a Tab",faces:gE},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"This project's live PRD queue + scheduler policy",faces:Kp},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Jr},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Your ~/.claude/CLAUDE.md — house rules for every session on this machine",faces:Jr},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Jr},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Jr},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Jr},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Jr},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Kp},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Jr},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window — per-session model lives in Agent Library",faces:Jr},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Jr},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Session intent tags and their /develop behavior",faces:Jr},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:Kp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Jr}];function vE(i){return Kf.filter(e=>e.faces.includes(i)).map(e=>{var t,n;return{...e,label:((t=e.labelByFace)==null?void 0:t[i])??e.label,hint:((n=e.hintByFace)==null?void 0:n[i])??e.hint}})}const _E=Object.fromEntries(Kf.map(i=>[i.key,i.group]));function bE(i){const e=Kf.find(t=>t.key===i);return e!=null&&e.faces.length===1&&e.faces[0]==="home"}function wE(i){const e=Kf.find(t=>t.key===i);return e!=null&&e.faces.length===1&&e.faces[0]==="project"}const Wv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},_1=["overview","project-home","terminal","scheduler","history","skills","plugins","mcp","hooks","memory","projects","system-prompt","permissions","settings","agent-library","tag-library","bilko-host","voice","editor"],yE={editor:"Editor"},xE=Object.fromEntries(Kf.map(i=>[i.key,i.label])),SE=Object.fromEntries(_1.map(i=>[i,yE[i]??xE[i]??i])),b1="~/.claude/session-manager/app-prefs.json";async function w1(){var i,e;if(typeof window>"u"||!((e=(i=window.api)==null?void 0:i.config)!=null&&e.readJson))return{};try{const t=await window.api.config.readJson(b1);if(t!=null&&t.exists&&t.data&&typeof t.data=="object")return t.data}catch{}return{}}async function oL(i){var t,n;if(typeof window>"u"||!((n=(t=window.api)==null?void 0:t.config)!=null&&n.writeJson))return;const e=await w1();await window.api.config.writeJson(b1,{...e,...i})}const id=_1.map(i=>({id:i,title:SE[i],component:"screen"}));function dy(i){return i==="overview"||bE(i)?{navFace:"home"}:wE(i)?{navFace:"project"}:{}}const Ei=In((i,e)=>{var t;return{panels:[...id],focusedPanelId:((t=id[0])==null?void 0:t.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:n=>i({epicsWorkspaceOpen:n}),navFace:"home",setNavFace:n=>i({navFace:n}),openPanel:n=>{e().panels.some(l=>l.id===n)&&i(l=>({focusedPanelId:n,focusToken:l.focusToken+1,...dy(n)}))},openProjectPanel:n=>{e().panels.some(l=>l.id===n)&&i(l=>({focusedPanelId:n,focusToken:l.focusToken+1,navFace:"project"}))},focusPanel:n=>{e().panels.some(l=>l.id===n)&&i({focusedPanelId:n,...dy(n)})},resetLayout:()=>{i(n=>{var r;return{resetToken:n.resetToken+1,focusedPanelId:((r=id[0])==null?void 0:r.id)??null,focusToken:n.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var r;(await w1()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((r=id[0])==null?void 0:r.id)??null)&&i({focusedPanelId:"overview",navFace:"home"})}}});function CE(i){return Ei.getState().panels.find(e=>e.id===i)}function kE(i,e,t="project"){return i==="projects"&&e===null&&t==="project"}function rs({name:i,size:e=17,stroke:t=1.6,className:n}){const r={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",className:n};switch(i){case"home":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M4 11l8-7 8 7"}),h.jsx("path",{d:"M6 10v9h12v-9"}),h.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),h.jsx("path",{d:"M7 10l3 2-3 2"}),h.jsx("path",{d:"M13 14h4"})]});case"skills":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M12 7v5l3 2"}),h.jsx("path",{d:"M4 6l2 2"})]});case"usage":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),h.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),h.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),h.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),h.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"8",cy:"12",r:"4"}),h.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),h.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"11",cy:"11",r:"6"}),h.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return h.jsx("svg",{...r,children:h.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M7 3h7l4 4v14H7z"}),h.jsx("path",{d:"M14 3v4h4"})]});case"play":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),h.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),h.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),h.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"3"}),h.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),h.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"system-prompt":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),h.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),h.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),h.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),h.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"wifi":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),h.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M9 12h6"}),h.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),h.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"target":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),h.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"eye":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"arrowleft":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),h.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),h.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return h.jsx("svg",{...r,children:h.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12h14"})});case"paperclip":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});case"expand":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M8 3H3v5"}),h.jsx("path",{d:"M16 3h5v5"}),h.jsx("path",{d:"M8 21H3v-5"}),h.jsx("path",{d:"M16 21h5v-5"})]});case"collapse":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M3 8h5V3"}),h.jsx("path",{d:"M21 8h-5V3"}),h.jsx("path",{d:"M3 16h5v5"}),h.jsx("path",{d:"M21 16h-5v5"})]});default:return null}}const EE=4,uy=40,hy=6;function TE(i){const{onReorder:e,onActivate:t}=i,n=G.useRef(null),r=G.useRef(null),l=G.useRef(0),p=G.useRef(0),[a,d]=G.useState(!1),[,f]=G.useState(0),v=G.useRef(t);v.current=t;const m=G.useCallback(()=>n.current?Array.from(n.current.querySelectorAll("[data-drag-index]")):[],[]),y=G.useCallback((b,C,w)=>{for(let x=0;x<C.length;x++){const $=C[x].left+C[x].width/2;if(b<$)return x<=w?x:x-1}return C.length-1},[]),D=G.useCallback(()=>{const b=r.current,C=n.current;if(!(b!=null&&b.active)||!C)return;const w=C.getBoundingClientRect(),x=b.startX+b.deltaX,$=x-w.left,R=w.right-x;$<uy?C.scrollLeft-=hy:R<uy&&(C.scrollLeft+=hy),l.current=requestAnimationFrame(D)},[]);G.useEffect(()=>{const b=n.current;if(!b)return;let C=!1;const w=()=>{C||(C=!0,p.current=requestAnimationFrame(()=>{C=!1,f(R=>R+1)}))},x=R=>{var U;const N=r.current;if(!N)return;const L=R.clientX-N.startX;if(!N.active&&Math.abs(L)<EE)return;if(!N.active){N.active=!0,N.tabRects=m().map(oe=>oe.getBoundingClientRect()),d(!0);try{(U=n.current)==null||U.setPointerCapture(N.pointerId)}catch{}l.current=requestAnimationFrame(D)}N.deltaX=L;const j=N.tabRects[N.fromIndex],H=j.left+j.width/2+L;N.currentIndex=y(H,N.tabRects,N.fromIndex),w()},$=R=>{const N=r.current;if(N&&N.pointerId===R.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(p.current);try{b.releasePointerCapture(N.pointerId)}catch{}N.active&&N.fromIndex!==N.currentIndex?e(N.fromIndex,N.currentIndex):v.current(N.fromIndex),r.current=null,d(!1),f(L=>L+1)}};return b.addEventListener("pointermove",x),b.addEventListener("pointerup",$),b.addEventListener("pointercancel",$),()=>{b.removeEventListener("pointermove",x),b.removeEventListener("pointerup",$),b.removeEventListener("pointercancel",$),cancelAnimationFrame(l.current),cancelAnimationFrame(p.current)}},[e,m,y,D]);const k=G.useCallback((b,C)=>{b.button!==0||b.target.closest("button")||(r.current={active:!1,fromIndex:C,currentIndex:C,startX:b.clientX,deltaX:0,tabRects:[],pointerId:b.pointerId})},[]);return{getTabDragProps:G.useCallback(b=>{var x;const C=r.current,w={};if(C!=null&&C.active)if(b===C.fromIndex)w.transform=`translateX(${C.deltaX}px) scale(1.03)`,w.zIndex=10,w.opacity=.85,w.boxShadow="0 2px 8px rgba(0,0,0,0.4)",w.position="relative",w.pointerEvents="none";else{const $=C.fromIndex,R=C.currentIndex,L=(((x=C.tabRects[$])==null?void 0:x.width)??0)+4;w.transition="transform 0.15s ease",$<R&&b>$&&b<=R?w.transform=`translateX(-${L}px)`:$>R&&b>=R&&b<$?w.transform=`translateX(${L}px)`:w.transform="translateX(0)"}return{onPointerDown:$=>k($,b),style:w,"data-drag-index":b}},[k]),isDragging:a,containerRef:n}}function DE(){const[i,e]=G.useState(()=>typeof document>"u"?!0:document.visibilityState!=="hidden");return G.useEffect(()=>{if(typeof document>"u")return;const t=()=>e(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[]),i}const $E=3e4;function AE(){const i=xt(w=>w.tabs),e=xt(w=>w.activeTabId),t=xt(w=>w.closeTab),n=xt(w=>w.setActive),r=xt(w=>w.reorderTab),l=Tf(w=>w.watchers),p=Ei(w=>w.openPanel),a=Ei(w=>w.openProjectPanel),d=Ei(w=>w.setEpicsWorkspaceOpen),f=Ei(w=>w.navFace==="home"),[v,m]=G.useState(()=>Date.now()),y=DE();G.useEffect(()=>{if(!y)return;m(Date.now());const w=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(w)},[y]);const D=w=>{for(const x of Object.values(l))if(x.tabId===w&&x.lastLineAt&&v-x.lastLineAt<$E)return!0;return!1},{getTabDragProps:k,isDragging:T,containerRef:b}=TE({tabCount:i.length,onReorder:r,onActivate:w=>{const x=i[w];x&&(n(x.id),d(!1),a("terminal"))}}),C=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return h.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[h.jsxs("button",{onClick:()=>p("overview"),title:"This machine — home","aria-current":f?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 py-1.5 mb-1 rounded-full text-[13px] shrink-0 transition-colors ${f?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[h.jsx(rs,{name:"home",className:"w-[15px] h-[15px]"}),h.jsx("span",{children:"Home"})]}),h.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),h.jsx("div",{ref:b,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${T?"cursor-grabbing":""}`,children:i.map((w,x)=>{const $=w.id===e,R=k(x),N=C[x%C.length];return h.jsxs("div",{...R,style:R.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${T?"":"cursor-grab"} ${$?"bg-bg text-fg font-medium relative z-10 -mb-px border border-accent shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:w.cwd,"aria-current":$?"true":void 0,children:[h.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:N,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:w.status==="spawning"?.55:1}}),h.jsx("span",{className:"truncate max-w-[200px]",children:w.label}),w.status==="spawning"&&h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),D(w.id)&&h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),h.jsx("button",{onClick:L=>{L.stopPropagation(),t(w.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${w.label}`,children:"×"})]},w.id)})}),h.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[h.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),h.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.67.0"]})]})]})}var Uv={},Yp={},py;function y1(){if(py)return Yp;py=1,Object.defineProperty(Yp,"__esModule",{value:!0}),Yp.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let t="/";return e&&(t=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Yp.baseAssetPath=t,Yp}var Xp={},fy;function zb(){if(fy)return Xp;fy=1,Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.defaultModelFetcher=void 0;const i=e=>fetch(e).then(t=>t.arrayBuffer());return Xp.defaultModelFetcher=i,Xp}var Ha={},Jp={},my;function Yf(){if(my)return Jp;my=1,Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.log=void 0;const i=e=>t=>{console.log(`VAD | ${e} >`,t)};return Jp.log={error:i("error"),debug:i("debug"),warn:i("warn")},Jp}var Zp={},gy;function mv(){if(gy)return Zp;gy=1,Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.Message=void 0;var i;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(i||(Zp.Message=i={})),Zp}var vy;function Bb(){if(vy)return Ha;vy=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.FrameProcessor=Ha.validateOptions=Ha.defaultFrameProcessorOptions=void 0;const i=Yf(),e=mv();Ha.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function t(p){(p.positiveSpeechThreshold<0||p.positiveSpeechThreshold>1)&&i.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(p.negativeSpeechThreshold<0||p.negativeSpeechThreshold>p.positiveSpeechThreshold)&&i.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),p.preSpeechPadMs<0&&i.log.error("preSpeechPadMs should be positive"),p.redemptionMs<0&&i.log.error("redemptionMs should be positive"),p.minSpeechMs<0&&i.log.error("minSpeechMs should be positive")}Ha.validateOptions=t;const n=p=>{const a=p.reduce((f,v)=>(f.push(f.at(-1)+v.length),f),[0]),d=new Float32Array(a.at(-1));return p.forEach((f,v)=>{const m=a[v];d.set(f,m)}),d};function r(p,a){const d=Math.floor(p.redemptionMs/a),f=Math.floor(p.preSpeechPadMs/a),v=Math.floor(p.minSpeechMs/a);return{redemptionFrames:d,preSpeechPadFrames:f,minSpeechFrames:v}}class l{constructor(a,d,f,v){this.modelProcessFunc=a,this.modelResetFunc=d,this.options=f,this.msPerFrame=v,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=k=>{this.options={...this.options,...k};const{redemptionFrames:T,preSpeechPadFrames:b,minSpeechFrames:C}=r(this.options,this.msPerFrame);this.redemptionFrames=T,this.preSpeechPadFrames=b,this.minSpeechFrames=C},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=k=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(k):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=k=>{const T=this.audioBuffer;this.audioBuffer=[];const b=this.speaking;if(this.reset(),b)if(T.reduce((w,x)=>x.isSpeech?w+1:w,0)>=this.minSpeechFrames){const w=n(T.map(x=>x.frame));k({msg:e.Message.SpeechEnd,audio:w})}else k({msg:e.Message.VADMisfire});return{}},this.process=async(k,T)=>{if(!this.active)return;const b=await this.modelProcessFunc(k),C=b.isSpeech>=this.options.positiveSpeechThreshold;if(T({probs:b,msg:e.Message.FrameProcessed,frame:k}),this.audioBuffer.push({frame:k,isSpeech:C}),C&&(this.speechFrameCount++,this.redemptionCounter=0),C&&!this.speaking&&(this.speaking=!0,T({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,T({msg:e.Message.SpeechRealStart})),b.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const w=this.audioBuffer;if(this.audioBuffer=[],w.reduce(($,R)=>R.isSpeech?$+1:$,0)>=this.minSpeechFrames){const $=n(w.map(R=>R.frame));T({msg:e.Message.SpeechEnd,audio:$})}else T({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:m,preSpeechPadFrames:y,minSpeechFrames:D}=r(this.options,this.msPerFrame);this.redemptionFrames=m,this.preSpeechPadFrames=y,this.minSpeechFrames=D,this.reset()}}return Ha.FrameProcessor=l,Ha}var Wa={};function eo(i){throw new Error('Could not dynamically require "'+i+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Vv={exports:{}};/*!
|
|
56
|
+
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:n})}),window.api.chat.onError(({tabId:i,sessionId:e,message:t})=>{m1(i,e,t)}),window.api.chat.onNotice(({tabId:i,sessionId:e,message:t})=>{Yg(i,e,t)}),window.api.chat.onExternalSend(({tabId:i,prompt:e})=>{var r,l,p,a;const t=xt.getState().tabs.find(d=>d.id===i);if(t){di.getState().send({tabId:i,sessionId:t.sessionId,cwd:t.cwd,prompt:e,external:!0});return}const n=Yt.getState().sessions[i];if(n){if(n.status==="completed"){(l=(r=window.api)==null?void 0:r.logs)==null||l.write("chat","warn",`external send ignored: Epic ${i} is completed/archived — its claudeSessionId is dead`);return}di.getState().send({tabId:i,sessionId:n.claudeSessionId,cwd:n.cwd,prompt:e,external:!0});return}(a=(p=window.api)==null?void 0:p.logs)==null||a.write("chat","warn",`external send ignored: ${i} matches neither an open tab nor a known Epic`)}));function hE(i){const e=i.split("/").filter(Boolean);return e[e.length-1]||i}async function v1(i,e=!1,t=qg()){let n=!e;n&&(n=await fv(i.cwd,i.sessionId));const r=e&&!n?crypto.randomUUID():i.sessionId,l=n?`claude --dangerously-skip-permissions --resume ${Po(r)} --model ${t}`:`claude --dangerously-skip-permissions --session-id ${Po(r)} --model ${t}`;return{sessionId:r,startupCommand:l}}const xt=In((i,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(t,n)=>{i(r=>({pendingRawCommand:{...r.pendingRawCommand,[t]:n}}))},consumeRawCommand:t=>{const n=e().pendingRawCommand[t];return n===void 0?null:(i(r=>{const l={...r.pendingRawCommand};return delete l[t],{pendingRawCommand:l}}),n)},addTab:({id:t,cwd:n,startupCommand:r,presetId:l=null,label:p,dormant:a=!1})=>{const d=t??crypto.randomUUID();if(e().tabs.find(m=>m.id===d))return i({activeTabId:d}),d;a&&r&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",r);const v={id:d,sessionId:d,label:p??hE(n),cwd:n,pid:null,status:a?"dormant":"spawning",exitCode:null,startupCommand:a?null:r,presetId:l,generation:0};return i({tabs:[...e().tabs,v],activeTabId:d}),d},setTabRunning:(t,n)=>i({tabs:e().tabs.map(r=>r.id===t?{...r,pid:n,status:"running"}:r)}),setTabExited:(t,n)=>i({tabs:e().tabs.map(r=>r.id===t?{...r,status:"exited",exitCode:n}:r)}),closeTab:t=>{var l;window.api.pty.kill(t),window.api.watchers.killTab(t).catch(()=>{}),window.api.transcripts.closeTab(t).catch(()=>{}),di.getState().dropTab(t);const n=e().tabs.filter(p=>p.id!==t),r=e().activeTabId===t?((l=n[n.length-1])==null?void 0:l.id)??null:e().activeTabId;i({tabs:n,activeTabId:r})},setActive:t=>i({activeTabId:t}),restartTab:t=>{const n=e().tabs.find(p=>p.id===t);if(!n)return;window.api.pty.kill(t);const r=crypto.randomUUID(),l=p=>{i({tabs:e().tabs.map(a=>a.id===t?{...a,sessionId:r,pid:null,status:"spawning",exitCode:null,startupCommand:p,generation:a.generation+1}:a)})};n.presetId?s1(n.presetId).then(p=>{l(p?r1(p,{sessionId:r,cwd:n.cwd}):`claude --dangerously-skip-permissions --session-id ${Po(r)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Po(r)}`)},reorderTab:(t,n)=>{const r=[...e().tabs];if(t<0||t>=r.length||n<0||n>=r.length||t===n)return;const[l]=r.splice(t,1);r.splice(n,0,l),i({tabs:r})},restoreTabs:(t,n)=>i({tabs:t,activeTabId:n,hydrated:!0}),wakeTab:async(t,n)=>{var a;const r=e().tabs.find(d=>d.id===t);if(!r||r.status!=="dormant")return;(a=di.getState().chats[t])!=null&&a.running&&(await window.api.chat.cancel(t),lt.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:p}=await v1({cwd:r.cwd,sessionId:r.sessionId},!1,n??qg());i({tabs:e().tabs.map(d=>d.id===t?{...d,sessionId:l,status:"spawning",startupCommand:p,generation:d.generation+1}:d)})},sleepTab:t=>{const n=e().tabs.find(r=>r.id===t);!n||n.status==="dormant"||(window.api.pty.kill(t),i({tabs:e().tabs.map(r=>r.id===t?{...r,pid:null,status:"dormant"}:r)}))},newSession:t=>{e().tabs.find(r=>r.id===t)&&i({tabs:e().tabs.map(r=>r.id===t?{...r,sessionId:crypto.randomUUID()}:r)})},addSessionToProject:(t,n)=>e().addTab({cwd:t,startupCommand:null,dormant:!0,...n})}));async function M_(){var t;if(xt.getState().hydrated)return;try{const{tabs:n,activeTabId:r,freshStart:l}=await window.api.sessions.load();if(n.length>0){const a=(await Promise.all(n.map(async f=>{try{const{sessionId:v}=await v1(f,l);return{id:f.id,sessionId:v,cwd:f.cwd,label:f.label,presetId:f.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(v){return console.warn("[sessions] dropping malformed persisted tab:",f==null?void 0:f.id,v),null}}))).filter(f=>f!==null),d=r&&a.find(f=>f.id===r)?r:((t=a[0])==null?void 0:t.id)??null;xt.getState().restoreTabs(a,d)}else xt.setState({hydrated:!0})}catch(n){console.warn("[sessions] hydrate failed:",n),xt.setState({hydrated:!0})}const i=()=>{const{tabs:n,activeTabId:r}=xt.getState(),l=n.map(p=>({id:p.id,sessionId:p.sessionId,cwd:p.cwd,label:p.label,presetId:p.presetId}));window.api.sessions.save({tabs:l,activeTabId:r}).catch(p=>{console.warn("[sessions] save failed:",p)})};let e=null;xt.subscribe((n,r)=>{n.hydrated&&(n.tabs===r.tabs&&n.activeTabId===r.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(i,200)))}),i()}const pE=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:M_,useSessions:xt},Symbol.toStringTag,{value:"Module"})),cy=200,fE=/\x1b\[[0-9;]*m/g;function mE(i){return i.replace(fE,"")}const Tf=In((i,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(i({initialized:!0}),window.api.watchers.onLine(t=>e().ingestLine(t)),window.api.watchers.onClosed(({watcherId:t})=>e().closed(t)))},add:async({tabId:t,label:n,command:r,cwd:l})=>{try{const p=await window.api.watchers.add({tabId:t,label:n,command:r,cwd:l??null}),a={watcherId:p.watcherId,tabId:p.tabId,label:p.label,command:p.command,cwd:p.cwd,pid:p.pid,startedAt:p.startedAt,lineCount:0,lines:[],lastLineAt:null};return i({watchers:{...e().watchers,[a.watcherId]:a}}),a}catch(p){return console.error("[watchers] add failed:",p),lt.error("Failed to add watcher"),null}},remove:async t=>{try{await window.api.watchers.remove(t)}catch(r){console.error("[watchers] remove failed:",r);const l=r instanceof Error?r.message:String(r);lt.error(`Could not remove watcher: ${l}`)}const n={...e().watchers};delete n[t],i({watchers:n})},watchersForTab:t=>Object.values(e().watchers).filter(n=>n.tabId===t),ingestLine:t=>{const n=e().watchers[t.watcherId];if(!n)return;const r=mE(t.line),l=n.lines.length>=cy?[...n.lines.slice(n.lines.length-cy+1),{line:r,ts:t.ts}]:[...n.lines,{line:r,ts:t.ts}];i({watchers:{...e().watchers,[t.watcherId]:{...n,lines:l,lineCount:n.lineCount+1,lastLineAt:t.ts}}})},closed:t=>{if(!e().watchers[t])return;const n={...e().watchers};delete n[t],i({watchers:n})}})),Jr=["home"],Kp=["project"],gE=["home","project"],Kf=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Jr},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:Kp},{key:"terminal",group:"Workspace",label:"Sessions",icon:"terminal",hint:"Independent goal-scoped sessions for this project",faces:Kp},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit — starts at your home folder from Home, the active project from a Tab",faces:gE},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"This project's live PRD queue + scheduler policy",faces:Kp},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Jr},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Your ~/.claude/CLAUDE.md — house rules for every session on this machine",faces:Jr},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Jr},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Jr},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Jr},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Jr},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Kp},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Jr},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window — per-session model lives in Agent Library",faces:Jr},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Jr},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Session intent tags and their /develop behavior",faces:Jr},{key:"bilko-host",group:"Configure",label:"Host on Bilko.run",icon:"link",hint:"Publish this project's Marketing page to bilko.run",faces:Kp},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Jr}];function vE(i){return Kf.filter(e=>e.faces.includes(i)).map(e=>{var t,n;return{...e,label:((t=e.labelByFace)==null?void 0:t[i])??e.label,hint:((n=e.hintByFace)==null?void 0:n[i])??e.hint}})}const _E=Object.fromEntries(Kf.map(i=>[i.key,i.group]));function bE(i){const e=Kf.find(t=>t.key===i);return e!=null&&e.faces.length===1&&e.faces[0]==="home"}function wE(i){const e=Kf.find(t=>t.key===i);return e!=null&&e.faces.length===1&&e.faces[0]==="project"}const Wv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},_1=["overview","project-home","terminal","scheduler","history","skills","plugins","mcp","hooks","memory","projects","system-prompt","permissions","settings","agent-library","tag-library","bilko-host","voice","editor"],yE={editor:"Editor"},xE=Object.fromEntries(Kf.map(i=>[i.key,i.label])),SE=Object.fromEntries(_1.map(i=>[i,yE[i]??xE[i]??i])),b1="~/.claude/session-manager/app-prefs.json";async function w1(){var i,e;if(typeof window>"u"||!((e=(i=window.api)==null?void 0:i.config)!=null&&e.readJson))return{};try{const t=await window.api.config.readJson(b1);if(t!=null&&t.exists&&t.data&&typeof t.data=="object")return t.data}catch{}return{}}async function oL(i){var t,n;if(typeof window>"u"||!((n=(t=window.api)==null?void 0:t.config)!=null&&n.writeJson))return;const e=await w1();await window.api.config.writeJson(b1,{...e,...i})}const id=_1.map(i=>({id:i,title:SE[i],component:"screen"}));function dy(i){return i==="overview"||bE(i)?{navFace:"home"}:wE(i)?{navFace:"project"}:{}}const Ei=In((i,e)=>{var t;return{panels:[...id],focusedPanelId:((t=id[0])==null?void 0:t.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:n=>i({epicsWorkspaceOpen:n}),navFace:"home",setNavFace:n=>i({navFace:n}),openPanel:n=>{e().panels.some(l=>l.id===n)&&i(l=>({focusedPanelId:n,focusToken:l.focusToken+1,...dy(n)}))},openProjectPanel:n=>{e().panels.some(l=>l.id===n)&&i(l=>({focusedPanelId:n,focusToken:l.focusToken+1,navFace:"project"}))},focusPanel:n=>{e().panels.some(l=>l.id===n)&&i({focusedPanelId:n,...dy(n)})},resetLayout:()=>{i(n=>{var r;return{resetToken:n.resetToken+1,focusedPanelId:((r=id[0])==null?void 0:r.id)??null,focusToken:n.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var r;(await w1()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((r=id[0])==null?void 0:r.id)??null)&&i({focusedPanelId:"overview",navFace:"home"})}}});function CE(i){return Ei.getState().panels.find(e=>e.id===i)}function kE(i,e,t="project"){return i==="projects"&&e===null&&t==="project"}function rs({name:i,size:e=17,stroke:t=1.6,className:n}){const r={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:t,strokeLinecap:"round",strokeLinejoin:"round",className:n};switch(i){case"home":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M4 11l8-7 8 7"}),h.jsx("path",{d:"M6 10v9h12v-9"}),h.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),h.jsx("path",{d:"M7 10l3 2-3 2"}),h.jsx("path",{d:"M13 14h4"})]});case"skills":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M12 7v5l3 2"}),h.jsx("path",{d:"M4 6l2 2"})]});case"usage":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),h.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),h.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),h.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),h.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"8",cy:"12",r:"4"}),h.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),h.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"11",cy:"11",r:"6"}),h.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return h.jsx("svg",{...r,children:h.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M7 3h7l4 4v14H7z"}),h.jsx("path",{d:"M14 3v4h4"})]});case"play":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),h.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),h.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),h.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"3"}),h.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),h.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"system-prompt":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),h.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),h.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),h.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),h.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"wifi":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),h.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M9 12h6"}),h.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),h.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"target":return h.jsxs("svg",{...r,children:[h.jsx("circle",{cx:"12",cy:"12",r:"8"}),h.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),h.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"eye":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"arrowleft":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),h.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return h.jsxs("svg",{...r,children:[h.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),h.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return h.jsx("svg",{...r,children:h.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M5 12h14"})});case"paperclip":return h.jsx("svg",{...r,children:h.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});case"expand":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M8 3H3v5"}),h.jsx("path",{d:"M16 3h5v5"}),h.jsx("path",{d:"M8 21H3v-5"}),h.jsx("path",{d:"M16 21h5v-5"})]});case"collapse":return h.jsxs("svg",{...r,children:[h.jsx("path",{d:"M3 8h5V3"}),h.jsx("path",{d:"M21 8h-5V3"}),h.jsx("path",{d:"M3 16h5v5"}),h.jsx("path",{d:"M21 16h-5v5"})]});default:return null}}const EE=4,uy=40,hy=6;function TE(i){const{onReorder:e,onActivate:t}=i,n=G.useRef(null),r=G.useRef(null),l=G.useRef(0),p=G.useRef(0),[a,d]=G.useState(!1),[,f]=G.useState(0),v=G.useRef(t);v.current=t;const m=G.useCallback(()=>n.current?Array.from(n.current.querySelectorAll("[data-drag-index]")):[],[]),y=G.useCallback((b,C,w)=>{for(let x=0;x<C.length;x++){const $=C[x].left+C[x].width/2;if(b<$)return x<=w?x:x-1}return C.length-1},[]),D=G.useCallback(()=>{const b=r.current,C=n.current;if(!(b!=null&&b.active)||!C)return;const w=C.getBoundingClientRect(),x=b.startX+b.deltaX,$=x-w.left,R=w.right-x;$<uy?C.scrollLeft-=hy:R<uy&&(C.scrollLeft+=hy),l.current=requestAnimationFrame(D)},[]);G.useEffect(()=>{const b=n.current;if(!b)return;let C=!1;const w=()=>{C||(C=!0,p.current=requestAnimationFrame(()=>{C=!1,f(R=>R+1)}))},x=R=>{var U;const N=r.current;if(!N)return;const L=R.clientX-N.startX;if(!N.active&&Math.abs(L)<EE)return;if(!N.active){N.active=!0,N.tabRects=m().map(oe=>oe.getBoundingClientRect()),d(!0);try{(U=n.current)==null||U.setPointerCapture(N.pointerId)}catch{}l.current=requestAnimationFrame(D)}N.deltaX=L;const j=N.tabRects[N.fromIndex],H=j.left+j.width/2+L;N.currentIndex=y(H,N.tabRects,N.fromIndex),w()},$=R=>{const N=r.current;if(N&&N.pointerId===R.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(p.current);try{b.releasePointerCapture(N.pointerId)}catch{}N.active&&N.fromIndex!==N.currentIndex?e(N.fromIndex,N.currentIndex):v.current(N.fromIndex),r.current=null,d(!1),f(L=>L+1)}};return b.addEventListener("pointermove",x),b.addEventListener("pointerup",$),b.addEventListener("pointercancel",$),()=>{b.removeEventListener("pointermove",x),b.removeEventListener("pointerup",$),b.removeEventListener("pointercancel",$),cancelAnimationFrame(l.current),cancelAnimationFrame(p.current)}},[e,m,y,D]);const k=G.useCallback((b,C)=>{b.button!==0||b.target.closest("button")||(r.current={active:!1,fromIndex:C,currentIndex:C,startX:b.clientX,deltaX:0,tabRects:[],pointerId:b.pointerId})},[]);return{getTabDragProps:G.useCallback(b=>{var x;const C=r.current,w={};if(C!=null&&C.active)if(b===C.fromIndex)w.transform=`translateX(${C.deltaX}px) scale(1.03)`,w.zIndex=10,w.opacity=.85,w.boxShadow="0 2px 8px rgba(0,0,0,0.4)",w.position="relative",w.pointerEvents="none";else{const $=C.fromIndex,R=C.currentIndex,L=(((x=C.tabRects[$])==null?void 0:x.width)??0)+4;w.transition="transform 0.15s ease",$<R&&b>$&&b<=R?w.transform=`translateX(-${L}px)`:$>R&&b>=R&&b<$?w.transform=`translateX(${L}px)`:w.transform="translateX(0)"}return{onPointerDown:$=>k($,b),style:w,"data-drag-index":b}},[k]),isDragging:a,containerRef:n}}function DE(){const[i,e]=G.useState(()=>typeof document>"u"?!0:document.visibilityState!=="hidden");return G.useEffect(()=>{if(typeof document>"u")return;const t=()=>e(document.visibilityState!=="hidden");return document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t)},[]),i}const $E=3e4;function AE(){const i=xt(w=>w.tabs),e=xt(w=>w.activeTabId),t=xt(w=>w.closeTab),n=xt(w=>w.setActive),r=xt(w=>w.reorderTab),l=Tf(w=>w.watchers),p=Ei(w=>w.openPanel),a=Ei(w=>w.openProjectPanel),d=Ei(w=>w.setEpicsWorkspaceOpen),f=Ei(w=>w.navFace==="home"),[v,m]=G.useState(()=>Date.now()),y=DE();G.useEffect(()=>{if(!y)return;m(Date.now());const w=window.setInterval(()=>m(Date.now()),1e3);return()=>window.clearInterval(w)},[y]);const D=w=>{for(const x of Object.values(l))if(x.tabId===w&&x.lastLineAt&&v-x.lastLineAt<$E)return!0;return!1},{getTabDragProps:k,isDragging:T,containerRef:b}=TE({tabCount:i.length,onReorder:r,onActivate:w=>{const x=i[w];x&&(n(x.id),d(!1),a("terminal"))}}),C=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return h.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[h.jsxs("button",{onClick:()=>p("overview"),title:"This machine — home","aria-current":f?"true":void 0,"data-testid":"tabbar-machine-home",className:`flex items-center gap-2 px-3.5 py-1.5 mb-1 rounded-full text-[13px] shrink-0 transition-colors ${f?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[h.jsx(rs,{name:"home",className:"w-[15px] h-[15px]"}),h.jsx("span",{children:"Home"})]}),h.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),h.jsx("div",{ref:b,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${T?"cursor-grabbing":""}`,children:i.map((w,x)=>{const $=w.id===e,R=k(x),N=C[x%C.length];return h.jsxs("div",{...R,style:R.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${T?"":"cursor-grab"} ${$?"bg-bg text-fg font-medium relative z-10 -mb-px border border-accent shadow-[inset_0_2px_0_theme(colors.accent.DEFAULT)]":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:w.cwd,"aria-current":$?"true":void 0,children:[h.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:N,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:w.status==="spawning"?.55:1}}),h.jsx("span",{className:"truncate max-w-[200px]",children:w.label}),w.status==="spawning"&&h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),D(w.id)&&h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),h.jsx("button",{onClick:L=>{L.stopPropagation(),t(w.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${w.label}`,children:"×"})]},w.id)})}),h.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[h.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),h.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.68.0"]})]})]})}var Uv={},Yp={},py;function y1(){if(py)return Yp;py=1,Object.defineProperty(Yp,"__esModule",{value:!0}),Yp.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let t="/";return e&&(t=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Yp.baseAssetPath=t,Yp}var Xp={},fy;function zb(){if(fy)return Xp;fy=1,Object.defineProperty(Xp,"__esModule",{value:!0}),Xp.defaultModelFetcher=void 0;const i=e=>fetch(e).then(t=>t.arrayBuffer());return Xp.defaultModelFetcher=i,Xp}var Ha={},Jp={},my;function Yf(){if(my)return Jp;my=1,Object.defineProperty(Jp,"__esModule",{value:!0}),Jp.log=void 0;const i=e=>t=>{console.log(`VAD | ${e} >`,t)};return Jp.log={error:i("error"),debug:i("debug"),warn:i("warn")},Jp}var Zp={},gy;function mv(){if(gy)return Zp;gy=1,Object.defineProperty(Zp,"__esModule",{value:!0}),Zp.Message=void 0;var i;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(i||(Zp.Message=i={})),Zp}var vy;function Bb(){if(vy)return Ha;vy=1,Object.defineProperty(Ha,"__esModule",{value:!0}),Ha.FrameProcessor=Ha.validateOptions=Ha.defaultFrameProcessorOptions=void 0;const i=Yf(),e=mv();Ha.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function t(p){(p.positiveSpeechThreshold<0||p.positiveSpeechThreshold>1)&&i.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(p.negativeSpeechThreshold<0||p.negativeSpeechThreshold>p.positiveSpeechThreshold)&&i.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),p.preSpeechPadMs<0&&i.log.error("preSpeechPadMs should be positive"),p.redemptionMs<0&&i.log.error("redemptionMs should be positive"),p.minSpeechMs<0&&i.log.error("minSpeechMs should be positive")}Ha.validateOptions=t;const n=p=>{const a=p.reduce((f,v)=>(f.push(f.at(-1)+v.length),f),[0]),d=new Float32Array(a.at(-1));return p.forEach((f,v)=>{const m=a[v];d.set(f,m)}),d};function r(p,a){const d=Math.floor(p.redemptionMs/a),f=Math.floor(p.preSpeechPadMs/a),v=Math.floor(p.minSpeechMs/a);return{redemptionFrames:d,preSpeechPadFrames:f,minSpeechFrames:v}}class l{constructor(a,d,f,v){this.modelProcessFunc=a,this.modelResetFunc=d,this.options=f,this.msPerFrame=v,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=k=>{this.options={...this.options,...k};const{redemptionFrames:T,preSpeechPadFrames:b,minSpeechFrames:C}=r(this.options,this.msPerFrame);this.redemptionFrames=T,this.preSpeechPadFrames=b,this.minSpeechFrames=C},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=k=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(k):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=k=>{const T=this.audioBuffer;this.audioBuffer=[];const b=this.speaking;if(this.reset(),b)if(T.reduce((w,x)=>x.isSpeech?w+1:w,0)>=this.minSpeechFrames){const w=n(T.map(x=>x.frame));k({msg:e.Message.SpeechEnd,audio:w})}else k({msg:e.Message.VADMisfire});return{}},this.process=async(k,T)=>{if(!this.active)return;const b=await this.modelProcessFunc(k),C=b.isSpeech>=this.options.positiveSpeechThreshold;if(T({probs:b,msg:e.Message.FrameProcessed,frame:k}),this.audioBuffer.push({frame:k,isSpeech:C}),C&&(this.speechFrameCount++,this.redemptionCounter=0),C&&!this.speaking&&(this.speaking=!0,T({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,T({msg:e.Message.SpeechRealStart})),b.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const w=this.audioBuffer;if(this.audioBuffer=[],w.reduce(($,R)=>R.isSpeech?$+1:$,0)>=this.minSpeechFrames){const $=n(w.map(R=>R.frame));T({msg:e.Message.SpeechEnd,audio:$})}else T({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:m,preSpeechPadFrames:y,minSpeechFrames:D}=r(this.options,this.msPerFrame);this.redemptionFrames=m,this.preSpeechPadFrames=y,this.minSpeechFrames=D,this.reset()}}return Ha.FrameProcessor=l,Ha}var Wa={};function eo(i){throw new Error('Could not dynamically require "'+i+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Vv={exports:{}};/*!
|
|
57
57
|
* ONNX Runtime Web v1.26.0
|
|
58
58
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
59
59
|
* Licensed under the MIT License.
|
|
@@ -2907,7 +2907,7 @@ ${I}`,M=g.createShaderModule({code:P,label:s.name});ni("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 Ey;function OE(){return Ey||(Ey=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof eo<"u"?eo:typeof Proxy<"u"?new Proxy(Y,{get:(se,he)=>(typeof eo<"u"?eo:se)[he]}):Y)(function(Y){if(typeof eo<"u")return eo.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),d=(Y,se)=>()=>(Y&&(se=Y(Y=0)),se),f=(Y,se)=>{for(var he in se)n(Y,he,{get:se[he],enumerable:!0})},v=(Y,se,he,Te)=>{if(se&&typeof se=="object"||typeof se=="function")for(let xe of l(se))!p.call(Y,xe)&&xe!==he&&n(Y,xe,{get:()=>se[xe],enumerable:!(Te=r(se,xe))||Te.enumerable});return Y},m=Y=>v(n({},"__esModule",{value:!0}),Y),y,D,k,T,b,C=d(()=>{y=new Map,D=[],k=(Y,se,he)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Te=y.get(Y);if(Te===void 0)y.set(Y,{backend:se,priority:he});else{if(Te.priority>he)return;if(Te.priority===he&&Te.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${he}`)}if(he>=0){let xe=D.indexOf(Y);xe!==-1&&D.splice(xe,1);for(let Oe=0;Oe<D.length;Oe++)if(y.get(D[Oe]).priority<=he){D.splice(Oe,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},T=async Y=>{let se=y.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let he=!!se.initPromise;try{return he||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Te){return he||(se.error=`${Te}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],he=se.map(Le=>typeof Le=="string"?Le:Le.name),Te=he.length===0?D:he,xe,Oe=[],$e=new Set;for(let Le of Te){let tt=await T(Le);typeof tt=="string"?Oe.push({name:Le,err:tt}):(xe||(xe=tt),xe===tt&&$e.add(Le))}if(!xe)throw new Error(`no available backend found. ERR: ${Oe.map(Le=>`[${Le.name}] ${Le.err}`).join(", ")}`);for(let{name:Le,err:tt}of Oe)he.includes(Le)&&console.warn(`removing requested execution provider "${Le}" from session options because it is not available: ${tt}`);let Ae=se.filter(Le=>$e.has(typeof Le=="string"?Le:Le.name));return[xe,new Proxy(Y,{get:(Le,tt)=>tt==="executionProviders"?Ae:Reflect.get(Le,tt)})]}}),w=d(()=>{C()}),x,$=d(()=>{x="1.26.0"}),R,N,L=d(()=>{$(),R="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);R=Y}},get logLevel(){return R}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,H=d(()=>{L(),j=N}),U,oe,de=d(()=>{U=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=Y.dims[3],he.height=Y.dims[2];let Te=he.getContext("2d");if(Te!=null){let xe,Oe;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2]);let $e=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Le,tt;Ae===void 0||Ae.mean===void 0?Le=[255,255,255,255]:typeof Ae.mean=="number"?Le=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Le=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Le[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?tt=[0,0,0,0]:typeof Ae.bias=="number"?tt=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(tt=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(tt[3]=Ae.bias[3]));let rt=Oe*xe,it=0,qe=rt,It=rt*2,Ne=-1;$e==="RGBA"?(it=0,qe=rt,It=rt*2,Ne=rt*3):$e==="RGB"?(it=0,qe=rt,It=rt*2):$e==="RBG"&&(it=0,It=rt,qe=rt*2);for(let dt=0;dt<Oe;dt++)for(let Ci=0;Ci<xe;Ci++){let Zt=(Y.data[it++]-tt[0])*Le[0],Qt=(Y.data[qe++]-tt[1])*Le[1],ki=(Y.data[It++]-tt[2])*Le[2],Ot=Ne===-1?255:(Y.data[Ne++]-tt[3])*Le[3];Te.fillStyle="rgba("+Zt+","+Qt+","+ki+","+Ot+")",Te.fillRect(Ci,dt,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")},oe=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(he!=null){let xe,Oe,$e;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[1],$e=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2],$e=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Le=se==null?void 0:se.norm,tt,rt;Le===void 0||Le.mean===void 0?tt=[255,255,255,255]:typeof Le.mean=="number"?tt=[Le.mean,Le.mean,Le.mean,Le.mean]:(tt=[Le.mean[0],Le.mean[1],Le.mean[2],255],Le.mean[3]!==void 0&&(tt[3]=Le.mean[3])),Le===void 0||Le.bias===void 0?rt=[0,0,0,0]:typeof Le.bias=="number"?rt=[Le.bias,Le.bias,Le.bias,Le.bias]:(rt=[Le.bias[0],Le.bias[1],Le.bias[2],0],Le.bias[3]!==void 0&&(rt[3]=Le.bias[3]));let it=Oe*xe;if(se!==void 0&&(se.format!==void 0&&$e===4&&se.format!=="RGBA"||$e===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let qe=4,It=0,Ne=1,dt=2,Ci=3,Zt=0,Qt=it,ki=it*2,Ot=-1;Ae==="RGBA"?(Zt=0,Qt=it,ki=it*2,Ot=it*3):Ae==="RGB"?(Zt=0,Qt=it,ki=it*2):Ae==="RBG"&&(Zt=0,ki=it,Qt=it*2),Te=he.createImageData(xe,Oe);for(let Ri=0;Ri<Oe*xe;It+=qe,Ne+=qe,dt+=qe,Ci+=qe,Ri++)Te.data[It]=(Y.data[Zt++]-rt[0])*tt[0],Te.data[Ne]=(Y.data[Qt++]-rt[1])*tt[1],Te.data[dt]=(Y.data[ki++]-rt[2])*tt[2],Te.data[Ci]=Ot===-1?255:(Y.data[Ot++]-rt[3])*tt[3]}else throw new Error("Can not access image data");return Te}}),Z,me,ie,ue,Ce,Ee,W=d(()=>{Ie(),Z=(Y,se)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(se.height===void 0||se.width===void 0)throw new Error("Image height and width must be defined");if(se.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:he,width:Te}=se,xe=se.norm??{mean:255,bias:0},Oe,$e;typeof xe.mean=="number"?Oe=[xe.mean,xe.mean,xe.mean,xe.mean]:Oe=[xe.mean[0],xe.mean[1],xe.mean[2],xe.mean[3]??255],typeof xe.bias=="number"?$e=[xe.bias,xe.bias,xe.bias,xe.bias]:$e=[xe.bias[0],xe.bias[1],xe.bias[2],xe.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Le=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",tt=he*Te,rt=Le==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,qe=0,It=1,Ne=2,dt=3,Ci=0,Zt=tt,Qt=tt*2,ki=-1;Ae==="RGB"&&(it=3,qe=0,It=1,Ne=2,dt=-1),Le==="RGBA"?ki=tt*3:Le==="RBG"?(Ci=0,Qt=tt,Zt=tt*2):Le==="BGR"&&(Qt=0,Zt=tt,Ci=tt*2);for(let Ot=0;Ot<tt;Ot++,qe+=it,Ne+=it,It+=it,dt+=it)rt[Ci++]=(Y[qe]+$e[0])/Oe[0],rt[Zt++]=(Y[It]+$e[1])/Oe[1],rt[Qt++]=(Y[Ne]+$e[2])/Oe[2],ki!==-1&&dt!==-1&&(rt[ki++]=(Y[dt]+$e[3])/Oe[3]);return Le==="RGBA"?new X("float32",rt,[1,4,he,Te]):new X("float32",rt,[1,3,he,Te])},me=async(Y,se)=>{let he=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,xe=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Oe=typeof Y=="string",$e,Ae=se??{},Le=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(qe=se.resizedHeight,It=se.resizedWidth),se!==void 0){if(Ae=se,se.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It;it.drawImage(Y,0,0),$e=it.getImageData(0,0,It,qe).data}else throw new Error("Can not access image data")}else if(Te){let rt,it;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,it=se.resizedWidth):(rt=Y.height,it=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=it,se!==void 0){let qe=Le();qe.width=it,qe.height=rt;let It=tt(qe);if(It!=null)It.putImageData(Y,0,0),$e=It.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else $e=Y.data}else if(xe){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;return it.drawImage(Y,0,0,It,qe),$e=it.getImageData(0,0,It,qe).data,Ae.height=qe,Ae.width=It,Z($e,Ae)}else throw new Error("Can not access image data")}else{if(Oe)return new Promise((rt,it)=>{let qe=Le(),It=tt(qe);if(!Y||!It)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=Y,Ne.onload=()=>{qe.width=Ne.width,qe.height=Ne.height,It.drawImage(Ne,0,0,qe.width,qe.height);let dt=It.getImageData(0,0,qe.width,qe.height);Ae.height=qe.height,Ae.width=qe.width,rt(Z(dt.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},ie=(Y,se)=>{let{width:he,height:Te,download:xe,dispose:Oe}=se,$e=[1,Te,he,4];return new X({location:"texture",type:"float32",texture:Y,dims:$e,download:xe,dispose:Oe})},ue=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"gpu-buffer",type:he??"float32",gpuBuffer:Y,dims:Te,download:xe,dispose:Oe})},Ce=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"ml-tensor",type:he??"float32",mlTensor:Y,dims:Te,download:xe,dispose:Oe})},Ee=(Y,se,he)=>new X({location:"cpu-pinned",type:Y,data:se,dims:he??[se.length]})}),te,K,re,ve,_e=d(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),re=!1,ve=()=>{if(!re){re=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,Te=typeof he<"u"&&he.from;Y&&(te.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),se&&(te.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),Te?(te.set("float16",he),K.set(he,"float16")):te.set("float16",Uint16Array)}}}),Me,et,we=d(()=>{Ie(),Me=Y=>{let se=1;for(let he=0;he<Y.length;he++){let Te=Y[he];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${he}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${Te}`);se*=Te}return se},et=(Y,se)=>{switch(Y.location){case"cpu":return new X(Y.type,Y.data,se);case"cpu-pinned":return new X({location:"cpu-pinned",data:Y.data,type:Y.type,dims:se});case"texture":return new X({location:"texture",texture:Y.texture,type:Y.type,dims:se});case"gpu-buffer":return new X({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:se});case"ml-tensor":return new X({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:se});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),X,Ie=d(()=>{de(),W(),_e(),we(),X=class{constructor(Y,se,he){ve();let Te,xe;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,xe=Y.dims,Y.location){case"cpu-pinned":{let $e=te.get(Te);if(!$e)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(Y.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=Y.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=Y.mlTensor,this.downloader=Y.download,this.disposer=Y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Ae;if(typeof Y=="string")if(Te=Y,Ae=he,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");$e=se}else{let Le=te.get(Y);if(Le===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Le===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Le.name} as data.`);Y==="uint64"||Y==="int64"?$e=Le.from(se,BigInt):$e=Le.from(se)}else if(se instanceof Le)$e=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")$e=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Le!==Uint16Array)$e=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Le}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Le=typeof Y[0];if(Le==="string")Te="string",$e=Y;else if(Le==="boolean")Te="bool",$e=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Le}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",$e=Uint8Array.from(Y);else{let Le=K.get(Y.constructor);if(Le===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Le,$e=Y}if(Ae===void 0)Ae=[$e.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");xe=Ae,this.cpuData=$e,this.dataLocation="cpu"}let Oe=Me(xe);if(this.cpuData&&Oe!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Oe/2)===this.cpuData.length))throw new Error(`Tensor's size(${Oe}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=xe,this.size=Oe}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return ie(Y,se)}static fromGpuBuffer(Y,se){return ue(Y,se)}static fromMLTensor(Y,se){return Ce(Y,se)}static fromPinnedBuffer(Y,se,he){return Ee(Y,se,he)}toDataURL(Y){return U(this,Y)}toImageData(Y){return oe(this,Y)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Y){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let se=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=se,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),se}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(Y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return et(this,Y)}}}),pe,Ze=d(()=>{Ie(),pe=X}),ge,Ke,vt,st,Kt,Be,Dt=d(()=>{L(),ge=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},Ke=(Y,se)=>{var xe;let he=((xe=new Error().stack)==null?void 0:xe.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Oe=0;Oe<he.length;Oe++){if(Te&&!he[Oe].includes("TRACE_FUNC")){let $e=`FUNC_${Y}::${he[Oe].trim().split(" ")[1]}`;se&&($e+=`::${se}`),ge("CPU",$e);return}he[Oe].includes("TRACE_FUNC")&&(Te=!0)}},vt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("BEGIN",Y)},st=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("END",Y)},Kt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Be=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),_t,ri=d(()=>{C(),Ze(),Dt(),_t=class E1{constructor(se){this.handler=se}async run(se,he,Te){vt(),Kt("InferenceSession.run");let xe={},Oe={};if(typeof se!="object"||se===null||se instanceof pe||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof pe)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.");$e=!1;for(let tt of he){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);xe[tt]=null}if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let qe=he[it];(qe===null||qe instanceof pe)&&(tt=!0,$e=!1,xe[it]=qe)}if(tt){if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Oe=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof se[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)xe[tt]=null;let Ae=await this.handler.run(se,xe,Oe),Le={};for(let tt in Ae)if(Object.hasOwnProperty.call(Ae,tt)){let rt=Ae[tt];rt instanceof pe?Le[tt]=rt:Le[tt]=new pe(rt.type,rt.data,rt.dims)}return Be("InferenceSession.run"),st(),Le}async release(){return this.handler.dispose()}static async create(se,he,Te,xe){vt(),Kt("InferenceSession.create");let Oe,$e={};if(typeof se=="string"){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,it=0,qe=se.byteLength;if(typeof he=="object"&&he!==null)$e=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(qe=se.byteLength-it,typeof Te=="number"){if(qe=Te,!Number.isSafeInteger(qe))throw new RangeError("'byteLength' must be an integer.");if(qe<=0||it+qe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof xe=="object"&&xe!==null)$e=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Oe=new Uint8Array(rt,it,qe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Le]=await b($e),tt=await Ae.createInferenceSessionHandler(Oe,Le);return Be("InferenceSession.create"),st(),new E1(tt)}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,St=d(()=>{ri(),Ye=_t}),ut=d(()=>{}),Xe=d(()=>{}),Pt=d(()=>{}),oi=d(()=>{}),Fi={};f(Fi,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,env:()=>j,registerBackend:()=>k});var li=d(()=>{w(),H(),St(),Ze(),ut(),Xe(),Dt(),Pt(),oi()}),tn=d(()=>{}),Ii={};f(Ii,{default:()=>pr});var Ui,ui,pr,ga=d(()=>{var Y;fe(),Hn(),Fn(),Ui="ort-wasm-proxy-worker",ui=((Y=globalThis.self)==null?void 0:Y.name)===Ui,ui&&(self.onmessage=se=>{let{type:he,in:Te}=se.data;try{switch(he){case"init-wasm":Js(Te.wasm).then(()=>{Lo(Te).then(()=>{postMessage({type:he})},xe=>{postMessage({type:he,err:xe})})},xe=>{postMessage({type:he,err:xe})});break;case"init-ep":{let{epName:xe,env:Oe}=Te;wr(Oe,xe).then(()=>{postMessage({type:he})},$e=>{postMessage({type:he,err:$e})});break}case"copy-from":{let{buffer:xe}=Te,Oe=ni(xe);postMessage({type:he,out:Oe});break}case"create":{let{model:xe,options:Oe}=Te;us(xe,Oe).then($e=>{postMessage({type:he,out:$e})},$e=>{postMessage({type:he,err:$e})});break}case"release":zr(Te),postMessage({type:he});break;case"run":{let{sessionId:xe,inputIndices:Oe,inputs:$e,outputIndices:Ae,options:Le}=Te;Ve(xe,Oe,$e,Ae,new Array(Ae.length).fill(null),Le).then(tt=>{tt.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:tt},ft([...$e,...tt]))},tt=>{postMessage({type:he,err:tt})});break}case"end-profiling":Un(Te),postMessage({type:he});break;default:}}catch(xe){postMessage({type:he,err:xe})}}),pr=ui?null:se=>new Worker(se??vi,{type:"classic",name:Ui})}),Mo,fr,vi,Gn,nn,mr,Rs,as,Mr,gr,vr,js,Pn,Fn=d(()=>{tn(),Mo=typeof location>"u"?void 0:location.origin,fr=()=>{var Y,se;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(se=self.location)==null?void 0:se.href:void 0},vi=fr(),Gn=()=>{if(vi&&!vi.startsWith("blob:"))return vi.substring(0,vi.lastIndexOf("/")+1)},nn=(Y,se)=>{try{let he=se??vi;return(he?new URL(Y,he):new URL(Y)).origin===Mo}catch{return!1}},mr=(Y,se)=>{let he=se??vi;try{return(he?new URL(Y,he):new URL(Y)).href}catch{return}},Rs=(Y,se)=>`${se??"./"}${Y}`,as=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},Mr=async Y=>(await import(Y)).default,gr=(ga(),m(Ii)).default,vr=async()=>{if(!vi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(vi))return[void 0,gr()];let Y=await as(vi);return[Y,gr(Y)]},js=void 0,Pn=async(Y,se,he,Te)=>{let xe=js&&!(Y||se);if(xe)if(vi)xe=nn(vi)||Te&&!he;else if(Te&&!he)xe=!0;else throw new Error("cannot determine the script source URL.");if(xe)return[void 0,js];{let Oe="ort-wasm-simd-threaded.mjs",$e=Y??mr(Oe,se),Ae=he&&$e&&!nn($e,se),Le=Ae?await as($e):$e??Rs(Oe,se);return[Ae?Le:void 0,await Mr(Le)]}}}),Ks,Rn,ls,Es,no,Ys,Xs,Js,zt,Hn=d(()=>{Fn(),Rn=!1,ls=!1,Es=!1,no=()=>{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}},Ys=()=>{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}},Xs=()=>{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 Y=>{if(Rn)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let se=Y.initTimeout,he=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!Xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ys())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=no();he>1&&!Te&&(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."),Y.numThreads=he=1);let xe=Y.wasmPaths,Oe=typeof xe=="string"?xe:void 0,$e=xe==null?void 0:xe.mjs,Ae=($e==null?void 0:$e.href)??$e,Le=xe==null?void 0:xe.wasm,tt=(Le==null?void 0:Le.href)??Le,rt=Y.wasmBinary,[it,qe]=await Pn(Ae,Oe,he>1,!!rt||!!tt),It=!1,Ne=[];if(se>0&&Ne.push(new Promise(dt=>{setTimeout(()=>{It=!0,dt()},se)})),Ne.push(new Promise((dt,Ci)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(tt||Oe)Zt.locateFile=Qt=>tt??Oe+Qt;else if(Ae&&Ae.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Ae).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=ki=>Qt+ki)}qe(Zt).then(Qt=>{ls=!1,Rn=!0,Ks=Qt,dt(),it&&URL.revokeObjectURL(it)},Qt=>{ls=!1,Es=!0,Ci(Qt)})})),await Promise.race(Ne),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Hi,yi,kt,Or=d(()=>{Hn(),Hi=(Y,se)=>{let he=zt(),Te=he.lengthBytesUTF8(Y)+1,xe=he._malloc(Te);return he.stringToUTF8(Y,xe,Te),se.push(xe),xe},yi=(Y,se,he,Te)=>{if(typeof Y=="object"&&Y!==null){if(he.has(Y))throw new Error("Circular reference in options");he.add(Y)}Object.entries(Y).forEach(([xe,Oe])=>{let $e=se?se+xe:xe;if(typeof Oe=="object")yi(Oe,$e+".",he,Te);else if(typeof Oe=="string"||typeof Oe=="number")Te($e,Oe.toString());else if(typeof Oe=="boolean")Te($e,Oe?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Oe}`)})},kt=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetLastError(xe,xe+Te);let Oe=Number(se.getValue(xe,Te===4?"i32":"i64")),$e=se.getValue(xe+Te,"*"),Ae=$e?se.UTF8ToString($e):"";throw new Error(`${Y} ERROR_CODE: ${Oe}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(he)}}}),so,va=d(()=>{Hn(),Or(),so=Y=>{let se=zt(),he=0,Te=[],xe=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)xe.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)xe.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(xe.terminate=!1);let Oe=0;return(Y==null?void 0:Y.tag)!==void 0&&(Oe=Hi(Y.tag,Te)),he=se._OrtCreateRunOptions(xe.logSeverityLevel,xe.logVerbosityLevel,!!xe.terminate,Oe),he===0&&kt("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&yi(Y.extra,"",new WeakSet,($e,Ae)=>{let Le=Hi($e,Te),tt=Hi(Ae,Te);se._OrtAddRunConfigEntry(he,Le,tt)!==0&&kt(`Can't set a run config entry: ${$e} - ${Ae}.`)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseRunOptions(he),Te.forEach($e=>se._free($e)),Oe}}}),ro,oo,Oo,kn,_a,ba,xi=d(()=>{Hn(),Or(),ro=Y=>{switch(Y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${Y}`)}},oo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},Oo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let se=Y.extra.session;se.use_ort_model_bytes_directly||(se.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(Y.enableMemPattern=!1)},kn=(Y,se,he,Te)=>{let xe=Hi(se,Te),Oe=Hi(he,Te);zt()._OrtAddSessionConfigEntry(Y,xe,Oe)!==0&&kt(`Can't set a session config entry: ${se} - ${he}.`)},_a=async(Y,se,he)=>{let Te=se.executionProviders;for(let xe of Te){let Oe=typeof xe=="string"?xe:xe.name,$e=[];switch(Oe){case"webnn":if(Oe="WEBNN",kn(Y,"session.disable_quant_qdq","1",he),kn(Y,"session.disable_qdq_constant_folding","1",he),typeof xe!="string"){let it=xe==null?void 0:xe.deviceType;it&&kn(Y,"deviceType",it,he)}break;case"webgpu":if(Oe="JS",typeof xe!="string"){let it=xe;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);kn(Y,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Oe}`)}let Ae=Hi(Oe,he),Le=$e.length,tt=0,rt=0;if(Le>0){tt=zt()._malloc(Le*zt().PTR_SIZE),he.push(tt),rt=zt()._malloc(Le*zt().PTR_SIZE),he.push(rt);for(let it=0;it<Le;it++)zt().setValue(tt+it*zt().PTR_SIZE,$e[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,$e[it][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,tt,rt,Le)!==0&&kt(`Can't append execution provider: ${Oe}.`)}},ba=async Y=>{let se=zt(),he=0,Te=[],xe=Y||{};Oo(xe);try{let Oe=ro(xe.graphOptimizationLevel??"all"),$e=oo(xe.executionMode??"sequential"),Ae=typeof xe.logId=="string"?Hi(xe.logId,Te):0,Le=xe.logSeverityLevel??2;if(!Number.isInteger(Le)||Le<0||Le>4)throw new Error(`log severity level is not valid: ${Le}`);let tt=xe.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let rt=typeof xe.optimizedModelFilePath=="string"?Hi(xe.optimizedModelFilePath,Te):0;if(he=se._OrtCreateSessionOptions(Oe,!!xe.enableCpuMemArena,!!xe.enableMemPattern,$e,!!xe.enableProfiling,0,Ae,Le,tt,rt),he===0&&kt("Can't create session options."),xe.executionProviders&&await _a(he,xe,Te),xe.enableGraphCapture!==void 0){if(typeof xe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${xe.enableGraphCapture}`);kn(he,"enableGraphCapture",xe.enableGraphCapture.toString(),Te)}if(xe.freeDimensionOverrides)for(let[it,qe]of Object.entries(xe.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof qe!="number"||!Number.isInteger(qe)||qe<0)throw new Error(`free dimension override value must be a non-negative integer: ${qe}`);let It=Hi(it,Te);se._OrtAddFreeDimensionOverride(he,It,qe)!==0&&kt(`Can't set a free dimension override: ${it} - ${qe}.`)}return xe.extra!==void 0&&yi(xe.extra,"",new WeakSet,(it,qe)=>{kn(he,it,qe,Te)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseSessionOptions(he)!==0&&kt("Can't release session options."),Te.forEach($e=>se._free($e)),Oe}}}),jn,Vi,Nn,Zs,Lr,_r,cs,gn,Bt=d(()=>{jn=Y=>{switch(Y){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${Y}`)}},Vi=Y=>{switch(Y){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${Y}`)}},Nn=(Y,se)=>{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][Y],Te=typeof se=="number"?se:se.reduce((xe,Oe)=>xe*Oe,1);return he>0?Math.ceil(Te*he):void 0},Zs=Y=>{switch(Y){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${Y}`)}},Lr=Y=>{switch(Y){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${Y}`)}},_r=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",cs=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",gn=Y=>{switch(Y){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${Y}`)}}}),qi,br=d(()=>{tn(),qi=async Y=>{if(typeof Y=="string"){let se=await fetch(Y);if(!se.ok)throw new Error(`failed to load external data file: ${Y}`);let he=se.headers.get("Content-Length"),Te=he?parseInt(he,10):0;if(Te<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let xe=se.body.getReader(),Oe;try{Oe=new ArrayBuffer(Te)}catch(Ae){if(Ae instanceof RangeError){let Le=Math.ceil(Te/65536);Oe=new WebAssembly.Memory({initial:Le,maximum:Le}).buffer}else throw Ae}let $e=0;for(;;){let{done:Ae,value:Le}=await xe.read();if(Ae)break;let tt=Le.byteLength;new Uint8Array(Oe,$e,tt).set(Le),$e+=tt}return new Uint8Array(Oe,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),ds,Lo,wr,Wn,Ns,yr,ni,us,zr,Ts,Ve,Un,ft,fe=d(()=>{li(),va(),xi(),Bt(),Hn(),Or(),br(),ds=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&kt("Can't initialize onnxruntime.")},Lo=async Y=>{ds(Y.wasm.numThreads,Lr(Y.logLevel))},wr=async(Y,se)=>{var Te,xe;(xe=(Te=zt()).asyncInit)==null||xe.call(Te);let he=Y.webgpu.adapter;if(se==="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 Oe=Y.webgpu.powerPreference;if(Oe!==void 0&&Oe!=="low-power"&&Oe!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Oe}"`);let $e=Y.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Oe,forceFallbackAdapter:$e}),!he)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(se==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wn=new Map,Ns=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetInputOutputCount(Y,xe,xe+Te)!==0&&kt("Can't get session input/output count.");let Oe=Te===4?"i32":"i64";return[Number(se.getValue(xe,Oe)),Number(se.getValue(xe+Te,Oe))]}finally{se.stackRestore(he)}},yr=(Y,se)=>{let he=zt(),Te=he.stackSave(),xe=0;try{let Oe=he.PTR_SIZE,$e=he.stackAlloc(2*Oe);he._OrtGetInputOutputMetadata(Y,se,$e,$e+Oe)!==0&&kt("Can't get session input/output metadata.");let Ae=Number(he.getValue($e,"*"));xe=Number(he.getValue($e+Oe,"*"));let Le=he.HEAP32[xe/4];if(Le===0)return[Ae,0];let tt=he.HEAPU32[xe/4+1],rt=[];for(let it=0;it<tt;it++){let qe=Number(he.getValue(xe+8+it*Oe,"*"));rt.push(qe!==0?he.UTF8ToString(qe):Number(he.getValue(xe+8+(it+tt)*Oe,"*")))}return[Ae,Le,rt]}finally{he.stackRestore(Te),xe!==0&&he._OrtFree(xe)}},ni=Y=>{let se=zt(),he=se._malloc(Y.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,he),[he,Y.byteLength]},us=async(Y,se)=>{var rt,it,qe;let he,Te,xe=zt();Array.isArray(Y)?[he,Te]=Y:Y.buffer===xe.HEAPU8.buffer?[he,Te]=[Y.byteOffset,Y.byteLength]:[he,Te]=ni(Y);let Oe=0,$e=0,Ae=[],Le=[],tt=[];try{if([$e,Ae]=await ba(se),(se==null?void 0:se.externalData)&&xe.mountExternalData){let Ri=[];for(let ci of se.externalData){let vn=typeof ci=="string"?ci:ci.path;Ri.push(qi(typeof ci=="string"?ci:ci.data).then(Mn=>{xe.mountExternalData(vn,Mn)}))}await Promise.all(Ri)}for(let Ri of(se==null?void 0:se.executionProviders)??[])if((typeof Ri=="string"?Ri:Ri.name)==="webnn"){if(xe.shouldTransferToMLTensor=!1,typeof Ri!="string"){let ci=Ri,vn=ci==null?void 0:ci.context,Mn=ci==null?void 0:ci.gpuDevice,Vn=ci==null?void 0:ci.deviceType,ya=ci==null?void 0:ci.powerPreference;vn?xe.currentContext=vn:Mn?xe.currentContext=await xe.webnnCreateMLContext(Mn):xe.currentContext=await xe.webnnCreateMLContext({deviceType:Vn,powerPreference:ya})}else xe.currentContext=await xe.webnnCreateMLContext();break}Oe=await xe._OrtCreateSession(he,Te,$e),(rt=xe.webgpuOnCreateSession)==null||rt.call(xe,Oe),Oe===0&&kt("Can't create a session."),(it=xe.jsepOnCreateSession)==null||it.call(xe),xe.currentContext&&(xe.webnnRegisterMLContext(Oe,xe.currentContext),xe.currentContext=void 0,xe.shouldTransferToMLTensor=!0);let[It,Ne]=Ns(Oe),dt=!!(se!=null&&se.enableGraphCapture),Ci=[],Zt=[],Qt=[],ki=[],Ot=[];for(let Ri=0;Ri<It;Ri++){let[ci,vn,Mn]=yr(Oe,Ri);ci===0&&kt("Can't get an input name."),Le.push(ci);let Vn=xe.UTF8ToString(ci);Ci.push(Vn),Qt.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}for(let Ri=0;Ri<Ne;Ri++){let[ci,vn,Mn]=yr(Oe,Ri+It);ci===0&&kt("Can't get an output name."),tt.push(ci);let Vn=xe.UTF8ToString(ci);Zt.push(Vn),ki.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}return Wn.set(Oe,[Oe,Le,tt,null,dt,!1]),[Oe,Ci,Zt,Qt,ki]}catch(It){throw Le.forEach(Ne=>xe._OrtFree(Ne)),tt.forEach(Ne=>xe._OrtFree(Ne)),Oe!==0&&xe._OrtReleaseSession(Oe)!==0&&kt("Can't release session."),It}finally{xe._free(he),$e!==0&&xe._OrtReleaseSessionOptions($e)!==0&&kt("Can't release session options."),Ae.forEach(It=>xe._free(It)),(qe=xe.unmountExternalData)==null||qe.call(xe)}},zr=Y=>{var Le,tt,rt;let se=zt(),he=Wn.get(Y);if(!he)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,xe,Oe,$e,Ae]=he;$e&&(Ae&&se._OrtClearBoundOutputs($e.handle)!==0&&kt("Can't clear bound outputs."),se._OrtReleaseBinding($e.handle)!==0&&kt("Can't release IO binding.")),(Le=se.jsepOnReleaseSession)==null||Le.call(se,Y),(tt=se.webnnOnReleaseSession)==null||tt.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),xe.forEach(it=>se._OrtFree(it)),Oe.forEach(it=>se._OrtFree(it)),se._OrtReleaseSession(Te)!==0&&kt("Can't release session."),Wn.delete(Y)},Ts=async(Y,se,he,Te,xe,Oe,$e=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Le=Ae.PTR_SIZE,tt=Y[0],rt=Y[1],it=Y[3],qe=it,It,Ne;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Oe} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=Y[2].gpuBuffer;Ne=Nn(jn(tt),rt);{let Qt=Ae.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=Qt(Te,Oe,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=Y[2].mlTensor;Ne=Nn(jn(tt),rt);let Qt=Ae.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=Qt(Te,Zt,jn(tt),rt)}else{let Zt=Y[2];if(Array.isArray(Zt)){Ne=Le*Zt.length,It=Ae._malloc(Ne),he.push(It);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`);Ae.setValue(It+Qt*Le,Hi(Zt[Qt],he),"*")}}else{let Qt=Ae.webnnIsGraphInput,ki=Ae.webnnIsGraphOutput;if(tt!=="string"&&Qt&&ki){let Ot=Ae.UTF8ToString(xe);if(Qt(Te,Ot)||ki(Te,Ot)){let Ri=jn(tt);Ne=Nn(Ri,rt),qe="ml-tensor";let ci=Ae.webnnCreateTemporaryTensor,vn=Ae.webnnUploadTensor;if(!ci||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Mn=await ci(Te,Ri,rt);vn(Mn,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),It=Mn}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}}let dt=Ae.stackSave(),Ci=Ae.stackAlloc(4*rt.length);try{rt.forEach((Qt,ki)=>Ae.setValue(Ci+ki*Le,Qt,Le===4?"i32":"i64"));let Zt=Ae._OrtCreateTensor(jn(tt),It,Ne,Ci,rt.length,gn(qe));Zt===0&&kt(`Can't create tensor for input/output. session=${Te}, index=${Oe}.`),se.push(Zt)}finally{Ae.stackRestore(dt)}},Ve=async(Y,se,he,Te,xe,Oe)=>{var qn,ol,nc;let $e=zt(),Ae=$e.PTR_SIZE,Le=Wn.get(Y);if(!Le)throw new Error(`cannot run inference. invalid session id: ${Y}`);let tt=Le[0],rt=Le[1],it=Le[2],qe=Le[3],It=Le[4];Le[5];let Ne=se.length,dt=Te.length,Ci=0,Zt=[],Qt=[],ki=[],Ot=[],Ri=[],ci=$e.stackSave(),vn=$e.stackAlloc(Ne*Ae),Mn=$e.stackAlloc(Ne*Ae),Vn=$e.stackAlloc(dt*Ae),ya=$e.stackAlloc(dt*Ae);try{[Ci,Zt]=so(Oe),Kt("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)await Ts(he[ai],Qt,Ot,Y,rt[se[ai]],se[ai],It);for(let ai=0;ai<dt;ai++)await Ts(xe[ai],ki,Ot,Y,it[Te[ai]],Ne+Te[ai],It);Be("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)$e.setValue(vn+ai*Ae,Qt[ai],"*"),$e.setValue(Mn+ai*Ae,rt[se[ai]],"*");for(let ai=0;ai<dt;ai++)$e.setValue(Vn+ai*Ae,ki[ai],"*"),$e.setValue(ya+ai*Ae,it[Te[ai]],"*");(qn=$e.jsepOnRunStart)==null||qn.call($e,tt),(ol=$e.webnnOnRunStart)==null||ol.call($e,tt);let _n;_n=await $e._OrtRun(tt,Mn,vn,Ne,ya,dt,Vn,Ci),_n!==0&&kt("failed to call OrtRun().");let er=[],sc=[];Kt("wasm ProcessOutputTensor");for(let ai=0;ai<dt;ai++){let Os=Number($e.getValue(Vn+ai*Ae,"*"));if(Os===ki[ai]||Ri.includes(ki[ai])){er.push(xe[ai]),Os!==ki[ai]&&$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.");continue}let dd=$e.stackSave(),Cr=$e.stackAlloc(4*Ae),zo=!1,an,Kn=0;try{$e._OrtGetTensorData(Os,Cr,Cr+Ae,Cr+2*Ae,Cr+3*Ae)!==0&&kt(`Can't access output tensor data on index ${ai}.`);let al=Ae===4?"i32":"i64",Yn=Number($e.getValue(Cr,al));Kn=$e.getValue(Cr+Ae,"*");let rc=$e.getValue(Cr+Ae*2,"*"),ud=Number($e.getValue(Cr+Ae*3,al)),kr=[];for(let ln=0;ln<ud;ln++)kr.push(Number($e.getValue(rc+ln*Ae,al)));$e._OrtFree(rc)!==0&&kt("Can't free memory for tensor dims.");let Ls=kr.reduce((ln,Wi)=>ln*Wi,1);an=Vi(Yn);let tr=qe==null?void 0:qe.outputPreferredLocations[Te[ai]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Wi=0;Wi<Ls;Wi++){let zs=$e.getValue(Kn+Wi*Ae,"*"),oc=$e.getValue(Kn+(Wi+1)*Ae,"*"),ac=Wi===Ls-1?void 0:oc-zs;ln.push($e.UTF8ToString(zs,ac))}er.push([an,kr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ls>0){let ln=$e.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wi=ln(Kn),zs=Nn(Yn,Ls);if(zs===void 0||!_r(an))throw new Error(`Unsupported data type: ${an}`);zo=!0,er.push([an,kr,{gpuBuffer:Wi,download:$e.jsepCreateDownloader(Wi,zs,an),dispose:()=>{$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ls>0){let ln=$e.webnnEnsureTensor,Wi=$e.webnnIsGraphInputOutputTypeSupported;if(!ln||!Wi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Nn(Yn,Ls)===void 0||!cs(an))throw new Error(`Unsupported data type: ${an}`);if(!Wi(Y,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let zs=await ln(Y,Kn,Yn,kr,!1);zo=!0,er.push([an,kr,{mlTensor:zs,download:$e.webnnCreateMLTensorDownloader(Kn,an),dispose:()=>{$e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ls>0){let ln=$e.webnnCreateMLTensorDownloader(Kn,an)(),Wi=er.length;zo=!0,sc.push((async()=>{let zs=[Wi,await ln];return $e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os),zs})()),er.push([an,kr,[],"cpu"])}else{let ln=Zs(an),Wi=new ln(Ls);new Uint8Array(Wi.buffer,Wi.byteOffset,Wi.byteLength).set($e.HEAPU8.subarray(Kn,Kn+Wi.byteLength)),er.push([an,kr,Wi,"cpu"])}}finally{$e.stackRestore(dd),an==="string"&&Kn&&$e._free(Kn),zo||$e._OrtReleaseTensor(Os)}}qe&&!It&&($e._OrtClearBoundOutputs(qe.handle)!==0&&kt("Can't clear bound outputs."),Wn.set(Y,[tt,rt,it,qe,It,!1]));for(let[ai,Os]of await Promise.all(sc))er[ai][2]=Os;return Be("wasm ProcessOutputTensor"),er}finally{(nc=$e.webnnOnRunEnd)==null||nc.call($e,tt),$e.stackRestore(ci),Qt.forEach(_n=>$e._OrtReleaseTensor(_n)),ki.forEach(_n=>$e._OrtReleaseTensor(_n)),Ot.forEach(_n=>$e._free(_n)),Ci!==0&&$e._OrtReleaseRunOptions(Ci),Zt.forEach(_n=>$e._free(_n))}},Un=Y=>{let se=zt(),he=Wn.get(Y);if(!he)throw new Error("invalid session id");let Te=he[0],xe=se._OrtEndProfiling(Te);xe===0&&kt("Can't get an profile file name."),se._OrtFree(xe)},ft=Y=>{let se=[];for(let he of Y){let Te=he[2];!Array.isArray(Te)&&"buffer"in Te&&se.push(Te.buffer)}return se}}),Re,Je,Tt,ti,si,Pi,Ti,sn,Oi,on,Di,Ms,Br,ao,Qs,cd,lo,co,ec=d(()=>{li(),fe(),Hn(),Fn(),Re=()=>!!j.wasm.proxy&&typeof document<"u",Tt=!1,ti=!1,si=!1,sn=new Map,Oi=(Y,se)=>{let he=sn.get(Y);he?he.push(se):sn.set(Y,[se])},on=()=>{if(Tt||!ti||si||!Je)throw new Error("worker not ready")},Di=Y=>{switch(Y.data.type){case"init-wasm":Tt=!1,Y.data.err?(si=!0,Ti[1](Y.data.err)):(ti=!0,Ti[0]()),Pi&&(URL.revokeObjectURL(Pi),Pi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=sn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Ms=async()=>{if(!ti){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(si)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Re())return new Promise((Y,se)=>{Je==null||Je.terminate(),vr().then(([he,Te])=>{try{Je=Te,Je.onerror=Oe=>se(Oe),Je.onmessage=Di,Ti=[Y,se];let xe={type:"init-wasm",in:j};if(!xe.in.wasm.wasmPaths&&he){let Oe=Gn();Oe&&(xe.in.wasm.wasmPaths=Oe)}Je.postMessage(xe),Pi=he}catch(xe){se(xe)}},se)});try{await Js(j.wasm),await Lo(j),ti=!0}catch(Y){throw si=!0,Y}finally{Tt=!1}}},Br=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("init-ep",[se,he]);let Te={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Te)});await wr(j,Y)},ao=async Y=>Re()?(on(),new Promise((se,he)=>{Oi("copy-from",[se,he]);let Te={type:"copy-from",in:{buffer:Y}};Je.postMessage(Te,[Y.buffer])})):ni(Y),Qs=async(Y,se)=>{if(Re()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,Te)=>{Oi("create",[he,Te]);let xe={type:"create",in:{model:Y,options:{...se}}},Oe=[];Y instanceof Uint8Array&&Oe.push(Y.buffer),Je.postMessage(xe,Oe)})}else return us(Y,se)},cd=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("release",[se,he]);let Te={type:"release",in:Y};Je.postMessage(Te)});zr(Y)},lo=async(Y,se,he,Te,xe,Oe)=>{if(Re()){if(he.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(xe.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise(($e,Ae)=>{Oi("run",[$e,Ae]);let Le=he,tt={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Le,outputIndices:Te,options:Oe}};Je.postMessage(tt,ft(Le))})}else return Ve(Y,se,he,Te,xe,Oe)},co=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("end-profiling",[se,he]);let Te={type:"end-profiling",in:Y};Je.postMessage(Te)});Un(Y)}}),il,uo,wa,nl=d(()=>{li(),ec(),Bt(),tn(),br(),il=(Y,se)=>{switch(Y.location){case"cpu":return[Y.type,Y.dims,Y.data,"cpu"];case"gpu-buffer":return[Y.type,Y.dims,{gpuBuffer:Y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Y.type,Y.dims,{mlTensor:Y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Y.location} for ${se()}`)}},uo=Y=>{switch(Y[3]){case"cpu":return new pe(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!_r(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:he,download:Te,dispose:xe}=Y[2];return pe.fromGpuBuffer(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}case"ml-tensor":{let se=Y[0];if(!cs(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:he,download:Te,dispose:xe}=Y[2];return pe.fromMLTensor(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}default:throw new Error(`invalid data location: ${Y[3]}`)}},wa=class{async fetchModelAndCopyToWasmMemory(Y){return ao(await qi(Y))}async loadModel(Y,se){vt();let he;typeof Y=="string"?he=await this.fetchModelAndCopyToWasmMemory(Y):he=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,se),st()}async dispose(){return cd(this.sessionId)}async run(Y,se,he){vt();let Te=[],xe=[];Object.entries(Y).forEach(it=>{let qe=it[0],It=it[1],Ne=this.inputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid input '${qe}'`);Te.push(It),xe.push(Ne)});let Oe=[],$e=[];Object.entries(se).forEach(it=>{let qe=it[0],It=it[1],Ne=this.outputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid output '${qe}'`);Oe.push(It),$e.push(Ne)});let Ae=Te.map((it,qe)=>il(it,()=>`input "${this.inputNames[xe[qe]]}"`)),Le=Oe.map((it,qe)=>it?il(it,()=>`output "${this.outputNames[$e[qe]]}"`):null),tt=await lo(this.sessionId,xe,Ae,$e,Le,he),rt={};for(let it=0;it<tt.length;it++)rt[this.outputNames[$e[it]]]=Oe[it]??uo(tt[it]);return st(),rt}startProfiling(){}endProfiling(){co(this.sessionId)}}}),xr={};f(xr,{OnnxruntimeWebAssemblyBackend:()=>Sr,initializeFlags:()=>Gr,wasmBackend:()=>ho});var Gr,Sr,ho,tc=d(()=>{li(),ec(),nl(),Gr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let Y=j.wasm.simd;if(typeof Y!="boolean"&&Y!==void 0&&Y!=="fixed"&&Y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Y}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let se=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((se||1)/2))}},Sr=class{async init(Y){Gr(),await Ms(),await Br(Y)}async createInferenceSessionHandler(Y,se){let he=new wa;return await he.loadModel(Y,se),he}},ho=new Sr}),ic={};f(ic,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,default:()=>rl,env:()=>j,registerBackend:()=>k}),li(),li(),li();var sl="1.26.0",rl=Fi;{let Y=(tc(),m(xr)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:sl,enumerable:!0}),m(ic)})();i.exports=t})(Kv)),Kv.exports}var Ty;function LE(){return Ty||(Ty=1,(function(i){var e=Ua&&Ua.__createBinding||(Object.create?(function(x,$,R,N){N===void 0&&(N=R);var L=Object.getOwnPropertyDescriptor($,R);(!L||("get"in L?!$.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return $[R]}}),Object.defineProperty(x,N,L)}):(function(x,$,R,N){N===void 0&&(N=R),x[N]=$[R]})),t=Ua&&Ua.__setModuleDefault||(Object.create?(function(x,$){Object.defineProperty(x,"default",{enumerable:!0,value:$})}):function(x,$){x.default=$}),n=Ua&&Ua.__importStar||function(x){if(x&&x.__esModule)return x;var $={};if(x!=null)for(var R in x)R!=="default"&&Object.prototype.hasOwnProperty.call(x,R)&&e($,x,R);return t($,x),$};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(OE()),l=zb(),p=Bb(),a=Yf(),d=mv(),f=C1(),v=k1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",y="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",k=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 $=>{$.getTracks().forEach(R=>{R.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:$=>{$.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const T=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,$,R,N,L){await R.audioWorklet.addModule(x),$.processorOptions={...$.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(R,"vad-helper-worklet",$);return j.port.onmessage=async H=>{const U=H.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case d.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const oe=new Float32Array(U.data);await L(oe);break}}},j}async function C(x,$,R){const N=new v.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:$});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async U=>{if(!H){H=!0;try{const oe=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=N.process(oe);for(const me of Z)await R(me)}catch(oe){console.error("Error processing audio:",oe)}finally{H=!1}}},j.connect(x.destination),j}class w{constructor($,R,N,L,j=!1,H=null,U=null,oe=null,de=null,Z=null,me=null,ie="uninitialized",ue=!1){this.options=$,this.frameProcessor=R,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=U,this._audioContext=oe,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=ie,this.ownsAudioContext=ue,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ce=>{this.initializationState="errored",this.errored=Ce},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?T(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await C(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:Ce,audioContext:Ee,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const te=new MediaStreamAudioSourceNode(Ee,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(W);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ce,mediaStreamAudioSourceNode:Ee}=this.getAudioInstances();await this.options.pauseStream(Ce),Ee.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ee;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ee=this._audioContext)==null?void 0:Ee.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(Ce.audio);break}}}static async new($={}){const R={...(0,i.getDefaultRealTimeVADOptions)($.model??i.DEFAULT_MODEL),...$};(0,p.validateOptions)(R),i.ort.env.wasm.wasmPaths=R.onnxWASMBasePath,R.ortConfig!==void 0&&R.ortConfig(i.ort);const N=R.model==="v5"?y:D,L=R.baseAssetPath+N,j=R.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let H;try{H=await j(i.ort,()=>(0,l.defaultModelFetcher)(L))}catch(me){throw console.error(`Encountered an error while loading model file ${L}`),me}const U=R.model==="v5"?512:1536,oe=U/16,de=new p.FrameProcessor(H.process,H.reset_state,{positiveSpeechThreshold:R.positiveSpeechThreshold,negativeSpeechThreshold:R.negativeSpeechThreshold,redemptionMs:R.redemptionMs,preSpeechPadMs:R.preSpeechPadMs,minSpeechMs:R.minSpeechMs,submitUserSpeechOnPause:R.submitUserSpeechOnPause},oe),Z=new w(R,de,H,U);if(R.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=w})(Ua)),Ua}var Dy;function zE(){return Dy||(Dy=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=zb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Bb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=mv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=NE();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=ME();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=LE();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}})})(Uv)),Uv}var BE=zE();function ig(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)=>ig(i,"debug",e,t),info:(i,e,t)=>ig(i,"info",e,t),warn:(i,e,t)=>ig(i,"warn",e,t),error:(i,e,t,n)=>ig(i,"error",e,t,n)},T1=16e3,GE=6,Wu=T1*GE,FE=400,HE=T1*FE/1e3,$y=300,Ay=2e3,Iy=1500,Py=3e3,WE=600,D1=.5,$1=.35,Ry=.85,jy=.7;let hr=null,pa=!1,qs=!1;const O_=new Set;function ng(i){for(const e of Array.from(O_))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Yv=0;const Ny=2;let ih=!1,A1=!1;function I1(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}),UE(`error:${e.message||"unknown"}`)})}function Zg(){return hr||(hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),I1(hr),pt.info("speech","worker spawned"),hr)}let sg=!1;function UE(i){if(!ih){if(sg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(sg=!0,Yv+=1,A1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:Yv}),ng({reason:i,respawned:!1,finalOnly:!0}),Yv>Ny){if(ih=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Ny}),hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1,ng({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),sg=!1;return}if(hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1;try{hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),I1(hr),qs=!0,hr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),ng({reason:i,respawned:!0,finalOnly:!0})}catch(e){ih=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),ng({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{sg=!1}}}function VE(i,e){if(pa||qs)return;qs=!0;const t=Zg();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"&&(pa=!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 qE(){pt.info("speech","resetModel: clearing load flags"),pa=!1,qs=!1}function gv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function KE(i){const e=Zg();return!pa&&!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"&&(pa=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function P1(i){let e=Zg(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let v=null,m=0,y=!1,D=0,k=!1,T=!1,b=0,C=0,w=0,x=-1,$=$y,R=0,N=null,L="",j="",H=!1,U=0;function oe(ve,_e){const Me=Math.min(ve.length,_e.length);let et=0;for(;et<Me&&ve.charCodeAt(et)===_e.charCodeAt(et);)et++;return et}function de(ve){const _e=oe(L,ve);return L=ve,_e>j.length&&(j=ve.slice(0,_e)),j.length>ve.length&&(j=ve),j}const Z=()=>(v||(v=new Float32Array(Wu)),v),me=()=>{m=0},ie=ve=>{const _e=Z(),Me=ve.length;if(Me>=Wu){_e.set(ve.subarray(Me-Wu)),m=Wu;return}if(m+Me<=Wu){_e.set(ve,m),m+=Me;return}const et=m+Me-Wu;_e.copyWithin(0,et,m),m-=et,_e.set(ve,m),m+=Me},ue=()=>{N&&(clearTimeout(N),N=null)},Ce=()=>{ue(),y=!1,k=!1,T=!1,$=$y,L="",j="",H=!1,U=0,me()},Ee=()=>{if(t||!y||T||k||N)return;if(m<HE){N=setTimeout(()=>{N=null,Ee()},$);return}const ve=performance.now()-b;if(ve<$&&b!==0){N=setTimeout(()=>{N=null,Ee()},$-ve);return}if(A1||ih||i.partialsEnabled&&!i.partialsEnabled())return;const _e=Z(),Me=new Float32Array(m);Me.set(_e.subarray(0,m)),C+=1,w=C,k=!0,R=performance.now(),b=R,e.postMessage({type:"transcribe-partial",audio:Me,seq:C},[Me.buffer])},W=ve=>ve.length===0?Promise.resolve():ih?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(_e=>{d.push(_e),C+=1;const Me=C;x=Me,e.postMessage({type:"transcribe",audio:ve,seq:Me},[ve.buffer])}),te=ve=>{const _e=W(ve);return f.add(_e),_e.finally(()=>{f.delete(_e)}),_e},K=ve=>{var _e,Me,et,we,X;if(ve.data.type==="result"){const Ie=ve.data.text,pe=ve.data.seq??0;pe&&pe<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:pe,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(_e=d.shift())==null||_e()}else if(ve.data.type==="partial"){const Ie=ve.data.seq??0,pe=ve.data.text??"",Ze=performance.now()-R;k=!1,Ze>=Py?(T=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ze),seq:Ie})):Ze>=Iy&&($=Math.min($*2,Ay),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ze),newIntervalMs:$,seq:Ie})),H||(H=!0,Ze>WE&&$<500&&($=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ze),newIntervalMs:500})));const ge=Ie!==w||Ie<=x;if(!t&&!ge&&pe){const Ke=de(pe);Ke&&((Me=i.onPartial)==null||Me.call(i,Ke),U===0&&(U=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-D)})))}Ee()}else if(ve.data.type==="partial-error"){const Ie=performance.now()-R;k=!1,Ie>=Py?(T=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ve.data.seq})):Ie>=Iy&&($=Math.min($*2,Ay),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:$,seq:ve.data.seq})),pt.warn("speech","partial encode failed",{error:ve.data.error,seq:ve.data.seq}),Ee()}else ve.data.type==="error"?(t||i.onError(ve.data.error),(et=d.shift())==null||et()):ve.data.type==="status"?(t||(we=i.onModelStatus)==null||we.call(i,ve.data.status,ve.data.message),ve.data.status==="ready"&&(pa=!0,qs=!1)):ve.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ve.data.pct))};e.addEventListener("message",K);const re=ve=>{var _e,Me;if(!t){for(pt.warn("speech","createRecognition: worker death event",ve),(_e=i.onStatusChange)==null||_e.call(i,"restarting");d.length;)(Me=d.shift())==null||Me();if(f.clear(),ue(),k=!1,ve.respawned){try{e.removeEventListener("message",K)}catch{}e=Zg(),e.addEventListener("message",K)}}};return O_.add(re),{start:async()=>{if(!t){if(ih){i.onError("Speech recognition disabled — please reload the app.");return}!pa&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:pa,modelLoading:qs});try{const ve=new URL("vad/",document.baseURI).href,_e=i.inputDeviceId||null,Me={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};_e&&(Me.deviceId={exact:_e}),pt.info("speech","getUserMedia",{hasDeviceId:!!_e,deviceIdPrefix:_e?_e.slice(0,8):null});const et=await navigator.mediaDevices.getUserMedia({audio:Me});r=et,l=new AudioContext;for(const we of et.getAudioTracks())we.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(we){pt.warn("speech","analyser init failed",{error:we instanceof Error?we.message:String(we)}),a=null,p=null}n=await BE.MicVAD.new({audioContext:l,getStream:async()=>et,resumeStream:async()=>et,pauseStream:async()=>{},baseAssetPath:ve,onnxWASMBasePath:ve,model:"v5",positiveSpeechThreshold:D1,negativeSpeechThreshold:$1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(we,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,we),y&&(ie(X),Ee()))},onSpeechStart:()=>{var we;t||(Ce(),y=!0,D=performance.now(),(we=i.onSpeechStart)==null||we.call(i))},onSpeechEnd:we=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),Ce(),te(we))},onVADMisfire:()=>{var we,X;t||((we=i.onStatusChange)==null||we.call(i,"idle"),Ce(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ve){const _e=ve instanceof Error?ve.message:"Microphone access denied",Me=ve instanceof Error?ve.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:_e,stack:Me}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(et=>et.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(_e)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(Ce();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(ve=>ve.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ve,_e)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ve,negativeSpeechThreshold:_e})}catch(Me){pt.warn("speech","setVadThresholds failed",{error:Me instanceof Error?Me.message:String(Me)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,Ce(),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(ve=>ve.stop())}catch{}r=null}O_.delete(re),e.removeEventListener("message",K)}}}let Df=null;const L_=new Set,z_=new Set;function YE(){for(const i of L_)try{i()}catch{}}function B_(){for(const i of z_)try{i()}catch{}}function XE(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 JE(i){if(!window.speechSynthesis)return;const e=XE(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Df=performance.now(),YE()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,B_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,B_())},window.speechSynthesis.speak(t)}function R1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Df=null,B_())}function j1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function ZE(){return Df}function QE(i){return L_.add(i),()=>{L_.delete(i)}}function e2(i){return z_.add(i),()=>{z_.delete(i)}}function t2(i){j1()&&(i.setVadThresholds(Ry,jy),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=QE(()=>{i.setVadThresholds(Ry,jy),pt.info("voice","tts.duck.on")}),t=e2(()=>{i.setVadThresholds(D1,$1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const i2=[{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 n2(i){const e=i.trim();return i2.find(t=>t.match.test(e))??null}const s2=4e4;let nd=null;function nh(){nd&&clearTimeout(nd),nd=setTimeout(()=>{nd=null,Ct.getState().stopRecording()},s2)}function rg(){nd&&(clearTimeout(nd),nd=null)}let Xl=null,Ul=null;const r2=.04,o2=.3;let Qg=0,G_=0;function a2(i){Ul!==null&&cancelAnimationFrame(Ul);const e=()=>{if(Xl===null||Ct.getState().submitCountdownStartAt===null){Ul=null;return}const t=performance.now();if(t-G_<200&&Qg>o2){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Qg.toFixed(2),msIntoCountdown:Math.round(r)}),Hl(),nh();return}const n=N1();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>r2){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Hl(),nh();return}}Ul=requestAnimationFrame(e)};Ul=requestAnimationFrame(e)}function My(i){Xl&&clearTimeout(Xl);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),Xl=setTimeout(()=>{var r;Xl=null,Ct.setState({submitCountdownStartAt:null});const n=xt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=di.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(di.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),di.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)})}nh()},e),a2(t)}function Hl(){Ul!==null&&(cancelAnimationFrame(Ul),Ul=null),Xl&&(clearTimeout(Xl),Xl=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let ss=null,Is=null,nf=null;function N1(){var i;return((i=ss==null?void 0:ss.getAnalyser)==null?void 0:i.call(ss))??null}const og=1e4;let $f=null;function ag(){$f&&(clearTimeout($f),$f=null)}let Og=null,Lg=null;function lg(){Og=null,Lg&&(Lg(),Lg=null)}const l2=1500,c2=9e4;let cg=0,zg=null,F_=-1;function dg(){zg&&(clearTimeout(zg),zg=null,F_=-1)}const d2=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=In((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=++cg,n=()=>{t===cg&&(dg(),F_=t,zg=setTimeout(()=>{F_===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},c2))};n(),VE((r,l)=>{t===cg&&(r==="ready"?(dg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(dg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===cg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),dg(),qE(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ss){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!gv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=P1({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=>{Qg=a.isSpeech,G_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),rg(),Hl(),j1()){const d=ZE(),f=d!==null?performance.now()-d:null;R1(),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"}),nh();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 y;nh();const d=a.trim();if(!d||d2.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(nf){nf(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((y=xt.getState().tabs.find(D=>D.id===t))==null?void 0:y.status)==="dormant"){di.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&My(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const v=n2(d);if(v){pt.info("voice","voice-command",{tabId:t,label:v.label,transcript:d}),window.api.pty.write({tabId:t,data:v.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Hl();const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&My(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}),Hl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,rg(),ss==null||ss.destroy(),ss=null,nf=null,lt.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)})});ss=p,nf=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),nh(),p.start().then(()=>{ss===p&&(Is==null||Is(),Is=t2(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),lt.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=ss;t&&(rg(),Hl(),Qg=0,G_=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ss===t&&(ss=null,nf=null),e().hotkeyState==="stopping"&&(ag(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ss;if(!t)return;rg(),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(),ss===t&&(ss=null);const{useSessions:n}=await os(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>pE);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:()=>Hl(),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}=ev(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"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),lg(),Og={tabId:l,source:n,mode:r},Lg=Ct.subscribe((f,v)=>{if(Og&&f.modelStatus==="ready"&&v.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Og;if(lg(),!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"){lg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(lg(),Hl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(ag(),i({hotkeyState:"destroyed"}))}})),u2=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),ev=i=>gv()?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 h2=6e4,p2=5e3,Af=In(()=>({data:null,refreshing:!1}));let Oy=!1,Bg=null,Ly=null,zy=!1;async function Gb(){Af.setState({refreshing:!0});let i=h2;try{const e=await jb(window.api.billing.fetch(),p2,"billing.fetch");Af.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Ly==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Ly=e.kind}catch(e){if(Af.setState({refreshing:!1}),!zy){zy=!0;const t=e instanceof Error?e.message:String(e);lt.warn(`Billing usage fetch failed: ${t}`)}}Bg=setTimeout(Gb,i)}function f2(){Oy||(Oy=!0,Gb())}function M1(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 m2(){Bg!==null&&(clearTimeout(Bg),Bg=null),Gb()}function Fb(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku)[-_](\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}`}const ug=new Map,g2=3e4;function Hb(i){const[e,t]=G.useState(()=>{var n;return i?((n=ug.get(i))==null?void 0:n.value)??null:null});return G.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=ug.get(i);if(l&&Date.now()-l.ts<g2){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;ug.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;ug.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function v2(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 H_="sm.almanac.sidebarWidth",O1=180,L1=480,W_=252;function _2(){try{const i=parseInt(localStorage.getItem(H_)??"",10);if(Number.isFinite(i))return Math.min(L1,Math.max(O1,i))}catch{}return W_}const b2=52,z1="sm.almanac.sidebarCollapsed";function w2(){try{return localStorage.getItem(z1)==="1"}catch{}return!1}const B1="sm.almanac.collapsedGroups";function y2(){try{const i=localStorage.getItem(B1);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 x2(){const i=xt(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:jr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function S2({active:i,onNavigate:e,onNewSession:t}){const[n,r]=G.useState(()=>y2()),l=G.useCallback(j=>{r(H=>{const U=new Set(H);U.has(j)?U.delete(j):U.add(j);try{localStorage.setItem(B1,JSON.stringify(Array.from(U)))}catch{}return U})},[]),[p,a]=G.useState(()=>w2()),d=G.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(z1,H?"1":"0")}catch{}return H})},[]),f=xt(j=>j.tabs),v=xt(j=>j.activeTabId),m=f.find(j=>j.id===v)??null,y=x2(),D=Ei(j=>j.navFace),k=vE(D),T=k.filter(j=>j.group==="Workspace"),b=k.filter(j=>j.group==="Configure"),C=v2(k),w=D==="home"&&!p,[x,$]=G.useState(()=>_2()),R=G.useRef(x);R.current=x;const N=G.useCallback(j=>{j.preventDefault();const H=j.clientX,U=R.current;let oe=U;const de=me=>{oe=Math.min(L1,Math.max(O1,U+(me.clientX-H))),$(oe)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(H_,String(oe))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=G.useCallback(()=>{$(W_);try{localStorage.setItem(H_,String(W_))}catch{}},[]);return h.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?b2:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx(C2,{tab:m,navFace:D,onNewSession:t,rail:p,onToggleRail:d}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:w?h.jsxs(h.Fragment,{children:[h.jsx(Xv,{label:"Workspace",desc:Wv.Workspace,collapsed:n.has("Workspace"),count:T.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&T.map(j=>h.jsx(Jv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Xv,{label:"Configure",desc:Wv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Jv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Xv,{label:"Tools",desc:Wv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(By,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:k.map(j=>j.group==="Tools"?h.jsx(By,{tool:{key:j.key,label:j.label,icon:j.icon,hint:j.hint},active:i===j.key,onClick:()=>e(j.key),rail:p},j.key):h.jsx(Jv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(k2,{rail:p,navFace:D}),!p&&h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:L,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 C2({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Hb((i==null?void 0:i.cwd)??null);return n?h.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[h.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:h.jsx(rs,{name:"plus",size:15,stroke:1.8})}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:h.jsx(rs,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(rs,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.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:[h.jsx(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(rs,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[h.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),h.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),h.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.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:[h.jsx(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Xv({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return h.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[h.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:[h.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),h.jsx("span",{className:"flex-1",children:i}),t&&h.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&h.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 Jv({item:i,active:e,live:t,onClick:n,rail:r}){return h.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(rs,{name:i.icon,size:17,stroke:1.6})}),!r&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&h.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 By({tool:i,active:e,onClick:t,rail:n}){return h.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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(rs,{name:i.icon,size:15,stroke:1.6})}),!n&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function k2({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=xt(d=>d.tabs),r=xt(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=G.useState(null);return G.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return s1(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?h.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):h.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:[h.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")&&h.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Fb(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]"},E2={dialog:50};function T2(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function D2(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 $2(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 v of["command","file_path","pattern","url","query","subagent_type","description"])d&&v in d&&(f[v]=d[v]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const v=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),y=typeof(v==null?void 0:v.file_path)=="string"?v.file_path:void 0,D=typeof(v==null?void 0:v.command)=="string"?v.command:void 0,k=y?y.split("/").pop()??y:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:y??D,toolName:a.name}),m&&y&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(y.split("/").pop()??y,34)}`,target:y,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,v=a.output_tokens??a.outputTokens??0,m=d+f+v;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+v,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=T2(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Gg=In((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]:D2(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:v}=await os(async()=>{const{toast:m}=await Promise.resolve().then(()=>a1);return{toast:m}},void 0,import.meta.url);v.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:v}=$2(p,d,r);p=f,a=a.concat(v)}if(a.length>0){let d=l.activitySeq;const f=a.map(v=>({...v,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function A2(i){const e=Gg(r=>r.subscribe),t=Gg(r=>r.unsubscribe),n=Gg(r=>i?r.tabs[i.id]:void 0);return G.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 I2({onNavigate:i}){const e=xt(x=>x.tabs),t=xt(x=>x.activeTabId),n=e.find(x=>x.id===t)??null,r=A2(n),l=(r==null?void 0:r.lastEventAt)??0,p=Af(x=>x.data),a=jr(x=>{var $;return(($=x.snapshot)==null?void 0:$.paused)??null}),d=Hb((n==null?void 0:n.cwd)??null),[,f]=G.useState(0);G.useEffect(()=>{const x=setInterval(()=>f($=>$+1),6e4);return()=>clearInterval(x)},[]);const v=(r==null?void 0:r.todos)??[],[m,y]=G.useState(!1),D=G.useRef(null);G.useEffect(()=>{if(!m)return;const x=$=>{D.current&&!D.current.contains($.target)&&y(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[m]),G.useEffect(()=>{v.length===0&&y(!1)},[v.length]);const k=M1(p),T=(k==null?void 0:k.usage.five_hour)??null,b=T?Math.round(T.utilization):null,C=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",w=l>0?j2(Date.now()-l):"—";return h.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:[h.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:C?"Connected to Anthropic":"Disconnected",children:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${C?"bg-sage":"bg-fg-faint"}`}),h.jsx("span",{children:C?"connected":"offline"})]}),h.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:b!=null?`${b}% of 5h window used`:"5h —"}),a&&h.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:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&h.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&h.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),h.jsxs("span",{className:"text-fg-faint",children:["last activity: ",h.jsx("span",{className:"text-fg-dim",children:w})]}),v.length>0&&h.jsx(P2,{ref:D,todos:v,open:m,onToggle:()=>y(x=>!x)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.67.0"]})]})}const P2=G.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 h.jsxs("div",{ref:r,className:"relative",children:[h.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:[h.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),h.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),h.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),h.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&h.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:h.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>h.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[h.jsx(R2,{status:p.status}),h.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 R2({status:i}){return i==="completed"?h.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?h.jsx("span",{className:"w-3 shrink-0",children:h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):h.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function j2(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 N2({onClose:i,onSent:e}){const t=xt(L=>L.tabs),[n,r]=G.useState(""),[l,p]=G.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=G.useState(!1),[f,v]=G.useState({}),m=G.useRef(null),y=G.useRef(e);G.useEffect(()=>{y.current=e},[e]),G.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),G.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),G.useEffect(()=>window.api.pty.onWriteError(j=>{v(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),G.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>y.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,T=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!T,C=()=>{if(!b)return;d(!0);const L=xt.getState().tabs,j=new Set(L.map(U=>U.id)),H={};for(const U of D)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),H[U]="sent"):H[U]="skipped";v(H),d(!1)},w=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),C())},x=t.length>0&&t.every(L=>l[L.id]),$=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},R=Object.values(f).some(L=>L==="skipped"),N=T?R?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return h.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:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),h.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),h.jsx("textarea",{ref:m,value:n,onChange:L=>r(L.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"}),h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:x,onChange:$,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),h.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>h.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:j=>p(H=>({...H,[L.id]:j.target.checked})),className:"accent-accent"}),h.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&h.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&h.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),h.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[h.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"}),h.jsx("button",{onClick:C,disabled:!b,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:N})]})]})}function M2({tabId:i,cwd:e,onClose:t}){const n=Tf(k=>k.watchersForTab(i)),r=Tf(k=>k.add),l=Tf(k=>k.remove),p=G.useRef(null),[a,d]=G.useState(""),[f,v]=G.useState(""),[m,y]=G.useState(!1);G.useEffect(()=>{const k=T=>{T.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),G.useEffect(()=>{const k=T=>{p.current&&!p.current.contains(T.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||m)return;y(!0);const T=await r({tabId:i,label:a.trim(),command:k,cwd:e});y(!1),T&&(d(""),v(""))};return h.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:[h.jsxs("div",{className:"flex items-center mb-2",children:[h.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),h.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),h.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[h.jsx("input",{value:a,onChange:k=>d(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("input",{value:f,onChange:k=>v(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},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"}),h.jsx("button",{onClick:D,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"})]}),h.jsxs("span",{className:"text-fg-faint",children:["cwd: ",h.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?h.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):h.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const T=k.lines[k.lines.length-1];return h.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),h.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(T==null?void 0:T.line)??"",children:T?T.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2910
|
+
*/var Ey;function OE(){return Ey||(Ey=1,(function(i,e){var t=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,p=Object.prototype.hasOwnProperty,a=(Y=>typeof eo<"u"?eo:typeof Proxy<"u"?new Proxy(Y,{get:(se,he)=>(typeof eo<"u"?eo:se)[he]}):Y)(function(Y){if(typeof eo<"u")return eo.apply(this,arguments);throw Error('Dynamic require of "'+Y+'" is not supported')}),d=(Y,se)=>()=>(Y&&(se=Y(Y=0)),se),f=(Y,se)=>{for(var he in se)n(Y,he,{get:se[he],enumerable:!0})},v=(Y,se,he,Te)=>{if(se&&typeof se=="object"||typeof se=="function")for(let xe of l(se))!p.call(Y,xe)&&xe!==he&&n(Y,xe,{get:()=>se[xe],enumerable:!(Te=r(se,xe))||Te.enumerable});return Y},m=Y=>v(n({},"__esModule",{value:!0}),Y),y,D,k,T,b,C=d(()=>{y=new Map,D=[],k=(Y,se,he)=>{if(se&&typeof se.init=="function"&&typeof se.createInferenceSessionHandler=="function"){let Te=y.get(Y);if(Te===void 0)y.set(Y,{backend:se,priority:he});else{if(Te.priority>he)return;if(Te.priority===he&&Te.backend!==se)throw new Error(`cannot register backend "${Y}" using priority ${he}`)}if(he>=0){let xe=D.indexOf(Y);xe!==-1&&D.splice(xe,1);for(let Oe=0;Oe<D.length;Oe++)if(y.get(D[Oe]).priority<=he){D.splice(Oe,0,Y);return}D.push(Y)}return}throw new TypeError("not a valid backend")},T=async Y=>{let se=y.get(Y);if(!se)return"backend not found.";if(se.initialized)return se.backend;if(se.aborted)return se.error;{let he=!!se.initPromise;try{return he||(se.initPromise=se.backend.init(Y)),await se.initPromise,se.initialized=!0,se.backend}catch(Te){return he||(se.error=`${Te}`,se.aborted=!0),se.error}finally{delete se.initPromise}}},b=async Y=>{let se=Y.executionProviders||[],he=se.map(Le=>typeof Le=="string"?Le:Le.name),Te=he.length===0?D:he,xe,Oe=[],$e=new Set;for(let Le of Te){let tt=await T(Le);typeof tt=="string"?Oe.push({name:Le,err:tt}):(xe||(xe=tt),xe===tt&&$e.add(Le))}if(!xe)throw new Error(`no available backend found. ERR: ${Oe.map(Le=>`[${Le.name}] ${Le.err}`).join(", ")}`);for(let{name:Le,err:tt}of Oe)he.includes(Le)&&console.warn(`removing requested execution provider "${Le}" from session options because it is not available: ${tt}`);let Ae=se.filter(Le=>$e.has(typeof Le=="string"?Le:Le.name));return[xe,new Proxy(Y,{get:(Le,tt)=>tt==="executionProviders"?Ae:Reflect.get(Le,tt)})]}}),w=d(()=>{C()}),x,$=d(()=>{x="1.26.0"}),R,N,L=d(()=>{$(),R="warning",N={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(Y){if(Y!==void 0){if(typeof Y!="string"||["verbose","info","warning","error","fatal"].indexOf(Y)===-1)throw new Error(`Unsupported logging level: ${Y}`);R=Y}},get logLevel(){return R}},Object.defineProperty(N,"logLevel",{enumerable:!0})}),j,H=d(()=>{L(),j=N}),U,oe,de=d(()=>{U=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);he.width=Y.dims[3],he.height=Y.dims[2];let Te=he.getContext("2d");if(Te!=null){let xe,Oe;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2]);let $e=(se==null?void 0:se.format)!==void 0?se.format:"RGB",Ae=se==null?void 0:se.norm,Le,tt;Ae===void 0||Ae.mean===void 0?Le=[255,255,255,255]:typeof Ae.mean=="number"?Le=[Ae.mean,Ae.mean,Ae.mean,Ae.mean]:(Le=[Ae.mean[0],Ae.mean[1],Ae.mean[2],0],Ae.mean[3]!==void 0&&(Le[3]=Ae.mean[3])),Ae===void 0||Ae.bias===void 0?tt=[0,0,0,0]:typeof Ae.bias=="number"?tt=[Ae.bias,Ae.bias,Ae.bias,Ae.bias]:(tt=[Ae.bias[0],Ae.bias[1],Ae.bias[2],0],Ae.bias[3]!==void 0&&(tt[3]=Ae.bias[3]));let rt=Oe*xe,it=0,qe=rt,It=rt*2,Ne=-1;$e==="RGBA"?(it=0,qe=rt,It=rt*2,Ne=rt*3):$e==="RGB"?(it=0,qe=rt,It=rt*2):$e==="RBG"&&(it=0,It=rt,qe=rt*2);for(let dt=0;dt<Oe;dt++)for(let Ci=0;Ci<xe;Ci++){let Zt=(Y.data[it++]-tt[0])*Le[0],Qt=(Y.data[qe++]-tt[1])*Le[1],ki=(Y.data[It++]-tt[2])*Le[2],Ot=Ne===-1?255:(Y.data[Ne++]-tt[3])*Le[3];Te.fillStyle="rgba("+Zt+","+Qt+","+ki+","+Ot+")",Te.fillRect(Ci,dt,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")},oe=(Y,se)=>{let he=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(he!=null){let xe,Oe,$e;(se==null?void 0:se.tensorLayout)!==void 0&&se.tensorLayout==="NHWC"?(xe=Y.dims[2],Oe=Y.dims[1],$e=Y.dims[3]):(xe=Y.dims[3],Oe=Y.dims[2],$e=Y.dims[1]);let Ae=se!==void 0&&se.format!==void 0?se.format:"RGB",Le=se==null?void 0:se.norm,tt,rt;Le===void 0||Le.mean===void 0?tt=[255,255,255,255]:typeof Le.mean=="number"?tt=[Le.mean,Le.mean,Le.mean,Le.mean]:(tt=[Le.mean[0],Le.mean[1],Le.mean[2],255],Le.mean[3]!==void 0&&(tt[3]=Le.mean[3])),Le===void 0||Le.bias===void 0?rt=[0,0,0,0]:typeof Le.bias=="number"?rt=[Le.bias,Le.bias,Le.bias,Le.bias]:(rt=[Le.bias[0],Le.bias[1],Le.bias[2],0],Le.bias[3]!==void 0&&(rt[3]=Le.bias[3]));let it=Oe*xe;if(se!==void 0&&(se.format!==void 0&&$e===4&&se.format!=="RGBA"||$e===3&&se.format!=="RGB"&&se.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let qe=4,It=0,Ne=1,dt=2,Ci=3,Zt=0,Qt=it,ki=it*2,Ot=-1;Ae==="RGBA"?(Zt=0,Qt=it,ki=it*2,Ot=it*3):Ae==="RGB"?(Zt=0,Qt=it,ki=it*2):Ae==="RBG"&&(Zt=0,ki=it,Qt=it*2),Te=he.createImageData(xe,Oe);for(let Ri=0;Ri<Oe*xe;It+=qe,Ne+=qe,dt+=qe,Ci+=qe,Ri++)Te.data[It]=(Y.data[Zt++]-rt[0])*tt[0],Te.data[Ne]=(Y.data[Qt++]-rt[1])*tt[1],Te.data[dt]=(Y.data[ki++]-rt[2])*tt[2],Te.data[Ci]=Ot===-1?255:(Y.data[Ot++]-rt[3])*tt[3]}else throw new Error("Can not access image data");return Te}}),Z,me,ie,ue,Ce,Ee,W=d(()=>{Ie(),Z=(Y,se)=>{if(Y===void 0)throw new Error("Image buffer must be defined");if(se.height===void 0||se.width===void 0)throw new Error("Image height and width must be defined");if(se.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:he,width:Te}=se,xe=se.norm??{mean:255,bias:0},Oe,$e;typeof xe.mean=="number"?Oe=[xe.mean,xe.mean,xe.mean,xe.mean]:Oe=[xe.mean[0],xe.mean[1],xe.mean[2],xe.mean[3]??255],typeof xe.bias=="number"?$e=[xe.bias,xe.bias,xe.bias,xe.bias]:$e=[xe.bias[0],xe.bias[1],xe.bias[2],xe.bias[3]??0];let Ae=se.format!==void 0?se.format:"RGBA",Le=se.tensorFormat!==void 0&&se.tensorFormat!==void 0?se.tensorFormat:"RGB",tt=he*Te,rt=Le==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),it=4,qe=0,It=1,Ne=2,dt=3,Ci=0,Zt=tt,Qt=tt*2,ki=-1;Ae==="RGB"&&(it=3,qe=0,It=1,Ne=2,dt=-1),Le==="RGBA"?ki=tt*3:Le==="RBG"?(Ci=0,Qt=tt,Zt=tt*2):Le==="BGR"&&(Qt=0,Zt=tt,Ci=tt*2);for(let Ot=0;Ot<tt;Ot++,qe+=it,Ne+=it,It+=it,dt+=it)rt[Ci++]=(Y[qe]+$e[0])/Oe[0],rt[Zt++]=(Y[It]+$e[1])/Oe[1],rt[Qt++]=(Y[Ne]+$e[2])/Oe[2],ki!==-1&&dt!==-1&&(rt[ki++]=(Y[dt]+$e[3])/Oe[3]);return Le==="RGBA"?new X("float32",rt,[1,4,he,Te]):new X("float32",rt,[1,3,he,Te])},me=async(Y,se)=>{let he=typeof HTMLImageElement<"u"&&Y instanceof HTMLImageElement,Te=typeof ImageData<"u"&&Y instanceof ImageData,xe=typeof ImageBitmap<"u"&&Y instanceof ImageBitmap,Oe=typeof Y=="string",$e,Ae=se??{},Le=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=rt=>typeof HTMLCanvasElement<"u"&&rt instanceof HTMLCanvasElement||rt instanceof OffscreenCanvas?rt.getContext("2d"):null;if(he){let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;if(se!==void 0&&se.resizedHeight!==void 0&&se.resizedWidth!==void 0&&(qe=se.resizedHeight,It=se.resizedWidth),se!==void 0){if(Ae=se,se.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It}else Ae.tensorFormat="RGBA",Ae.height=qe,Ae.width=It;it.drawImage(Y,0,0),$e=it.getImageData(0,0,It,qe).data}else throw new Error("Can not access image data")}else if(Te){let rt,it;if(se!==void 0&&se.resizedWidth!==void 0&&se.resizedHeight!==void 0?(rt=se.resizedHeight,it=se.resizedWidth):(rt=Y.height,it=Y.width),se!==void 0&&(Ae=se),Ae.format="RGBA",Ae.height=rt,Ae.width=it,se!==void 0){let qe=Le();qe.width=it,qe.height=rt;let It=tt(qe);if(It!=null)It.putImageData(Y,0,0),$e=It.getImageData(0,0,it,rt).data;else throw new Error("Can not access image data")}else $e=Y.data}else if(xe){if(se===void 0)throw new Error("Please provide image config with format for Imagebitmap");let rt=Le();rt.width=Y.width,rt.height=Y.height;let it=tt(rt);if(it!=null){let qe=Y.height,It=Y.width;return it.drawImage(Y,0,0,It,qe),$e=it.getImageData(0,0,It,qe).data,Ae.height=qe,Ae.width=It,Z($e,Ae)}else throw new Error("Can not access image data")}else{if(Oe)return new Promise((rt,it)=>{let qe=Le(),It=tt(qe);if(!Y||!It)return it();let Ne=new Image;Ne.crossOrigin="Anonymous",Ne.src=Y,Ne.onload=()=>{qe.width=Ne.width,qe.height=Ne.height,It.drawImage(Ne,0,0,qe.width,qe.height);let dt=It.getImageData(0,0,qe.width,qe.height);Ae.height=qe.height,Ae.width=qe.width,rt(Z(dt.data,Ae))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Ae);throw new Error("Input data provided is not supported - aborted tensor creation")},ie=(Y,se)=>{let{width:he,height:Te,download:xe,dispose:Oe}=se,$e=[1,Te,he,4];return new X({location:"texture",type:"float32",texture:Y,dims:$e,download:xe,dispose:Oe})},ue=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"gpu-buffer",type:he??"float32",gpuBuffer:Y,dims:Te,download:xe,dispose:Oe})},Ce=(Y,se)=>{let{dataType:he,dims:Te,download:xe,dispose:Oe}=se;return new X({location:"ml-tensor",type:he??"float32",mlTensor:Y,dims:Te,download:xe,dispose:Oe})},Ee=(Y,se,he)=>new X({location:"cpu-pinned",type:Y,data:se,dims:he??[se.length]})}),te,K,re,ve,_e=d(()=>{te=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),K=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),re=!1,ve=()=>{if(!re){re=!0;let Y=typeof BigInt64Array<"u"&&BigInt64Array.from,se=typeof BigUint64Array<"u"&&BigUint64Array.from,he=globalThis.Float16Array,Te=typeof he<"u"&&he.from;Y&&(te.set("int64",BigInt64Array),K.set(BigInt64Array,"int64")),se&&(te.set("uint64",BigUint64Array),K.set(BigUint64Array,"uint64")),Te?(te.set("float16",he),K.set(he,"float16")):te.set("float16",Uint16Array)}}}),Me,et,we=d(()=>{Ie(),Me=Y=>{let se=1;for(let he=0;he<Y.length;he++){let Te=Y[he];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${he}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${he}] must be a non-negative integer, got: ${Te}`);se*=Te}return se},et=(Y,se)=>{switch(Y.location){case"cpu":return new X(Y.type,Y.data,se);case"cpu-pinned":return new X({location:"cpu-pinned",data:Y.data,type:Y.type,dims:se});case"texture":return new X({location:"texture",texture:Y.texture,type:Y.type,dims:se});case"gpu-buffer":return new X({location:"gpu-buffer",gpuBuffer:Y.gpuBuffer,type:Y.type,dims:se});case"ml-tensor":return new X({location:"ml-tensor",mlTensor:Y.mlTensor,type:Y.type,dims:se});default:throw new Error(`tensorReshape: tensor location ${Y.location} is not supported`)}}}),X,Ie=d(()=>{de(),W(),_e(),we(),X=class{constructor(Y,se,he){ve();let Te,xe;if(typeof Y=="object"&&"location"in Y)switch(this.dataLocation=Y.location,Te=Y.type,xe=Y.dims,Y.location){case"cpu-pinned":{let $e=te.get(Te);if(!$e)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(Y.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=Y.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=Y.texture,this.downloader=Y.download,this.disposer=Y.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=Y.gpuBuffer,this.downloader=Y.download,this.disposer=Y.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=Y.mlTensor,this.downloader=Y.download,this.disposer=Y.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Ae;if(typeof Y=="string")if(Te=Y,Ae=he,Y==="string"){if(!Array.isArray(se))throw new TypeError("A string tensor's data must be a string array.");$e=se}else{let Le=te.get(Y);if(Le===void 0)throw new TypeError(`Unsupported tensor type: ${Y}.`);if(Array.isArray(se)){if(Y==="float16"&&Le===Uint16Array||Y==="uint4"||Y==="int4")throw new TypeError(`Creating a ${Y} tensor from number array is not supported. Please use ${Le.name} as data.`);Y==="uint64"||Y==="int64"?$e=Le.from(se,BigInt):$e=Le.from(se)}else if(se instanceof Le)$e=se;else if(se instanceof Uint8ClampedArray)if(Y==="uint8")$e=Uint8Array.from(se);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(Y==="float16"&&se instanceof Uint16Array&&Le!==Uint16Array)$e=new globalThis.Float16Array(se.buffer,se.byteOffset,se.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Le}`)}else if(Ae=se,Array.isArray(Y)){if(Y.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Le=typeof Y[0];if(Le==="string")Te="string",$e=Y;else if(Le==="boolean")Te="bool",$e=Uint8Array.from(Y);else throw new TypeError(`Invalid element type of data array: ${Le}.`)}else if(Y instanceof Uint8ClampedArray)Te="uint8",$e=Uint8Array.from(Y);else{let Le=K.get(Y.constructor);if(Le===void 0)throw new TypeError(`Unsupported type for tensor data: ${Y.constructor}.`);Te=Le,$e=Y}if(Ae===void 0)Ae=[$e.length];else if(!Array.isArray(Ae))throw new TypeError("A tensor's dims must be a number array");xe=Ae,this.cpuData=$e,this.dataLocation="cpu"}let Oe=Me(xe);if(this.cpuData&&Oe!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Oe/2)===this.cpuData.length))throw new Error(`Tensor's size(${Oe}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=xe,this.size=Oe}static async fromImage(Y,se){return me(Y,se)}static fromTexture(Y,se){return ie(Y,se)}static fromGpuBuffer(Y,se){return ue(Y,se)}static fromMLTensor(Y,se){return Ce(Y,se)}static fromPinnedBuffer(Y,se,he){return Ee(Y,se,he)}toDataURL(Y){return U(this,Y)}toImageData(Y){return oe(this,Y)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(Y){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let se=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=se,Y&&this.disposer&&(this.disposer(),this.disposer=void 0),se}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(Y){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return et(this,Y)}}}),pe,Ze=d(()=>{Ie(),pe=X}),ge,Ke,vt,st,Kt,Be,Dt=d(()=>{L(),ge=(Y,se)=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeStamp(`${Y}::ORT::${se}`)},Ke=(Y,se)=>{var xe;let he=((xe=new Error().stack)==null?void 0:xe.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Oe=0;Oe<he.length;Oe++){if(Te&&!he[Oe].includes("TRACE_FUNC")){let $e=`FUNC_${Y}::${he[Oe].trim().split(" ")[1]}`;se&&($e+=`::${se}`),ge("CPU",$e);return}he[Oe].includes("TRACE_FUNC")&&(Te=!0)}},vt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("BEGIN",Y)},st=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||Ke("END",Y)},Kt=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.time(`ORT::${Y}`)},Be=Y=>{(typeof N.trace>"u"?!N.wasm.trace:!N.trace)||console.timeEnd(`ORT::${Y}`)}}),_t,ri=d(()=>{C(),Ze(),Dt(),_t=class E1{constructor(se){this.handler=se}async run(se,he,Te){vt(),Kt("InferenceSession.run");let xe={},Oe={};if(typeof se!="object"||se===null||se instanceof pe||Array.isArray(se))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof he=="object"){if(he===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(he instanceof pe)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.");$e=!1;for(let tt of he){if(typeof tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${tt}.`);xe[tt]=null}if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,rt=Object.getOwnPropertyNames(he);for(let it of this.outputNames)if(rt.indexOf(it)!==-1){let qe=he[it];(qe===null||qe instanceof pe)&&(tt=!0,$e=!1,xe[it]=qe)}if(tt){if(typeof Te=="object"&&Te!==null)Oe=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Oe=he}}else if(typeof he<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof se[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)xe[tt]=null;let Ae=await this.handler.run(se,xe,Oe),Le={};for(let tt in Ae)if(Object.hasOwnProperty.call(Ae,tt)){let rt=Ae[tt];rt instanceof pe?Le[tt]=rt:Le[tt]=new pe(rt.type,rt.data,rt.dims)}return Be("InferenceSession.run"),st(),Le}async release(){return this.handler.dispose()}static async create(se,he,Te,xe){vt(),Kt("InferenceSession.create");let Oe,$e={};if(typeof se=="string"){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof Uint8Array){if(Oe=se,typeof he=="object"&&he!==null)$e=he;else if(typeof he<"u")throw new TypeError("'options' must be an object.")}else if(se instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&se instanceof SharedArrayBuffer){let rt=se,it=0,qe=se.byteLength;if(typeof he=="object"&&he!==null)$e=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(qe=se.byteLength-it,typeof Te=="number"){if(qe=Te,!Number.isSafeInteger(qe))throw new RangeError("'byteLength' must be an integer.");if(qe<=0||it+qe>rt.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${rt.byteLength-it}].`);if(typeof xe=="object"&&xe!==null)$e=xe;else if(typeof xe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof he<"u")throw new TypeError("'options' must be an object.");Oe=new Uint8Array(rt,it,qe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ae,Le]=await b($e),tt=await Ae.createInferenceSessionHandler(Oe,Le);return Be("InferenceSession.create"),st(),new E1(tt)}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,St=d(()=>{ri(),Ye=_t}),ut=d(()=>{}),Xe=d(()=>{}),Pt=d(()=>{}),oi=d(()=>{}),Fi={};f(Fi,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,env:()=>j,registerBackend:()=>k});var li=d(()=>{w(),H(),St(),Ze(),ut(),Xe(),Dt(),Pt(),oi()}),tn=d(()=>{}),Ii={};f(Ii,{default:()=>pr});var Ui,ui,pr,ga=d(()=>{var Y;fe(),Hn(),Fn(),Ui="ort-wasm-proxy-worker",ui=((Y=globalThis.self)==null?void 0:Y.name)===Ui,ui&&(self.onmessage=se=>{let{type:he,in:Te}=se.data;try{switch(he){case"init-wasm":Js(Te.wasm).then(()=>{Lo(Te).then(()=>{postMessage({type:he})},xe=>{postMessage({type:he,err:xe})})},xe=>{postMessage({type:he,err:xe})});break;case"init-ep":{let{epName:xe,env:Oe}=Te;wr(Oe,xe).then(()=>{postMessage({type:he})},$e=>{postMessage({type:he,err:$e})});break}case"copy-from":{let{buffer:xe}=Te,Oe=ni(xe);postMessage({type:he,out:Oe});break}case"create":{let{model:xe,options:Oe}=Te;us(xe,Oe).then($e=>{postMessage({type:he,out:$e})},$e=>{postMessage({type:he,err:$e})});break}case"release":zr(Te),postMessage({type:he});break;case"run":{let{sessionId:xe,inputIndices:Oe,inputs:$e,outputIndices:Ae,options:Le}=Te;Ve(xe,Oe,$e,Ae,new Array(Ae.length).fill(null),Le).then(tt=>{tt.some(rt=>rt[3]!=="cpu")?postMessage({type:he,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:he,out:tt},ft([...$e,...tt]))},tt=>{postMessage({type:he,err:tt})});break}case"end-profiling":Un(Te),postMessage({type:he});break;default:}}catch(xe){postMessage({type:he,err:xe})}}),pr=ui?null:se=>new Worker(se??vi,{type:"classic",name:Ui})}),Mo,fr,vi,Gn,nn,mr,Rs,as,Mr,gr,vr,js,Pn,Fn=d(()=>{tn(),Mo=typeof location>"u"?void 0:location.origin,fr=()=>{var Y,se;return typeof document<"u"?(Y=document.currentScript)==null?void 0:Y.src:typeof self<"u"?(se=self.location)==null?void 0:se.href:void 0},vi=fr(),Gn=()=>{if(vi&&!vi.startsWith("blob:"))return vi.substring(0,vi.lastIndexOf("/")+1)},nn=(Y,se)=>{try{let he=se??vi;return(he?new URL(Y,he):new URL(Y)).origin===Mo}catch{return!1}},mr=(Y,se)=>{let he=se??vi;try{return(he?new URL(Y,he):new URL(Y)).href}catch{return}},Rs=(Y,se)=>`${se??"./"}${Y}`,as=async Y=>{let se=await(await fetch(Y,{credentials:"same-origin"})).blob();return URL.createObjectURL(se)},Mr=async Y=>(await import(Y)).default,gr=(ga(),m(Ii)).default,vr=async()=>{if(!vi)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(nn(vi))return[void 0,gr()];let Y=await as(vi);return[Y,gr(Y)]},js=void 0,Pn=async(Y,se,he,Te)=>{let xe=js&&!(Y||se);if(xe)if(vi)xe=nn(vi)||Te&&!he;else if(Te&&!he)xe=!0;else throw new Error("cannot determine the script source URL.");if(xe)return[void 0,js];{let Oe="ort-wasm-simd-threaded.mjs",$e=Y??mr(Oe,se),Ae=he&&$e&&!nn($e,se),Le=Ae?await as($e):$e??Rs(Oe,se);return[Ae?Le:void 0,await Mr(Le)]}}}),Ks,Rn,ls,Es,no,Ys,Xs,Js,zt,Hn=d(()=>{Fn(),Rn=!1,ls=!1,Es=!1,no=()=>{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}},Ys=()=>{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}},Xs=()=>{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 Y=>{if(Rn)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Es)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let se=Y.initTimeout,he=Y.numThreads;if(Y.simd!==!1){if(Y.simd==="relaxed"){if(!Xs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Ys())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=no();he>1&&!Te&&(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."),Y.numThreads=he=1);let xe=Y.wasmPaths,Oe=typeof xe=="string"?xe:void 0,$e=xe==null?void 0:xe.mjs,Ae=($e==null?void 0:$e.href)??$e,Le=xe==null?void 0:xe.wasm,tt=(Le==null?void 0:Le.href)??Le,rt=Y.wasmBinary,[it,qe]=await Pn(Ae,Oe,he>1,!!rt||!!tt),It=!1,Ne=[];if(se>0&&Ne.push(new Promise(dt=>{setTimeout(()=>{It=!0,dt()},se)})),Ne.push(new Promise((dt,Ci)=>{let Zt={numThreads:he};if(rt)Zt.wasmBinary=rt,Zt.locateFile=Qt=>Qt;else if(tt||Oe)Zt.locateFile=Qt=>tt??Oe+Qt;else if(Ae&&Ae.indexOf("blob:")!==0)Zt.locateFile=Qt=>new URL(Qt,Ae).href;else if(it){let Qt=Gn();Qt&&(Zt.locateFile=ki=>Qt+ki)}qe(Zt).then(Qt=>{ls=!1,Rn=!0,Ks=Qt,dt(),it&&URL.revokeObjectURL(it)},Qt=>{ls=!1,Es=!0,Ci(Qt)})})),await Promise.race(Ne),It)throw new Error(`WebAssembly backend initializing failed due to timeout: ${se}ms`)},zt=()=>{if(Rn&&Ks)return Ks;throw new Error("WebAssembly is not initialized yet.")}}),Hi,yi,kt,Or=d(()=>{Hn(),Hi=(Y,se)=>{let he=zt(),Te=he.lengthBytesUTF8(Y)+1,xe=he._malloc(Te);return he.stringToUTF8(Y,xe,Te),se.push(xe),xe},yi=(Y,se,he,Te)=>{if(typeof Y=="object"&&Y!==null){if(he.has(Y))throw new Error("Circular reference in options");he.add(Y)}Object.entries(Y).forEach(([xe,Oe])=>{let $e=se?se+xe:xe;if(typeof Oe=="object")yi(Oe,$e+".",he,Te);else if(typeof Oe=="string"||typeof Oe=="number")Te($e,Oe.toString());else if(typeof Oe=="boolean")Te($e,Oe?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Oe}`)})},kt=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetLastError(xe,xe+Te);let Oe=Number(se.getValue(xe,Te===4?"i32":"i64")),$e=se.getValue(xe+Te,"*"),Ae=$e?se.UTF8ToString($e):"";throw new Error(`${Y} ERROR_CODE: ${Oe}, ERROR_MESSAGE: ${Ae}`)}finally{se.stackRestore(he)}}}),so,va=d(()=>{Hn(),Or(),so=Y=>{let se=zt(),he=0,Te=[],xe=Y||{};try{if((Y==null?void 0:Y.logSeverityLevel)===void 0)xe.logSeverityLevel=2;else if(typeof Y.logSeverityLevel!="number"||!Number.isInteger(Y.logSeverityLevel)||Y.logSeverityLevel<0||Y.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${Y.logSeverityLevel}`);if((Y==null?void 0:Y.logVerbosityLevel)===void 0)xe.logVerbosityLevel=0;else if(typeof Y.logVerbosityLevel!="number"||!Number.isInteger(Y.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${Y.logVerbosityLevel}`);(Y==null?void 0:Y.terminate)===void 0&&(xe.terminate=!1);let Oe=0;return(Y==null?void 0:Y.tag)!==void 0&&(Oe=Hi(Y.tag,Te)),he=se._OrtCreateRunOptions(xe.logSeverityLevel,xe.logVerbosityLevel,!!xe.terminate,Oe),he===0&&kt("Can't create run options."),(Y==null?void 0:Y.extra)!==void 0&&yi(Y.extra,"",new WeakSet,($e,Ae)=>{let Le=Hi($e,Te),tt=Hi(Ae,Te);se._OrtAddRunConfigEntry(he,Le,tt)!==0&&kt(`Can't set a run config entry: ${$e} - ${Ae}.`)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseRunOptions(he),Te.forEach($e=>se._free($e)),Oe}}}),ro,oo,Oo,kn,_a,ba,xi=d(()=>{Hn(),Or(),ro=Y=>{switch(Y){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${Y}`)}},oo=Y=>{switch(Y){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${Y}`)}},Oo=Y=>{Y.extra||(Y.extra={}),Y.extra.session||(Y.extra.session={});let se=Y.extra.session;se.use_ort_model_bytes_directly||(se.use_ort_model_bytes_directly="1"),Y.executionProviders&&Y.executionProviders.some(he=>(typeof he=="string"?he:he.name)==="webgpu")&&(Y.enableMemPattern=!1)},kn=(Y,se,he,Te)=>{let xe=Hi(se,Te),Oe=Hi(he,Te);zt()._OrtAddSessionConfigEntry(Y,xe,Oe)!==0&&kt(`Can't set a session config entry: ${se} - ${he}.`)},_a=async(Y,se,he)=>{let Te=se.executionProviders;for(let xe of Te){let Oe=typeof xe=="string"?xe:xe.name,$e=[];switch(Oe){case"webnn":if(Oe="WEBNN",kn(Y,"session.disable_quant_qdq","1",he),kn(Y,"session.disable_qdq_constant_folding","1",he),typeof xe!="string"){let it=xe==null?void 0:xe.deviceType;it&&kn(Y,"deviceType",it,he)}break;case"webgpu":if(Oe="JS",typeof xe!="string"){let it=xe;if(it!=null&&it.preferredLayout){if(it.preferredLayout!=="NCHW"&&it.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${it.preferredLayout}`);kn(Y,"preferredLayout",it.preferredLayout,he)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Oe}`)}let Ae=Hi(Oe,he),Le=$e.length,tt=0,rt=0;if(Le>0){tt=zt()._malloc(Le*zt().PTR_SIZE),he.push(tt),rt=zt()._malloc(Le*zt().PTR_SIZE),he.push(rt);for(let it=0;it<Le;it++)zt().setValue(tt+it*zt().PTR_SIZE,$e[it][0],"*"),zt().setValue(rt+it*zt().PTR_SIZE,$e[it][1],"*")}await zt()._OrtAppendExecutionProvider(Y,Ae,tt,rt,Le)!==0&&kt(`Can't append execution provider: ${Oe}.`)}},ba=async Y=>{let se=zt(),he=0,Te=[],xe=Y||{};Oo(xe);try{let Oe=ro(xe.graphOptimizationLevel??"all"),$e=oo(xe.executionMode??"sequential"),Ae=typeof xe.logId=="string"?Hi(xe.logId,Te):0,Le=xe.logSeverityLevel??2;if(!Number.isInteger(Le)||Le<0||Le>4)throw new Error(`log severity level is not valid: ${Le}`);let tt=xe.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let rt=typeof xe.optimizedModelFilePath=="string"?Hi(xe.optimizedModelFilePath,Te):0;if(he=se._OrtCreateSessionOptions(Oe,!!xe.enableCpuMemArena,!!xe.enableMemPattern,$e,!!xe.enableProfiling,0,Ae,Le,tt,rt),he===0&&kt("Can't create session options."),xe.executionProviders&&await _a(he,xe,Te),xe.enableGraphCapture!==void 0){if(typeof xe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${xe.enableGraphCapture}`);kn(he,"enableGraphCapture",xe.enableGraphCapture.toString(),Te)}if(xe.freeDimensionOverrides)for(let[it,qe]of Object.entries(xe.freeDimensionOverrides)){if(typeof it!="string")throw new Error(`free dimension override name must be a string: ${it}`);if(typeof qe!="number"||!Number.isInteger(qe)||qe<0)throw new Error(`free dimension override value must be a non-negative integer: ${qe}`);let It=Hi(it,Te);se._OrtAddFreeDimensionOverride(he,It,qe)!==0&&kt(`Can't set a free dimension override: ${it} - ${qe}.`)}return xe.extra!==void 0&&yi(xe.extra,"",new WeakSet,(it,qe)=>{kn(he,it,qe,Te)}),[he,Te]}catch(Oe){throw he!==0&&se._OrtReleaseSessionOptions(he)!==0&&kt("Can't release session options."),Te.forEach($e=>se._free($e)),Oe}}}),jn,Vi,Nn,Zs,Lr,_r,cs,gn,Bt=d(()=>{jn=Y=>{switch(Y){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${Y}`)}},Vi=Y=>{switch(Y){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${Y}`)}},Nn=(Y,se)=>{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][Y],Te=typeof se=="number"?se:se.reduce((xe,Oe)=>xe*Oe,1);return he>0?Math.ceil(Te*he):void 0},Zs=Y=>{switch(Y){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${Y}`)}},Lr=Y=>{switch(Y){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${Y}`)}},_r=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",cs=Y=>Y==="float32"||Y==="float16"||Y==="int32"||Y==="int64"||Y==="uint32"||Y==="uint64"||Y==="int8"||Y==="uint8"||Y==="bool"||Y==="uint4"||Y==="int4",gn=Y=>{switch(Y){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${Y}`)}}}),qi,br=d(()=>{tn(),qi=async Y=>{if(typeof Y=="string"){let se=await fetch(Y);if(!se.ok)throw new Error(`failed to load external data file: ${Y}`);let he=se.headers.get("Content-Length"),Te=he?parseInt(he,10):0;if(Te<1073741824)return new Uint8Array(await se.arrayBuffer());{if(!se.body)throw new Error(`failed to load external data file: ${Y}, no response body.`);let xe=se.body.getReader(),Oe;try{Oe=new ArrayBuffer(Te)}catch(Ae){if(Ae instanceof RangeError){let Le=Math.ceil(Te/65536);Oe=new WebAssembly.Memory({initial:Le,maximum:Le}).buffer}else throw Ae}let $e=0;for(;;){let{done:Ae,value:Le}=await xe.read();if(Ae)break;let tt=Le.byteLength;new Uint8Array(Oe,$e,tt).set(Le),$e+=tt}return new Uint8Array(Oe,0,Te)}}else return Y instanceof Blob?new Uint8Array(await Y.arrayBuffer()):Y instanceof Uint8Array?Y:new Uint8Array(Y)}}),ds,Lo,wr,Wn,Ns,yr,ni,us,zr,Ts,Ve,Un,ft,fe=d(()=>{li(),va(),xi(),Bt(),Hn(),Or(),br(),ds=(Y,se)=>{zt()._OrtInit(Y,se)!==0&&kt("Can't initialize onnxruntime.")},Lo=async Y=>{ds(Y.wasm.numThreads,Lr(Y.logLevel))},wr=async(Y,se)=>{var Te,xe;(xe=(Te=zt()).asyncInit)==null||xe.call(Te);let he=Y.webgpu.adapter;if(se==="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 Oe=Y.webgpu.powerPreference;if(Oe!==void 0&&Oe!=="low-power"&&Oe!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Oe}"`);let $e=Y.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(he=await navigator.gpu.requestAdapter({powerPreference:Oe,forceFallbackAdapter:$e}),!he)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(se==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wn=new Map,Ns=Y=>{let se=zt(),he=se.stackSave();try{let Te=se.PTR_SIZE,xe=se.stackAlloc(2*Te);se._OrtGetInputOutputCount(Y,xe,xe+Te)!==0&&kt("Can't get session input/output count.");let Oe=Te===4?"i32":"i64";return[Number(se.getValue(xe,Oe)),Number(se.getValue(xe+Te,Oe))]}finally{se.stackRestore(he)}},yr=(Y,se)=>{let he=zt(),Te=he.stackSave(),xe=0;try{let Oe=he.PTR_SIZE,$e=he.stackAlloc(2*Oe);he._OrtGetInputOutputMetadata(Y,se,$e,$e+Oe)!==0&&kt("Can't get session input/output metadata.");let Ae=Number(he.getValue($e,"*"));xe=Number(he.getValue($e+Oe,"*"));let Le=he.HEAP32[xe/4];if(Le===0)return[Ae,0];let tt=he.HEAPU32[xe/4+1],rt=[];for(let it=0;it<tt;it++){let qe=Number(he.getValue(xe+8+it*Oe,"*"));rt.push(qe!==0?he.UTF8ToString(qe):Number(he.getValue(xe+8+(it+tt)*Oe,"*")))}return[Ae,Le,rt]}finally{he.stackRestore(Te),xe!==0&&he._OrtFree(xe)}},ni=Y=>{let se=zt(),he=se._malloc(Y.byteLength);if(he===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${Y.byteLength}.`);return se.HEAPU8.set(Y,he),[he,Y.byteLength]},us=async(Y,se)=>{var rt,it,qe;let he,Te,xe=zt();Array.isArray(Y)?[he,Te]=Y:Y.buffer===xe.HEAPU8.buffer?[he,Te]=[Y.byteOffset,Y.byteLength]:[he,Te]=ni(Y);let Oe=0,$e=0,Ae=[],Le=[],tt=[];try{if([$e,Ae]=await ba(se),(se==null?void 0:se.externalData)&&xe.mountExternalData){let Ri=[];for(let ci of se.externalData){let vn=typeof ci=="string"?ci:ci.path;Ri.push(qi(typeof ci=="string"?ci:ci.data).then(Mn=>{xe.mountExternalData(vn,Mn)}))}await Promise.all(Ri)}for(let Ri of(se==null?void 0:se.executionProviders)??[])if((typeof Ri=="string"?Ri:Ri.name)==="webnn"){if(xe.shouldTransferToMLTensor=!1,typeof Ri!="string"){let ci=Ri,vn=ci==null?void 0:ci.context,Mn=ci==null?void 0:ci.gpuDevice,Vn=ci==null?void 0:ci.deviceType,ya=ci==null?void 0:ci.powerPreference;vn?xe.currentContext=vn:Mn?xe.currentContext=await xe.webnnCreateMLContext(Mn):xe.currentContext=await xe.webnnCreateMLContext({deviceType:Vn,powerPreference:ya})}else xe.currentContext=await xe.webnnCreateMLContext();break}Oe=await xe._OrtCreateSession(he,Te,$e),(rt=xe.webgpuOnCreateSession)==null||rt.call(xe,Oe),Oe===0&&kt("Can't create a session."),(it=xe.jsepOnCreateSession)==null||it.call(xe),xe.currentContext&&(xe.webnnRegisterMLContext(Oe,xe.currentContext),xe.currentContext=void 0,xe.shouldTransferToMLTensor=!0);let[It,Ne]=Ns(Oe),dt=!!(se!=null&&se.enableGraphCapture),Ci=[],Zt=[],Qt=[],ki=[],Ot=[];for(let Ri=0;Ri<It;Ri++){let[ci,vn,Mn]=yr(Oe,Ri);ci===0&&kt("Can't get an input name."),Le.push(ci);let Vn=xe.UTF8ToString(ci);Ci.push(Vn),Qt.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}for(let Ri=0;Ri<Ne;Ri++){let[ci,vn,Mn]=yr(Oe,Ri+It);ci===0&&kt("Can't get an output name."),tt.push(ci);let Vn=xe.UTF8ToString(ci);Zt.push(Vn),ki.push(vn===0?{name:Vn,isTensor:!1}:{name:Vn,isTensor:!0,type:Vi(vn),shape:Mn})}return Wn.set(Oe,[Oe,Le,tt,null,dt,!1]),[Oe,Ci,Zt,Qt,ki]}catch(It){throw Le.forEach(Ne=>xe._OrtFree(Ne)),tt.forEach(Ne=>xe._OrtFree(Ne)),Oe!==0&&xe._OrtReleaseSession(Oe)!==0&&kt("Can't release session."),It}finally{xe._free(he),$e!==0&&xe._OrtReleaseSessionOptions($e)!==0&&kt("Can't release session options."),Ae.forEach(It=>xe._free(It)),(qe=xe.unmountExternalData)==null||qe.call(xe)}},zr=Y=>{var Le,tt,rt;let se=zt(),he=Wn.get(Y);if(!he)throw new Error(`cannot release session. invalid session id: ${Y}`);let[Te,xe,Oe,$e,Ae]=he;$e&&(Ae&&se._OrtClearBoundOutputs($e.handle)!==0&&kt("Can't clear bound outputs."),se._OrtReleaseBinding($e.handle)!==0&&kt("Can't release IO binding.")),(Le=se.jsepOnReleaseSession)==null||Le.call(se,Y),(tt=se.webnnOnReleaseSession)==null||tt.call(se,Y),(rt=se.webgpuOnReleaseSession)==null||rt.call(se,Y),xe.forEach(it=>se._OrtFree(it)),Oe.forEach(it=>se._OrtFree(it)),se._OrtReleaseSession(Te)!==0&&kt("Can't release session."),Wn.delete(Y)},Ts=async(Y,se,he,Te,xe,Oe,$e=!1)=>{if(!Y){se.push(0);return}let Ae=zt(),Le=Ae.PTR_SIZE,tt=Y[0],rt=Y[1],it=Y[3],qe=it,It,Ne;if(tt==="string"&&(it==="gpu-buffer"||it==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&it!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Oe} when enableGraphCapture is true.`);if(it==="gpu-buffer"){let Zt=Y[2].gpuBuffer;Ne=Nn(jn(tt),rt);{let Qt=Ae.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');It=Qt(Te,Oe,Zt,Ne)}}else if(it==="ml-tensor"){let Zt=Y[2].mlTensor;Ne=Nn(jn(tt),rt);let Qt=Ae.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');It=Qt(Te,Zt,jn(tt),rt)}else{let Zt=Y[2];if(Array.isArray(Zt)){Ne=Le*Zt.length,It=Ae._malloc(Ne),he.push(It);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`);Ae.setValue(It+Qt*Le,Hi(Zt[Qt],he),"*")}}else{let Qt=Ae.webnnIsGraphInput,ki=Ae.webnnIsGraphOutput;if(tt!=="string"&&Qt&&ki){let Ot=Ae.UTF8ToString(xe);if(Qt(Te,Ot)||ki(Te,Ot)){let Ri=jn(tt);Ne=Nn(Ri,rt),qe="ml-tensor";let ci=Ae.webnnCreateTemporaryTensor,vn=Ae.webnnUploadTensor;if(!ci||!vn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Mn=await ci(Te,Ri,rt);vn(Mn,new Uint8Array(Zt.buffer,Zt.byteOffset,Zt.byteLength)),It=Mn}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}else Ne=Zt.byteLength,It=Ae._malloc(Ne),he.push(It),Ae.HEAPU8.set(new Uint8Array(Zt.buffer,Zt.byteOffset,Ne),It)}}let dt=Ae.stackSave(),Ci=Ae.stackAlloc(4*rt.length);try{rt.forEach((Qt,ki)=>Ae.setValue(Ci+ki*Le,Qt,Le===4?"i32":"i64"));let Zt=Ae._OrtCreateTensor(jn(tt),It,Ne,Ci,rt.length,gn(qe));Zt===0&&kt(`Can't create tensor for input/output. session=${Te}, index=${Oe}.`),se.push(Zt)}finally{Ae.stackRestore(dt)}},Ve=async(Y,se,he,Te,xe,Oe)=>{var qn,ol,nc;let $e=zt(),Ae=$e.PTR_SIZE,Le=Wn.get(Y);if(!Le)throw new Error(`cannot run inference. invalid session id: ${Y}`);let tt=Le[0],rt=Le[1],it=Le[2],qe=Le[3],It=Le[4];Le[5];let Ne=se.length,dt=Te.length,Ci=0,Zt=[],Qt=[],ki=[],Ot=[],Ri=[],ci=$e.stackSave(),vn=$e.stackAlloc(Ne*Ae),Mn=$e.stackAlloc(Ne*Ae),Vn=$e.stackAlloc(dt*Ae),ya=$e.stackAlloc(dt*Ae);try{[Ci,Zt]=so(Oe),Kt("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)await Ts(he[ai],Qt,Ot,Y,rt[se[ai]],se[ai],It);for(let ai=0;ai<dt;ai++)await Ts(xe[ai],ki,Ot,Y,it[Te[ai]],Ne+Te[ai],It);Be("wasm prepareInputOutputTensor");for(let ai=0;ai<Ne;ai++)$e.setValue(vn+ai*Ae,Qt[ai],"*"),$e.setValue(Mn+ai*Ae,rt[se[ai]],"*");for(let ai=0;ai<dt;ai++)$e.setValue(Vn+ai*Ae,ki[ai],"*"),$e.setValue(ya+ai*Ae,it[Te[ai]],"*");(qn=$e.jsepOnRunStart)==null||qn.call($e,tt),(ol=$e.webnnOnRunStart)==null||ol.call($e,tt);let _n;_n=await $e._OrtRun(tt,Mn,vn,Ne,ya,dt,Vn,Ci),_n!==0&&kt("failed to call OrtRun().");let er=[],sc=[];Kt("wasm ProcessOutputTensor");for(let ai=0;ai<dt;ai++){let Os=Number($e.getValue(Vn+ai*Ae,"*"));if(Os===ki[ai]||Ri.includes(ki[ai])){er.push(xe[ai]),Os!==ki[ai]&&$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.");continue}let dd=$e.stackSave(),Cr=$e.stackAlloc(4*Ae),zo=!1,an,Kn=0;try{$e._OrtGetTensorData(Os,Cr,Cr+Ae,Cr+2*Ae,Cr+3*Ae)!==0&&kt(`Can't access output tensor data on index ${ai}.`);let al=Ae===4?"i32":"i64",Yn=Number($e.getValue(Cr,al));Kn=$e.getValue(Cr+Ae,"*");let rc=$e.getValue(Cr+Ae*2,"*"),ud=Number($e.getValue(Cr+Ae*3,al)),kr=[];for(let ln=0;ln<ud;ln++)kr.push(Number($e.getValue(rc+ln*Ae,al)));$e._OrtFree(rc)!==0&&kt("Can't free memory for tensor dims.");let Ls=kr.reduce((ln,Wi)=>ln*Wi,1);an=Vi(Yn);let tr=qe==null?void 0:qe.outputPreferredLocations[Te[ai]];if(an==="string"){if(tr==="gpu-buffer"||tr==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ln=[];for(let Wi=0;Wi<Ls;Wi++){let zs=$e.getValue(Kn+Wi*Ae,"*"),oc=$e.getValue(Kn+(Wi+1)*Ae,"*"),ac=Wi===Ls-1?void 0:oc-zs;ln.push($e.UTF8ToString(zs,ac))}er.push([an,kr,ln,"cpu"])}else if(tr==="gpu-buffer"&&Ls>0){let ln=$e.jsepGetBuffer;if(!ln)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wi=ln(Kn),zs=Nn(Yn,Ls);if(zs===void 0||!_r(an))throw new Error(`Unsupported data type: ${an}`);zo=!0,er.push([an,kr,{gpuBuffer:Wi,download:$e.jsepCreateDownloader(Wi,zs,an),dispose:()=>{$e._OrtReleaseTensor(Os)!==0&&kt("Can't release tensor.")}},"gpu-buffer"])}else if(tr==="ml-tensor"&&Ls>0){let ln=$e.webnnEnsureTensor,Wi=$e.webnnIsGraphInputOutputTypeSupported;if(!ln||!Wi)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Nn(Yn,Ls)===void 0||!cs(an))throw new Error(`Unsupported data type: ${an}`);if(!Wi(Y,an,!1))throw new Error(`preferredLocation "ml-tensor" for ${an} output is not supported by current WebNN Context.`);let zs=await ln(Y,Kn,Yn,kr,!1);zo=!0,er.push([an,kr,{mlTensor:zs,download:$e.webnnCreateMLTensorDownloader(Kn,an),dispose:()=>{$e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(tr==="ml-tensor-cpu-output"&&Ls>0){let ln=$e.webnnCreateMLTensorDownloader(Kn,an)(),Wi=er.length;zo=!0,sc.push((async()=>{let zs=[Wi,await ln];return $e.webnnReleaseTensorId(Kn),$e._OrtReleaseTensor(Os),zs})()),er.push([an,kr,[],"cpu"])}else{let ln=Zs(an),Wi=new ln(Ls);new Uint8Array(Wi.buffer,Wi.byteOffset,Wi.byteLength).set($e.HEAPU8.subarray(Kn,Kn+Wi.byteLength)),er.push([an,kr,Wi,"cpu"])}}finally{$e.stackRestore(dd),an==="string"&&Kn&&$e._free(Kn),zo||$e._OrtReleaseTensor(Os)}}qe&&!It&&($e._OrtClearBoundOutputs(qe.handle)!==0&&kt("Can't clear bound outputs."),Wn.set(Y,[tt,rt,it,qe,It,!1]));for(let[ai,Os]of await Promise.all(sc))er[ai][2]=Os;return Be("wasm ProcessOutputTensor"),er}finally{(nc=$e.webnnOnRunEnd)==null||nc.call($e,tt),$e.stackRestore(ci),Qt.forEach(_n=>$e._OrtReleaseTensor(_n)),ki.forEach(_n=>$e._OrtReleaseTensor(_n)),Ot.forEach(_n=>$e._free(_n)),Ci!==0&&$e._OrtReleaseRunOptions(Ci),Zt.forEach(_n=>$e._free(_n))}},Un=Y=>{let se=zt(),he=Wn.get(Y);if(!he)throw new Error("invalid session id");let Te=he[0],xe=se._OrtEndProfiling(Te);xe===0&&kt("Can't get an profile file name."),se._OrtFree(xe)},ft=Y=>{let se=[];for(let he of Y){let Te=he[2];!Array.isArray(Te)&&"buffer"in Te&&se.push(Te.buffer)}return se}}),Re,Je,Tt,ti,si,Pi,Ti,sn,Oi,on,Di,Ms,Br,ao,Qs,cd,lo,co,ec=d(()=>{li(),fe(),Hn(),Fn(),Re=()=>!!j.wasm.proxy&&typeof document<"u",Tt=!1,ti=!1,si=!1,sn=new Map,Oi=(Y,se)=>{let he=sn.get(Y);he?he.push(se):sn.set(Y,[se])},on=()=>{if(Tt||!ti||si||!Je)throw new Error("worker not ready")},Di=Y=>{switch(Y.data.type){case"init-wasm":Tt=!1,Y.data.err?(si=!0,Ti[1](Y.data.err)):(ti=!0,Ti[0]()),Pi&&(URL.revokeObjectURL(Pi),Pi=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let se=sn.get(Y.data.type);Y.data.err?se.shift()[1](Y.data.err):se.shift()[0](Y.data.out);break}}},Ms=async()=>{if(!ti){if(Tt)throw new Error("multiple calls to 'initWasm()' detected.");if(si)throw new Error("previous call to 'initWasm()' failed.");if(Tt=!0,Re())return new Promise((Y,se)=>{Je==null||Je.terminate(),vr().then(([he,Te])=>{try{Je=Te,Je.onerror=Oe=>se(Oe),Je.onmessage=Di,Ti=[Y,se];let xe={type:"init-wasm",in:j};if(!xe.in.wasm.wasmPaths&&he){let Oe=Gn();Oe&&(xe.in.wasm.wasmPaths=Oe)}Je.postMessage(xe),Pi=he}catch(xe){se(xe)}},se)});try{await Js(j.wasm),await Lo(j),ti=!0}catch(Y){throw si=!0,Y}finally{Tt=!1}}},Br=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("init-ep",[se,he]);let Te={type:"init-ep",in:{epName:Y,env:j}};Je.postMessage(Te)});await wr(j,Y)},ao=async Y=>Re()?(on(),new Promise((se,he)=>{Oi("copy-from",[se,he]);let Te={type:"copy-from",in:{buffer:Y}};Je.postMessage(Te,[Y.buffer])})):ni(Y),Qs=async(Y,se)=>{if(Re()){if(se!=null&&se.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return on(),new Promise((he,Te)=>{Oi("create",[he,Te]);let xe={type:"create",in:{model:Y,options:{...se}}},Oe=[];Y instanceof Uint8Array&&Oe.push(Y.buffer),Je.postMessage(xe,Oe)})}else return us(Y,se)},cd=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("release",[se,he]);let Te={type:"release",in:Y};Je.postMessage(Te)});zr(Y)},lo=async(Y,se,he,Te,xe,Oe)=>{if(Re()){if(he.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(xe.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return on(),new Promise(($e,Ae)=>{Oi("run",[$e,Ae]);let Le=he,tt={type:"run",in:{sessionId:Y,inputIndices:se,inputs:Le,outputIndices:Te,options:Oe}};Je.postMessage(tt,ft(Le))})}else return Ve(Y,se,he,Te,xe,Oe)},co=async Y=>{if(Re())return on(),new Promise((se,he)=>{Oi("end-profiling",[se,he]);let Te={type:"end-profiling",in:Y};Je.postMessage(Te)});Un(Y)}}),il,uo,wa,nl=d(()=>{li(),ec(),Bt(),tn(),br(),il=(Y,se)=>{switch(Y.location){case"cpu":return[Y.type,Y.dims,Y.data,"cpu"];case"gpu-buffer":return[Y.type,Y.dims,{gpuBuffer:Y.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[Y.type,Y.dims,{mlTensor:Y.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${Y.location} for ${se()}`)}},uo=Y=>{switch(Y[3]){case"cpu":return new pe(Y[0],Y[2],Y[1]);case"gpu-buffer":{let se=Y[0];if(!_r(se))throw new Error(`not supported data type: ${se} for deserializing GPU tensor`);let{gpuBuffer:he,download:Te,dispose:xe}=Y[2];return pe.fromGpuBuffer(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}case"ml-tensor":{let se=Y[0];if(!cs(se))throw new Error(`not supported data type: ${se} for deserializing MLTensor tensor`);let{mlTensor:he,download:Te,dispose:xe}=Y[2];return pe.fromMLTensor(he,{dataType:se,dims:Y[1],download:Te,dispose:xe})}default:throw new Error(`invalid data location: ${Y[3]}`)}},wa=class{async fetchModelAndCopyToWasmMemory(Y){return ao(await qi(Y))}async loadModel(Y,se){vt();let he;typeof Y=="string"?he=await this.fetchModelAndCopyToWasmMemory(Y):he=Y,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Qs(he,se),st()}async dispose(){return cd(this.sessionId)}async run(Y,se,he){vt();let Te=[],xe=[];Object.entries(Y).forEach(it=>{let qe=it[0],It=it[1],Ne=this.inputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid input '${qe}'`);Te.push(It),xe.push(Ne)});let Oe=[],$e=[];Object.entries(se).forEach(it=>{let qe=it[0],It=it[1],Ne=this.outputNames.indexOf(qe);if(Ne===-1)throw new Error(`invalid output '${qe}'`);Oe.push(It),$e.push(Ne)});let Ae=Te.map((it,qe)=>il(it,()=>`input "${this.inputNames[xe[qe]]}"`)),Le=Oe.map((it,qe)=>it?il(it,()=>`output "${this.outputNames[$e[qe]]}"`):null),tt=await lo(this.sessionId,xe,Ae,$e,Le,he),rt={};for(let it=0;it<tt.length;it++)rt[this.outputNames[$e[it]]]=Oe[it]??uo(tt[it]);return st(),rt}startProfiling(){}endProfiling(){co(this.sessionId)}}}),xr={};f(xr,{OnnxruntimeWebAssemblyBackend:()=>Sr,initializeFlags:()=>Gr,wasmBackend:()=>ho});var Gr,Sr,ho,tc=d(()=>{li(),ec(),nl(),Gr=()=>{(typeof j.wasm.initTimeout!="number"||j.wasm.initTimeout<0)&&(j.wasm.initTimeout=0);let Y=j.wasm.simd;if(typeof Y!="boolean"&&Y!==void 0&&Y!=="fixed"&&Y!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${Y}". Reset it to \`false\` and ignore SIMD feature checking.`),j.wasm.simd=!1),typeof j.wasm.proxy!="boolean"&&(j.wasm.proxy=!1),typeof j.wasm.trace!="boolean"&&(j.wasm.trace=!1),typeof j.wasm.numThreads!="number"||!Number.isInteger(j.wasm.numThreads)||j.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)j.wasm.numThreads=1;else{let se=typeof navigator>"u"?a("node:os").cpus().length:navigator.hardwareConcurrency;j.wasm.numThreads=Math.min(4,Math.ceil((se||1)/2))}},Sr=class{async init(Y){Gr(),await Ms(),await Br(Y)}async createInferenceSessionHandler(Y,se){let he=new wa;return await he.loadModel(Y,se),he}},ho=new Sr}),ic={};f(ic,{InferenceSession:()=>Ye,TRACE:()=>ge,TRACE_EVENT_BEGIN:()=>Kt,TRACE_EVENT_END:()=>Be,TRACE_FUNC_BEGIN:()=>vt,TRACE_FUNC_END:()=>st,Tensor:()=>pe,default:()=>rl,env:()=>j,registerBackend:()=>k}),li(),li(),li();var sl="1.26.0",rl=Fi;{let Y=(tc(),m(xr)).wasmBackend;k("cpu",Y,10),k("wasm",Y,10)}return Object.defineProperty(j.versions,"web",{value:sl,enumerable:!0}),m(ic)})();i.exports=t})(Kv)),Kv.exports}var Ty;function LE(){return Ty||(Ty=1,(function(i){var e=Ua&&Ua.__createBinding||(Object.create?(function(x,$,R,N){N===void 0&&(N=R);var L=Object.getOwnPropertyDescriptor($,R);(!L||("get"in L?!$.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return $[R]}}),Object.defineProperty(x,N,L)}):(function(x,$,R,N){N===void 0&&(N=R),x[N]=$[R]})),t=Ua&&Ua.__setModuleDefault||(Object.create?(function(x,$){Object.defineProperty(x,"default",{enumerable:!0,value:$})}):function(x,$){x.default=$}),n=Ua&&Ua.__importStar||function(x){if(x&&x.__esModule)return x;var $={};if(x!=null)for(var R in x)R!=="default"&&Object.prototype.hasOwnProperty.call(x,R)&&e($,x,R);return t($,x),$};Object.defineProperty(i,"__esModule",{value:!0}),i.MicVAD=i.getDefaultRealTimeVADOptions=i.ort=i.DEFAULT_MODEL=void 0;const r=n(OE()),l=zb(),p=Bb(),a=Yf(),d=mv(),f=C1(),v=k1();i.DEFAULT_MODEL="legacy",i.ort=r;const m="vad.worklet.bundle.min.js",y="silero_vad_v5.onnx",D="silero_vad_legacy.onnx",k=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 $=>{$.getTracks().forEach(R=>{R.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:$=>{$.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});i.getDefaultRealTimeVADOptions=k;const T=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function b(x,$,R,N,L){await R.audioWorklet.addModule(x),$.processorOptions={...$.processorOptions??{},frameSamples:N};const j=new AudioWorkletNode(R,"vad-helper-worklet",$);return j.port.onmessage=async H=>{const U=H.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case d.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const oe=new Float32Array(U.data);await L(oe);break}}},j}async function C(x,$,R){const N=new v.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:$});a.log.debug("using script processor");const j=x.createScriptProcessor(4096,1,1);let H=!1;return j.onaudioprocess=async U=>{if(!H){H=!0;try{const oe=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=N.process(oe);for(const me of Z)await R(me)}catch(oe){console.error("Error processing audio:",oe)}finally{H=!1}}},j.connect(x.destination),j}class w{constructor($,R,N,L,j=!1,H=null,U=null,oe=null,de=null,Z=null,me=null,ie="uninitialized",ue=!1){this.options=$,this.frameProcessor=R,this.model=N,this.frameSamples=L,this.listening=j,this.errored=H,this._stream=U,this._audioContext=oe,this._vadNode=de,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=me,this.initializationState=ie,this.ownsAudioContext=ue,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=Ce=>{this.initializationState="errored",this.errored=Ce},this.start=async()=>{switch(this.initializationState){case"uninitialized":{a.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(Ce){throw Ce instanceof Error?this.setErrored(Ce.message):this.setErrored(String(Ce)),Ce}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?T(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await b(this.options.baseAssetPath+m,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await C(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:Ce,audioContext:Ee,vadNode:W}=this.getAudioInstances();this._stream=await this.options.resumeStream(Ce);const te=new MediaStreamAudioSourceNode(Ee,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=te,te.connect(W);break}case"destroyed":{a.log.warn("start called after destroyed");break}case"errored":{a.log.error("start called after errored");break}default:{a.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:Ce,mediaStreamAudioSourceNode:Ee}=this.getAudioInstances();await this.options.pauseStream(Ce),Ee.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var Ee;a.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:Ce}=this.getAudioInstances();Ce instanceof AudioWorkletNode&&Ce.port.postMessage(d.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((Ee=this._audioContext)==null?void 0:Ee.close())},this.setOptions=Ce=>{this.frameProcessor.setOptions(Ce)},this.processFrame=async Ce=>{await this.frameProcessor.process(Ce,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=Ce=>{switch(Ce.msg){case d.Message.FrameProcessed:this.options.onFrameProcessed(Ce.probs,Ce.frame);break;case d.Message.SpeechStart:this.options.onSpeechStart();break;case d.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case d.Message.VADMisfire:this.options.onVADMisfire();break;case d.Message.SpeechEnd:this.options.onSpeechEnd(Ce.audio);break}}}static async new($={}){const R={...(0,i.getDefaultRealTimeVADOptions)($.model??i.DEFAULT_MODEL),...$};(0,p.validateOptions)(R),i.ort.env.wasm.wasmPaths=R.onnxWASMBasePath,R.ortConfig!==void 0&&R.ortConfig(i.ort);const N=R.model==="v5"?y:D,L=R.baseAssetPath+N,j=R.model==="v5"?f.SileroV5.new:f.SileroLegacy.new;let H;try{H=await j(i.ort,()=>(0,l.defaultModelFetcher)(L))}catch(me){throw console.error(`Encountered an error while loading model file ${L}`),me}const U=R.model==="v5"?512:1536,oe=U/16,de=new p.FrameProcessor(H.process,H.reset_state,{positiveSpeechThreshold:R.positiveSpeechThreshold,negativeSpeechThreshold:R.negativeSpeechThreshold,redemptionMs:R.redemptionMs,preSpeechPadMs:R.preSpeechPadMs,minSpeechMs:R.minSpeechMs,submitUserSpeechOnPause:R.submitUserSpeechOnPause},oe),Z=new w(R,de,H,U);if(R.startOnLoad)try{await Z.start()}catch(me){throw console.error("Error starting micVad",me),me}return Z}}i.MicVAD=w})(Ua)),Ua}var Dy;function zE(){return Dy||(Dy=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=zb();Object.defineProperty(i,"defaultModelFetcher",{enumerable:!0,get:function(){return t.defaultModelFetcher}});var n=Bb();Object.defineProperty(i,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=mv();Object.defineProperty(i,"Message",{enumerable:!0,get:function(){return r.Message}});var l=NE();Object.defineProperty(i,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const p=ME();i.utils={audioFileToArray:p.audioFileToArray,minFramesForTargetMS:p.minFramesForTargetMS,arrayBufferToBase64:p.arrayBufferToBase64,encodeWAV:p.encodeWAV};var a=LE();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}})})(Uv)),Uv}var BE=zE();function ig(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)=>ig(i,"debug",e,t),info:(i,e,t)=>ig(i,"info",e,t),warn:(i,e,t)=>ig(i,"warn",e,t),error:(i,e,t,n)=>ig(i,"error",e,t,n)},T1=16e3,GE=6,Wu=T1*GE,FE=400,HE=T1*FE/1e3,$y=300,Ay=2e3,Iy=1500,Py=3e3,WE=600,D1=.5,$1=.35,Ry=.85,jy=.7;let hr=null,pa=!1,qs=!1;const O_=new Set;function ng(i){for(const e of Array.from(O_))try{e(i)}catch(t){pt.warn("speech","workerDeath listener threw",{error:t instanceof Error?t.message:String(t)})}}let Yv=0;const Ny=2;let ih=!1,A1=!1;function I1(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}),UE(`error:${e.message||"unknown"}`)})}function Zg(){return hr||(hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),I1(hr),pt.info("speech","worker spawned"),hr)}let sg=!1;function UE(i){if(!ih){if(sg){pt.warn("speech","respawnWorker: already in flight, ignoring",{reason:i});return}if(sg=!0,Yv+=1,A1=!0,pt.warn("speech","respawnWorker: starting",{reason:i,attempt:Yv}),ng({reason:i,respawned:!1,finalOnly:!0}),Yv>Ny){if(ih=!0,pt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:Ny}),hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1,ng({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),sg=!1;return}if(hr)try{hr.terminate()}catch{}hr=null,pa=!1,qs=!1;try{hr=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),I1(hr),qs=!0,hr.postMessage({type:"load"}),pt.info("speech","respawnWorker: new worker spawned, load posted"),ng({reason:i,respawned:!0,finalOnly:!0})}catch(e){ih=!0,pt.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),ng({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{sg=!1}}}function VE(i,e){if(pa||qs)return;qs=!0;const t=Zg();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"&&(pa=!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 qE(){pt.info("speech","resetModel: clearing load flags"),pa=!1,qs=!1}function gv(){var i;return typeof Worker<"u"&&!!((i=navigator.mediaDevices)!=null&&i.getUserMedia)&&typeof AudioWorkletNode<"u"}function KE(i){const e=Zg();return!pa&&!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"&&(pa=!0,qs=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:i},[i.buffer])})}function P1(i){let e=Zg(),t=!1,n=null,r=null,l=null,p=null,a=null;const d=[],f=new Set;let v=null,m=0,y=!1,D=0,k=!1,T=!1,b=0,C=0,w=0,x=-1,$=$y,R=0,N=null,L="",j="",H=!1,U=0;function oe(ve,_e){const Me=Math.min(ve.length,_e.length);let et=0;for(;et<Me&&ve.charCodeAt(et)===_e.charCodeAt(et);)et++;return et}function de(ve){const _e=oe(L,ve);return L=ve,_e>j.length&&(j=ve.slice(0,_e)),j.length>ve.length&&(j=ve),j}const Z=()=>(v||(v=new Float32Array(Wu)),v),me=()=>{m=0},ie=ve=>{const _e=Z(),Me=ve.length;if(Me>=Wu){_e.set(ve.subarray(Me-Wu)),m=Wu;return}if(m+Me<=Wu){_e.set(ve,m),m+=Me;return}const et=m+Me-Wu;_e.copyWithin(0,et,m),m-=et,_e.set(ve,m),m+=Me},ue=()=>{N&&(clearTimeout(N),N=null)},Ce=()=>{ue(),y=!1,k=!1,T=!1,$=$y,L="",j="",H=!1,U=0,me()},Ee=()=>{if(t||!y||T||k||N)return;if(m<HE){N=setTimeout(()=>{N=null,Ee()},$);return}const ve=performance.now()-b;if(ve<$&&b!==0){N=setTimeout(()=>{N=null,Ee()},$-ve);return}if(A1||ih||i.partialsEnabled&&!i.partialsEnabled())return;const _e=Z(),Me=new Float32Array(m);Me.set(_e.subarray(0,m)),C+=1,w=C,k=!0,R=performance.now(),b=R,e.postMessage({type:"transcribe-partial",audio:Me,seq:C},[Me.buffer])},W=ve=>ve.length===0?Promise.resolve():ih?(pt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),t||i.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(_e=>{d.push(_e),C+=1;const Me=C;x=Me,e.postMessage({type:"transcribe",audio:ve,seq:Me},[ve.buffer])}),te=ve=>{const _e=W(ve);return f.add(_e),_e.finally(()=>{f.delete(_e)}),_e},K=ve=>{var _e,Me,et,we,X;if(ve.data.type==="result"){const Ie=ve.data.text,pe=ve.data.seq??0;pe&&pe<x&&pt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:pe,latestFinalSeq:x}),!t&&Ie&&i.onFinal(Ie),(_e=d.shift())==null||_e()}else if(ve.data.type==="partial"){const Ie=ve.data.seq??0,pe=ve.data.text??"",Ze=performance.now()-R;k=!1,Ze>=Py?(T=!0,pt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ze),seq:Ie})):Ze>=Iy&&($=Math.min($*2,Ay),pt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ze),newIntervalMs:$,seq:Ie})),H||(H=!0,Ze>WE&&$<500&&($=500,pt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ze),newIntervalMs:500})));const ge=Ie!==w||Ie<=x;if(!t&&!ge&&pe){const Ke=de(pe);Ke&&((Me=i.onPartial)==null||Me.call(i,Ke),U===0&&(U=performance.now(),pt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-D)})))}Ee()}else if(ve.data.type==="partial-error"){const Ie=performance.now()-R;k=!1,Ie>=Py?(T=!0,pt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Ie),seq:ve.data.seq})):Ie>=Iy&&($=Math.min($*2,Ay),pt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Ie),newIntervalMs:$,seq:ve.data.seq})),pt.warn("speech","partial encode failed",{error:ve.data.error,seq:ve.data.seq}),Ee()}else ve.data.type==="error"?(t||i.onError(ve.data.error),(et=d.shift())==null||et()):ve.data.type==="status"?(t||(we=i.onModelStatus)==null||we.call(i,ve.data.status,ve.data.message),ve.data.status==="ready"&&(pa=!0,qs=!1)):ve.data.type==="progress"&&(t||(X=i.onProgress)==null||X.call(i,ve.data.pct))};e.addEventListener("message",K);const re=ve=>{var _e,Me;if(!t){for(pt.warn("speech","createRecognition: worker death event",ve),(_e=i.onStatusChange)==null||_e.call(i,"restarting");d.length;)(Me=d.shift())==null||Me();if(f.clear(),ue(),k=!1,ve.respawned){try{e.removeEventListener("message",K)}catch{}e=Zg(),e.addEventListener("message",K)}}};return O_.add(re),{start:async()=>{if(!t){if(ih){i.onError("Speech recognition disabled — please reload the app.");return}!pa&&!qs&&(qs=!0,pt.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),pt.info("speech","createRecognition.start: initializing VAD",{modelReady:pa,modelLoading:qs});try{const ve=new URL("vad/",document.baseURI).href,_e=i.inputDeviceId||null,Me={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};_e&&(Me.deviceId={exact:_e}),pt.info("speech","getUserMedia",{hasDeviceId:!!_e,deviceIdPrefix:_e?_e.slice(0,8):null});const et=await navigator.mediaDevices.getUserMedia({audio:Me});r=et,l=new AudioContext;for(const we of et.getAudioTracks())we.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(we){pt.warn("speech","analyser init failed",{error:we instanceof Error?we.message:String(we)}),a=null,p=null}n=await BE.MicVAD.new({audioContext:l,getStream:async()=>et,resumeStream:async()=>et,pauseStream:async()=>{},baseAssetPath:ve,onnxWASMBasePath:ve,model:"v5",positiveSpeechThreshold:D1,negativeSpeechThreshold:$1,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(we,X)=>{var Ie;t||((Ie=i.onFrame)==null||Ie.call(i,we),y&&(ie(X),Ee()))},onSpeechStart:()=>{var we;t||(Ce(),y=!0,D=performance.now(),(we=i.onSpeechStart)==null||we.call(i))},onSpeechEnd:we=>{var X;t||((X=i.onStatusChange)==null||X.call(i,"transcribing"),Ce(),te(we))},onVADMisfire:()=>{var we,X;t||((we=i.onStatusChange)==null||we.call(i,"idle"),Ce(),(X=i.onMisfire)==null||X.call(i))}}),n.start()}catch(ve){const _e=ve instanceof Error?ve.message:"Microphone access denied",Me=ve instanceof Error?ve.stack:"";if(pt.error("speech","createRecognition.start: VAD init failed",{error:_e,stack:Me}),p){try{p.disconnect()}catch{}p=null}if(a){try{a.disconnect()}catch{}a=null}if(r){try{r.getTracks().forEach(et=>et.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}i.onError(_e)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(Ce();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(ve=>ve.stop())}catch{}r=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ve,_e)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ve,negativeSpeechThreshold:_e})}catch(Me){pt.warn("speech","setVadThresholds failed",{error:Me instanceof Error?Me.message:String(Me)})}},getAnalyser:()=>p,destroy:()=>{if(t=!0,Ce(),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(ve=>ve.stop())}catch{}r=null}O_.delete(re),e.removeEventListener("message",K)}}}let Df=null;const L_=new Set,z_=new Set;function YE(){for(const i of L_)try{i()}catch{}}function B_(){for(const i of z_)try{i()}catch{}}function XE(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 JE(i){if(!window.speechSynthesis)return;const e=XE(i);if(!e)return;const t=new SpeechSynthesisUtterance(e);t.rate=1,t.pitch=1,t.onstart=()=>{Df=performance.now(),YE()},t.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,B_())},t.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Df=null,B_())},window.speechSynthesis.speak(t)}function R1(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Df=null,B_())}function j1(){var i;return((i=window.speechSynthesis)==null?void 0:i.speaking)??!1}function ZE(){return Df}function QE(i){return L_.add(i),()=>{L_.delete(i)}}function e2(i){return z_.add(i),()=>{z_.delete(i)}}function t2(i){j1()&&(i.setVadThresholds(Ry,jy),pt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=QE(()=>{i.setVadThresholds(Ry,jy),pt.info("voice","tts.duck.on")}),t=e2(()=>{i.setVadThresholds(D1,$1),pt.info("voice","tts.duck.off")});return()=>{e(),t()}}const i2=[{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 n2(i){const e=i.trim();return i2.find(t=>t.match.test(e))??null}const s2=4e4;let nd=null;function nh(){nd&&clearTimeout(nd),nd=setTimeout(()=>{nd=null,Ct.getState().stopRecording()},s2)}function rg(){nd&&(clearTimeout(nd),nd=null)}let Xl=null,Ul=null;const r2=.04,o2=.3;let Qg=0,G_=0;function a2(i){Ul!==null&&cancelAnimationFrame(Ul);const e=()=>{if(Xl===null||Ct.getState().submitCountdownStartAt===null){Ul=null;return}const t=performance.now();if(t-G_<200&&Qg>o2){const r=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Qg.toFixed(2),msIntoCountdown:Math.round(r)}),Hl(),nh();return}const n=N1();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>r2){const a=t-i;pt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:p.toFixed(3),msIntoCountdown:Math.round(a)}),Hl(),nh();return}}Ul=requestAnimationFrame(e)};Ul=requestAnimationFrame(e)}function My(i){Xl&&clearTimeout(Xl);const e=Ct.getState().submitDelayMs,t=performance.now();Ct.setState({submitCountdownStartAt:t}),Xl=setTimeout(()=>{var r;Xl=null,Ct.setState({submitCountdownStartAt:null});const n=xt.getState().tabs.find(l=>l.id===i);if((n==null?void 0:n.status)==="dormant"){const l=(r=di.getState().chats[i])==null?void 0:r.pendingVoiceText;l&&(di.getState().send({tabId:i,sessionId:n.sessionId,cwd:n.cwd,prompt:l}),di.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)})}nh()},e),a2(t)}function Hl(){Ul!==null&&(cancelAnimationFrame(Ul),Ul=null),Xl&&(clearTimeout(Xl),Xl=null),Ct.getState().submitCountdownStartAt!==null&&Ct.setState({submitCountdownStartAt:null})}let ss=null,Is=null,nf=null;function N1(){var i;return((i=ss==null?void 0:ss.getAnalyser)==null?void 0:i.call(ss))??null}const og=1e4;let $f=null;function ag(){$f&&(clearTimeout($f),$f=null)}let Og=null,Lg=null;function lg(){Og=null,Lg&&(Lg(),Lg=null)}const l2=1500,c2=9e4;let cg=0,zg=null,F_=-1;function dg(){zg&&(clearTimeout(zg),zg=null,F_=-1)}const d2=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),Ct=In((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=++cg,n=()=>{t===cg&&(dg(),F_=t,zg=setTimeout(()=>{F_===t&&e().modelStatus==="loading"&&(pt.warn("voice","mic.gate.timeout: no progress within 90s"),i({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},c2))};n(),VE((r,l)=>{t===cg&&(r==="ready"?(dg(),pt.info("voice","modelStatus -> ready"),i({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(dg(),pt.error("voice","modelStatus -> error",{msg:l}),i({modelStatus:"error",error:l,errorKind:"load"})):(n(),i({modelStatus:"loading"})))},r=>{t===cg&&(n(),i({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{pt.info("voice","mic.gate.retry"),dg(),qE(),i({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(t,n)=>{if(e().isRecording)return;if(ss){pt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!gv()){i({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const r=l=>{try{const p=P1({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=>{Qg=a.isSpeech,G_=performance.now()},onSpeechStart:()=>{if(i({statusPill:"listening",lastPartial:""}),rg(),Hl(),j1()){const d=ZE(),f=d!==null?performance.now()-d:null;R1(),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"}),nh();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 y;nh();const d=a.trim();if(!d||d2.has(d)){i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(nf){nf(d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((y=xt.getState().tabs.find(D=>D.id===t))==null?void 0:y.status)==="dormant"){di.getState().setPendingVoiceText(t,d),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&My(t);const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}const v=n2(d);if(v){pt.info("voice","voice-command",{tabId:t,label:v.label,transcript:d}),window.api.pty.write({tabId:t,data:v.data}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Hl();const D=window;D.__transcripts&&(D.__transcripts.push({tabId:t,text:d}),D.__transcripts.length>500&&D.__transcripts.shift());return}window.api.pty.write({tabId:t,data:d}),i({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&My(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}),Hl(),i({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Is==null||Is(),Is=null,rg(),ss==null||ss.destroy(),ss=null,nf=null,lt.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)})});ss=p,nf=(n==null?void 0:n.sink)??null,i({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),nh(),p.start().then(()=>{ss===p&&(Is==null||Is(),Is=t2(p))}).catch(a=>{const d=a instanceof Error?a.message:String(a);pt.error("voice","handle.start() failed",{error:d}),lt.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=ss;t&&(rg(),Hl(),Qg=0,G_=0,Is==null||Is(),Is=null,i({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),t.stop().finally(()=>{t.destroy(),ss===t&&(ss=null,nf=null),e().hotkeyState==="stopping"&&(ag(),i({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const t=ss;if(!t)return;rg(),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(),ss===t&&(ss=null);const{useSessions:n}=await os(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>pE);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:()=>Hl(),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}=ev(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"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording());return}if(d==="loading"){p.hotkeyState!=="armed"&&(i({hotkeyState:"armed"}),pt.info("voice-hotkey","armed",{source:n,modelStatus:p.modelStatus})),lg(),Og={tabId:l,source:n,mode:r},Lg=Ct.subscribe((f,v)=>{if(Og&&f.modelStatus==="ready"&&v.modelStatus!=="ready"&&f.hotkeyState==="armed"){const m=Og;if(lg(),!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"){lg(),pt.info("voice-hotkey","miss-model-loading-armed-up"),i({hotkeyState:"idle"});return}p.hotkeyState==="recording"&&(i({hotkeyState:"stopping"}),ag(),$f=setTimeout(()=>{e().hotkeyState==="stopping"&&(pt.warn("voice-hotkey","drain-timeout",{durationMs:og}),i({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&i({hotkeyState:"idle"})},0))},og),p.stopRecording())}},destroyHotkey:()=>{const t=e();if(lg(),Hl(),t.hotkeyState==="recording"){pt.warn("voice-hotkey","destroyed-mid-recording"),i({hotkeyState:"destroyed"});try{t.stopRecording()}catch{}}else(t.hotkeyState==="armed"||t.hotkeyState==="stopping")&&(ag(),i({hotkeyState:"destroyed"}))}})),u2=i=>({isRecording:i.isRecording,statusPill:i.statusPill,lastPartial:i.lastPartial,lastTranscript:i.lastTranscript,submitCountdownStartAt:i.submitCountdownStartAt}),ev=i=>gv()?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 h2=6e4,p2=5e3,Af=In(()=>({data:null,refreshing:!1}));let Oy=!1,Bg=null,Ly=null,zy=!1;async function Gb(){Af.setState({refreshing:!0});let i=h2;try{const e=await jb(window.api.billing.fetch(),p2,"billing.fetch");Af.setState({data:e,refreshing:!1}),e.kind==="transient"?i=Ly==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(i=3e4),Ly=e.kind}catch(e){if(Af.setState({refreshing:!1}),!zy){zy=!0;const t=e instanceof Error?e.message:String(e);lt.warn(`Billing usage fetch failed: ${t}`)}}Bg=setTimeout(Gb,i)}function f2(){Oy||(Oy=!0,Gb())}function M1(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 m2(){Bg!==null&&(clearTimeout(Bg),Bg=null),Gb()}function Fb(i){if(!i||i==="—"||i==="unknown")return i;const e=/\[(\dm)\]/.exec(i),t=/(opus|sonnet|haiku)[-_](\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}`}const ug=new Map,g2=3e4;function Hb(i){const[e,t]=G.useState(()=>{var n;return i?((n=ug.get(i))==null?void 0:n.value)??null:null});return G.useEffect(()=>{if(!i){t(null);return}let n=!1;return(async()=>{const l=ug.get(i);if(l&&Date.now()-l.ts<g2){n||t(l.value);return}try{const p=await window.api.app.gitBranch(i);if(n)return;ug.set(i,{value:p,ts:Date.now()}),t(p)}catch{if(n)return;ug.set(i,{value:null,ts:Date.now()}),t(null)}})(),()=>{n=!0}},[i]),e}function v2(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 H_="sm.almanac.sidebarWidth",O1=180,L1=480,W_=252;function _2(){try{const i=parseInt(localStorage.getItem(H_)??"",10);if(Number.isFinite(i))return Math.min(L1,Math.max(O1,i))}catch{}return W_}const b2=52,z1="sm.almanac.sidebarCollapsed";function w2(){try{return localStorage.getItem(z1)==="1"}catch{}return!1}const B1="sm.almanac.collapsedGroups";function y2(){try{const i=localStorage.getItem(B1);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 x2(){const i=xt(t=>{var n;return((n=t.tabs.find(r=>r.id===t.activeTabId))==null?void 0:n.cwd)??null});return{scheduler:jr(t=>{var n;return(((n=t.snapshot)==null?void 0:n.jobs)??[]).some(r=>r.status==="running"&&(!i||r.cwd===i))})}}function S2({active:i,onNavigate:e,onNewSession:t}){const[n,r]=G.useState(()=>y2()),l=G.useCallback(j=>{r(H=>{const U=new Set(H);U.has(j)?U.delete(j):U.add(j);try{localStorage.setItem(B1,JSON.stringify(Array.from(U)))}catch{}return U})},[]),[p,a]=G.useState(()=>w2()),d=G.useCallback(()=>{a(j=>{const H=!j;try{localStorage.setItem(z1,H?"1":"0")}catch{}return H})},[]),f=xt(j=>j.tabs),v=xt(j=>j.activeTabId),m=f.find(j=>j.id===v)??null,y=x2(),D=Ei(j=>j.navFace),k=vE(D),T=k.filter(j=>j.group==="Workspace"),b=k.filter(j=>j.group==="Configure"),C=v2(k),w=D==="home"&&!p,[x,$]=G.useState(()=>_2()),R=G.useRef(x);R.current=x;const N=G.useCallback(j=>{j.preventDefault();const H=j.clientX,U=R.current;let oe=U;const de=me=>{oe=Math.min(L1,Math.max(O1,U+(me.clientX-H))),$(oe)},Z=()=>{window.removeEventListener("pointermove",de),window.removeEventListener("pointerup",Z),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(H_,String(oe))}catch{}};window.addEventListener("pointermove",de),window.addEventListener("pointerup",Z),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),L=G.useCallback(()=>{$(W_);try{localStorage.setItem(H_,String(W_))}catch{}},[]);return h.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:p?b2:x},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[h.jsx(C2,{tab:m,navFace:D,onNewSession:t,rail:p,onToggleRail:d}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:p?"4px":"8px"},children:w?h.jsxs(h.Fragment,{children:[h.jsx(Xv,{label:"Workspace",desc:Wv.Workspace,collapsed:n.has("Workspace"),count:T.length,onToggle:()=>l("Workspace")}),!n.has("Workspace")&&T.map(j=>h.jsx(Jv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:!1},j.key)),h.jsx(Xv,{label:"Configure",desc:Wv.Configure,collapsed:n.has("Configure"),count:b.length,onToggle:()=>l("Configure")}),!n.has("Configure")&&b.map(j=>h.jsx(Jv,{item:j,active:i===j.key,live:!1,onClick:()=>e(j.key),rail:!1},j.key)),C.length>0&&h.jsx(Xv,{label:"Tools",desc:Wv.Tools,collapsed:n.has("Tools"),count:C.length,onToggle:()=>l("Tools")}),C.length>0&&!n.has("Tools")&&C.map(j=>h.jsx(By,{tool:j,active:i===j.key,onClick:()=>e(j.key),rail:!1},j.key))]}):h.jsx("div",{className:"pt-2",children:k.map(j=>j.group==="Tools"?h.jsx(By,{tool:{key:j.key,label:j.label,icon:j.icon,hint:j.hint},active:i===j.key,onClick:()=>e(j.key),rail:p},j.key):h.jsx(Jv,{item:j,active:i===j.key,live:j.liveKind?y[j.liveKind]:!1,onClick:()=>e(j.key),rail:p},j.key))})}),h.jsx(k2,{rail:p,navFace:D}),!p&&h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:L,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 C2({tab:i,navFace:e,onNewSession:t,rail:n,onToggleRail:r}){const l=(i==null?void 0:i.label)??"no session",p=Hb((i==null?void 0:i.cwd)??null);return n?h.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[h.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:h.jsx(rs,{name:"plus",size:15,stroke:1.8})}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:h.jsx(rs,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(rs,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.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:[h.jsx(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):h.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),h.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:h.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:h.jsx(rs,{name:"chevron",size:13,stroke:1.8})})})]}),h.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[h.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),h.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(i==null?void 0:i.cwd)??"",children:l})]}),h.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:p?`⌥${p}`:i?i.cwd:"—"}),h.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:h.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:[h.jsx(rs,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function Xv({label:i,desc:e,collapsed:t,count:n,onToggle:r}){return h.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[h.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:[h.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:t?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),h.jsx("span",{className:"flex-1",children:i}),t&&h.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:n})]}),!t&&h.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 Jv({item:i,active:e,live:t,onClick:n,rail:r}){return h.jsxs("button",{onClick:n,title:i.hint,"data-testid":i.key==="scheduler"?"tour-scheduler":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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(rs,{name:i.icon,size:17,stroke:1.6})}),!r&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]}),!r&&t&&h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),r&&t&&h.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 By({tool:i,active:e,onClick:t,rail:n}){return h.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&&h.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${n?"-left-[4px]":"-left-[10px]"}`}),h.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:h.jsx(rs,{name:i.icon,size:15,stroke:1.6})}),!n&&h.jsxs("span",{className:"flex-1 min-w-0",children:[h.jsx("span",{className:"block truncate",children:i.label}),i.hint&&h.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:i.hint})]})]})}function k2({rail:i,navFace:e}){const t=Ct(d=>d.isRecording),n=xt(d=>d.tabs),r=xt(d=>d.activeTabId),l=n.find(d=>d.id===r)??null,[p,a]=G.useState(null);return G.useEffect(()=>{let d=!1;if(!(l!=null&&l.presetId)){a(null);return}return s1(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?h.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${t?"bg-red-500 animate-pulse":"bg-sage"}`,title:t?"recording":"idle"})}):h.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:[h.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")&&h.jsx("span",{className:"truncate",title:p??"",children:t?"recording…":p?`Claude · ${Fb(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]"},E2={dialog:50};function T2(i,e,t){return e?i.map(n=>n.id===e?{...n,lastActivityAt:t}:n):i}function D2(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 $2(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 v of["command","file_path","pattern","url","query","subagent_type","description"])d&&v in d&&(f[v]=d[v]);if(r.lastToolUses=[{id:a.id,name:a.name,input:f,at:n},...i.lastToolUses].slice(0,50),!(t!=null&&t.replay)){const v=a.input,m=["Edit","Write","NotebookEdit"].includes(a.name),y=typeof(v==null?void 0:v.file_path)=="string"?v.file_path:void 0,D=typeof(v==null?void 0:v.command)=="string"?v.command:void 0,k=y?y.split("/").pop()??y:D?p(D,28):"";l.push({id:0,kind:"tool-use",at:n,label:k?`${a.name} · ${k}`:a.name,target:y??D,toolName:a.name}),m&&y&&l.push({id:0,kind:"file-edit",at:n,label:`${a.name} · ${p(y.split("/").pop()??y,34)}`,target:y,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,v=a.output_tokens??a.outputTokens??0,m=d+f+v;r.usage={inputTokens:(i.usage.inputTokens||0)+f,outputTokens:(i.usage.outputTokens||0)+v,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=T2(i.agents,a==null?void 0:a.toolUseId,n);break}}return{next:r,newActivity:l}}const Gg=In((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]:D2(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:v}=await os(async()=>{const{toast:m}=await Promise.resolve().then(()=>a1);return{toast:m}},void 0,import.meta.url);v.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:v}=$2(p,d,r);p=f,a=a.concat(v)}if(a.length>0){let d=l.activitySeq;const f=a.map(v=>({...v,id:++d}));p={...p,activitySeq:d,activityRing:[...l.activityRing,...f].slice(-32)}}i({tabs:{...e().tabs,[t]:p}})}}));function A2(i){const e=Gg(r=>r.subscribe),t=Gg(r=>r.unsubscribe),n=Gg(r=>i?r.tabs[i.id]:void 0);return G.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 I2({onNavigate:i}){const e=xt(x=>x.tabs),t=xt(x=>x.activeTabId),n=e.find(x=>x.id===t)??null,r=A2(n),l=(r==null?void 0:r.lastEventAt)??0,p=Af(x=>x.data),a=jr(x=>{var $;return(($=x.snapshot)==null?void 0:$.paused)??null}),d=Hb((n==null?void 0:n.cwd)??null),[,f]=G.useState(0);G.useEffect(()=>{const x=setInterval(()=>f($=>$+1),6e4);return()=>clearInterval(x)},[]);const v=(r==null?void 0:r.todos)??[],[m,y]=G.useState(!1),D=G.useRef(null);G.useEffect(()=>{if(!m)return;const x=$=>{D.current&&!D.current.contains($.target)&&y(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[m]),G.useEffect(()=>{v.length===0&&y(!1)},[v.length]);const k=M1(p),T=(k==null?void 0:k.usage.five_hour)??null,b=T?Math.round(T.utilization):null,C=(p==null?void 0:p.kind)==="ok"||(p==null?void 0:p.kind)==="ok-stale",w=l>0?j2(Date.now()-l):"—";return h.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:[h.jsxs("button",{onClick:()=>i==null?void 0:i("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:C?"Connected to Anthropic":"Disconnected",children:[h.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${C?"bg-sage":"bg-fg-faint"}`}),h.jsx("span",{children:C?"connected":"offline"})]}),h.jsx("button",{onClick:()=>i==null?void 0:i("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:b!=null?`${b}% of 5h window used`:"5h —"}),a&&h.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:[h.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",a.reason]}),n&&h.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,d&&h.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",d]})]}),h.jsxs("span",{className:"text-fg-faint",children:["last activity: ",h.jsx("span",{className:"text-fg-dim",children:w})]}),v.length>0&&h.jsx(P2,{ref:D,todos:v,open:m,onToggle:()=>y(x=>!x)}),h.jsx("span",{className:"flex-1"}),h.jsxs("span",{className:"text-fg-faint",children:["v","0.68.0"]})]})}const P2=G.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 h.jsxs("div",{ref:r,className:"relative",children:[h.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:[h.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),h.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),h.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),h.jsxs("span",{className:"text-fg-faint",children:["todos ",t?"▾":"▴"]})]}),t&&h.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:h.jsx("ul",{className:"space-y-0.5",children:e.map((p,a)=>h.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${p.status==="in_progress"?"bg-bg-hi":""}`,children:[h.jsx(R2,{status:p.status}),h.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 R2({status:i}){return i==="completed"?h.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):i==="in_progress"?h.jsx("span",{className:"w-3 shrink-0",children:h.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):h.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function j2(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 N2({onClose:i,onSent:e}){const t=xt(L=>L.tabs),[n,r]=G.useState(""),[l,p]=G.useState(()=>Object.fromEntries(t.map(L=>[L.id,!0]))),[a,d]=G.useState(!1),[f,v]=G.useState({}),m=G.useRef(null),y=G.useRef(e);G.useEffect(()=>{y.current=e},[e]),G.useEffect(()=>{p(L=>{const j={};for(const H of t)j[H.id]=L[H.id]??!0;return j})},[t]),G.useEffect(()=>{var L;(L=m.current)==null||L.focus()},[]),G.useEffect(()=>window.api.pty.onWriteError(j=>{v(H=>j.tabId in H?{...H,[j.tabId]:"skipped"}:H)}),[]),G.useEffect(()=>{if(Object.keys(f).length===0)return;const L=Object.values(f).filter(H=>H==="sent").length,j=window.setTimeout(()=>y.current(L),1500);return()=>window.clearTimeout(j)},[f]);const D=t.filter(L=>l[L.id]).map(L=>L.id),k=D.length,T=Object.keys(f).length>0,b=n.length>0&&k>0&&!a&&!T,C=()=>{if(!b)return;d(!0);const L=xt.getState().tabs,j=new Set(L.map(U=>U.id)),H={};for(const U of D)j.has(U)?(window.api.pty.write({tabId:U,data:n+"\r"}),H[U]="sent"):H[U]="skipped";v(H),d(!1)},w=L=>{if(L.key==="Escape"){L.preventDefault(),L.stopPropagation(),i();return}L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),C())},x=t.length>0&&t.every(L=>l[L.id]),$=()=>{const L=!x;p(Object.fromEntries(t.map(j=>[j.id,L])))},R=Object.values(f).some(L=>L==="skipped"),N=T?R?"Sent (some skipped)":"Sent":`Send to ${k} tab${k===1?"":"s"}`;return h.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:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),h.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),h.jsx("textarea",{ref:m,value:n,onChange:L=>r(L.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"}),h.jsxs("div",{className:"flex flex-col gap-1",children:[h.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:x,onChange:$,className:"accent-accent"}),h.jsxs("span",{children:["All tabs (",k,"/",t.length,")"]})]}),h.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:t.map(L=>h.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[h.jsx("input",{type:"checkbox",checked:!!l[L.id],onChange:j=>p(H=>({...H,[L.id]:j.target.checked})),className:"accent-accent"}),h.jsx("span",{className:"truncate max-w-[12rem]",children:L.label}),f[L.id]==="sent"&&h.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),f[L.id]==="skipped"&&h.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},L.id))})]}),h.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[h.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"}),h.jsx("button",{onClick:C,disabled:!b,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:N})]})]})}function M2({tabId:i,cwd:e,onClose:t}){const n=Tf(k=>k.watchersForTab(i)),r=Tf(k=>k.add),l=Tf(k=>k.remove),p=G.useRef(null),[a,d]=G.useState(""),[f,v]=G.useState(""),[m,y]=G.useState(!1);G.useEffect(()=>{const k=T=>{T.key==="Escape"&&t()};return document.addEventListener("keydown",k),()=>document.removeEventListener("keydown",k)},[t]),G.useEffect(()=>{const k=T=>{p.current&&!p.current.contains(T.target)&&t()};return document.addEventListener("mousedown",k),()=>document.removeEventListener("mousedown",k)},[t]);const D=async()=>{const k=f.trim();if(!k||m)return;y(!0);const T=await r({tabId:i,label:a.trim(),command:k,cwd:e});y(!1),T&&(d(""),v(""))};return h.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:[h.jsxs("div",{className:"flex items-center mb-2",children:[h.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),h.jsxs("span",{className:"text-fg-faint ml-2",children:[n.length," active"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:t,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),h.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[h.jsx("input",{value:a,onChange:k=>d(k.target.value),placeholder:"label (optional)",className:"bg-bg border border-line rounded px-2 py-1 text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("input",{value:f,onChange:k=>v(k.target.value),onKeyDown:k=>{k.key==="Enter"&&D()},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"}),h.jsx("button",{onClick:D,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"})]}),h.jsxs("span",{className:"text-fg-faint",children:["cwd: ",h.jsx("span",{className:"font-mono",children:e})]})]}),n.length===0?h.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):h.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:n.map(k=>{const T=k.lines[k.lines.length-1];return h.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"font-medium text-fg truncate",children:k.label}),h.jsxs("span",{className:"text-fg-faint",children:[k.lineCount," line",k.lineCount===1?"":"s"]}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>l(k.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${k.watcherId}`,children:"stop"})]}),h.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:k.command,children:k.command}),h.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(T==null?void 0:T.line)??"",children:T?T.line:h.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},k.watcherId)})})]})}/**
|
|
2911
2911
|
* dockview-core
|
|
2912
2912
|
* @version 6.6.1
|
|
2913
2913
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3018,7 +3018,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3018
3018
|
|
|
3019
3019
|
${t}`}const Cf={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},SR=["popover","review","diff"],uC=["popover","review"];function CR(i,e){switch(e.type){case"SELECT":return{...Cf,editCount:i.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...Cf,editCount:i.editCount};case"LISTEN":return uC.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 SR.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:{...Cf,editCount:i.editCount+1};case"RESET_FILE":return{...Cf,editCount:0};case"MODEL_STATUS":return i.phase!=="listening"?i:{...i,modelStatus:`${e.status}: ${e.message}`};default:return i}}function kR(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 ER(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 TR="sonnet";function DR(i,e){const[t,n]=G.useReducer(CR,Cf),r=G.useRef(0),l=G.useRef(null),p=G.useRef(i),a=G.useRef(new Map);G.useEffect(()=>window.api.docEdit.onSessionResult(x=>{const $=a.current.get(x.requestId);$&&(a.current.delete(x.requestId),$(x))}),[]),G.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=G.useCallback(x=>{r.current+=1,d(),n({type:"SELECT",selection:x})},[]),v=G.useCallback(()=>{r.current+=1,d(),n({type:"CANCEL"})},[]),m=G.useCallback(()=>{if(!uC.includes(t.phase))return;if(Ct.getState().isRecording){lt.error("Microphone is already in use");return}if(!gv()){lt.error("Microphone or Web Worker not available");return}const x=++r.current;n({type:"LISTEN"}),Ct.setState({externalRecording:!0});const $=()=>{l.current===R&&(l.current=null),Ct.setState({externalRecording:!1})},R=P1({onFinal:N=>{if(r.current!==x)return;R.stop().catch(()=>{}),R.destroy(),$();const L=N.trim();if(!L){n({type:"CANCEL"});return}n({type:"HEARD",transcript:L})},onError:N=>{r.current===x&&(R.destroy(),$(),lt.error(`Microphone error: ${N}`),n({type:"CANCEL"}))},onModelStatus:(N,L)=>{r.current===x&&n({type:"MODEL_STATUS",status:N,message:L})},onProgress:N=>{r.current===x&&n({type:"MODEL_STATUS",status:"loading",message:`${N}%`})}});l.current=R,R.start().catch(N=>{r.current===x&&(R.destroy(),$(),lt.error(`Could not start mic: ${N instanceof Error?N.message:String(N)}`),n({type:"CANCEL"}))})},[t.phase]),y=G.useCallback(()=>{const x=kR(i,xt.getState().tabs);if(!x)return null;const $=ER(x,xt.getState().tabs,Gg.getState().tabs);return!$||di.getState().get($.id).running?null:$},[i]),D=G.useCallback((x,$,R,N,L,j)=>{const H=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{a.current.set(H,U),window.api.docEdit.runInSession({tabId:x,sessionId:$,cwd:R,before:N,instruction:L,documentText:j,requestId:H})})},[]),k=G.useCallback(async(x,$)=>{const R=t.selection;if(!R)return;const N=++r.current;n({type:"RUN",instruction:x,recordInstruction:$});const L=xR(e);try{const j=y(),H=j?await D(j.id,j.sessionId,j.cwd,R.text,x,L):await window.api.docEdit.run({path:i,before:R.text,instruction:x,documentText:L});if(r.current!==N)return;if(!H.ok){lt.error(H.error||"Edit failed"),n({type:"RUN_ERR"});return}n({type:"RUN_OK",diff:{before:R.text,after:H.after??""}})}catch(j){if(r.current!==N)return;lt.error(j instanceof Error?j.message:"Edit failed"),n({type:"RUN_ERR"})}},[i,t.selection,e,y,D]),T=G.useCallback(x=>{k(x,!0)},[k]),b=G.useCallback(()=>{t.phase==="review"&&k(t.transcript,!0)},[k,t.phase,t.transcript]),C=G.useCallback(()=>{const x=t.instruction;x&&k(`${x}
|
|
3020
3020
|
|
|
3021
|
-
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),w=G.useCallback(x=>{const $=t.diff;if(!$)return{ok:!1,reason:"not-found"};const R=wR(x,$.before,$.after);return R.ok?(r.current+=1,n({type:"ACCEPT"})):lt.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:v,listen:m,sendHeard:b,run:T,retry:C,accept:w}}const $R=[{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."}],Qx=320,pf=8;function AR(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function IR(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,pf),Math.max(pf,e-Qx-pf)),n=Math.max(i.top-pf,pf);return{position:"fixed",left:t,top:n,width:Qx,transform:"translateY(-100%)",zIndex:E2.dialog}}function PR({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:v,onReject:m,onRetry:y}){const[D,k]=G.useState(""),T=()=>{const b=D.trim();b&&(p(b),k(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:IR(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&h.jsxs("div",{className:"p-2",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.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"}),$R.map(b=>h.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),h.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),h.jsx("input",{autoFocus:!0,value:D,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?T():b.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"&&h.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[h.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[h.jsxs("span",{className:"flex items-center gap-2",children:[h.jsx(AR,{}),"Listening…"]}),r&&h.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),h.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"&&h.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[h.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsxs("div",{className:"p-3 flex items-center justify-between",children:[h.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),h.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&&h.jsxs("div",{className:"p-3",children:[h.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:y,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function RR(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function e0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:v}){return h.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[h.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),h.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Fb(TR)})]}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&h.jsxs("div",{className:"text-fg-faint",children:[h.jsx("p",{children:"Select text in the doc…"}),h.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&h.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&h.jsxs("div",{children:[h.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[h.jsx(RR,{}),"Listening…"]}),r&&h.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),h.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"&&h.jsxs("div",{children:[h.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&h.jsxs("div",{children:[h.jsxs("div",{className:"mb-3 space-y-2",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function jR(){const i=xt(t=>t.tabs),e=xt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function t0(i){return i.split("/").filter(Boolean).pop()||i}function NR({path:i,onRenamed:e,onDeleted:t}){const[n,r]=G.useState(!1),[l,p]=G.useState(!1),[a,d]=G.useState(""),[f,v]=G.useState(!1),m=$i(U=>U.buffers[i]),y=$i(U=>U.openFile),D=$i(U=>U.renameOpenFile),k=$i(U=>U.closeFile),T=jR(),b=t0(i),C=()=>r(!1),w=()=>{d(b),p(!0),C()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const oe=await window.api.files.rename(i,U);if(oe.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=oe.newPath??`${de}/${U}`;D(i,Z),e==null||e(i,Z),lt.info(`Renamed to ${U}`)}else lt.error(oe.error??`Couldn't rename ${b}`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't rename ${b}`)}p(!1)},$=async()=>{C();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(y(U.path),lt.info(`Duplicated as ${t0(U.path)}`)):lt.error(U.error??`Couldn't duplicate ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const U=await window.api.files.delete(i);U.ok?(k(i),t==null||t(i),lt.info(`Deleted ${b}`)):lt.error(U.error??`Couldn't delete ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}v(!1)},N=async()=>{C();const U=m??"";try{await navigator.clipboard.writeText(U),lt.info(`Copied ${U.length} chars`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!T){lt.error("No terminal tab is active");return}window.api.pty.write({tabId:T.id,data:`@${i} `}),lt.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't open ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(U=>!U),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&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:C}),h.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:[h.jsx(p_,{children:"Edit"}),h.jsx(Zc,{label:"Rename",onClick:w}),h.jsx(Zc,{label:"Duplicate",onClick:$}),h.jsx(Zc,{label:"Delete document",danger:!0,onClick:()=>{C(),v(!0)}}),h.jsx(i0,{}),h.jsx(p_,{children:"Open"}),h.jsx(Zc,{label:"Open in default app",onClick:j}),h.jsx(Zc,{label:"Reveal in OS",onClick:H}),h.jsx(i0,{}),h.jsx(p_,{children:"Export"}),h.jsx(Zc,{label:"Copy as Markdown",onClick:N}),h.jsx(Zc,{label:"Add to Claude context",onClick:L,disabled:!T,title:T?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(MR,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(OR,{name:b,onCancel:()=>v(!1),onConfirm:()=>void R()})]})}function p_({children:i}){return h.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function Zc({label:i,onClick:e,danger:t,disabled:n,title:r}){return h.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 i0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function MR({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),h.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"}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function OR({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function LR(){const[i,e]=G.useState(!1),t=Qu();return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.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&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.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:[h.jsx(Yu,{label:"Text size",children:h.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[h.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−"}),h.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),h.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+"})]})}),h.jsx(Yu,{label:"Word wrap",children:h.jsx(Eg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Yu,{label:"Minimap",children:h.jsx(Eg,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Yu,{label:"Theme",children:h.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"})}),h.jsx(Yu,{label:"Autosave",children:h.jsx(Eg,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Yu,{label:"Wide measure",children:h.jsx(Eg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Yu({label:i,children:e}){return h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Eg({on:i,onClick:e}){return h.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 zR=G.lazy(()=>os(()=>import("./TiptapBody-faCtLj9L.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Tg(i){return i.split("/").filter(Boolean).pop()||i}function Dg(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 $g(i){return OS(i)||LS(i)}function BR(){const i=tw(),e=$i(Ye=>Ye.openFiles),t=$i(Ye=>Ye.activeFilePath),n=$i(Ye=>Ye.dirty),r=$i(Ye=>Ye.viewMode),l=$i(Ye=>Ye.buffers),p=$i(Ye=>Ye.setActive),a=$i(Ye=>Ye.closeFile),d=$i(Ye=>Ye.closeOthers),f=$i(Ye=>Ye.closeToTheRight),v=$i(Ye=>Ye.closeAll),m=$i(Ye=>Ye.loadBuffer),y=$i(Ye=>Ye.setBuffer),D=$i(Ye=>Ye.markSaved),k=$i(Ye=>Ye.setViewMode),T=Qu(),[b,C]=G.useState({}),[w,x]=G.useState({}),[$,R]=G.useState(null),[N,L]=G.useState(null),[j,H]=G.useState(!1),[U,oe]=G.useState(!1),[de,Z]=G.useState(!0),me=G.useRef(null),ie=G.useRef(null),ue=G.useRef(void 0),Ce=G.useRef(null),Ee=G.useRef(null),W=DR(t??"",l[t??""]??""),te=G.useCallback(Ye=>{me.current=Ye},[]),K=G.useCallback(()=>me.current,[]);G.useEffect(()=>{const Ye=t;if(!Ye||$g(Ye))return;if($i.getState().hasBuffer(Ye)){C(ut=>ut[Ye]==="ready"?ut:{...ut,[Ye]:"ready"});return}let St=!1;return C(ut=>({...ut,[Ye]:"loading"})),window.api.files.read(Ye).then(ut=>{St||(ut.binary?C(Xe=>({...Xe,[Ye]:{binary:!0,size:ut.size??0,mime:ut.mime??"application/octet-stream",reason:ut.error??"Binary file"}})):ut.ok?(m(Ye,ut.text),C(Xe=>({...Xe,[Ye]:"ready"}))):C(Xe=>({...Xe,[Ye]:{error:ut.error??"failed to read"}})))}),()=>{St=!0}},[t,m]),G.useEffect(()=>{L(null)},[t]);const re=G.useCallback(async(Ye,St=!1)=>{const ut=$i.getState().buffers[Ye];if(ut==null)return;St&&H(!0);const Xe=await window.api.files.write(Ye,ut);Xe.ok?(D(Ye),x(Pt=>({...Pt,[Ye]:(Pt[Ye]??0)+1})),St||lt.info(`Saved ${Tg(Ye)}`)):lt.error(Xe.error??`Couldn't save ${Tg(Ye)}`),St&&H(!1)},[D]);G.useEffect(()=>{if(!T.autosave)return;const Ye=t;if(!(!Ye||$g(Ye)||!n[Ye]))return window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{re(Ye,!0)},1200),()=>window.clearTimeout(ue.current)},[T.autosave,t,n,l,re]);const ve=G.useCallback(Ye=>{Ye.length&&(C(St=>Dg(St,Ye)),x(St=>Dg(St,Ye)))},[]),_e=G.useCallback((Ye,St)=>{C(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut),x(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut)},[]),Me=G.useCallback(Ye=>{n[Ye]?R({kind:"one",path:Ye}):(a(Ye),ve([Ye]))},[n,a,ve]),et=G.useCallback(Ye=>{e.some(ut=>ut.path!==Ye&&n[ut.path])?R({kind:"others",path:Ye}):(d(Ye),ve(e.filter(ut=>ut.path!==Ye).map(ut=>ut.path)))},[e,n,d,ve]),we=G.useCallback(Ye=>{const St=e.findIndex(Xe=>Xe.path===Ye);St!==-1&&e.slice(St+1).some(Xe=>n[Xe.path])?R({kind:"right",path:Ye}):(f(Ye),ve(St!==-1?e.slice(St+1).map(Xe=>Xe.path):[]))},[e,n,f,ve]);G.useEffect(()=>{const Ye=St=>{if(i.current)if((St.metaKey||St.ctrlKey)&&(St.key==="s"||St.key==="S")){const ut=$i.getState().activeFilePath;ut&&!$g(ut)&&(St.preventDefault(),re(ut))}else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="f"||St.key==="F"))St.preventDefault(),oe(ut=>!ut);else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="w"||St.key==="W")){const ut=$i.getState().activeFilePath;ut&&$i.getState().openFiles.length>1&&(St.preventDefault(),et(ut))}else St.key==="Escape"&&W.state.phase!=="idle"?W.cancel():St.key==="Escape"&&U&&oe(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[re,U,et,W.state.phase,W.cancel]),G.useEffect(()=>{if(W.state.phase==="idle")return;const Ye=St=>{var Xe,Pt;const ut=St.target;(Xe=Ee.current)!=null&&Xe.contains(ut)||(Pt=Ce.current)!=null&&Pt.contains(ut)||W.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[W.state.phase,W.cancel]),G.useEffect(()=>{W.cancel()},[t,W.cancel]);const X=G.useCallback(()=>{e.some(St=>n[St.path])?R({kind:"all",path:""}):(v(),C({}),x({}))},[e,n,v]),Ie=()=>{if($){if($.kind==="one")a($.path),ve([$.path]);else if($.kind==="others"){const Ye=e.filter(St=>St.path!==$.path).map(St=>St.path);d($.path),ve(Ye)}else if($.kind==="right"){const Ye=e.findIndex(ut=>ut.path===$.path),St=Ye!==-1?e.slice(Ye+1).map(ut=>ut.path):[];f($.path),ve(St)}else v(),C({}),x({});R(null)}};if(e.length===0)return h.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"mb-2",children:"no file open"}),h.jsxs("div",{children:["open the ",h.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const pe=t,Ze=pe?Tg(pe):"",ge=pe?b[pe]:void 0,Ke=pe?GS(pe):!1,vt=pe?EA(pe):!1,st=pe&&Ke?r[pe]??TA(pe):"edit",Kt=!!pe&&!$g(pe)&&ge==="ready",Be=Kt,Dt=vt?["edit","wysiwyg","preview","split"]:Ke?["edit","preview"]:[],_t=pe&&h.jsx(FI,{path:pe,name:Ze,value:l[pe]??"",onChange:Ye=>y(pe,Ye),onSave:()=>void re(pe),onReady:te,onCursor:L}),ri=j?"Saving…":pe&&n[pe]?T.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&h.jsx(AA,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Me,onCloseOthers:et,onCloseToTheRight:we,onCloseAll:X}),pe&&!U&&h.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[h.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ze}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:pe}),Kt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ri]}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:()=>Z(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:T.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${T.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ye=>h.jsx("button",{onClick:()=>k(pe,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${st===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),h.jsx("div",{className:"flex-1"}),h.jsx(NR,{path:pe,onRenamed:_e,onDeleted:Ye=>ve([Ye])}),Kt&&h.jsx(LR,{}),h.jsx("button",{onClick:()=>oe(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&h.jsx("button",{onClick:()=>oe(!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"}),h.jsx("div",{className:"flex-1 min-h-0",children:pe?OS(pe)?h.jsx(uR,{path:pe,name:Ze}):LS(pe)?h.jsx(hR,{path:pe}):ge&&typeof ge=="object"&&"binary"in ge?h.jsx(bR,{path:pe,name:Ze,size:ge.size,mime:ge.mime,reason:ge.reason}):ge&&typeof ge=="object"&&"error"in ge?h.jsx("div",{className:"p-6 text-xs text-red-400",children:ge.error}):ge!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):st==="wysiwyg"&&qa(pe)?h.jsx(G.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(zR,{value:l[pe]??"",onChange:Ye=>y(pe,Ye)},pe)}):st==="split"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(Xx,{text:l[pe]??"",scrollRef:ie}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(Yx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(db,{ref:ie,text:l[pe]??"",flush:!0,wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(e0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(Xx,{text:l[pe]??"",scrollRef:ie}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(db,{ref:ie,text:l[pe]??"",wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(e0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&MS(pe)?h.jsx(cR,{path:pe,dirty:!!n[pe],reloadToken:w[pe]??0}):st==="preview"&&zS(pe)?h.jsx(fR,{path:pe,text:l[pe]??""}):st==="preview"&&BS(pe)?h.jsx(vR,{path:pe,text:l[pe]??""}):qa(pe)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(Yx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),Be&&h.jsx(lR,{text:l[pe]??"",cursor:N,language:Nr(pe)||void 0}),pe&&qa(pe)&&(st==="preview"||st==="split")&&W.state.phase!=="idle"&&W.state.selection&&h.jsx("div",{ref:Ee,children:h.jsx(PR,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)}})}),$&&h.jsx(GR,{message:$.kind==="one"?`Discard unsaved changes to ${Tg($.path)}?`:$.kind==="others"?"Discard unsaved changes in the other open files?":$.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>R(null),onConfirm:Ie})]})}const pb=G.memo(BR);function GR({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const FR={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},n0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function vw({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?h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&h.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),h.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=G.useRef(null),f=G.useRef(null),v=G.useRef(e);if(v.current=e,G.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(n0);C?C.focus():b.focus()},0),T=b=>{if(b.key==="Escape"){b.stopPropagation(),v.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const w=Array.from(C.querySelectorAll(n0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(w.length===0){b.preventDefault(),C.focus();return}const x=w[0],$=w[w.length-1],R=document.activeElement;b.shiftKey?(R===x||!C.contains(R))&&(b.preventDefault(),$.focus()):(R===$||!C.contains(R))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",T),()=>{clearTimeout(k),document.removeEventListener("keydown",T);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=D=>{D.target===D.currentTarget&&e()},y=h.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:h.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 ${FR[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?h.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?h.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Jf.createPortal(y,document.body):y}class hC extends G.Component{constructor(){super(...arguments);Bi(this,"state",{error:null});Bi(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):h.jsxs("div",{className:"p-6 text-xs",children:[h.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),h.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),h.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 HR({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(vw,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&h.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[h.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),h.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:"✕"})]}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(hC,{children:n})})]})}function pC(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 s0=i=>Symbol.iterator in i,r0=i=>"entries"in i,o0=(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},WR=(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 UR(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:s0(i)&&s0(e)?r0(i)&&r0(e)?o0(i,e):WR(i,e):o0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function _w(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return UR(e.current,n)?e.current:e.current=n}}let a0=0;const VR=1e3;function qR(i){const e=performance.now();e-a0<VR||(a0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function KR(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(_w(ev)),r=()=>{const f=Ct.getState(),{canRecord:v,reason:m}=ev(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(!v)return qR(m);const y=xt.getState().activeTabId;y&&f.startRecording(y)},l=pC(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 h.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:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),h.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),h.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function YR(){const i=Ct(t=>t.ttsEnabled),e=Ct(t=>t.toggleTTS);return h.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:[h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?h.jsxs(h.Fragment,{children:[h.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),h.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),h.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),h.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function XR(i){return/^monitor of /i.test(i.trim())}function l0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function c0(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=l0(e),l=t.filter(p=>p.label&&l0(p.label)===r);return l.length===1?l[0]:null}async function d0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&XR(n.label))):[]}const u0=!1;function fC(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=G.useState([]),[n,r]=G.useState(null),[l,p]=G.useState(null);G.useEffect(()=>{let f=!1;return(async()=>{try{const v=await window.api.voice.getDevicePref();if(f)return;const m=await d0(u0);if(f)return;t(m),p(v.selectedLabel);const y=c0(v.selectedDeviceId,v.selectedLabel,m);y?(r(y.deviceId),v.selectedDeviceId&&y.deviceId!==v.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:v.selectedDeviceId.slice(0,8),toIdPrefix:y.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:y.deviceId,selectedLabel:y.label||v.selectedLabel}).catch(()=>{}))):((v.selectedDeviceId||v.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:v.selectedLabel,hadId:!!v.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!v.selectedDeviceId})),r(null))}catch(v){pt.warn("voice","device-picker init failed",{error:v instanceof Error?v.message:String(v)})}})(),()=>{f=!0}},[]);const a=G.useCallback(async()=>{try{const f=await d0(u0);if(t(f),n&&!f.some(v=>v.deviceId===n)){const v=c0(null,l,f);v?(r(v.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);G.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var D;const v=f.target.value,m=v===""?null:v,y=m?((D=e.find(k=>k.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(y);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:y}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){pt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await Ct.getState().restartWithDevice()}catch(k){pt.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return h.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:[h.jsx("option",{value:"",children:"Default"}),e.map(f=>h.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function JR(){const i=Ct(D=>D.isRecording),e=Ct(D=>D.levelMeterEnabled),[t,n]=G.useState(0),[r,l]=G.useState(0),p=G.useRef(0);p.current=r;const[a,d]=G.useState(0),[f,v]=G.useState(!1),m=G.useRef(null);if(G.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,T=null,b=null;const C=()=>{if(k)return;const x=b??N1();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,T=new Uint8Array(new ArrayBuffer(x.fftSize)));const $=T;x.getByteTimeDomainData($);let R=0;for(let H=0;H<$.length;H++){const U=$[H]-128;R+=U*U}const N=Math.sqrt(R/$.length)/128,L=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(L+60)/60));l(N),n(j),N>=.95&&(v(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>v(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const w=setInterval(()=>{k||d(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const y=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return h.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:h.jsx("div",{className:`h-full ${y} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function mC(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=G.useState(()=>performance.now());if(G.useEffect(()=>{if(i===null)return;let f;const v=()=>{n(performance.now()),f=requestAnimationFrame(v)};return f=requestAnimationFrame(v),()=>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 h.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:h.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:h.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function ZR({open:i,onClose:e,variant:t="overlay"}){return h.jsx(HR,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(ij,{}),h.jsx(mC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(KR,{}),h.jsx(fC,{}),h.jsx(YR,{})]}),h.jsx(QR,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.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"}),h.jsx(tj,{})]}),h.jsx(JR,{})]})})}function QR(){const i=Ct(l=>l.isRecording),[e,t]=G.useState(null);if(G.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=ej(e.accelerator);return h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("span",{children:[n," "]}),h.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),h.jsx("span",{children:" to record"})]})}function ej(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 tj(){const[i,e]=G.useState(null);if(G.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 h.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:[h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),h.jsx("span",{children:"Tap on/off"})]}),h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),h.jsx("span",{children:"Hold to talk"})]})]})}function ij(){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?h.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?h.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),h.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{children:"Loading speech model"}),h.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),h.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const gC="~/.claude/session-manager/projects-prefs.json",nj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function zl(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(gC,t).catch(()=>{})}const h0=In((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(gC);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}),zl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":nj[t];i({sort:{col:t,dir:r}}),zl(e)},setRecentFilter:t=>{i({recentFilter:t}),zl(e)},setHasRemote:t=>{i({hasRemote:t}),zl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),zl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),zl(e)},setSearch:t=>{i({search:t}),zl(e)},setEditor:t=>{i({editor:t}),zl(e)}})),vC=i=>`sm.fileTree.expanded:${i}`;function sj(i){try{const e=localStorage.getItem(vC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function rj(i,e){try{localStorage.setItem(vC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const _C="sm.fileTree.showHidden";function oj(){try{const i=localStorage.getItem(_C);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function aj(i){try{localStorage.setItem(_C,JSON.stringify(i))}catch{}}function f_(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 m_={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:"!"}},lj=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 cj(i){const e=Nr(i);return lj.has(e)||NS.has(e)||e==="pdf"}function dj(i,e){if(e)return"#d97757";switch(Nr(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 ff(i){var e;try{const t=window.api;return(e=t==null?void 0:t.git)!=null&&e.fileStatus?await t.git.fileStatus(i):{}}catch{return{}}}function uj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=tw(),l=ew(),[p,a]=G.useState([]),[d,f]=G.useState(new Set),v=G.useRef(d);v.current=d;const[m,y]=G.useState(""),[D,k]=G.useState(oj),T=G.useCallback(Be=>{k(Dt=>{const _t=typeof Be=="function"?Be(Dt):Be;return aj(_t),_t})},[]),[b,C]=G.useState(!1),[w,x]=G.useState(null),[$,R]=G.useState({}),[N,L]=G.useState(null),[j,H]=G.useState(null),[U,oe]=G.useState(""),[de,Z]=G.useState(null),[me,ie]=G.useState(""),[ue,Ce]=G.useState(null),Ee=G.useRef(null),W=G.useRef(null),te=G.useRef(0),K=G.useCallback(async()=>{if(!i)return;const Be=++te.current;C(!0),x(null);const Dt=await window.api.files.list(i,D);te.current===Be&&(Dt.ok?a(Dt.entries.map(_t=>({..._t}))):(x(Dt.error??"failed to list"),a([])),C(!1))},[i,D]),re=G.useCallback(async Be=>{const Dt=te.current,_t=new Map;for(const Ye of Be){const St=Ye.split("/").length,ut=_t.get(St);ut?ut.push(Ye):_t.set(St,[Ye])}const ri=[];for(const Ye of[..._t.keys()].sort((St,ut)=>St-ut)){const St=_t.get(Ye),ut=await Promise.all(St.map(async Xe=>({p:Xe,result:await window.api.files.list(Xe,D)})));if(te.current!==Dt)return ri;for(const{p:Xe,result:Pt}of ut)Pt.ok?a(oi=>Wg(oi,Xe,Pt.entries.map(Fi=>({...Fi})))):ri.push(Xe)}return ri},[D]),ve=G.useCallback(async Be=>(await K(),Be.length?re(Be):[]),[K,re]);G.useEffect(()=>{y(""),H(null),L(null),Z(null),Ce(null),R({});const Be=sj(i),Dt=new Set(Be);v.current=Dt,f(Dt);let _t=!1;return(async()=>{const ri=await ve(Be);_t||!ri.length||Me(Ye=>{const St=new Set;let ut=!1;for(const Xe of Ye){if(ri.some(Pt=>Xe===Pt||Xe.startsWith(Pt+"/"))){ut=!0;continue}St.add(Xe)}return ut?St:Ye})})(),ff(i).then(ri=>{_t||R(ri)}),()=>{_t=!0}},[i]);const _e=G.useRef(!0);G.useEffect(()=>{if(_e.current){_e.current=!1;return}ve([...v.current])},[D]),G.useEffect(()=>{if(!i||!l)return;ff(i).then(R);const Be=window.setInterval(()=>{ff(i).then(R)},5e3);return()=>window.clearInterval(Be)},[i,l]),G.useEffect(()=>{if(!N)return;const Be=()=>L(null),Dt=_t=>{r.current&&_t.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Be),window.addEventListener("keydown",Dt),()=>{window.removeEventListener("mousedown",Be),window.removeEventListener("keydown",Dt)}},[N]),G.useEffect(()=>{j&&setTimeout(()=>{var Be;return(Be=Ee.current)==null?void 0:Be.select()},30)},[j]),G.useEffect(()=>{de&&setTimeout(()=>{var Be;return(Be=W.current)==null?void 0:Be.focus()},30)},[de]);const Me=G.useCallback(Be=>{const Dt=v.current,_t=Be(Dt);_t!==Dt&&(v.current=_t,f(_t),rj(i,_t))},[i]),et=G.useCallback(async Be=>{if(d.has(Be.path)){Me(_t=>f_(_t,Be.path));return}if(Me(_t=>new Set(_t).add(Be.path)),Be.children)return;const Dt=await window.api.files.list(Be.path,D);Dt.ok&&a(_t=>Wg(_t,Be.path,Dt.entries.map(ri=>({...ri}))))},[d,D,Me]),we=G.useCallback(async Be=>{if(Be===i){await K();return}const Dt=await window.api.files.list(Be,D);Dt.ok&&a(_t=>Wg(_t,Be,Dt.entries.map(ri=>({...ri}))))},[i,K,D]),X=G.useCallback(Be=>{if(Be.isDirectory){et(Be);return}cj(Be.name)&&e?e(Be.path):window.api.shell.open({as:"openPath",path:Be.path})},[et,e]),Ie=G.useCallback(Be=>{if(t){t(Be);return}if(n){const Dt=Be.startsWith(i+"/")?Be.slice(i.length+1):Be;window.api.pty.write({tabId:n,data:`@${Dt} `})}},[t,n,i]),pe=G.useCallback((Be,Dt)=>{Be.preventDefault(),Be.stopPropagation(),L({x:Be.clientX,y:Be.clientY,node:Dt})},[]),Ze=Be=>{H(Be.path),oe(Be.name)},ge=async()=>{if(!j)return;const Be=U.trim();if(!Be){H(null);return}const Dt=await window.api.files.rename(j,Be);if(H(null),Dt.ok){const _t=j.slice(0,j.lastIndexOf("/"));Me(ri=>f_(ri,j)),await we(_t||i),ff(i).then(R)}else{const _t=Dt.error??"rename failed";x(_t),lt.error(_t)}},Ke=async()=>{if(!de)return;const Be=me.trim();if(!Be){Z(null),ie("");return}const Dt=await window.api.files.create(de.parent,Be,de.kind);if(Z(null),ie(""),Dt.ok)await we(de.parent),de.kind==="folder"&&Me(_t=>new Set(_t).add(de.parent));else{const _t=Dt.error??"create failed";x(_t),lt.error(_t)}},vt=async()=>{if(!ue)return;const Be=await window.api.files.delete(ue.path),Dt=ue.path.slice(0,ue.path.lastIndexOf("/"));if(Ce(null),Be.ok)Me(_t=>f_(_t,ue.path)),await we(Dt||i),ff(i).then(R);else{const _t=Be.error??"delete failed";x(_t),lt.error(_t)}},st=G.useMemo(()=>{if(!m.trim())return p;const Be=m.toLowerCase();return p.filter(Dt=>Dt.name.toLowerCase().includes(Be))},[p,m]),Kt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return h.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[h.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[h.jsx(wC,{size:14,className:"shrink-0 text-accent"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("p",{className:"text-xs font-medium text-fg truncate",children:Kt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:K,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(vj,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Be=>y(Be.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"})})]}),h.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[h.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:h.jsx(_j,{size:12})}),h.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:h.jsx(bj,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>T(Be=>!Be),className:`p-1.5 rounded transition-colors ${D?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:D?"Hide hidden files":"Show hidden files",children:D?h.jsx(wj,{size:12}):h.jsx(yj,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&st.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&h.jsx(bC,{nodes:st,depth:0,expanded:d,gitStatus:$,renaming:j,renameValue:U,renameInputRef:Ee,onRenameChange:oe,onRenameCommit:ge,onRenameCancel:()=>H(null),onToggleDir:et,onFileClick:X,onSendToChat:Ie,onContextMenu:pe})]}),h.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"}),N&&h.jsx(hj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Ze(N.node),L(null)},onDelete:()=>{Ce(N.node),L(null)},onNewFile:()=>{Z({parent:N.node.path,kind:"file"}),L(null)},onNewFolder:()=>{Z({parent:N.node.path,kind:"folder"}),L(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:N.node.path}),L(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:N.node.path}),L(null)},onCopyPath:()=>{var Be;(Be=navigator.clipboard)==null||Be.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx(p0,{title:`New ${de.kind}`,subtitle:`in ${pj(de.parent)}`,onCancel:()=>{Z(null),ie("")},onConfirm:Ke,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:W,value:me,onChange:Be=>ie(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"&&Ke(),Be.key==="Escape"&&(Z(null),ie(""))},placeholder:de.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"})}),ue&&h.jsx(p0,{title:`Delete ${ue.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>Ce(null),onConfirm:vt,confirmLabel:"Delete",danger:!0,children:h.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",h.jsxs("span",{className:"text-fg font-medium",children:['"',ue.name,'"']})," to the trash?",ue.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function bC(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return h.jsx(h.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,v=r[a.path],m=dj(a.name,a.isDirectory);return h.jsxs("div",{children:[h.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:y=>p(y,a),children:[a.isDirectory?h.jsx(gj,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):h.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?h.jsx(fj,{size:12,color:m}):h.jsx(wC,{size:12,color:m}):h.jsx(mj,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:y=>i.onRenameChange(y.target.value),onClick:y=>y.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:y=>{y.key==="Enter"&&i.onRenameCommit(),y.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"}):h.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),v&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:m_[v].color,backgroundColor:`${m_[v].color}20`},title:v,children:m_[v].label}),!a.isDirectory&&h.jsx("button",{onClick:y=>{y.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:h.jsx(xj,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(bC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function hj(i){const{x:e,y:t,node:n}=i;return h.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&&h.jsx(Bl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Bl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Bl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(g_,{}),h.jsx(Bl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Bl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(g_,{}),h.jsx(Bl,{label:"New file",onClick:i.onNewFile}),h.jsx(Bl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(g_,{}),h.jsx(Bl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Bl({label:i,onClick:e,danger:t}){return h.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 g_(){return h.jsx("div",{className:"my-1 border-t border-line"})}function p0(i){return h.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:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&h.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),h.jsx("div",{className:"mb-4",children:i.children}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.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"}),h.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 pj(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Wg(n.children,e,t)}:n)}function ma({size:i,children:e,className:t,color:n}){return h.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 wC({size:i,className:e,color:t}){return h.jsx(ma,{size:i,className:e,color:t,children:h.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 fj({size:i,className:e,color:t}){return h.jsx(ma,{size:i,className:e,color:t,children:h.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 mj({size:i,className:e,color:t}){return h.jsxs(ma,{size:i,className:e,color:t,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function gj({size:i,className:e}){return h.jsx(ma,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function vj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("polyline",{points:"1 20 1 14 7 14"}),h.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 _j({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"}),h.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),h.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function bj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.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"}),h.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),h.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function wj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function yj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.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"}),h.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function xj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),h.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Sj({content:i,children:e,align:t="bottom-right"}){const[n,r]=G.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return h.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&h.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 Of(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const fb="sm.projects.splitPct",mb=33,yC=20,xC=60,SC="sm.projects.fileTreeCollapsed",Cj=32;function kj(){try{const i=parseFloat(localStorage.getItem(fb)??"");if(Number.isFinite(i))return Math.min(xC,Math.max(yC,i))}catch{}return mb}function Ej(){try{return localStorage.getItem(SC)==="1"}catch{return!1}}function Tj(){const i=xt(U=>U.tabs),e=xt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ei(U=>U.navFace),[r,l]=G.useState(null);G.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(oe=>{U||l(oe)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=G.useState(()=>kj()),[f,v]=G.useState(()=>Ej()),[m,y]=G.useState(!1),D=G.useRef(a);D.current=a;const k=G.useRef(null),T=G.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:w}=hh(),x=h0(U=>U.pinned),$=h0(U=>U.togglePin),R=[...b].sort((U,oe)=>(x[oe.cwd]?1:0)-(x[U.cwd]?1:0));G.useEffect(()=>{if(!m)return;const U=oe=>{T.current&&!T.current.contains(oe.target)&&y(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=G.useCallback(U=>{$i.getState().openFile(U)},[]),L=G.useCallback(U=>{U.preventDefault();const oe=U.clientX,de=D.current;let Z=de;const me=ue=>{const Ce=k.current;if(!Ce)return;const Ee=Ce.getBoundingClientRect(),W=ue.clientX-oe;Z=Math.min(xC,Math.max(yC,de+W/Ee.width*100)),d(Z)},ie=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",ie),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(fb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",ie),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=G.useCallback(()=>{d(mb);try{localStorage.setItem(fb,String(mb))}catch{}},[]),H=G.useCallback(()=>{v(U=>{const oe=!U;try{localStorage.setItem(SC,oe?"1":"0")}catch{}return oe})},[]);return f?h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("button",{onClick:H,"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:Cj},children:[h.jsx("span",{className:"text-[11px]",children:"▸"}),h.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(pb,{})})]}):h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[h.jsxs("div",{ref:T,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>y(U=>!U),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:[h.jsx("span",{className:"flex-1 truncate text-left",children:p?Of(p):"Projects"}),h.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),h.jsx("button",{onClick:H,"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&&h.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:R.length===0?h.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):R.map(U=>{const oe=Of(U.cwd);return h.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[h.jsx(Sj,{content:x[U.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>$(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(U.cwd),y(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:oe}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${oe}?`)&&await w(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.cwd)})})]}),p?h.jsxs(h.Fragment,{children:[h.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:Of(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(uj,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):h.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:L,onDoubleClick:j,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(pb,{})})]})}const Dj=G.memo(Tj),$j={"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 Marketing page",intro:"Turns the Marketing lens of this project's already-generated Project Pages 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 Marketing Project Page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]}},bw="sm.learningPanel.collapsed";function f0(){try{const i=localStorage.getItem(bw);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 m0(i){try{localStorage.setItem(bw,i?"1":"0")}catch{}}function Aj({active:i}){const[e,t]=G.useState(()=>!f0()),n=G.useRef(null),r=G.useCallback(()=>{t(a=>{const d=!a;return m0(!d),d})},[]);G.useEffect(()=>{const a=d=>{d.key===bw&&t(!f0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),G.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),m0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=G.useRef(!1);G.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=$j[i];return p?h.jsxs("span",{ref:n,className:"relative inline-block",children:[h.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&&h.jsxs("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:[h.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.intro}),p.sections.map(a=>h.jsxs("div",{className:"mb-3 last:mb-0",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:a.title}),h.jsx("ul",{className:"space-y-1",children:a.items.map((d,f)=>h.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[d.term&&h.jsx("span",{className:"text-fg font-medium",children:d.term}),d.term&&" — ",h.jsx("span",{children:d.body})]},f))})]},a.title)),p.tips&&p.tips.length>0&&h.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),h.jsx("ul",{className:"space-y-1",children:p.tips.map((a,d)=>h.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",a]},d))})]})]})]}):null}function Ij({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&h.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[h.jsxs("div",{className:"max-w-[820px]",children:[i&&h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&h.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&h.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&h.jsx(Aj,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const Pj=G.lazy(()=>os(()=>import("./Skills-BXkVyCo5.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),Rj=G.lazy(()=>os(()=>import("./History-DbzjII2Z.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),jj=G.lazy(()=>os(()=>import("./Scheduler-C4Ti9TCc.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),Nj=G.lazy(()=>os(()=>import("./Settings-CxyhPuYQ.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),Mj=G.lazy(()=>os(()=>import("./Permissions-DrDjCRFl.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),Oj=G.lazy(()=>os(()=>import("./SystemPrompt-Bwe3NTbi.js"),__vite__mapDeps([19,4,7,6,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),Lj=G.lazy(()=>os(()=>import("./Memory-DmxoxxxY.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),zj=G.lazy(()=>os(()=>import("./Plugins-KexSQwk0.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),Bj=G.lazy(()=>os(()=>import("./McpServers-DsRWWpU3.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),Gj=G.lazy(()=>os(()=>import("./Hooks-C0PTplI_.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),Fj=G.lazy(()=>os(()=>import("./AgentLibrary-CiqimwWl.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),Hj=G.lazy(()=>os(()=>import("./TagLibrary-CnwEf6EI.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),Wj=G.lazy(()=>os(()=>import("./HostBilko-vGc1FYLD.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),Uj=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ir({children:i}){return h.jsx(G.Suspense,{fallback:Uj,children:i})}const Vj={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."}},qj=()=>{},g0=new Map;function Kj(i,e){const t=g0.get(i);if(t&&t.ctx===e)return t.node;const n=Yj(i,e);return g0.set(i,{ctx:e,node:n}),n}function Yj(i,e){switch(i){case"overview":return h.jsx($$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(wA,{});case"editor":return h.jsx(pb,{});case"projects":return h.jsx(Dj,{})}const t=Vj[i],n=(()=>{switch(i){case"skills":return h.jsx(Ir,{children:h.jsx(Pj,{})});case"history":return h.jsx(Ir,{children:h.jsx(Rj,{})});case"scheduler":return h.jsx(Ir,{children:h.jsx(jj,{navigate:e.onNavigate})});case"plugins":return h.jsx(Ir,{children:h.jsx(zj,{})});case"mcp":return h.jsx(Ir,{children:h.jsx(Bj,{})});case"hooks":return h.jsx(Ir,{children:h.jsx(Gj,{})});case"memory":return h.jsx(Ir,{children:h.jsx(Lj,{})});case"system-prompt":return h.jsx(Ir,{children:h.jsx(Oj,{})});case"permissions":return h.jsx(Ir,{children:h.jsx(Mj,{})});case"settings":return h.jsx(Ir,{children:h.jsx(Nj,{})});case"agent-library":return h.jsx(Ir,{children:h.jsx(Fj,{})});case"tag-library":return h.jsx(Ir,{children:h.jsx(Hj,{})});case"bilko-host":return h.jsx(Ir,{children:h.jsx(Wj,{})});case"voice":return h.jsx(ZR,{open:!0,onClose:qj,variant:"page"});default:return null}})();if(!n)return null;const r=_E[i];return t&&r?h.jsx(Ij,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var v_={exports:{}},v0;function Xj(){return v0||(v0=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,$,R){var N,L=arguments.length,j=L<3?x:R===null?R=Object.getOwnPropertyDescriptor(x,$):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(w,x,$,R);else for(var H=w.length-1;H>=0;H--)(N=w[H])&&(j=(L<3?N(j):L>3?N(x,$,j):N(x,$))||j);return L>3&&j&&Object.defineProperty(x,$,j),j},v=this&&this.__param||function(w,x){return function($,R){x($,R,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),y=d(9924),D=d(844),k=d(4725),T=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(w,x,$,R){super(),this._terminal=w,this._coreBrowserService=$,this._renderService=R,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new y.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3021
|
+
(Give a different rewrite than the last one.)`,!1)},[k,t.instruction]),w=G.useCallback(x=>{const $=t.diff;if(!$)return{ok:!1,reason:"not-found"};const R=wR(x,$.before,$.after);return R.ok?(r.current+=1,n({type:"ACCEPT"})):lt.error(R.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),R},[t.diff]);return{state:t,select:f,cancel:v,listen:m,sendHeard:b,run:T,retry:C,accept:w}}const $R=[{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."}],Qx=320,pf=8;function AR(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function IR(i){const e=typeof window<"u"?window.innerWidth:1024,t=Math.min(Math.max(i.left,pf),Math.max(pf,e-Qx-pf)),n=Math.max(i.top-pf,pf);return{position:"fixed",left:t,top:n,width:Qx,transform:"translateY(-100%)",zIndex:E2.dialog}}function PR({phase:i,rect:e,diff:t,transcript:n,modelStatus:r,onQuickAction:l,onRunCustom:p,onListen:a,onSendHeard:d,onCancel:f,onAccept:v,onReject:m,onRetry:y}){const[D,k]=G.useState(""),T=()=>{const b=D.trim();b&&(p(b),k(""))};return h.jsxs("div",{"data-doc-edit-popover":!0,style:IR(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[i==="popover"&&h.jsxs("div",{className:"p-2",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.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"}),$R.map(b=>h.jsx("button",{onClick:()=>l(b.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:b.label},b.label))]}),h.jsx("button",{onClick:f,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),h.jsx("input",{autoFocus:!0,value:D,onChange:b=>k(b.target.value),onKeyDown:b=>{b.key==="Enter"?T():b.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"&&h.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[h.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[h.jsxs("span",{className:"flex items-center gap-2",children:[h.jsx(AR,{}),"Listening…"]}),r&&h.jsx("span",{className:"text-[10px] text-fg-faint",children:r})]}),h.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"&&h.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[h.jsxs("p",{className:"italic text-fg mb-2",children:["«",n,"»"]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsxs("div",{className:"p-3 flex items-center justify-between",children:[h.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),h.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&&h.jsxs("div",{className:"p-3",children:[h.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]}),h.jsxs("div",{className:"flex justify-end gap-1.5",children:[h.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:y,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function RR(){return h.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),h.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function e0({phase:i,transcript:e,diff:t,editCount:n,modelStatus:r,onListen:l,onSendHeard:p,onCancel:a,onAccept:d,onReject:f,onRetry:v}){return h.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[h.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[h.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),h.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Fb(TR)})]}),h.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[i==="idle"&&h.jsxs("div",{className:"text-fg-faint",children:[h.jsx("p",{children:"Select text in the doc…"}),h.jsxs("p",{className:"mt-2 text-[10px]",children:[n," edit",n===1?"":"s"," this session"]})]}),i==="popover"&&h.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),i==="listening"&&h.jsxs("div",{children:[h.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[h.jsx(RR,{}),"Listening…"]}),r&&h.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:r}),h.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"&&h.jsxs("div",{children:[h.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),h.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),i==="thinking"&&h.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),i==="diff"&&t&&h.jsxs("div",{children:[h.jsxs("div",{className:"mb-3 space-y-2",children:[h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),h.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:t.before})]}),h.jsxs("div",{children:[h.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),h.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:t.after})]})]}),h.jsxs("div",{className:"flex gap-1.5",children:[h.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),h.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),h.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function jR(){const i=xt(t=>t.tabs),e=xt(t=>t.activeTabId);return i.find(t=>t.id===e)??null}function t0(i){return i.split("/").filter(Boolean).pop()||i}function NR({path:i,onRenamed:e,onDeleted:t}){const[n,r]=G.useState(!1),[l,p]=G.useState(!1),[a,d]=G.useState(""),[f,v]=G.useState(!1),m=$i(U=>U.buffers[i]),y=$i(U=>U.openFile),D=$i(U=>U.renameOpenFile),k=$i(U=>U.closeFile),T=jR(),b=t0(i),C=()=>r(!1),w=()=>{d(b),p(!0),C()},x=async()=>{const U=a.trim();if(!U||U===b){p(!1);return}try{const oe=await window.api.files.rename(i,U);if(oe.ok){const de=i.slice(0,i.lastIndexOf("/")),Z=oe.newPath??`${de}/${U}`;D(i,Z),e==null||e(i,Z),lt.info(`Renamed to ${U}`)}else lt.error(oe.error??`Couldn't rename ${b}`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't rename ${b}`)}p(!1)},$=async()=>{C();try{const U=await window.api.files.duplicate(i);U.ok&&U.path?(y(U.path),lt.info(`Duplicated as ${t0(U.path)}`)):lt.error(U.error??`Couldn't duplicate ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't duplicate ${b}`)}},R=async()=>{try{const U=await window.api.files.delete(i);U.ok?(k(i),t==null||t(i),lt.info(`Deleted ${b}`)):lt.error(U.error??`Couldn't delete ${b}`)}catch(U){lt.error(U instanceof Error?U.message:`Couldn't delete ${b}`)}v(!1)},N=async()=>{C();const U=m??"";try{await navigator.clipboard.writeText(U),lt.info(`Copied ${U.length} chars`)}catch(oe){lt.error(oe instanceof Error?oe.message:`Couldn't copy ${b}`)}},L=()=>{if(C(),!T){lt.error("No terminal tab is active");return}window.api.pty.write({tabId:T.id,data:`@${i} `}),lt.info(`Added ${b} to Claude context`)},j=()=>{C(),window.api.shell.open({as:"openPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't open ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't open ${b}`))},H=()=>{C(),window.api.shell.open({as:"revealPath",path:i}).then(U=>{U.ok||lt.error(U.error??`Couldn't reveal ${b}`)}).catch(U=>lt.error(U instanceof Error?U.message:`Couldn't reveal ${b}`))};return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.jsx("button",{onClick:()=>r(U=>!U),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&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:C}),h.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:[h.jsx(p_,{children:"Edit"}),h.jsx(Zc,{label:"Rename",onClick:w}),h.jsx(Zc,{label:"Duplicate",onClick:$}),h.jsx(Zc,{label:"Delete document",danger:!0,onClick:()=>{C(),v(!0)}}),h.jsx(i0,{}),h.jsx(p_,{children:"Open"}),h.jsx(Zc,{label:"Open in default app",onClick:j}),h.jsx(Zc,{label:"Reveal in OS",onClick:H}),h.jsx(i0,{}),h.jsx(p_,{children:"Export"}),h.jsx(Zc,{label:"Copy as Markdown",onClick:N}),h.jsx(Zc,{label:"Add to Claude context",onClick:L,disabled:!T,title:T?void 0:"No terminal tab is active"})]})]}),l&&h.jsx(MR,{value:a,onChange:d,onCancel:()=>p(!1),onConfirm:()=>void x()}),f&&h.jsx(OR,{name:b,onCancel:()=>v(!1),onConfirm:()=>void R()})]})}function p_({children:i}){return h.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:i})}function Zc({label:i,onClick:e,danger:t,disabled:n,title:r}){return h.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 i0(){return h.jsx("div",{className:"my-1 border-t border-line"})}function MR({value:i,onChange:e,onCancel:t,onConfirm:n}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:r=>{r.target===r.currentTarget&&t()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),h.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"}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function OR({name:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",i,"? This cannot be undone."]}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function LR(){const[i,e]=G.useState(!1),t=Qu();return h.jsxs("div",{className:"relative inline-block mr-1",children:[h.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&&h.jsxs(h.Fragment,{children:[h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuScrim}`,onMouseDown:()=>e(!1)}),h.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:[h.jsx(Yu,{label:"Text size",children:h.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[h.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−"}),h.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:t.fontSize}),h.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+"})]})}),h.jsx(Yu,{label:"Word wrap",children:h.jsx(Eg,{on:t.wordWrap,onClick:t.toggleWordWrap})}),h.jsx(Yu,{label:"Minimap",children:h.jsx(Eg,{on:t.minimap,onClick:t.toggleMinimap})}),h.jsx(Yu,{label:"Theme",children:h.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"})}),h.jsx(Yu,{label:"Autosave",children:h.jsx(Eg,{on:t.autosave,onClick:t.toggleAutosave})}),h.jsx(Yu,{label:"Wide measure",children:h.jsx(Eg,{on:t.wideMeasure,onClick:t.toggleWideMeasure})})]})]})]})}function Yu({label:i,children:e}){return h.jsxs("div",{className:"flex items-center justify-between gap-2",children:[h.jsx("span",{className:"text-fg-faint",children:i}),e]})}function Eg({on:i,onClick:e}){return h.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 zR=G.lazy(()=>os(()=>import("./TiptapBody-DxzA0zb5.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(i=>({default:i.TiptapBody})));function Tg(i){return i.split("/").filter(Boolean).pop()||i}function Dg(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 $g(i){return OS(i)||LS(i)}function BR(){const i=tw(),e=$i(Ye=>Ye.openFiles),t=$i(Ye=>Ye.activeFilePath),n=$i(Ye=>Ye.dirty),r=$i(Ye=>Ye.viewMode),l=$i(Ye=>Ye.buffers),p=$i(Ye=>Ye.setActive),a=$i(Ye=>Ye.closeFile),d=$i(Ye=>Ye.closeOthers),f=$i(Ye=>Ye.closeToTheRight),v=$i(Ye=>Ye.closeAll),m=$i(Ye=>Ye.loadBuffer),y=$i(Ye=>Ye.setBuffer),D=$i(Ye=>Ye.markSaved),k=$i(Ye=>Ye.setViewMode),T=Qu(),[b,C]=G.useState({}),[w,x]=G.useState({}),[$,R]=G.useState(null),[N,L]=G.useState(null),[j,H]=G.useState(!1),[U,oe]=G.useState(!1),[de,Z]=G.useState(!0),me=G.useRef(null),ie=G.useRef(null),ue=G.useRef(void 0),Ce=G.useRef(null),Ee=G.useRef(null),W=DR(t??"",l[t??""]??""),te=G.useCallback(Ye=>{me.current=Ye},[]),K=G.useCallback(()=>me.current,[]);G.useEffect(()=>{const Ye=t;if(!Ye||$g(Ye))return;if($i.getState().hasBuffer(Ye)){C(ut=>ut[Ye]==="ready"?ut:{...ut,[Ye]:"ready"});return}let St=!1;return C(ut=>({...ut,[Ye]:"loading"})),window.api.files.read(Ye).then(ut=>{St||(ut.binary?C(Xe=>({...Xe,[Ye]:{binary:!0,size:ut.size??0,mime:ut.mime??"application/octet-stream",reason:ut.error??"Binary file"}})):ut.ok?(m(Ye,ut.text),C(Xe=>({...Xe,[Ye]:"ready"}))):C(Xe=>({...Xe,[Ye]:{error:ut.error??"failed to read"}})))}),()=>{St=!0}},[t,m]),G.useEffect(()=>{L(null)},[t]);const re=G.useCallback(async(Ye,St=!1)=>{const ut=$i.getState().buffers[Ye];if(ut==null)return;St&&H(!0);const Xe=await window.api.files.write(Ye,ut);Xe.ok?(D(Ye),x(Pt=>({...Pt,[Ye]:(Pt[Ye]??0)+1})),St||lt.info(`Saved ${Tg(Ye)}`)):lt.error(Xe.error??`Couldn't save ${Tg(Ye)}`),St&&H(!1)},[D]);G.useEffect(()=>{if(!T.autosave)return;const Ye=t;if(!(!Ye||$g(Ye)||!n[Ye]))return window.clearTimeout(ue.current),ue.current=window.setTimeout(()=>{re(Ye,!0)},1200),()=>window.clearTimeout(ue.current)},[T.autosave,t,n,l,re]);const ve=G.useCallback(Ye=>{Ye.length&&(C(St=>Dg(St,Ye)),x(St=>Dg(St,Ye)))},[]),_e=G.useCallback((Ye,St)=>{C(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut),x(ut=>Ye in ut?{...Dg(ut,[Ye]),[St]:ut[Ye]}:ut)},[]),Me=G.useCallback(Ye=>{n[Ye]?R({kind:"one",path:Ye}):(a(Ye),ve([Ye]))},[n,a,ve]),et=G.useCallback(Ye=>{e.some(ut=>ut.path!==Ye&&n[ut.path])?R({kind:"others",path:Ye}):(d(Ye),ve(e.filter(ut=>ut.path!==Ye).map(ut=>ut.path)))},[e,n,d,ve]),we=G.useCallback(Ye=>{const St=e.findIndex(Xe=>Xe.path===Ye);St!==-1&&e.slice(St+1).some(Xe=>n[Xe.path])?R({kind:"right",path:Ye}):(f(Ye),ve(St!==-1?e.slice(St+1).map(Xe=>Xe.path):[]))},[e,n,f,ve]);G.useEffect(()=>{const Ye=St=>{if(i.current)if((St.metaKey||St.ctrlKey)&&(St.key==="s"||St.key==="S")){const ut=$i.getState().activeFilePath;ut&&!$g(ut)&&(St.preventDefault(),re(ut))}else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="f"||St.key==="F"))St.preventDefault(),oe(ut=>!ut);else if((St.metaKey||St.ctrlKey)&&St.shiftKey&&(St.key==="w"||St.key==="W")){const ut=$i.getState().activeFilePath;ut&&$i.getState().openFiles.length>1&&(St.preventDefault(),et(ut))}else St.key==="Escape"&&W.state.phase!=="idle"?W.cancel():St.key==="Escape"&&U&&oe(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[re,U,et,W.state.phase,W.cancel]),G.useEffect(()=>{if(W.state.phase==="idle")return;const Ye=St=>{var Xe,Pt;const ut=St.target;(Xe=Ee.current)!=null&&Xe.contains(ut)||(Pt=Ce.current)!=null&&Pt.contains(ut)||W.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[W.state.phase,W.cancel]),G.useEffect(()=>{W.cancel()},[t,W.cancel]);const X=G.useCallback(()=>{e.some(St=>n[St.path])?R({kind:"all",path:""}):(v(),C({}),x({}))},[e,n,v]),Ie=()=>{if($){if($.kind==="one")a($.path),ve([$.path]);else if($.kind==="others"){const Ye=e.filter(St=>St.path!==$.path).map(St=>St.path);d($.path),ve(Ye)}else if($.kind==="right"){const Ye=e.findIndex(ut=>ut.path===$.path),St=Ye!==-1?e.slice(Ye+1).map(ut=>ut.path):[];f($.path),ve(St)}else v(),C({}),x({});R(null)}};if(e.length===0)return h.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:h.jsxs("div",{className:"text-center",children:[h.jsx("div",{className:"mb-2",children:"no file open"}),h.jsxs("div",{children:["open the ",h.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const pe=t,Ze=pe?Tg(pe):"",ge=pe?b[pe]:void 0,Ke=pe?GS(pe):!1,vt=pe?EA(pe):!1,st=pe&&Ke?r[pe]??TA(pe):"edit",Kt=!!pe&&!$g(pe)&&ge==="ready",Be=Kt,Dt=vt?["edit","wysiwyg","preview","split"]:Ke?["edit","preview"]:[],_t=pe&&h.jsx(FI,{path:pe,name:Ze,value:l[pe]??"",onChange:Ye=>y(pe,Ye),onSave:()=>void re(pe),onReady:te,onCursor:L}),ri=j?"Saving…":pe&&n[pe]?T.autosave?"Editing…":"Unsaved":"All changes saved";return h.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&h.jsx(AA,{openFiles:e,activeFilePath:t,dirty:n,onSelectFile:p,onCloseFile:Me,onCloseOthers:et,onCloseToTheRight:we,onCloseAll:X}),pe&&!U&&h.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[h.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ze}),h.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:pe}),Kt&&h.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",ri]}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:()=>Z(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${de?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),qa(pe)&&(st==="preview"||st==="split")&&h.jsx("button",{onClick:T.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${T.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&h.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Ye=>h.jsx("button",{onClick:()=>k(pe,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${st===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),h.jsx("div",{className:"flex-1"}),h.jsx(NR,{path:pe,onRenamed:_e,onDeleted:Ye=>ve([Ye])}),Kt&&h.jsx(LR,{}),h.jsx("button",{onClick:()=>oe(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),U&&h.jsx("button",{onClick:()=>oe(!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"}),h.jsx("div",{className:"flex-1 min-h-0",children:pe?OS(pe)?h.jsx(uR,{path:pe,name:Ze}):LS(pe)?h.jsx(hR,{path:pe}):ge&&typeof ge=="object"&&"binary"in ge?h.jsx(bR,{path:pe,name:Ze,size:ge.size,mime:ge.mime,reason:ge.reason}):ge&&typeof ge=="object"&&"error"in ge?h.jsx("div",{className:"p-6 text-xs text-red-400",children:ge.error}):ge!=="ready"?h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):st==="wysiwyg"&&qa(pe)?h.jsx(G.Suspense,{fallback:h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:h.jsx(zR,{value:l[pe]??"",onChange:Ye=>y(pe,Ye)},pe)}):st==="split"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(Xx,{text:l[pe]??"",scrollRef:ie}),h.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[h.jsx(Yx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(db,{ref:ie,text:l[pe]??"",flush:!0,wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(e0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&qa(pe)?h.jsxs("div",{className:"flex h-full",children:[de&&h.jsx(Xx,{text:l[pe]??"",scrollRef:ie}),h.jsx("div",{ref:Ce,className:"flex-1 min-w-0",children:h.jsx(db,{ref:ie,text:l[pe]??"",wideMeasure:T.wideMeasure,onSelect:W.select,onDismissSelection:W.cancel})}),!U&&T.assistantRail&&h.jsx(e0,{phase:W.state.phase,transcript:W.state.transcript,diff:W.state.diff,editCount:W.state.editCount,modelStatus:W.state.modelStatus,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)},onReject:W.cancel,onRetry:W.retry})]}):st==="preview"&&MS(pe)?h.jsx(cR,{path:pe,dirty:!!n[pe],reloadToken:w[pe]??0}):st==="preview"&&zS(pe)?h.jsx(fR,{path:pe,text:l[pe]??""}):st==="preview"&&BS(pe)?h.jsx(vR,{path:pe,text:l[pe]??""}):qa(pe)?h.jsxs("div",{className:"flex flex-col h-full",children:[h.jsx(Yx,{getEditor:K}),h.jsx("div",{className:"flex-1 min-h-0",children:_t})]}):_t:null}),Be&&h.jsx(lR,{text:l[pe]??"",cursor:N,language:Nr(pe)||void 0}),pe&&qa(pe)&&(st==="preview"||st==="split")&&W.state.phase!=="idle"&&W.state.selection&&h.jsx("div",{ref:Ee,children:h.jsx(PR,{phase:W.state.phase,rect:W.state.selection.rect,diff:W.state.diff,transcript:W.state.transcript,modelStatus:W.state.modelStatus,onQuickAction:W.run,onRunCustom:W.run,onListen:W.listen,onSendHeard:W.sendHeard,onCancel:W.cancel,onReject:W.cancel,onRetry:W.retry,onAccept:()=>{const Ye=W.accept(l[pe]??"");Ye.ok&&y(pe,Ye.next)}})}),$&&h.jsx(GR,{message:$.kind==="one"?`Discard unsaved changes to ${Tg($.path)}?`:$.kind==="others"?"Discard unsaved changes in the other open files?":$.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>R(null),onConfirm:Ie})]})}const pb=G.memo(BR);function GR({message:i,onCancel:e,onConfirm:t}){return h.jsx("div",{className:`fixed inset-0 ${Cn.contextMenuDialog} flex items-center justify-center bg-black/60`,onMouseDown:n=>{n.target===n.currentTarget&&e()},children:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:i}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),h.jsx("button",{onClick:t,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const FR={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},n0='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function vw({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?h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[n&&h.jsx("h2",{className:`text-base font-medium text-fg ${p?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:n}),h.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${p?"":"p-6 pt-0"}`,children:t})]}):null;const d=G.useRef(null),f=G.useRef(null),v=G.useRef(e);if(v.current=e,G.useEffect(()=>{if(!i)return;f.current=typeof document<"u"?document.activeElement:null;const k=setTimeout(()=>{const b=d.current;if(!b)return;const C=b.querySelector(n0);C?C.focus():b.focus()},0),T=b=>{if(b.key==="Escape"){b.stopPropagation(),v.current();return}if(b.key==="Tab"){const C=d.current;if(!C)return;const w=Array.from(C.querySelectorAll(n0)).filter(N=>!N.hasAttribute("disabled")&&N.tabIndex!==-1);if(w.length===0){b.preventDefault(),C.focus();return}const x=w[0],$=w[w.length-1],R=document.activeElement;b.shiftKey?(R===x||!C.contains(R))&&(b.preventDefault(),$.focus()):(R===$||!C.contains(R))&&(b.preventDefault(),x.focus())}};return document.addEventListener("keydown",T),()=>{clearTimeout(k),document.removeEventListener("keydown",T);const b=f.current;if(b&&b instanceof HTMLElement)try{b.focus()}catch{}f.current=null}},[i]),!i)return null;const m=D=>{D.target===D.currentTarget&&e()},y=h.jsx("div",{className:`fixed inset-0 ${Cn.dialog} flex items-center justify-center bg-black/60`,onClick:m,"data-testid":"modal-backdrop",children:h.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 ${FR[r]} ${l?"max-h-[90vh] h-[90vh]":""} ${p?"":"p-6"}`,"data-testid":"modal-dialog",children:[n?h.jsx("h2",{className:`text-base font-medium text-fg break-words ${p?"px-6 pt-6 pb-3":"mb-3"}`,children:n}):null,l?h.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:t}):t]})});return typeof document<"u"&&document.body?Jf.createPortal(y,document.body):y}class hC extends G.Component{constructor(){super(...arguments);Bi(this,"state",{error:null});Bi(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):h.jsxs("div",{className:"p-6 text-xs",children:[h.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),h.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),h.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 HR({open:i,onClose:e,title:t,children:n,variant:r="overlay"}){return h.jsxs(vw,{open:i,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:r,children:[r==="overlay"&&h.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[h.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:t}),h.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:"✕"})]}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(hC,{children:n})})]})}function pC(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 s0=i=>Symbol.iterator in i,r0=i=>"entries"in i,o0=(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},WR=(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 UR(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:s0(i)&&s0(e)?r0(i)&&r0(e)?o0(i,e):WR(i,e):o0({entries:()=>Object.entries(i)},{entries:()=>Object.entries(e)})}function _w(i){const e=Rt.useRef(void 0);return t=>{const n=i(t);return UR(e.current,n)?e.current:e.current=n}}let a0=0;const VR=1e3;function qR(i){const e=performance.now();e-a0<VR||(a0=e,pt.debug("voice","mic.gate.click_rejected",{reason:i}))}function KR(){const i=Ct(f=>f.isRecording),e=Ct(f=>f.error),t=Ct(f=>f.loadingProgress),n=Ct(_w(ev)),r=()=>{const f=Ct.getState(),{canRecord:v,reason:m}=ev(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(!v)return qR(m);const y=xt.getState().activeTabId;y&&f.startRecording(y)},l=pC(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 h.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:h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),h.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),h.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),h.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function YR(){const i=Ct(t=>t.ttsEnabled),e=Ct(t=>t.toggleTTS);return h.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:[h.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[h.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i?h.jsxs(h.Fragment,{children:[h.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),h.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):h.jsxs(h.Fragment,{children:[h.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),h.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),h.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function XR(i){return/^monitor of /i.test(i.trim())}function l0(i){return i.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function c0(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=l0(e),l=t.filter(p=>p.label&&l0(p.label)===r);return l.length===1?l[0]:null}async function d0(i){var t;return(t=navigator.mediaDevices)!=null&&t.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(n=>!(n.kind!=="audioinput"||n.label&&XR(n.label))):[]}const u0=!1;function fC(){const i=Ct(f=>f.isRecording);Ct(f=>f.startRecording),Ct(f=>f.stopRecording);const[e,t]=G.useState([]),[n,r]=G.useState(null),[l,p]=G.useState(null);G.useEffect(()=>{let f=!1;return(async()=>{try{const v=await window.api.voice.getDevicePref();if(f)return;const m=await d0(u0);if(f)return;t(m),p(v.selectedLabel);const y=c0(v.selectedDeviceId,v.selectedLabel,m);y?(r(y.deviceId),v.selectedDeviceId&&y.deviceId!==v.selectedDeviceId&&(pt.info("voice","device-picker rebind-by-label",{fromIdPrefix:v.selectedDeviceId.slice(0,8),toIdPrefix:y.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:y.deviceId,selectedLabel:y.label||v.selectedLabel}).catch(()=>{}))):((v.selectedDeviceId||v.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:v.selectedLabel,hadId:!!v.selectedDeviceId}),pt.warn("voice","device-picker selected-unavailable",{hadId:!!v.selectedDeviceId})),r(null))}catch(v){pt.warn("voice","device-picker init failed",{error:v instanceof Error?v.message:String(v)})}})(),()=>{f=!0}},[]);const a=G.useCallback(async()=>{try{const f=await d0(u0);if(t(f),n&&!f.some(v=>v.deviceId===n)){const v=c0(null,l,f);v?(r(v.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||l}).catch(()=>{})):r(null)}}catch(f){pt.warn("voice","device-picker refresh failed",{error:f instanceof Error?f.message:String(f)})}},[n,l]);G.useEffect(()=>{const f=()=>{a()};return window.addEventListener("mic-device-change",f),()=>window.removeEventListener("mic-device-change",f)},[a]);const d=async f=>{var D;const v=f.target.value,m=v===""?null:v,y=m?((D=e.find(k=>k.deviceId===m))==null?void 0:D.label)??null:null;r(m),p(y);try{await window.api.voice.setDevicePref({selectedDeviceId:m,selectedLabel:y}),pt.info("voice","device-picker selected",{deviceIdPrefix:m?m.slice(0,8):null})}catch(k){pt.warn("voice","setDevicePref failed",{error:k instanceof Error?k.message:String(k)})}if(i)try{await Ct.getState().restartWithDevice()}catch(k){pt.warn("voice","device-picker restart failed",{error:k instanceof Error?k.message:String(k)})}};return h.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:[h.jsx("option",{value:"",children:"Default"}),e.map(f=>h.jsx("option",{value:f.deviceId,children:f.label||`Mic ${f.deviceId.slice(0,6)}`},f.deviceId))]})}function JR(){const i=Ct(D=>D.isRecording),e=Ct(D=>D.levelMeterEnabled),[t,n]=G.useState(0),[r,l]=G.useState(0),p=G.useRef(0);p.current=r;const[a,d]=G.useState(0),[f,v]=G.useState(!1),m=G.useRef(null);if(G.useEffect(()=>{if(!i||!e){n(0),l(0);return}let D=0,k=!1,T=null,b=null;const C=()=>{if(k)return;const x=b??N1();if(!x){D=requestAnimationFrame(C);return}b!==x&&(b=x,T=new Uint8Array(new ArrayBuffer(x.fftSize)));const $=T;x.getByteTimeDomainData($);let R=0;for(let H=0;H<$.length;H++){const U=$[H]-128;R+=U*U}const N=Math.sqrt(R/$.length)/128,L=N>0?20*Math.log10(N):-60,j=Math.max(0,Math.min(1,(L+60)/60));l(N),n(j),N>=.95&&(v(!0),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>v(!1),150)),D=requestAnimationFrame(C)};D=requestAnimationFrame(C);const w=setInterval(()=>{k||d(Math.round(p.current*100))},250);return()=>{k=!0,cancelAnimationFrame(D),clearInterval(w),m.current&&(clearTimeout(m.current),m.current=null)}},[i,e]),!i||!e)return null;const y=f?"bg-red-500":r>=.7?"bg-amber-400":"bg-green-500";return h.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:h.jsx("div",{className:`h-full ${y} transition-[width] duration-75 ease-out`,style:{width:`${t*100}%`}})})}function mC(){const i=Ct(f=>f.submitCountdownStartAt),e=Ct(f=>f.submitDelayMs),[t,n]=G.useState(()=>performance.now());if(G.useEffect(()=>{if(i===null)return;let f;const v=()=>{n(performance.now()),f=requestAnimationFrame(v)};return f=requestAnimationFrame(v),()=>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 h.jsx("div",{className:"px-3 pb-1",onClick:d,title:`Submitting in ${(l/1e3).toFixed(1)}s — click to cancel`,children:h.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:h.jsx("div",{className:`h-full transition-colors ${a?"bg-amber-400":"bg-accent"}`,style:{width:`${p}%`}})})})}function ZR({open:i,onClose:e,variant:t="overlay"}){return h.jsx(HR,{open:i,onClose:e,title:"Voice / Microphone",variant:t,children:h.jsxs("div",{className:"p-4 space-y-4",children:[h.jsx(ij,{}),h.jsx(mC,{}),h.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[h.jsx(KR,{}),h.jsx(fC,{}),h.jsx(YR,{})]}),h.jsx(QR,{}),h.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[h.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"}),h.jsx(tj,{})]}),h.jsx(JR,{})]})})}function QR(){const i=Ct(l=>l.isRecording),[e,t]=G.useState(null);if(G.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=ej(e.accelerator);return h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("span",{children:[n," "]}),h.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:r}),h.jsx("span",{children:" to record"})]})}function ej(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 tj(){const[i,e]=G.useState(null);if(G.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 h.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:[h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="toggle",onChange:()=>t("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),h.jsx("span",{children:"Tap on/off"})]}),h.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[h.jsx("input",{type:"radio",name:"hotkey-mode",checked:i.mode==="hold",onChange:()=>t("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),h.jsx("span",{children:"Hold to talk"})]})]})}function ij(){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?h.jsxs("div",{className:"text-[11px] text-red-400",title:t,children:["⚠ ",t]}):i?h.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[h.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),h.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):n==="loading"?h.jsxs("div",{className:"text-[11px] text-fg-faint",children:[h.jsxs("div",{className:"flex items-center justify-between mb-1",children:[h.jsx("span",{children:"Loading speech model"}),h.jsxs("span",{className:"font-mono",children:[r,"%"]})]}),h.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:h.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${r}%`}})})]}):null}const gC="~/.claude/session-manager/projects-prefs.json",nj={project:"asc",sessions:"desc",last:"desc",size:"desc"};function zl(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(gC,t).catch(()=>{})}const h0=In((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(gC);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}),zl(e)},setSort:t=>{const n=e(),r=n.sort.col===t?n.sort.dir==="asc"?"desc":"asc":nj[t];i({sort:{col:t,dir:r}}),zl(e)},setRecentFilter:t=>{i({recentFilter:t}),zl(e)},setHasRemote:t=>{i({hasRemote:t}),zl(e)},setHasClaudemd:t=>{i({hasClaudemd:t}),zl(e)},setPinnedOnly:t=>{i({pinnedOnly:t}),zl(e)},setSearch:t=>{i({search:t}),zl(e)},setEditor:t=>{i({editor:t}),zl(e)}})),vC=i=>`sm.fileTree.expanded:${i}`;function sj(i){try{const e=localStorage.getItem(vC(i)),t=e?JSON.parse(e):[];return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}catch{return[]}}function rj(i,e){try{localStorage.setItem(vC(i),JSON.stringify([...e].slice(0,500)))}catch{}}const _C="sm.fileTree.showHidden";function oj(){try{const i=localStorage.getItem(_C);return i===null?!0:JSON.parse(i)===!0}catch{return!0}}function aj(i){try{localStorage.setItem(_C,JSON.stringify(i))}catch{}}function f_(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 m_={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:"!"}},lj=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 cj(i){const e=Nr(i);return lj.has(e)||NS.has(e)||e==="pdf"}function dj(i,e){if(e)return"#d97757";switch(Nr(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 ff(i){var e;try{const t=window.api;return(e=t==null?void 0:t.git)!=null&&e.fileStatus?await t.git.fileStatus(i):{}}catch{return{}}}function uj({cwd:i,onPreviewFile:e,onSendToChat:t,activeTabId:n}){const r=tw(),l=ew(),[p,a]=G.useState([]),[d,f]=G.useState(new Set),v=G.useRef(d);v.current=d;const[m,y]=G.useState(""),[D,k]=G.useState(oj),T=G.useCallback(Be=>{k(Dt=>{const _t=typeof Be=="function"?Be(Dt):Be;return aj(_t),_t})},[]),[b,C]=G.useState(!1),[w,x]=G.useState(null),[$,R]=G.useState({}),[N,L]=G.useState(null),[j,H]=G.useState(null),[U,oe]=G.useState(""),[de,Z]=G.useState(null),[me,ie]=G.useState(""),[ue,Ce]=G.useState(null),Ee=G.useRef(null),W=G.useRef(null),te=G.useRef(0),K=G.useCallback(async()=>{if(!i)return;const Be=++te.current;C(!0),x(null);const Dt=await window.api.files.list(i,D);te.current===Be&&(Dt.ok?a(Dt.entries.map(_t=>({..._t}))):(x(Dt.error??"failed to list"),a([])),C(!1))},[i,D]),re=G.useCallback(async Be=>{const Dt=te.current,_t=new Map;for(const Ye of Be){const St=Ye.split("/").length,ut=_t.get(St);ut?ut.push(Ye):_t.set(St,[Ye])}const ri=[];for(const Ye of[..._t.keys()].sort((St,ut)=>St-ut)){const St=_t.get(Ye),ut=await Promise.all(St.map(async Xe=>({p:Xe,result:await window.api.files.list(Xe,D)})));if(te.current!==Dt)return ri;for(const{p:Xe,result:Pt}of ut)Pt.ok?a(oi=>Wg(oi,Xe,Pt.entries.map(Fi=>({...Fi})))):ri.push(Xe)}return ri},[D]),ve=G.useCallback(async Be=>(await K(),Be.length?re(Be):[]),[K,re]);G.useEffect(()=>{y(""),H(null),L(null),Z(null),Ce(null),R({});const Be=sj(i),Dt=new Set(Be);v.current=Dt,f(Dt);let _t=!1;return(async()=>{const ri=await ve(Be);_t||!ri.length||Me(Ye=>{const St=new Set;let ut=!1;for(const Xe of Ye){if(ri.some(Pt=>Xe===Pt||Xe.startsWith(Pt+"/"))){ut=!0;continue}St.add(Xe)}return ut?St:Ye})})(),ff(i).then(ri=>{_t||R(ri)}),()=>{_t=!0}},[i]);const _e=G.useRef(!0);G.useEffect(()=>{if(_e.current){_e.current=!1;return}ve([...v.current])},[D]),G.useEffect(()=>{if(!i||!l)return;ff(i).then(R);const Be=window.setInterval(()=>{ff(i).then(R)},5e3);return()=>window.clearInterval(Be)},[i,l]),G.useEffect(()=>{if(!N)return;const Be=()=>L(null),Dt=_t=>{r.current&&_t.key==="Escape"&&L(null)};return window.addEventListener("mousedown",Be),window.addEventListener("keydown",Dt),()=>{window.removeEventListener("mousedown",Be),window.removeEventListener("keydown",Dt)}},[N]),G.useEffect(()=>{j&&setTimeout(()=>{var Be;return(Be=Ee.current)==null?void 0:Be.select()},30)},[j]),G.useEffect(()=>{de&&setTimeout(()=>{var Be;return(Be=W.current)==null?void 0:Be.focus()},30)},[de]);const Me=G.useCallback(Be=>{const Dt=v.current,_t=Be(Dt);_t!==Dt&&(v.current=_t,f(_t),rj(i,_t))},[i]),et=G.useCallback(async Be=>{if(d.has(Be.path)){Me(_t=>f_(_t,Be.path));return}if(Me(_t=>new Set(_t).add(Be.path)),Be.children)return;const Dt=await window.api.files.list(Be.path,D);Dt.ok&&a(_t=>Wg(_t,Be.path,Dt.entries.map(ri=>({...ri}))))},[d,D,Me]),we=G.useCallback(async Be=>{if(Be===i){await K();return}const Dt=await window.api.files.list(Be,D);Dt.ok&&a(_t=>Wg(_t,Be,Dt.entries.map(ri=>({...ri}))))},[i,K,D]),X=G.useCallback(Be=>{if(Be.isDirectory){et(Be);return}cj(Be.name)&&e?e(Be.path):window.api.shell.open({as:"openPath",path:Be.path})},[et,e]),Ie=G.useCallback(Be=>{if(t){t(Be);return}if(n){const Dt=Be.startsWith(i+"/")?Be.slice(i.length+1):Be;window.api.pty.write({tabId:n,data:`@${Dt} `})}},[t,n,i]),pe=G.useCallback((Be,Dt)=>{Be.preventDefault(),Be.stopPropagation(),L({x:Be.clientX,y:Be.clientY,node:Dt})},[]),Ze=Be=>{H(Be.path),oe(Be.name)},ge=async()=>{if(!j)return;const Be=U.trim();if(!Be){H(null);return}const Dt=await window.api.files.rename(j,Be);if(H(null),Dt.ok){const _t=j.slice(0,j.lastIndexOf("/"));Me(ri=>f_(ri,j)),await we(_t||i),ff(i).then(R)}else{const _t=Dt.error??"rename failed";x(_t),lt.error(_t)}},Ke=async()=>{if(!de)return;const Be=me.trim();if(!Be){Z(null),ie("");return}const Dt=await window.api.files.create(de.parent,Be,de.kind);if(Z(null),ie(""),Dt.ok)await we(de.parent),de.kind==="folder"&&Me(_t=>new Set(_t).add(de.parent));else{const _t=Dt.error??"create failed";x(_t),lt.error(_t)}},vt=async()=>{if(!ue)return;const Be=await window.api.files.delete(ue.path),Dt=ue.path.slice(0,ue.path.lastIndexOf("/"));if(Ce(null),Be.ok)Me(_t=>f_(_t,ue.path)),await we(Dt||i),ff(i).then(R);else{const _t=Be.error??"delete failed";x(_t),lt.error(_t)}},st=G.useMemo(()=>{if(!m.trim())return p;const Be=m.toLowerCase();return p.filter(Dt=>Dt.name.toLowerCase().includes(Be))},[p,m]),Kt=(i==null?void 0:i.split("/").filter(Boolean).pop())||"project";return h.jsxs("div",{className:"w-full h-full flex flex-col bg-bg-elev text-fg",children:[h.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[h.jsx(wC,{size:14,className:"shrink-0 text-accent"}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("p",{className:"text-xs font-medium text-fg truncate",children:Kt}),h.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:i,children:i})]}),h.jsx("button",{onClick:K,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:b,children:h.jsx(vj,{size:12,className:b?"animate-spin":""})})]}),h.jsx("div",{className:"relative",children:h.jsx("input",{value:m,onChange:Be=>y(Be.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"})})]}),h.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[h.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:h.jsx(_j,{size:12})}),h.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:h.jsx(bj,{size:12})}),h.jsx("div",{className:"flex-1"}),h.jsx("button",{onClick:()=>T(Be=>!Be),className:`p-1.5 rounded transition-colors ${D?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:D?"Hide hidden files":"Show hidden files",children:D?h.jsx(wj,{size:12}):h.jsx(yj,{size:12})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[w&&h.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:w}),!w&&st.length===0&&!b&&h.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:m?"no matches":"empty folder"}),!w&&h.jsx(bC,{nodes:st,depth:0,expanded:d,gitStatus:$,renaming:j,renameValue:U,renameInputRef:Ee,onRenameChange:oe,onRenameCommit:ge,onRenameCancel:()=>H(null),onToggleDir:et,onFileClick:X,onSendToChat:Ie,onContextMenu:pe})]}),h.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"}),N&&h.jsx(hj,{x:N.x,y:N.y,node:N.node,onClose:()=>L(null),onRename:()=>{Ze(N.node),L(null)},onDelete:()=>{Ce(N.node),L(null)},onNewFile:()=>{Z({parent:N.node.path,kind:"file"}),L(null)},onNewFolder:()=>{Z({parent:N.node.path,kind:"folder"}),L(null)},onOpenExternal:()=>{window.api.shell.open({as:"openPath",path:N.node.path}),L(null)},onShowInFinder:()=>{window.api.shell.open({as:"revealPath",path:N.node.path}),L(null)},onCopyPath:()=>{var Be;(Be=navigator.clipboard)==null||Be.writeText(N.node.path),L(null)},onSendToChat:()=>{Ie(N.node.path),L(null)}}),de&&h.jsx(p0,{title:`New ${de.kind}`,subtitle:`in ${pj(de.parent)}`,onCancel:()=>{Z(null),ie("")},onConfirm:Ke,confirmLabel:"Create",confirmDisabled:!me.trim(),children:h.jsx("input",{ref:W,value:me,onChange:Be=>ie(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"&&Ke(),Be.key==="Escape"&&(Z(null),ie(""))},placeholder:de.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"})}),ue&&h.jsx(p0,{title:`Delete ${ue.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>Ce(null),onConfirm:vt,confirmLabel:"Delete",danger:!0,children:h.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",h.jsxs("span",{className:"text-fg font-medium",children:['"',ue.name,'"']})," to the trash?",ue.isDirectory&&h.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function bC(i){const{nodes:e,depth:t,expanded:n,gitStatus:r,renaming:l,onContextMenu:p}=i;return h.jsx(h.Fragment,{children:e.map(a=>{const d=n.has(a.path),f=l===a.path,v=r[a.path],m=dj(a.name,a.isDirectory);return h.jsxs("div",{children:[h.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:y=>p(y,a),children:[a.isDirectory?h.jsx(gj,{size:10,className:`shrink-0 text-fg-faint transition-transform ${d?"rotate-90":""}`}):h.jsx("span",{className:"w-[10px] shrink-0"}),a.isDirectory?d?h.jsx(fj,{size:12,color:m}):h.jsx(wC,{size:12,color:m}):h.jsx(mj,{size:12,color:m}),f?h.jsx("input",{ref:i.renameInputRef,value:i.renameValue,onChange:y=>i.onRenameChange(y.target.value),onClick:y=>y.stopPropagation(),onBlur:i.onRenameCommit,onKeyDown:y=>{y.key==="Enter"&&i.onRenameCommit(),y.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"}):h.jsx("span",{className:`flex-1 truncate text-xs ${a.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:a.name}),v&&h.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:m_[v].color,backgroundColor:`${m_[v].color}20`},title:v,children:m_[v].label}),!a.isDirectory&&h.jsx("button",{onClick:y=>{y.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:h.jsx(xj,{size:10})})]}),a.isDirectory&&d&&a.children&&h.jsx(bC,{...i,nodes:a.children,depth:t+1})]},a.path)})})}function hj(i){const{x:e,y:t,node:n}=i;return h.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&&h.jsx(Bl,{label:"Send to chat",onClick:i.onSendToChat}),h.jsx(Bl,{label:"Open in default app",onClick:i.onOpenExternal}),h.jsx(Bl,{label:"Reveal in OS",onClick:i.onShowInFinder}),h.jsx(g_,{}),h.jsx(Bl,{label:"Copy path",onClick:i.onCopyPath}),h.jsx(Bl,{label:"Rename",onClick:i.onRename}),n.isDirectory&&h.jsxs(h.Fragment,{children:[h.jsx(g_,{}),h.jsx(Bl,{label:"New file",onClick:i.onNewFile}),h.jsx(Bl,{label:"New folder",onClick:i.onNewFolder})]}),h.jsx(g_,{}),h.jsx(Bl,{label:"Delete",onClick:i.onDelete,danger:!0})]})}function Bl({label:i,onClick:e,danger:t}){return h.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 g_(){return h.jsx("div",{className:"my-1 border-t border-line"})}function p0(i){return h.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:h.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[h.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:i.title}),i.subtitle&&h.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:i.subtitle}),h.jsx("div",{className:"mb-4",children:i.children}),h.jsxs("div",{className:"flex justify-end gap-2",children:[h.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"}),h.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 pj(i){return i.split("/").filter(Boolean).pop()||i}function Wg(i,e,t){return i.map(n=>n.path===e?{...n,children:t}:n.children?{...n,children:Wg(n.children,e,t)}:n)}function ma({size:i,children:e,className:t,color:n}){return h.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 wC({size:i,className:e,color:t}){return h.jsx(ma,{size:i,className:e,color:t,children:h.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 fj({size:i,className:e,color:t}){return h.jsx(ma,{size:i,className:e,color:t,children:h.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 mj({size:i,className:e,color:t}){return h.jsxs(ma,{size:i,className:e,color:t,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function gj({size:i,className:e}){return h.jsx(ma,{size:i,className:e,children:h.jsx("polyline",{points:"9 18 15 12 9 6"})})}function vj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("polyline",{points:"23 4 23 10 17 10"}),h.jsx("polyline",{points:"1 20 1 14 7 14"}),h.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 _j({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),h.jsx("polyline",{points:"14 2 14 8 20 8"}),h.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),h.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function bj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.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"}),h.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),h.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function wj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),h.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function yj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.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"}),h.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function xj({size:i,className:e}){return h.jsxs(ma,{size:i,className:e,children:[h.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),h.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function Sj({content:i,children:e,align:t="bottom-right"}){const[n,r]=G.useState(!1),l=t==="bottom-right"?"top-full mt-1 right-0":"top-full mt-1 left-1/2 -translate-x-1/2";return h.jsxs("span",{className:"relative inline-flex",onMouseEnter:()=>r(!0),onMouseLeave:()=>r(!1),onFocus:()=>r(!0),onBlur:()=>r(!1),children:[e,n&&h.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 Of(i){const e="/home/";if(i.startsWith(e)){const t=i.slice(e.length).split("/").slice(1).join("/");return t?`~/${t}`:"~"}return i}const fb="sm.projects.splitPct",mb=33,yC=20,xC=60,SC="sm.projects.fileTreeCollapsed",Cj=32;function kj(){try{const i=parseFloat(localStorage.getItem(fb)??"");if(Number.isFinite(i))return Math.min(xC,Math.max(yC,i))}catch{}return mb}function Ej(){try{return localStorage.getItem(SC)==="1"}catch{return!1}}function Tj(){const i=xt(U=>U.tabs),e=xt(U=>U.activeTabId),t=i.find(U=>U.id===e)??null,n=Ei(U=>U.navFace),[r,l]=G.useState(null);G.useEffect(()=>{if(n!=="home"||r)return;let U=!1;return window.api.app.homeDir().then(oe=>{U||l(oe)}).catch(()=>{}),()=>{U=!0}},[n,r]);const p=n==="home"?r:(t==null?void 0:t.cwd)??null,[a,d]=G.useState(()=>kj()),[f,v]=G.useState(()=>Ej()),[m,y]=G.useState(!1),D=G.useRef(a);D.current=a;const k=G.useRef(null),T=G.useRef(null),{projects:b,openProject:C,archiveProjectByCwd:w}=hh(),x=h0(U=>U.pinned),$=h0(U=>U.togglePin),R=[...b].sort((U,oe)=>(x[oe.cwd]?1:0)-(x[U.cwd]?1:0));G.useEffect(()=>{if(!m)return;const U=oe=>{T.current&&!T.current.contains(oe.target)&&y(!1)};return document.addEventListener("mousedown",U),()=>document.removeEventListener("mousedown",U)},[m]);const N=G.useCallback(U=>{$i.getState().openFile(U)},[]),L=G.useCallback(U=>{U.preventDefault();const oe=U.clientX,de=D.current;let Z=de;const me=ue=>{const Ce=k.current;if(!Ce)return;const Ee=Ce.getBoundingClientRect(),W=ue.clientX-oe;Z=Math.min(xC,Math.max(yC,de+W/Ee.width*100)),d(Z)},ie=()=>{window.removeEventListener("pointermove",me),window.removeEventListener("pointerup",ie),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(fb,String(Z))}catch{}};window.addEventListener("pointermove",me),window.addEventListener("pointerup",ie),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),j=G.useCallback(()=>{d(mb);try{localStorage.setItem(fb,String(mb))}catch{}},[]),H=G.useCallback(()=>{v(U=>{const oe=!U;try{localStorage.setItem(SC,oe?"1":"0")}catch{}return oe})},[]);return f?h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("button",{onClick:H,"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:Cj},children:[h.jsx("span",{className:"text-[11px]",children:"▸"}),h.jsx("span",{className:"text-[10px] tracking-wide [writing-mode:vertical-rl]",children:"Files"})]}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(pb,{})})]}):h.jsxs("div",{ref:k,className:"flex h-full w-full","data-testid":"projects-workspace",children:[h.jsxs("div",{className:"shrink-0 flex flex-col border-r border-line overflow-hidden",style:{width:`${a}%`},"data-testid":"projects-file-tree-pane",children:[h.jsxs("div",{ref:T,className:"relative shrink-0 flex items-stretch border-b border-line",children:[h.jsxs("button",{"data-testid":"projects-launcher-trigger",onClick:()=>y(U=>!U),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:[h.jsx("span",{className:"flex-1 truncate text-left",children:p?Of(p):"Projects"}),h.jsx("span",{className:"text-fg-faint shrink-0 text-[10px]",children:m?"▲":"▼"})]}),h.jsx("button",{onClick:H,"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&&h.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:R.length===0?h.jsx("div",{className:"px-3 py-2 text-[11.5px] text-fg-faint",children:"No projects found."}):R.map(U=>{const oe=Of(U.cwd);return h.jsxs("div",{"data-testid":"projects-launcher-row",className:"flex items-center gap-1 px-2 py-1 hover:bg-bg-hi group",children:[h.jsx(Sj,{content:x[U.cwd]?"Unpin":"Pin to top",children:h.jsx("button",{onClick:()=>$(U.cwd),className:`shrink-0 text-sm leading-none transition-colors ${x[U.cwd]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:x[U.cwd]?"★":"☆"})}),h.jsx("button",{onClick:()=>{C(U.cwd),y(!1)},className:"flex-1 min-w-0 text-left text-[11.5px] font-mono truncate text-fg-dim hover:text-fg",children:oe}),h.jsx("button",{onClick:async()=>{window.confirm(`Archive ${oe}?`)&&await w(U)},className:"shrink-0 text-[10px] text-fg-faint hover:text-red-400 opacity-0 group-hover:opacity-100 transition-opacity",title:"Archive",children:"✕"})]},U.cwd)})})]}),p?h.jsxs(h.Fragment,{children:[h.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:Of(p)}),h.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:h.jsx(uj,{cwd:p,activeTabId:(t==null?void 0:t.id)??null,onPreviewFile:N})})]}):h.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:n==="home"?"Loading home folder…":"No session selected."})]}),h.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize panes",title:"Drag to resize · double-click to reset",onPointerDown:L,onDoubleClick:j,className:"w-1.5 shrink-0 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"}),h.jsx("div",{className:"flex-1 min-w-0","data-testid":"projects-editor-pane",children:h.jsx(pb,{})})]})}const Dj=G.memo(Tj),$j={"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 Marketing page",intro:"Turns the Marketing lens of this project's already-generated Project Pages 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 Marketing Project Page first — Project Home's "Generate Now" produces it.`,"Publish never bypasses a failing gate automatically — a human always decides whether to override."]}},bw="sm.learningPanel.collapsed";function f0(){try{const i=localStorage.getItem(bw);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 m0(i){try{localStorage.setItem(bw,i?"1":"0")}catch{}}function Aj({active:i}){const[e,t]=G.useState(()=>!f0()),n=G.useRef(null),r=G.useCallback(()=>{t(a=>{const d=!a;return m0(!d),d})},[]);G.useEffect(()=>{const a=d=>{d.key===bw&&t(!f0())};return window.addEventListener("storage",a),()=>window.removeEventListener("storage",a)},[]),G.useEffect(()=>{if(!e)return;const a=d=>{var f;(f=n.current)!=null&&f.contains(d.target)||(t(!1),m0(!0))};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[e]);const l=G.useRef(!1);G.useEffect(()=>{if(!l.current){l.current=!0;return}t(!1)},[i]);const p=$j[i];return p?h.jsxs("span",{ref:n,className:"relative inline-block",children:[h.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&&h.jsxs("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:[h.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:p.intro}),p.sections.map(a=>h.jsxs("div",{className:"mb-3 last:mb-0",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:a.title}),h.jsx("ul",{className:"space-y-1",children:a.items.map((d,f)=>h.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[d.term&&h.jsx("span",{className:"text-fg font-medium",children:d.term}),d.term&&" — ",h.jsx("span",{children:d.body})]},f))})]},a.title)),p.tips&&p.tips.length>0&&h.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[h.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),h.jsx("ul",{className:"space-y-1",children:p.tips.map((a,d)=>h.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",a]},d))})]})]})]}):null}function Ij({eyebrow:i,title:e,intro:t,frame:n=!0,learnKey:r,children:l}){const p=n&&(i||e||t);return h.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[p&&h.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[h.jsxs("div",{className:"max-w-[820px]",children:[i&&h.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:i}),e&&h.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),t&&h.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:t})]}),r&&h.jsx(Aj,{active:r})]}),h.jsx("div",{className:`flex-1 min-h-0 ${p?"px-8 pb-7":"p-8"}`,children:l})]})}const Pj=G.lazy(()=>os(()=>import("./Skills-CVlcQjVO.js"),__vite__mapDeps([3,4,5,6,7,8,9,10,11,12,13,1,2]),import.meta.url).then(i=>({default:i.Skills}))),Rj=G.lazy(()=>os(()=>import("./History-BySQczDf.js"),__vite__mapDeps([14,4,1,2]),import.meta.url).then(i=>({default:i.History}))),jj=G.lazy(()=>os(()=>import("./Scheduler-D4Gzz6iD.js"),__vite__mapDeps([15,12,9,1,2]),import.meta.url).then(i=>({default:i.Scheduler}))),Nj=G.lazy(()=>os(()=>import("./Settings-CXcfro2y.js"),__vite__mapDeps([16,4,8,7,17,9,1,2]),import.meta.url).then(i=>({default:i.Settings}))),Mj=G.lazy(()=>os(()=>import("./Permissions-u43I9j0-.js"),__vite__mapDeps([18,4,8,7,11,17,1,2]),import.meta.url).then(i=>({default:i.Permissions}))),Oj=G.lazy(()=>os(()=>import("./SystemPrompt-COLmPm10.js"),__vite__mapDeps([19,4,7,6,11,1,2]),import.meta.url).then(i=>({default:i.SystemPrompt}))),Lj=G.lazy(()=>os(()=>import("./Memory-C5Vv5Wim.js"),__vite__mapDeps([20,4,5,6,1,2]),import.meta.url).then(i=>({default:i.Memory}))),zj=G.lazy(()=>os(()=>import("./Plugins-DComjLBQ.js"),__vite__mapDeps([21,4,10,11,13,1,2,5,6]),import.meta.url).then(i=>({default:i.Plugins}))),Bj=G.lazy(()=>os(()=>import("./McpServers-CkowlPR7.js"),__vite__mapDeps([22,4,5,7,8,10,11,1,2]),import.meta.url).then(i=>({default:i.McpServers}))),Gj=G.lazy(()=>os(()=>import("./Hooks-CG8jWh3-.js"),__vite__mapDeps([23,4,5,7,8,10,11,17,1,2]),import.meta.url).then(i=>({default:i.Hooks}))),Fj=G.lazy(()=>os(()=>import("./AgentLibrary-D1SHQWCQ.js"),__vite__mapDeps([24,4,5,1,2]),import.meta.url).then(i=>({default:i.AgentLibrary}))),Hj=G.lazy(()=>os(()=>import("./TagLibrary-BN6bvsjU.js"),__vite__mapDeps([25,4,5,1,2]),import.meta.url).then(i=>({default:i.TagLibrary}))),Wj=G.lazy(()=>os(()=>import("./HostBilko-BxjPY1PW.js"),__vite__mapDeps([26,1,2]),import.meta.url).then(i=>({default:i.HostBilko}))),Uj=h.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading…"});function Ir({children:i}){return h.jsx(G.Suspense,{fallback:Uj,children:i})}const Vj={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."}},qj=()=>{},g0=new Map;function Kj(i,e){const t=g0.get(i);if(t&&t.ctx===e)return t.node;const n=Yj(i,e);return g0.set(i,{ctx:e,node:n}),n}function Yj(i,e){switch(i){case"overview":return h.jsx($$,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return h.jsx(wA,{});case"editor":return h.jsx(pb,{});case"projects":return h.jsx(Dj,{})}const t=Vj[i],n=(()=>{switch(i){case"skills":return h.jsx(Ir,{children:h.jsx(Pj,{})});case"history":return h.jsx(Ir,{children:h.jsx(Rj,{})});case"scheduler":return h.jsx(Ir,{children:h.jsx(jj,{navigate:e.onNavigate})});case"plugins":return h.jsx(Ir,{children:h.jsx(zj,{})});case"mcp":return h.jsx(Ir,{children:h.jsx(Bj,{})});case"hooks":return h.jsx(Ir,{children:h.jsx(Gj,{})});case"memory":return h.jsx(Ir,{children:h.jsx(Lj,{})});case"system-prompt":return h.jsx(Ir,{children:h.jsx(Oj,{})});case"permissions":return h.jsx(Ir,{children:h.jsx(Mj,{})});case"settings":return h.jsx(Ir,{children:h.jsx(Nj,{})});case"agent-library":return h.jsx(Ir,{children:h.jsx(Fj,{})});case"tag-library":return h.jsx(Ir,{children:h.jsx(Hj,{})});case"bilko-host":return h.jsx(Ir,{children:h.jsx(Wj,{})});case"voice":return h.jsx(ZR,{open:!0,onClose:qj,variant:"page"});default:return null}})();if(!n)return null;const r=_E[i];return t&&r?h.jsx(Ij,{eyebrow:r,title:t.title,intro:t.intro,learnKey:i,children:n}):n}var v_={exports:{}},v0;function Xj(){return v0||(v0=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,$,R){var N,L=arguments.length,j=L<3?x:R===null?R=Object.getOwnPropertyDescriptor(x,$):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(w,x,$,R);else for(var H=w.length-1;H>=0;H--)(N=w[H])&&(j=(L<3?N(j):L>3?N(x,$,j):N(x,$))||j);return L>3&&j&&Object.defineProperty(x,$,j),j},v=this&&this.__param||function(w,x){return function($,R){x($,R,w)}};Object.defineProperty(a,"__esModule",{value:!0}),a.AccessibilityManager=void 0;const m=d(9042),y=d(9924),D=d(844),k=d(4725),T=d(2585),b=d(3656);let C=a.AccessibilityManager=class extends D.Disposable{constructor(w,x,$,R){super(),this._terminal=w,this._coreBrowserService=$,this._renderService=R,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let N=0;N<this._terminal.rows;N++)this._rowElements[N]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[N]);if(this._topBoundaryFocusListener=N=>this._handleBoundaryFocus(N,0),this._bottomBoundaryFocusListener=N=>this._handleBoundaryFocus(N,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new y.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((N=>this._handleResize(N.rows)))),this.register(this._terminal.onRender((N=>this._refreshRows(N.start,N.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((N=>this._handleChar(N)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3022
3022
|
`)))),this.register(this._terminal.onA11yTab((N=>this._handleTab(N)))),this.register(this._terminal.onKey((N=>this._handleKey(N.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,b.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,D.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===`
|
|
3023
3023
|
`&&(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 $=this._terminal.buffer,R=$.lines.length.toString();for(let N=w;N<=x;N++){const L=$.lines.get($.ydisp+N),j=[],H=(L==null?void 0:L.translateToString(!0,void 0,void 0,j))||"",U=($.ydisp+N+1).toString(),oe=this._rowElements[N];oe&&(H.length===0?(oe.innerText=" ",this._rowColumns.set(oe,[0,1])):(oe.textContent=H,this._rowColumns.set(oe,j)),oe.setAttribute("aria-posinset",U),oe.setAttribute("aria-setsize",R))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(w,x){const $=w.target,R=this._rowElements[x===0?1:this._rowElements.length-2];if($.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||w.relatedTarget!==R)return;let N,L;if(x===0?(N=$,L=this._rowElements.pop(),this._rowContainer.removeChild(L)):(N=this._rowElements.shift(),L=$,this._rowContainer.removeChild(N)),N.removeEventListener("focus",this._topBoundaryFocusListener),L.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const j=this._createAccessibilityTreeNode();this._rowElements.unshift(j),this._rowContainer.insertAdjacentElement("afterbegin",j)}else{const j=this._createAccessibilityTreeNode();this._rowElements.push(j),this._rowContainer.appendChild(j)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),w.preventDefault(),w.stopImmediatePropagation()}_handleSelectionChange(){var H;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},$={node:w.focusNode,offset:w.focusOffset};if((x.node.compareDocumentPosition($.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===$.node&&x.offset>$.offset)&&([x,$]=[$,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 R=this._rowElements.slice(-1)[0];if($.node.compareDocumentPosition(R)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&($={node:R,offset:((H=R.textContent)==null?void 0:H.length)??0}),!this._rowContainer.contains($.node))return;const N=({node:U,offset:oe})=>{const de=U instanceof Text?U.parentNode:U;let Z=parseInt(de==null?void 0:de.getAttribute("aria-posinset"),10)-1;if(isNaN(Z))return console.warn("row is invalid. Race condition?"),null;const me=this._rowColumns.get(de);if(!me)return console.warn("columns is null. Race condition?"),null;let ie=oe<me.length?me[oe]:me.slice(-1)[0]+1;return ie>=this._terminal.cols&&(++Z,ie=0),{row:Z,column:ie}},L=N(x),j=N($);if(L&&j){if(L.row>j.row||L.row===j.row&&L.column>=j.column)throw new Error("invalid range");this._terminal.select(L.column,L.row,(j.row-L.row)*this._terminal.cols-L.column+j.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=C=f([v(1,T.IInstantiationService),v(2,k.ICoreBrowserService),v(3,k.IRenderService)],C)},3614:(p,a)=>{function d(y){return y.replace(/\r?\n/g,"\r")}function f(y,D){return D?"\x1B[200~"+y+"\x1B[201~":y}function v(y,D,k,T){y=f(y=d(y),k.decPrivateModes.bracketedPasteMode&&T.rawOptions.ignoreBracketedPasteMode!==!0),k.triggerDataEvent(y,!0),D.value=""}function m(y,D,k){const T=k.getBoundingClientRect(),b=y.clientX-T.left-10,C=y.clientY-T.top-10;D.style.width="20px",D.style.height="20px",D.style.left=`${b}px`,D.style.top=`${C}px`,D.style.zIndex="1000",D.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(y,D){y.clipboardData&&y.clipboardData.setData("text/plain",D.selectionText),y.preventDefault()},a.handlePasteEvent=function(y,D,k,T){y.stopPropagation(),y.clipboardData&&v(y.clipboardData.getData("text/plain"),D,k,T)},a.paste=v,a.moveTextAreaUnderMouseCursor=m,a.rightClickHandler=function(y,D,k,T,b){m(y,D,k),b&&T.rightClickSelect(y),D.value=T.selectionText,D.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(v,m,y){this._css.set(v,m,y)}getCss(v,m){return this._css.get(v,m)}setColor(v,m,y){this._color.set(v,m,y)}getColor(v,m){return this._color.get(v,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,v,m){d.addEventListener(f,v,m);let y=!1;return{dispose:()=>{y||(y=!0,d.removeEventListener(f,v,m))}}}},3551:function(p,a,d){var f=this&&this.__decorate||function(C,w,x,$){var R,N=arguments.length,L=N<3?w:$===null?$=Object.getOwnPropertyDescriptor(w,x):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")L=Reflect.decorate(C,w,x,$);else for(var j=C.length-1;j>=0;j--)(R=C[j])&&(L=(N<3?R(L):N>3?R(w,x,L):R(w,x))||L);return N>3&&L&&Object.defineProperty(w,x,L),L},v=this&&this.__param||function(C,w){return function(x,$){w(x,$,C)}};Object.defineProperty(a,"__esModule",{value:!0}),a.Linkifier=void 0;const m=d(3656),y=d(8460),D=d(844),k=d(2585),T=d(4725);let b=a.Linkifier=class extends D.Disposable{get currentLink(){return this._currentLink}constructor(C,w,x,$,R){super(),this._element=C,this._mouseService=w,this._renderService=x,this._bufferService=$,this._linkProviderService=R,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new y.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new y.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,D.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,D.toDisposable)((()=>{var N;this._lastMouseEvent=void 0,(N=this._activeProviderReplies)==null||N.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,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(C){this._lastMouseEvent=C;const w=this._positionFromMouseEvent(C,this._element,this._mouseService);if(!w)return;this._isMouseOut=!1;const x=C.composedPath();for(let $=0;$<x.length;$++){const R=x[$];if(R.classList.contains("xterm"))break;if(R.classList.contains("xterm-hover"))return}this._lastBufferCell&&w.x===this._lastBufferCell.x&&w.y===this._lastBufferCell.y||(this._handleHover(w),this._lastBufferCell=w)}_handleHover(C){if(this._activeLine!==C.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(C,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,C)||(this._clearCurrentLink(),this._askForLink(C,!0))}_askForLink(C,w){var $,R;this._activeProviderReplies&&w||(($=this._activeProviderReplies)==null||$.forEach((N=>{N==null||N.forEach((L=>{L.link.dispose&&L.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=C.y);let x=!1;for(const[N,L]of this._linkProviderService.linkProviders.entries())w?(R=this._activeProviderReplies)!=null&&R.get(N)&&(x=this._checkLinkProviderResult(N,C,x)):L.provideLinks(C.y,(j=>{var U,oe;if(this._isMouseOut)return;const H=j==null?void 0:j.map((de=>({link:de})));(U=this._activeProviderReplies)==null||U.set(N,H),x=this._checkLinkProviderResult(N,C,x),((oe=this._activeProviderReplies)==null?void 0:oe.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(C.y,this._activeProviderReplies)}))}_removeIntersectingLinks(C,w){const x=new Set;for(let $=0;$<w.size;$++){const R=w.get($);if(R)for(let N=0;N<R.length;N++){const L=R[N],j=L.link.range.start.y<C?0:L.link.range.start.x,H=L.link.range.end.y>C?this._bufferService.cols:L.link.range.end.x;for(let U=j;U<=H;U++){if(x.has(U)){R.splice(N--,1);break}x.add(U)}}}}_checkLinkProviderResult(C,w,x){var N;if(!this._activeProviderReplies)return x;const $=this._activeProviderReplies.get(C);let R=!1;for(let L=0;L<C;L++)this._activeProviderReplies.has(L)&&!this._activeProviderReplies.get(L)||(R=!0);if(!R&&$){const L=$.find((j=>this._linkAtPosition(j.link,w)));L&&(x=!0,this._handleNewLink(L))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let L=0;L<this._activeProviderReplies.size;L++){const j=(N=this._activeProviderReplies.get(L))==null?void 0:N.find((H=>this._linkAtPosition(H.link,w)));if(j){x=!0,this._handleNewLink(j);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(C){if(!this._currentLink)return;const w=this._positionFromMouseEvent(C,this._element,this._mouseService);w&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,w)&&this._currentLink.link.activate(C,this._currentLink.link.text)}_clearCurrentLink(C,w){this._currentLink&&this._lastMouseEvent&&(!C||!w||this._currentLink.link.range.start.y>=C&&this._currentLink.link.range.end.y<=w)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,D.disposeArray)(this._linkCacheDisposables))}_handleNewLink(C){if(!this._lastMouseEvent)return;const w=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);w&&this._linkAtPosition(C.link,w)&&(this._currentLink=C,this._currentLink.state={decorations:{underline:C.link.decorations===void 0||C.link.decorations.underline,pointerCursor:C.link.decorations===void 0||C.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,C.link,this._lastMouseEvent),C.link.decorations={},Object.defineProperties(C.link.decorations,{pointerCursor:{get:()=>{var x,$;return($=(x=this._currentLink)==null?void 0:x.state)==null?void 0:$.decorations.pointerCursor},set:x=>{var $;($=this._currentLink)!=null&&$.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,$;return($=(x=this._currentLink)==null?void 0:x.state)==null?void 0:$.decorations.underline},set:x=>{var $,R,N;($=this._currentLink)!=null&&$.state&&((N=(R=this._currentLink)==null?void 0:R.state)==null?void 0:N.decorations.underline)!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(C.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const $=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,R=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=$&&this._currentLink.link.range.end.y<=R&&(this._clearCurrentLink($,R),this._lastMouseEvent)){const N=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);N&&this._askForLink(N,!1)}}))))}_linkHover(C,w,x){var $;($=this._currentLink)!=null&&$.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!0),this._currentLink.state.decorations.pointerCursor&&C.classList.add("xterm-cursor-pointer")),w.hover&&w.hover(x,w.text)}_fireUnderlineEvent(C,w){const x=C.range,$=this._bufferService.buffer.ydisp,R=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-$-1,x.end.x,x.end.y-$-1,void 0);(w?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(R)}_linkLeave(C,w,x){var $;($=this._currentLink)!=null&&$.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(w,!1),this._currentLink.state.decorations.pointerCursor&&C.classList.remove("xterm-cursor-pointer")),w.leave&&w.leave(x,w.text)}_linkAtPosition(C,w){const x=C.range.start.y*this._bufferService.cols+C.range.start.x,$=C.range.end.y*this._bufferService.cols+C.range.end.x,R=w.y*this._bufferService.cols+w.x;return x<=R&&R<=$}_positionFromMouseEvent(C,w,x){const $=x.getCoords(C,w,this._bufferService.cols,this._bufferService.rows);if($)return{x:$[0],y:$[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(C,w,x,$,R){return{x1:C,y1:w,x2:x,y2:$,cols:this._bufferService.cols,fg:R}}};a.Linkifier=b=f([v(1,T.IMouseService),v(2,T.IRenderService),v(3,k.IBufferService),v(4,T.ILinkProviderService)],b)},9042:(p,a)=>{Object.defineProperty(a,"__esModule",{value:!0}),a.tooMuchOutput=a.promptLabel=void 0,a.promptLabel="Terminal input",a.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(p,a,d){var f=this&&this.__decorate||function(T,b,C,w){var x,$=arguments.length,R=$<3?b:w===null?w=Object.getOwnPropertyDescriptor(b,C):w;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")R=Reflect.decorate(T,b,C,w);else for(var N=T.length-1;N>=0;N--)(x=T[N])&&(R=($<3?x(R):$>3?x(b,C,R):x(b,C))||R);return $>3&&R&&Object.defineProperty(b,C,R),R},v=this&&this.__param||function(T,b){return function(C,w){b(C,w,T)}};Object.defineProperty(a,"__esModule",{value:!0}),a.OscLinkProvider=void 0;const m=d(511),y=d(2585);let D=a.OscLinkProvider=class{constructor(T,b,C){this._bufferService=T,this._optionsService=b,this._oscLinkService=C}provideLinks(T,b){var H;const C=this._bufferService.buffer.lines.get(T-1);if(!C)return void b(void 0);const w=[],x=this._optionsService.rawOptions.linkHandler,$=new m.CellData,R=C.getTrimmedLength();let N=-1,L=-1,j=!1;for(let U=0;U<R;U++)if(L!==-1||C.hasContent(U)){if(C.loadCell(U,$),$.hasExtendedAttrs()&&$.extended.urlId){if(L===-1){L=U,N=$.extended.urlId;continue}j=$.extended.urlId!==N}else L!==-1&&(j=!0);if(j||L!==-1&&U===R-1){const oe=(H=this._oscLinkService.getLinkData(N))==null?void 0:H.uri;if(oe){const de={start:{x:L+1,y:T},end:{x:U+(j||U!==R-1?0:1),y:T}};let Z=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const me=new URL(oe);["http:","https:"].includes(me.protocol)||(Z=!0)}catch{Z=!0}Z||w.push({text:oe,range:de,activate:(me,ie)=>x?x.activate(me,ie,de):k(0,ie),hover:(me,ie)=>{var ue;return(ue=x==null?void 0:x.hover)==null?void 0:ue.call(x,me,ie,de)},leave:(me,ie)=>{var ue;return(ue=x==null?void 0:x.leave)==null?void 0:ue.call(x,me,ie,de)}})}j=!1,$.hasExtendedAttrs()&&$.extended.urlId?(L=U,N=$.extended.urlId):(L=-1,N=-1)}}b(w)}};function k(T,b){if(confirm(`Do you want to navigate to ${b}?
|
|
3024
3024
|
|