claude-code-session-manager 0.55.0 → 0.55.1
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/{TiptapBody-6GmgSP5x.js → TiptapBody-g5zDcgLc.js} +1 -1
- package/dist/assets/{index-Bh-XKC4X.js → index-tW8C4h-7.js} +6 -6
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/main/index.cjs +24 -4
- package/src/preload/api.d.ts +2 -0
- package/src/preload/index.cjs +7 -0
|
@@ -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-g5zDcgLc.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var c$=Object.defineProperty;var d$=(n,e,i)=>e in n?c$(n,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):n[e]=i;var qn=(n,e,i)=>d$(n,typeof e!="symbol"?e+"":e,i);import{_ as nv}from"./monaco-editor-BW5C4Iv1.js";(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const d of a.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&r(d)}).observe(document,{childList:!0,subtree:!0});function i(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(s){if(s.ep)return;s.ep=!0;const a=i(s);fetch(s.href,a)}})();function xy(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var Zy={exports:{}},Im={},Qy={exports:{}},yn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -44,7 +44,7 @@ Error generating stack: `+X.message+`
|
|
|
44
44
|
|
|
45
45
|
${s}`,c={...a,goalText:l},p={...e().sessions,[i]:c};n({sessions:p}),await su(a.cwd,p,e().events)},duplicateEpic:(i,r)=>{const s=e().sessions[i];if(!s)throw new Error(`duplicateEpic: no PromptSession with id "${i}"`);const a=r??"unknown",d=e().createPromptSession(s.cwd,s.goalText,s.tag,a),l=e().approveProposed(d.id,a)??d;return vp("epic_duplicate",{cwd:s.cwd,epicId:l.id,source:a}),l},deleteEpic:async(i,r)=>{var p;const s=e().sessions[i];if(!s)throw new Error(`deleteEpic: no PromptSession with id "${i}"`);if((((p=to.getState().snapshot)==null?void 0:p.jobs)??[]).some(m=>(m.status==="running"||m.status==="pending")&&AT(m).includes(i)))throw new Error("deleteEpic: this Epic has a running or queued scheduler job — cancel it first");const d=An.getState().chats[i];if(d&&(d.running||d.queuedPosition>0))throw new Error("deleteEpic: this Epic has a chat run in flight — wait for it to finish first");if(Hl.getState().isAttached(i))throw new Error("deleteEpic: this Epic has a live Terminal session attached — detach it first");const l={...e().sessions},c={...e().events};delete l[i],delete c[i],n({sessions:l,events:c}),await su(s.cwd,l,c,[i]),vp("epic_delete",{cwd:s.cwd,epicId:i,source:r??"unknown"})},hydrate:async i=>{var r,s,a,d;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.readJson)))try{const l=W0(i),c=await window.api.config.readJson(l),p=c.exists&&c.data?c.data:{},m=p.sessions??{},f=p.events??{},b=e().sessions,_=Object.keys(m).filter(S=>!b[S]),y=U$(l)?[]:Object.keys(b).filter(S=>b[S].cwd===i&&(b[S].status==="active"||b[S].status==="proposed")&&!m[S]),k={...b},x={...e().events};let w=!1;for(const S of _)k[S]=m[S],x[S]=f[S]??[],w=!0;for(const S of y)delete k[S],delete x[S],w=!0;for(const S of Object.keys(f)){if(!b[S]||_.includes(S))continue;const E=f[S]??[],j=x[S]??[],N=new Set(j.map(P=>P.id)),A=E.filter(P=>!N.has(P.id));A.length>0&&(x[S]=[...j,...A].sort(AS),w=!0)}if(!w)return;n({sessions:k,events:x})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("promptSessions","warn",`hydrate failed for ${i}: ${c}`)}},hydrateArchived:async i=>{var r,s,a,d,l,c;if(!(typeof window>"u"||!((s=(r=window.api)==null?void 0:r.config)!=null&&s.listDir)||!((d=(a=window.api)==null?void 0:a.config)!=null&&d.readJson)))try{const p=`${i.replace(/\/+$/,"")}/session-manager-operations/prompt-sessions`,m=await window.api.config.listDir(p,{filesOnly:!0});if(!m.ok)return;const b={...e().sessions},_={...e().events};let y=!1;for(const k of m.entries){if(!k.name.endsWith(".json")||k.name==="active-index.json")continue;const x=k.name.slice(0,-5);if(b[x])continue;const w=await window.api.config.readJson(k.path);if(!w.exists||!w.data)continue;const S=w.data;!S.session||S.session.id!==x||(b[x]={...S.session,status:"completed"},_[x]=S.events??[],y=!0)}if(!y)return;n({sessions:b,events:_})}catch(p){const m=p instanceof Error?p.message:String(p);(c=(l=window.api)==null?void 0:l.logs)==null||c.write("promptSessions","warn",`hydrateArchived failed for ${i}: ${m}`)}},mergeAppendedEvent:(i,r,s)=>{const a=e().sessions[r];if(!a||a.cwd!==i)return;const d=e().events[r]??[];if(d.some(c=>c.id===s.id))return;const l={...e().events,[r]:[...d,s].sort(AS)};if(n({events:l}),s.kind==="response"&&r!==e().focusedEpicId){const{title:c}=G0(a.goalText),p=s.text?/^PRD (\S+) finished/.exec(s.text):null,m=p?`PRD ${p[1]} finished`:"Epic updated";Re.info(`${m} — ${c}`)}}}));var _T;typeof window<"u"&&((_T=window.api)!=null&&_T.promptSessions)&&window.api.promptSessions.onEventAppended(({cwd:n,promptSessionId:e,event:i})=>{rn.getState().mergeAppendedEvent(n,e,i)});const Qc={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},PS=20;function Ab(n,e){const i=[...n,e];return i.length>PS?i.slice(i.length-PS):i}let RS=0;function id(){return RS+=1,`t${Date.now().toString(36)}-${RS}`}const H$="Landed",IS=60;function W$(n){const e=n.trim();if(e.length<=IS)return e;const i=e.slice(0,IS),r=i.lastIndexOf(" ");return(r>0?i.slice(0,r):i).trim()}const An=ji((n,e)=>({chats:{},hydratedTabs:{},get:i=>e().chats[i]??Qc,hydrate:async({tabId:i,cwd:r,sessionId:s})=>{var a,d,l;if(!e().hydratedTabs[i]&&(n({hydratedTabs:{...e().hydratedTabs,[i]:!0}}),!(typeof window>"u"||!((a=window.api)!=null&&a.exchanges))))try{const c=await window.api.exchanges.list({cwd:r,sessionId:s});if(!c.length)return;const p=[];for(const f of[...c].reverse()){const b=new Date(f.ts).getTime();p.push({id:id(),role:"user",text:f.prompt,at:b}),p.push({id:id(),role:"assistant",text:f.result,at:b})}const m=e().chats[i]??Qc;n({chats:{...e().chats,[i]:{...m,turns:[...p,...m.turns],started:!0}}})}catch(c){const p=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`exchange hydration failed for tab ${i}: ${p}`)}},send:({tabId:i,sessionId:r,cwd:s,prompt:a,tag:d,chainRootId:l,external:c})=>{const p=a.trim();if(!p)return;if(Hl.getState().isAttached(i)){Re.error("Terminal mode is active for this Epic — switch back to Chat to send a message.");return}const m=e().chats[i]??Qc;if(m.running){const f={id:crypto.randomUUID(),tabId:i,sessionId:r,cwd:s,text:p,status:"queued",createdAt:Date.now(),tag:d,chainRootId:l,external:c};n({chats:{...e().chats,[i]:{...m,queue:[...m.queue,f]}}});return}V$(i),$T({tabId:i,sessionId:r,cwd:s,text:p,tag:d,chainRootId:l})},resetThread:i=>{n({chats:{...e().chats,[i]:{...Qc}}})},pushNotice:(i,r)=>{$b(i,"",r)},setPendingVoiceText:(i,r)=>{as(i,s=>({...s,pendingVoiceText:r}))},clearPendingVoiceText:i=>{as(i,r=>({...r,pendingVoiceText:void 0}))},dropTab:i=>{if(!(i in e().chats)&&!(i in e().hydratedTabs))return;const r={...e().chats};delete r[i];const s={...e().hydratedTabs};delete s[i],n({chats:r,hydratedTabs:s})}}));function as(n,e){const i=An.getState().chats[n]??Qc;An.setState({chats:{...An.getState().chats,[n]:e(i)}})}function lb(n,e,i={},r="done",s={}){as(n,a=>{const d=a.activeTicket?Ab(a.ticketHistory??[],{...a.activeTicket,status:r,completedAt:Date.now(),...s}):a.ticketHistory??[];return{...a,turns:[...a.turns,{...e,toolUses:a.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:d,...i}}),v_(n)}function V$(n){as(n,e=>{const i=e.ticketHistory??[];return i.some(r=>r.status==="needs-input")?{...e,ticketHistory:i.map(r=>r.status==="needs-input"?{...r,status:"done"}:r)}:e})}function $T(n){const{tabId:e,sessionId:i,cwd:r,text:s,promptId:a,tag:d,chainRootId:l}=n,c=An.getState().chats[e]??Qc,p={id:id(),role:"user",text:s,at:Date.now()};x_(e,"user",s);const m=c.activeTicket??{id:a??crypto.randomUUID(),tabId:e,sessionId:i,cwd:r,text:s,status:"running",createdAt:Date.now(),startedAt:Date.now(),tag:d,chainRootId:l};An.setState({chats:{...An.getState().chats,[e]:{...c,turns:[...c.turns,p],running:!0,queuedPosition:0,stream:"",activeTicket:m}}}),by(r,i).catch(f=>{var _,y;const b=f instanceof Error?f.message:String(f);return(y=(_=window.api)==null?void 0:_.logs)==null||y.write("chat","warn",`transcript-exists check failed for tab ${e}: ${b}`),c.started}).then(f=>window.api.chat.run({tabId:e,sessionId:i,prompt:s,cwd:r,resume:f,promptId:a})).catch(f=>{const b=f instanceof Error?f.message:String(f);PT(e,i,b)})}function v_(n){const e=An.getState().chats[n]??Qc;if(e.queue.length===0)return;const[i,...r]=e.queue;if(as(n,s=>({...s,queue:r,running:!0,queuedPosition:0,activeTicket:i})),i.external){fx(n,i);return}if(rn.getState().sessions[n]){fx(n,i);return}if(I$(i.tag)){fx(n,i);return}P$(i.text).then(s=>{if(s==="develop"){Y$(n,i);return}fx(n,i)})}function fx(n,e){const i={...e,status:"running",startedAt:Date.now()};as(n,r=>({...r,activeTicket:i})),$T({tabId:i.tabId,sessionId:i.sessionId,cwd:i.cwd,text:i.text,promptId:i.id,tag:i.tag,chainRootId:i.chainRootId})}function q$(n,e){var i,r,s,a,d;try{const l=(i=rn.getState().events[n])==null?void 0:i.slice(-1)[0];if(!l){(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendPrdCreatedEvent: PromptSession ${n} has no tail event — skipping prd_created append for ${e}`);return}rn.getState().appendPromptSessionEvent(n,{kind:"prd_created",causedByEventId:l.id,prdSlug:e})}catch(l){const c=l instanceof Error?l.message:String(l);(d=(a=window.api)==null?void 0:a.logs)==null||d.write("chat","warn",`appendPrdCreatedEvent failed for ${n}: ${c}`)}}const MS=2e3;function x_(n,e,i){var s,a,d,l;const r=rn.getState().sessions[n];if(r)try{(a=(s=window.api)==null?void 0:s.promptSessionTranscript)==null||a.append(r.cwd,n,{role:e,text:i})}catch(c){const p=c instanceof Error?c.message:String(c);(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`capturePromptSessionTurn failed for ${n}: ${p}`)}}function OS(n,e){var i,r,s;try{const a=(i=rn.getState().events[n])==null?void 0:i.slice(-1)[0];if(!a)return;const d=e.length>MS?`${e.slice(0,MS)}…`:e;rn.getState().appendPromptSessionEvent(n,{kind:"response",causedByEventId:a.id,text:d})}catch(a){const d=a instanceof Error?a.message:String(a);(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`appendResponseEvent failed for ${n}: ${d}`)}}async function K$(n,e){var r,s,a,d;const i=l=>{var c;return!!l&&((c=rn.getState().sessions[l])==null?void 0:c.status)==="active"};if(e.chainRootId){const c=((An.getState().chats[n]??Qc).ticketHistory??[]).find(m=>m.id===e.chainRootId),p=(c==null?void 0:c.promptSessionId)??null;if(p){const m=rn.getState().sessions[p];if(!m||m.status==="active")return p}}return i(n)||(await rn.getState().hydrate(e.cwd),i(n))?n:(e.chainRootId?(s=(r=window.api)==null?void 0:r.logs)==null||s.write("chat","warn",`continuation ticket ${e.id}: no resolvable PromptSession for chainRootId ${e.chainRootId} — refusing dispatch (sessions must never mint an Epic)`):(d=(a=window.api)==null?void 0:a.logs)==null||d.write("chat","warn",`ticket ${e.id}: no resolvable PromptSession for tab ${n} — refusing dispatch (sessions must never mint an Epic)`),null)}function Y$(n,e){const i=r=>{as(n,s=>({...s,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:Ab(s.ticketHistory??[],{...e,status:"failed",completedAt:Date.now()})})),$b(n,e.sessionId,r),Re.error(r),v_(n)};K$(n,e).then(r=>{if(!r){i(`→ 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:W$(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:r,sourceTabId:e.tabId,tag:e.tag}).then(s=>{if(!(s!=null&&s.ok)){i(`→ PRD authoring failed for ticket ${e.id}: ${(s==null?void 0:s.error)??"unknown error"}`);return}const a=s.filename,d=a.endsWith(".md")?a.slice(0,-3):a;q$(r,d);const l={...e,status:"dispatched-to-prd",completedAt:Date.now(),promptSessionId:r,...e.chainRootId?{}:{prdSlugs:[d]}};$b(n,l.sessionId,`→ dispatched to PRD ${a} (ticket ${l.id})`),as(n,c=>{let p=Ab(c.ticketHistory??[],l);if(e.chainRootId){const m=e.chainRootId;p=p.map(f=>f.id===m?{...f,prdSlugs:[...f.prdSlugs??[],d]}:f)}return{...c,running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:p}}),v_(n)}).catch(s=>{const a=s instanceof Error?s.message:String(s);i(`→ PRD authoring failed for ticket ${e.id}: ${a}`)})})}function PT(n,e,i){as(n,r=>r.activeTicket?{...r,activeTicket:null,ticketHistory:Ab(r.ticketHistory??[],{...r.activeTicket,status:"failed",completedAt:Date.now()})}:r),lb(n,{id:id(),role:"error",text:i,at:Date.now()}),Re.error(i)}function $b(n,e,i){as(n,r=>({...r,turns:[...r.turns,{id:id(),role:"notice",text:i,at:Date.now()}]}))}var ST;typeof window<"u"&&((ST=window.api)!=null&&ST.chat)&&(window.api.chat.onQueued(({tabId:n,position:e})=>{as(n,i=>({...i,running:!0,queuedPosition:e}))}),window.api.chat.onRunStarted(({tabId:n})=>{as(n,e=>({...e,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:n,delta:e})=>{as(n,i=>({...i,stream:i.stream+e}))}),window.api.chat.onToolUse(({tabId:n,id:e,kind:i,label:r,diff:s})=>{as(n,a=>({...a,liveToolUses:[...a.liveToolUses,{id:e,kind:i,label:r,diff:s}]}))}),window.api.chat.onComplete(({tabId:n,finalMessage:e})=>{x_(n,"assistant",e),OS(n,e),lb(n,{id:id(),role:"assistant",text:e,at:Date.now(),outcome:H$})}),window.api.chat.onNeedsInput(({tabId:n,questions:e,answerBody:i})=>{const r=id();if(i&&i.trim()){x_(n,"assistant",i),OS(n,i),as(n,s=>({...s,turns:[...s.turns,{id:id(),role:"assistant",text:i,at:Date.now(),toolUses:s.liveToolUses}],liveToolUses:[]})),lb(n,{id:r,role:"question",text:e.join(`
|
|
46
46
|
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r});return}lb(n,{id:r,role:"question",text:e.join(`
|
|
47
|
-
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{PT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{$b(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=vt.getState().tabs.find(c=>c.id===n);if(i){An.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=rn.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}An.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function X$(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function RT(n,e=!1,i=z0()){let r=!e;r&&(r=await by(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Ya(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Ya(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const vt=ji((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??X$(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{}),An.getState().dropTab(i);const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?ET(r.presetId).then(d=>{a(d?TT(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=An.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Re.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await RT({cwd:s.cwd,sessionId:s.sessionId},!1,r??z0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function b_(){var i;if(vt.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async p=>{try{const{sessionId:m}=await RT(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),c=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;vt.getState().restoreTabs(l,c)}else vt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),vt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=vt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;vt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const J$=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:b_,useSessions:vt},Symbol.toStringTag,{value:"Module"})),LS=200,Z$=/\x1b\[[0-9;]*m/g;function Q$(n){return n.replace(Z$,"")}const Eg=ji((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Re.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Re.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=Q$(i.line),a=r.lines.length>=LS?[...r.lines.slice(r.lines.length-LS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),eP="~/.claude/session-manager/browser/history.json",zS="~/.claude/session-manager/browser/bookmarks.json",tP=.25,nP=3,BS=.1,FS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let GS=0;function iP(){const n=FS[GS%FS.length];return GS+=1,n}const Pb=new Map;function rP(n){if(Pb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Pb.set(n,e)}function sP(n){const e=Pb.get(n);e&&(e(),Pb.delete(n))}const y_=new Map;let cb=null;function US(n){const e=y_.get(n);e&&(e(),y_.delete(n))}function HS(){cb&&(clearInterval(cb),cb=null)}const w_=new Map;function sw(n){const e=w_.get(n);e&&(e(),w_.delete(n))}const Pt=ji((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??iP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),rP(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,p;const l=d instanceof Error?d.message:String(d);(p=(c=window.api)==null?void 0:c.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(sP(r.viewId),sw(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),US(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});y_.set(i,r),HS(),cb=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),US(i),HS(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(zS),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(zS,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(eP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(nP,Math.max(tP,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+BS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-BS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),sw(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});w_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(sw(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),Rc=["home"],Om=["project"],Tl=["home","project"],V0=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Rc},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:Om},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:Om},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:Rc},{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:Tl},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Tl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Tl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:Tl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Tl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Rc},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Tl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Tl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:Rc},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Om},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Tl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:Tl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:Rc},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Rc},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:Rc},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Rc},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:Om},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:Om}];function oP(n){return V0.filter(e=>e.faces.includes(n)).map(e=>{var i,r;return{...e,label:((i=e.labelByFace)==null?void 0:i[n])??e.label,hint:((r=e.hintByFace)==null?void 0:r[n])??e.hint}})}const aP=Object.fromEntries(V0.map(n=>[n.key,n.group])),ow={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."},IT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","voice","repoviz","search","editor"],lP={editor:"Editor"},cP=Object.fromEntries(V0.map(n=>[n.key,n.label])),dP=Object.fromEntries(IT.map(n=>[n,lP[n]??cP[n]??n])),MT="~/.claude/session-manager/app-prefs.json";async function q0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(MT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function uP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await q0();await window.api.config.writeJson(MT,{...e,...n})}const xu=IT.map(n=>({id:n,title:dP[n],component:"screen"})),mn=ji((n,e)=>{var i;return{panels:[...xu],focusedPanelId:((i=xu[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),navFace:"home",setNavFace:r=>n({navFace:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,...r==="overview"?{navFace:"home"}:null}))},openProjectPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,navFace:"project"}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r,...r==="overview"?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=xu[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await q0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=xu[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function hP(n){return mn.getState().panels.find(e=>e.id===n)}function pP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function an({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.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"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.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 o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});default:return null}}const fP=4,WS=40,VS=6;function mP(n){const{onReorder:e,onActivate:i}=n,r=R.useRef(null),s=R.useRef(null),a=R.useRef(0),d=R.useRef(0),[l,c]=R.useState(!1),[,p]=R.useState(0),m=R.useRef(i);m.current=i;const f=R.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=R.useCallback((x,w,S)=>{for(let E=0;E<w.length;E++){const j=w[E].left+w[E].width/2;if(x<j)return E<=S?E:E-1}return w.length-1},[]),_=R.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-S.left,N=S.right-E;j<WS?w.scrollLeft-=VS:N<WS&&(w.scrollLeft+=VS),a.current=requestAnimationFrame(_)},[]);R.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,p(N=>N+1)}))},E=N=>{var U;const A=s.current;if(!A)return;const P=N.clientX-A.startX;if(!A.active&&Math.abs(P)<fP)return;if(!A.active){A.active=!0,A.tabRects=f().map(B=>B.getBoundingClientRect()),c(!0);try{(U=r.current)==null||U.setPointerCapture(A.pointerId)}catch{}a.current=requestAnimationFrame(_)}A.deltaX=P;const I=A.tabRects[A.fromIndex],O=I.left+I.width/2+P;A.currentIndex=b(O,A.tabRects,A.fromIndex),S()},j=N=>{const A=s.current;if(A&&A.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture(A.pointerId)}catch{}A.active&&A.fromIndex!==A.currentIndex?e(A.fromIndex,A.currentIndex):m.current(A.fromIndex),s.current=null,c(!1),p(P=>P+1)}};return x.addEventListener("pointermove",E),x.addEventListener("pointerup",j),x.addEventListener("pointercancel",j),()=>{x.removeEventListener("pointermove",E),x.removeEventListener("pointerup",j),x.removeEventListener("pointercancel",j),cancelAnimationFrame(a.current),cancelAnimationFrame(d.current)}},[e,f,b,_]);const y=R.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:R.useCallback(x=>{var E;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const j=w.fromIndex,N=w.currentIndex,P=(((E=w.tabRects[j])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",j<N&&x>j&&x<=N?S.transform=`translateX(-${P}px)`:j>N&&x>=N&&x<j?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:j=>y(j,x),style:S,"data-drag-index":x}},[y]),isDragging:l,containerRef:r}}const gP=3e4;function vP({onToggleSplitView:n,splitViewActive:e}={}){const i=vt(N=>N.tabs),r=vt(N=>N.activeTabId),s=vt(N=>N.closeTab),a=vt(N=>N.setActive),d=vt(N=>N.reorderTab),l=Eg(N=>N.watchers),c=Pt(N=>N.tabs.length>0),p=r!=null&&c,m=mn(N=>N.openPanel),f=mn(N=>N.openProjectPanel),b=mn(N=>N.setEpicsWorkspaceOpen),_=mn(N=>N.navFace==="home"),[y,k]=R.useState(()=>Date.now());R.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const x=N=>{for(const A of Object.values(l))if(A.tabId===N&&A.lastLineAt&&y-A.lastLineAt<gP)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:E}=mP({tabCount:i.length,onReorder:d,onActivate:N=>{const A=i[N];A&&(a(A.id),b(!1),f("terminal"))}}),j=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.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:[o.jsxs("button",{onClick:()=>m("overview"),title:"This machine — home","aria-current":_?"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 ${_?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,A)=>{const P=N.id===r,I=w(A),O=j[A%j.length];return o.jsxs("div",{...I,style:I.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 ${S?"":"cursor-grab"} ${P?"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:N.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:N.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:N.label}),N.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(N.id)&&o.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"}),o.jsx("button",{onClick:U=>{U.stopPropagation(),s(N.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${N.label}`,children:"×"})]},N.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&n&&o.jsxs("button",{onClick:n,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.55.0"]})]})]})}var aw={},Lm={},qS;function OT(){if(qS)return Lm;qS=1,Object.defineProperty(Lm,"__esModule",{value:!0}),Lm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Lm.baseAssetPath=i,Lm}var zm={},KS;function K0(){if(KS)return zm;KS=1,Object.defineProperty(zm,"__esModule",{value:!0}),zm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return zm.defaultModelFetcher=n,zm}var jl={},Bm={},YS;function iv(){if(YS)return Bm;YS=1,Object.defineProperty(Bm,"__esModule",{value:!0}),Bm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Bm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Bm}var Fm={},XS;function wy(){if(XS)return Fm;XS=1,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.Message=void 0;var n;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"})(n||(Fm.Message=n={})),Fm}var JS;function Y0(){if(JS)return jl;JS=1,Object.defineProperty(jl,"__esModule",{value:!0}),jl.FrameProcessor=jl.validateOptions=jl.defaultFrameProcessorOptions=void 0;const n=iv(),e=wy();jl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}jl.validateOptions=i;const r=d=>{const l=d.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),c=new Float32Array(l.at(-1));return d.forEach((p,m)=>{const f=l[m];c.set(p,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),p=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,c,p,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=y=>{this.options={...this.options,...y};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=y=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(y):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=y=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));y({msg:e.Message.SpeechEnd,audio:S})}else y({msg:e.Message.VADMisfire});return{}},this.process=async(y,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(y),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:y}),this.audioBuffer.push({frame:y,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((j,N)=>N.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(S.map(N=>N.frame));k({msg:e.Message.SpeechEnd,audio:j})}else k({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=_,this.reset()}}return jl.FrameProcessor=a,jl}var Nl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var lw={exports:{}};/*!
|
|
47
|
+
`),questions:e,at:Date.now()},{},"needs-input",{questionTurnId:r})}),window.api.chat.onError(({tabId:n,sessionId:e,message:i})=>{PT(n,e,i)}),window.api.chat.onNotice(({tabId:n,sessionId:e,message:i})=>{$b(n,e,i)}),window.api.chat.onExternalSend(({tabId:n,prompt:e})=>{var s,a,d,l;const i=vt.getState().tabs.find(c=>c.id===n);if(i){An.getState().send({tabId:n,sessionId:i.sessionId,cwd:i.cwd,prompt:e,external:!0});return}const r=rn.getState().sessions[n];if(r){if(r.status==="completed"){(a=(s=window.api)==null?void 0:s.logs)==null||a.write("chat","warn",`external send ignored: Epic ${n} is completed/archived — its claudeSessionId is dead`);return}An.getState().send({tabId:n,sessionId:r.claudeSessionId,cwd:r.cwd,prompt:e,external:!0});return}(l=(d=window.api)==null?void 0:d.logs)==null||l.write("chat","warn",`external send ignored: ${n} matches neither an open tab nor a known Epic`)}));function X$(n){const e=n.split("/").filter(Boolean);return e[e.length-1]||n}async function RT(n,e=!1,i=z0()){let r=!e;r&&(r=await by(n.cwd,n.sessionId));const s=e&&!r?crypto.randomUUID():n.sessionId,a=r?`claude --dangerously-skip-permissions --resume ${Ya(s)} --model ${i}`:`claude --dangerously-skip-permissions --session-id ${Ya(s)} --model ${i}`;return{sessionId:s,startupCommand:a}}const vt=ji((n,e)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(i,r)=>{n(s=>({pendingRawCommand:{...s.pendingRawCommand,[i]:r}}))},consumeRawCommand:i=>{const r=e().pendingRawCommand[i];return r===void 0?null:(n(s=>{const a={...s.pendingRawCommand};return delete a[i],{pendingRawCommand:a}}),r)},addTab:({id:i,cwd:r,startupCommand:s,presetId:a=null,label:d,dormant:l=!1})=>{const c=i??crypto.randomUUID();if(e().tabs.find(f=>f.id===c))return n({activeTabId:c}),c;l&&s&&console.warn("[sessions] addTab: dormant tab requested with a startupCommand — command is discarded:",s);const m={id:c,sessionId:c,label:d??X$(r),cwd:r,pid:null,status:l?"dormant":"spawning",exitCode:null,startupCommand:l?null:s,presetId:a,generation:0};return n({tabs:[...e().tabs,m],activeTabId:c}),c},setTabRunning:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:r,status:"running"}:s)}),setTabExited:(i,r)=>n({tabs:e().tabs.map(s=>s.id===i?{...s,status:"exited",exitCode:r}:s)}),closeTab:i=>{var a;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{}),window.api.transcripts.closeTab(i).catch(()=>{}),An.getState().dropTab(i);const r=e().tabs.filter(d=>d.id!==i),s=e().activeTabId===i?((a=r[r.length-1])==null?void 0:a.id)??null:e().activeTabId;n({tabs:r,activeTabId:s})},setActive:i=>n({activeTabId:i}),restartTab:i=>{const r=e().tabs.find(d=>d.id===i);if(!r)return;window.api.pty.kill(i);const s=crypto.randomUUID(),a=d=>{n({tabs:e().tabs.map(l=>l.id===i?{...l,sessionId:s,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:l.generation+1}:l)})};r.presetId?ET(r.presetId).then(d=>{a(d?TT(d,{sessionId:s,cwd:r.cwd}):`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)}):a(`claude --dangerously-skip-permissions --session-id ${Ya(s)}`)},reorderTab:(i,r)=>{const s=[...e().tabs];if(i<0||i>=s.length||r<0||r>=s.length||i===r)return;const[a]=s.splice(i,1);s.splice(r,0,a),n({tabs:s})},restoreTabs:(i,r)=>n({tabs:i,activeTabId:r,hydrated:!0}),wakeTab:async(i,r)=>{var l;const s=e().tabs.find(c=>c.id===i);if(!s||s.status!=="dormant")return;(l=An.getState().chats[i])!=null&&l.running&&(await window.api.chat.cancel(i),Re.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:a,startupCommand:d}=await RT({cwd:s.cwd,sessionId:s.sessionId},!1,r??z0());n({tabs:e().tabs.map(c=>c.id===i?{...c,sessionId:a,status:"spawning",startupCommand:d,generation:c.generation+1}:c)})},sleepTab:i=>{const r=e().tabs.find(s=>s.id===i);!r||r.status==="dormant"||(window.api.pty.kill(i),n({tabs:e().tabs.map(s=>s.id===i?{...s,pid:null,status:"dormant"}:s)}))},newSession:i=>{e().tabs.find(s=>s.id===i)&&n({tabs:e().tabs.map(s=>s.id===i?{...s,sessionId:crypto.randomUUID()}:s)})},addSessionToProject:(i,r)=>e().addTab({cwd:i,startupCommand:null,dormant:!0,...r})}));async function b_(){var i;if(vt.getState().hydrated)return;try{const{tabs:r,activeTabId:s,freshStart:a}=await window.api.sessions.load();if(r.length>0){const l=(await Promise.all(r.map(async p=>{try{const{sessionId:m}=await RT(p,a);return{id:p.id,sessionId:m,cwd:p.cwd,label:p.label,presetId:p.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(m){return console.warn("[sessions] dropping malformed persisted tab:",p==null?void 0:p.id,m),null}}))).filter(p=>p!==null),c=s&&l.find(p=>p.id===s)?s:((i=l[0])==null?void 0:i.id)??null;vt.getState().restoreTabs(l,c)}else vt.setState({hydrated:!0})}catch(r){console.warn("[sessions] hydrate failed:",r),vt.setState({hydrated:!0})}const n=()=>{const{tabs:r,activeTabId:s}=vt.getState(),a=r.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:a,activeTabId:s}).catch(d=>{console.warn("[sessions] save failed:",d)})};let e=null;vt.subscribe((r,s)=>{r.hydrated&&(r.tabs===s.tabs&&r.activeTabId===s.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(n,200)))}),n()}const J$=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:b_,useSessions:vt},Symbol.toStringTag,{value:"Module"})),LS=200,Z$=/\x1b\[[0-9;]*m/g;function Q$(n){return n.replace(Z$,"")}const Eg=ji((n,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(n({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:r,command:s,cwd:a})=>{try{const d=await window.api.watchers.add({tabId:i,label:r,command:s,cwd:a??null}),l={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return n({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(d){return console.error("[watchers] add failed:",d),Re.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(s){console.error("[watchers] remove failed:",s);const a=s instanceof Error?s.message:String(s);Re.error(`Could not remove watcher: ${a}`)}const r={...e().watchers};delete r[i],n({watchers:r})},watchersForTab:i=>Object.values(e().watchers).filter(r=>r.tabId===i),ingestLine:i=>{const r=e().watchers[i.watcherId];if(!r)return;const s=Q$(i.line),a=r.lines.length>=LS?[...r.lines.slice(r.lines.length-LS+1),{line:s,ts:i.ts}]:[...r.lines,{line:s,ts:i.ts}];n({watchers:{...e().watchers,[i.watcherId]:{...r,lines:a,lineCount:r.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const r={...e().watchers};delete r[i],n({watchers:r})}})),eP="~/.claude/session-manager/browser/history.json",zS="~/.claude/session-manager/browser/bookmarks.json",tP=.25,nP=3,BS=.1,FS=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let GS=0;function iP(){const n=FS[GS%FS.length];return GS+=1,n}const Pb=new Map;function rP(n){if(Pb.has(n))return;const e=window.api.browser.onNavState(n,i=>{Pt.setState(r=>({tabs:r.tabs.map(s=>s.viewId===n?{...s,url:i.url,title:i.title||s.title,canGoBack:i.canGoBack,canGoForward:i.canGoForward,loading:i.loading,isSecure:i.isSecure}:s)}))});Pb.set(n,e)}function sP(n){const e=Pb.get(n);e&&(e(),Pb.delete(n))}const y_=new Map;let cb=null;function US(n){const e=y_.get(n);e&&(e(),y_.delete(n))}function HS(){cb&&(clearInterval(cb),cb=null)}const w_=new Map;function sw(n){const e=w_.get(n);e&&(e(),w_.delete(n))}const Pt=ji((n,e)=>({tabs:[],activeTabId:null,openTab:i=>{const r=crypto.randomUUID(),s=r,a={id:r,viewId:s,title:"New Tab",url:(i==null?void 0:i.url)??"about:blank",color:(i==null?void 0:i.color)??iP(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return n(d=>({tabs:[...d.tabs,a],activeTabId:r})),rP(s),window.api.browser.create({viewId:s,partition:"persist:browser"}).then(()=>{i!=null&&i.url&&window.api.browser.navigate({viewId:s,url:i.url}).catch(()=>{})}).catch(d=>{var c,p;const l=d instanceof Error?d.message:String(d);(p=(c=window.api)==null?void 0:c.logs)==null||p.write("browser","error",`browser:create failed for viewId ${s}: ${l}`)}),r},closeTab:i=>{const r=e().tabs.find(s=>s.id===i);r&&(sP(r.viewId),sw(r.viewId),window.api.browser.destroy(r.viewId).catch(()=>{}),n(s=>{const a=s.tabs.filter(l=>l.id!==i),d=s.activeTabId===i?a.length?a[a.length-1].id:null:s.activeTabId;return{tabs:a,activeTabId:d}}))},setActive:i=>{n({activeTabId:i})},navigate:(i,r)=>{const s=e().tabs.find(a=>a.id===i);s&&window.api.browser.navigate({viewId:s.viewId,url:r}).catch(()=>{})},back:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.back(r.viewId).catch(()=>{})},forward:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.forward(r.viewId).catch(()=>{})},reload:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.reload(r.viewId).catch(()=>{})},stop:i=>{const r=e().tabs.find(s=>s.id===i);r&&window.api.browser.stop(r.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:i=>n(r=>({mode:i,captured:i==="capture"?r.captured:null})),setCaptureMode:i=>n({captureMode:i,captured:null}),onVerb:i=>{const{mode:r}=e();if(i==="shot"){n({mode:"capture",captureMode:"shot",captured:null});return}if(r===i){n({mode:"browse",captured:i==="capture"?null:e().captured});return}n({mode:i,captureMode:i==="capture"?"agent":e().captureMode,captured:i==="capture"?e().captured:null})},captured:null,capture:async i=>{const{activeTabId:r,tabs:s,captureMode:a}=e(),d=s.find(c=>c.id===r);if(!d)throw new Error("No active browser tab");if(a==="shot"){const c=await window.api.browser.captureShot(d.viewId);if(!c.ok)throw new Error(c.error);n({captured:{mode:a,url:c.url,title:c.title,dataUrl:c.dataUrl,at:Date.now()}});return}if(!i||!i.length)throw new Error("No element selected");const l=await window.api.browser.capture({viewId:d.viewId,selectors:i,mode:a});if(!l.ok)throw new Error(l.error);n({captured:{mode:a,url:d.url,title:d.title,text:l.text,meta:l.meta,selectors:i,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:i=>{if(e().recorderActive)return;n({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(i).catch(()=>{}),US(i);const r=window.api.browser.onRecordStep(i,s=>{Pt.getState().recording&&Pt.setState(a=>({recorderSteps:[...a.recorderSteps,s]}))});y_.set(i,r),HS(),cb=setInterval(()=>{Pt.getState().recording&&Pt.setState(s=>({recorderElapsedSec:s.recorderElapsedSec+1}))},1e3)},stopRecording:i=>{e().recorderActive&&(window.api.browser.recordStop(i).catch(()=>{}),US(i),HS(),n({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{e().recorderActive&&n(i=>({recording:!i.recording}))},toggleStepVariable:i=>{n(r=>({recorderSteps:r.recorderSteps.map(s=>s.n===i?{...s,variable:s.variable?null:s.variableSuggestion||"value"}:s)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!e().bookmarksHydrated)try{const i=await window.api.config.readJson(zS),r=i.exists&&Array.isArray(i.data)?i.data:[];n({bookmarks:r,bookmarksHydrated:!0})}catch{n({bookmarksHydrated:!0})}},toggleBookmark:i=>{const r=e().tabs.find(l=>l.id===i);if(!r||!r.url||r.url==="about:blank")return;const s=e().bookmarks,d=s.some(l=>l.url===r.url)?s.filter(l=>l.url!==r.url):[{url:r.url,title:r.title,ts:Date.now()},...s];n({bookmarks:d}),window.api.config.writeJson(zS,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const i=await window.api.config.readJson(eP),r=i.exists&&Array.isArray(i.data)?i.data:[];n({historyEntries:r})}catch{}},setZoom:(i,r)=>{const s=e().tabs.find(d=>d.id===i);if(!s)return;const a=Math.min(nP,Math.max(tP,r));n(d=>({tabs:d.tabs.map(l=>l.id===i?{...l,zoomFactor:a}:l)})),window.api.browser.setZoom({viewId:s.viewId,factor:a}).catch(()=>{})},zoomIn:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor+BS)},zoomOut:i=>{const r=e().tabs.find(s=>s.id===i);r&&e().setZoom(i,r.zoomFactor-BS)},zoomReset:i=>e().setZoom(i,1),findOpen:!1,findText:"",findMatches:null,openFind:i=>{const r=e().tabs.find(a=>a.id===i);if(!r)return;n({findOpen:!0,findText:"",findMatches:null}),sw(r.viewId);const s=window.api.browser.onFindResult(r.viewId,a=>{Pt.setState({findMatches:a})});w_.set(r.viewId,s)},closeFind:i=>{const r=e().tabs.find(s=>s.id===i);n({findOpen:!1,findText:"",findMatches:null}),r&&(sw(r.viewId),window.api.browser.stopFind(r.viewId).catch(()=>{}))},setFindText:(i,r)=>{const s=e().tabs.find(a=>a.id===i);if(n({findText:r}),!!s){if(!r){window.api.browser.find({viewId:s.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:s.viewId,text:r,forward:!0}).catch(()=>{})}},findNext:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!0}).catch(()=>{})},findPrev:i=>{const r=e().tabs.find(a=>a.id===i),{findText:s}=e();!r||!s||window.api.browser.find({viewId:r.viewId,text:s,forward:!1}).catch(()=>{})}})),Rc=["home"],Om=["project"],Tl=["home","project"],V0=[{key:"overview",group:"Workspace",label:"Dashboard",icon:"home",hint:"This machine — every project, every active session",faces:Rc},{key:"project-home",group:"Workspace",label:"Project Home",icon:"home",hint:"What this project is, and what is in flight",faces:Om},{key:"terminal",group:"Workspace",label:"Epics",icon:"terminal",hint:"Independent goal-scoped Epics for this project",faces:Om},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences",faces:Rc},{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:Tl},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Global policy + this project's live PRD queue",faces:Tl},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable",faces:Tl},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior",faces:Tl},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads",faces:Tl},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code",faces:Rc},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations",faces:Tl},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events",faces:Tl},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override",faces:Rc},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store",faces:Om},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules",faces:Tl},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window",faces:Tl},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default",faces:Rc},{key:"agent-library",group:"Configure",label:"Agent Library",icon:"book",hint:"Agent personas available to this machine, and which projects override them",faces:Rc},{key:"tag-library",group:"Configure",label:"Tag Library",icon:"target",hint:"Epic intent tags and their /develop behavior",faces:Rc},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk",faces:Rc},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map",faces:Om},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content",faces:Om}];function oP(n){return V0.filter(e=>e.faces.includes(n)).map(e=>{var i,r;return{...e,label:((i=e.labelByFace)==null?void 0:i[n])??e.label,hint:((r=e.hintByFace)==null?void 0:r[n])??e.hint}})}const aP=Object.fromEntries(V0.map(n=>[n.key,n.group])),ow={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."},IT=["overview","project-home","terminal","browser","scheduler","history","skills","plugins","mcp","hooks","keybindings","memory","projects","system-prompt","permissions","settings","remote","agent-library","tag-library","voice","repoviz","search","editor"],lP={editor:"Editor"},cP=Object.fromEntries(V0.map(n=>[n.key,n.label])),dP=Object.fromEntries(IT.map(n=>[n,lP[n]??cP[n]??n])),MT="~/.claude/session-manager/app-prefs.json";async function q0(){var n,e;if(typeof window>"u"||!((e=(n=window.api)==null?void 0:n.config)!=null&&e.readJson))return{};try{const i=await window.api.config.readJson(MT);if(i!=null&&i.exists&&i.data&&typeof i.data=="object")return i.data}catch{}return{}}async function uP(n){var i,r;if(typeof window>"u"||!((r=(i=window.api)==null?void 0:i.config)!=null&&r.writeJson))return;const e=await q0();await window.api.config.writeJson(MT,{...e,...n})}const xu=IT.map(n=>({id:n,title:dP[n],component:"screen"})),mn=ji((n,e)=>{var i;return{panels:[...xu],focusedPanelId:((i=xu[0])==null?void 0:i.id)??null,focusToken:0,resetToken:0,epicsWorkspaceOpen:!1,setEpicsWorkspaceOpen:r=>n({epicsWorkspaceOpen:r}),navFace:"home",setNavFace:r=>n({navFace:r}),openPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,...r==="overview"?{navFace:"home"}:null}))},openProjectPanel:r=>{e().panels.some(a=>a.id===r)&&n(a=>({focusedPanelId:r,focusToken:a.focusToken+1,navFace:"project"}))},focusPanel:r=>{e().panels.some(a=>a.id===r)&&n({focusedPanelId:r,...r==="overview"?{navFace:"home"}:null})},resetLayout:()=>{n(r=>{var s;return{resetToken:r.resetToken+1,focusedPanelId:((s=xu[0])==null?void 0:s.id)??null,focusToken:r.focusToken+1,navFace:"home"}})},hydrateOpenToHomePref:async()=>{var s;(await q0()).openToHomeOnLaunch===!0&&e().focusedPanelId===(((s=xu[0])==null?void 0:s.id)??null)&&n({focusedPanelId:"overview",navFace:"home"})}}});function hP(n){return mn.getState().panels.find(e=>e.id===n)}function pP(n,e,i="project"){return n==="projects"&&e===null&&i==="project"}function an({name:n,size:e=17,stroke:i=1.6,className:r}){const s={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:r};switch(n){case"home":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 11l8-7 8 7"}),o.jsx("path",{d:"M6 10v9h12v-9"}),o.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M7 10l3 2-3 2"}),o.jsx("path",{d:"M13 14h4"})]});case"skills":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"}),o.jsx("path",{d:"M4 6l2 2"})]});case"usage":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"plugins":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),o.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),o.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),o.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),o.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"8",cy:"12",r:"4"}),o.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"projects":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return o.jsxs("svg",{...s,children:[o.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"}),o.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"11",cy:"11",r:"6"}),o.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M7 3h7l4 4v14H7z"}),o.jsx("path",{d:"M14 3v4h4"})]});case"play":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),o.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),o.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),o.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"3"}),o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),o.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"repoviz":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"6",cy:"12",r:"3"}),o.jsx("circle",{cx:"18",cy:"6",r:"3"}),o.jsx("circle",{cx:"18",cy:"18",r:"3"}),o.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),o.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),o.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return o.jsx("svg",{...s,children:o.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 o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),o.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),o.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),o.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M9 12h6"}),o.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),o.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),o.jsx("path",{d:"M4 12h16"})]});case"target":return o.jsxs("svg",{...s,children:[o.jsx("circle",{cx:"12",cy:"12",r:"8"}),o.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),o.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return o.jsx("svg",{...s,children:o.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),o.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),o.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return o.jsxs("svg",{...s,children:[o.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),o.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return o.jsxs("svg",{...s,children:[o.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),o.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return o.jsx("svg",{...s,children:o.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return o.jsx("svg",{...s,children:o.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 o.jsx("svg",{...s,children:o.jsx("path",{d:"M5 12h14"})});case"paperclip":return o.jsx("svg",{...s,children:o.jsx("path",{d:"M8 12.5l6.5-6.5a3 3 0 014.2 4.2L11 18a5 5 0 01-7-7l7.5-7.5"})});default:return null}}const fP=4,WS=40,VS=6;function mP(n){const{onReorder:e,onActivate:i}=n,r=R.useRef(null),s=R.useRef(null),a=R.useRef(0),d=R.useRef(0),[l,c]=R.useState(!1),[,p]=R.useState(0),m=R.useRef(i);m.current=i;const f=R.useCallback(()=>r.current?Array.from(r.current.querySelectorAll("[data-drag-index]")):[],[]),b=R.useCallback((x,w,S)=>{for(let E=0;E<w.length;E++){const j=w[E].left+w[E].width/2;if(x<j)return E<=S?E:E-1}return w.length-1},[]),_=R.useCallback(()=>{const x=s.current,w=r.current;if(!(x!=null&&x.active)||!w)return;const S=w.getBoundingClientRect(),E=x.startX+x.deltaX,j=E-S.left,N=S.right-E;j<WS?w.scrollLeft-=VS:N<WS&&(w.scrollLeft+=VS),a.current=requestAnimationFrame(_)},[]);R.useEffect(()=>{const x=r.current;if(!x)return;let w=!1;const S=()=>{w||(w=!0,d.current=requestAnimationFrame(()=>{w=!1,p(N=>N+1)}))},E=N=>{var U;const A=s.current;if(!A)return;const P=N.clientX-A.startX;if(!A.active&&Math.abs(P)<fP)return;if(!A.active){A.active=!0,A.tabRects=f().map(B=>B.getBoundingClientRect()),c(!0);try{(U=r.current)==null||U.setPointerCapture(A.pointerId)}catch{}a.current=requestAnimationFrame(_)}A.deltaX=P;const I=A.tabRects[A.fromIndex],O=I.left+I.width/2+P;A.currentIndex=b(O,A.tabRects,A.fromIndex),S()},j=N=>{const A=s.current;if(A&&A.pointerId===N.pointerId){cancelAnimationFrame(a.current),cancelAnimationFrame(d.current);try{x.releasePointerCapture(A.pointerId)}catch{}A.active&&A.fromIndex!==A.currentIndex?e(A.fromIndex,A.currentIndex):m.current(A.fromIndex),s.current=null,c(!1),p(P=>P+1)}};return x.addEventListener("pointermove",E),x.addEventListener("pointerup",j),x.addEventListener("pointercancel",j),()=>{x.removeEventListener("pointermove",E),x.removeEventListener("pointerup",j),x.removeEventListener("pointercancel",j),cancelAnimationFrame(a.current),cancelAnimationFrame(d.current)}},[e,f,b,_]);const y=R.useCallback((x,w)=>{x.button!==0||x.target.closest("button")||(s.current={active:!1,fromIndex:w,currentIndex:w,startX:x.clientX,deltaX:0,tabRects:[],pointerId:x.pointerId})},[]);return{getTabDragProps:R.useCallback(x=>{var E;const w=s.current,S={};if(w!=null&&w.active)if(x===w.fromIndex)S.transform=`translateX(${w.deltaX}px) scale(1.03)`,S.zIndex=10,S.opacity=.85,S.boxShadow="0 2px 8px rgba(0,0,0,0.4)",S.position="relative",S.pointerEvents="none";else{const j=w.fromIndex,N=w.currentIndex,P=(((E=w.tabRects[j])==null?void 0:E.width)??0)+4;S.transition="transform 0.15s ease",j<N&&x>j&&x<=N?S.transform=`translateX(-${P}px)`:j>N&&x>=N&&x<j?S.transform=`translateX(${P}px)`:S.transform="translateX(0)"}return{onPointerDown:j=>y(j,x),style:S,"data-drag-index":x}},[y]),isDragging:l,containerRef:r}}const gP=3e4;function vP({onToggleSplitView:n,splitViewActive:e}={}){const i=vt(N=>N.tabs),r=vt(N=>N.activeTabId),s=vt(N=>N.closeTab),a=vt(N=>N.setActive),d=vt(N=>N.reorderTab),l=Eg(N=>N.watchers),c=Pt(N=>N.tabs.length>0),p=r!=null&&c,m=mn(N=>N.openPanel),f=mn(N=>N.openProjectPanel),b=mn(N=>N.setEpicsWorkspaceOpen),_=mn(N=>N.navFace==="home"),[y,k]=R.useState(()=>Date.now());R.useEffect(()=>{const N=window.setInterval(()=>k(Date.now()),1e3);return()=>window.clearInterval(N)},[]);const x=N=>{for(const A of Object.values(l))if(A.tabId===N&&A.lastLineAt&&y-A.lastLineAt<gP)return!0;return!1},{getTabDragProps:w,isDragging:S,containerRef:E}=mP({tabCount:i.length,onReorder:d,onActivate:N=>{const A=i[N];A&&(a(A.id),b(!1),f("terminal"))}}),j=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return o.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:[o.jsxs("button",{onClick:()=>m("overview"),title:"This machine — home","aria-current":_?"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 ${_?"bg-accent text-bg font-semibold shadow-sm":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,children:[o.jsx(an,{name:"home",className:"w-[15px] h-[15px]"}),o.jsx("span",{children:"Home"})]}),o.jsx("span",{className:"w-px self-stretch my-1.5 bg-line"}),o.jsx("div",{ref:E,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${S?"cursor-grabbing":""}`,children:i.map((N,A)=>{const P=N.id===r,I=w(A),O=j[A%j.length];return o.jsxs("div",{...I,style:I.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 ${S?"":"cursor-grab"} ${P?"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:N.cwd,"aria-current":P?"true":void 0,children:[o.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:O,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:N.status==="spawning"?.55:1}}),o.jsx("span",{className:"truncate max-w-[200px]",children:N.label}),N.status==="spawning"&&o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),x(N.id)&&o.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"}),o.jsx("button",{onClick:U=>{U.stopPropagation(),s(N.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${N.label}`,children:"×"})]},N.id)})}),o.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[p&&n&&o.jsxs("button",{onClick:n,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${e?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":e??!1,children:[o.jsx("span",{"aria-hidden":"true",children:"⇄"}),o.jsx("span",{children:"Split view"})]}),o.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.55.1"]})]})]})}var aw={},Lm={},qS;function OT(){if(qS)return Lm;qS=1,Object.defineProperty(Lm,"__esModule",{value:!0}),Lm.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Lm.baseAssetPath=i,Lm}var zm={},KS;function K0(){if(KS)return zm;KS=1,Object.defineProperty(zm,"__esModule",{value:!0}),zm.defaultModelFetcher=void 0;const n=e=>fetch(e).then(i=>i.arrayBuffer());return zm.defaultModelFetcher=n,zm}var jl={},Bm={},YS;function iv(){if(YS)return Bm;YS=1,Object.defineProperty(Bm,"__esModule",{value:!0}),Bm.log=void 0;const n=e=>i=>{console.log(`VAD | ${e} >`,i)};return Bm.log={error:n("error"),debug:n("debug"),warn:n("warn")},Bm}var Fm={},XS;function wy(){if(XS)return Fm;XS=1,Object.defineProperty(Fm,"__esModule",{value:!0}),Fm.Message=void 0;var n;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"})(n||(Fm.Message=n={})),Fm}var JS;function Y0(){if(JS)return jl;JS=1,Object.defineProperty(jl,"__esModule",{value:!0}),jl.FrameProcessor=jl.validateOptions=jl.defaultFrameProcessorOptions=void 0;const n=iv(),e=wy();jl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&n.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&n.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&n.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&n.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&n.log.error("minSpeechMs should be positive")}jl.validateOptions=i;const r=d=>{const l=d.reduce((p,m)=>(p.push(p.at(-1)+m.length),p),[0]),c=new Float32Array(l.at(-1));return d.forEach((p,m)=>{const f=l[m];c.set(p,f)}),c};function s(d,l){const c=Math.floor(d.redemptionMs/l),p=Math.floor(d.preSpeechPadMs/l),m=Math.floor(d.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:p,minSpeechFrames:m}}class a{constructor(l,c,p,m){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=p,this.msPerFrame=m,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=y=>{this.options={...this.options,...y};const{redemptionFrames:k,preSpeechPadFrames:x,minSpeechFrames:w}=s(this.options,this.msPerFrame);this.redemptionFrames=k,this.preSpeechPadFrames=x,this.minSpeechFrames=w},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=y=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(y):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=y=>{const k=this.audioBuffer;this.audioBuffer=[];const x=this.speaking;if(this.reset(),x)if(k.reduce((S,E)=>E.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=r(k.map(E=>E.frame));y({msg:e.Message.SpeechEnd,audio:S})}else y({msg:e.Message.VADMisfire});return{}},this.process=async(y,k)=>{if(!this.active)return;const x=await this.modelProcessFunc(y),w=x.isSpeech>=this.options.positiveSpeechThreshold;if(k({probs:x,msg:e.Message.FrameProcessed,frame:y}),this.audioBuffer.push({frame:y,isSpeech:w}),w&&(this.speechFrameCount++,this.redemptionCounter=0),w&&!this.speaking&&(this.speaking=!0,k({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,k({msg:e.Message.SpeechRealStart})),x.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const S=this.audioBuffer;if(this.audioBuffer=[],S.reduce((j,N)=>N.isSpeech?j+1:j,0)>=this.minSpeechFrames){const j=r(S.map(N=>N.frame));k({msg:e.Message.SpeechEnd,audio:j})}else k({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:f,preSpeechPadFrames:b,minSpeechFrames:_}=s(this.options,this.msPerFrame);this.redemptionFrames=f,this.preSpeechPadFrames=b,this.minSpeechFrames=_,this.reset()}}return jl.FrameProcessor=a,jl}var Nl={};function Eo(n){throw new Error('Could not dynamically require "'+n+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var lw={exports:{}};/*!
|
|
48
48
|
* ONNX Runtime Web v1.26.0
|
|
49
49
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
50
50
|
* Licensed under the MIT License.
|
|
@@ -2898,7 +2898,7 @@ ${L}`,F=C.createShaderModule({code:z,label:u.name});dn("verbose",()=>`[WebGPU] $
|
|
|
2898
2898
|
* ONNX Runtime Web v1.26.0
|
|
2899
2899
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2900
2900
|
* Licensed under the MIT License.
|
|
2901
|
-
*/var ok;function kP(){return ok||(ok=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(se=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(se,{get:(fe,_e)=>(typeof Eo<"u"?Eo:fe)[_e]}):se)(function(se){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+se+'" is not supported')}),c=(se,fe)=>()=>(se&&(fe=se(se=0)),fe),p=(se,fe)=>{for(var _e in fe)r(se,_e,{get:fe[_e],enumerable:!0})},m=(se,fe,_e,De)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ee of a(fe))!d.call(se,Ee)&&Ee!==_e&&r(se,Ee,{get:()=>fe[Ee],enumerable:!(De=s(fe,Ee))||De.enumerable});return se},f=se=>m(r({},"__esModule",{value:!0}),se),b,_,y,k,x,w=c(()=>{b=new Map,_=[],y=(se,fe,_e)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let De=b.get(se);if(De===void 0)b.set(se,{backend:fe,priority:_e});else{if(De.priority>_e)return;if(De.priority===_e&&De.backend!==fe)throw new Error(`cannot register backend "${se}" using priority ${_e}`)}if(_e>=0){let Ee=_.indexOf(se);Ee!==-1&&_.splice(Ee,1);for(let Be=0;Be<_.length;Be++)if(b.get(_[Be]).priority<=_e){_.splice(Be,0,se);return}_.push(se)}return}throw new TypeError("not a valid backend")},k=async se=>{let fe=b.get(se);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let _e=!!fe.initPromise;try{return _e||(fe.initPromise=fe.backend.init(se)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(De){return _e||(fe.error=`${De}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},x=async se=>{let fe=se.executionProviders||[],_e=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=_e.length===0?_:_e,Ee,Be=[],$e=new Set;for(let Fe of De){let tt=await k(Fe);typeof tt=="string"?Be.push({name:Fe,err:tt}):(Ee||(Ee=tt),Ee===tt&&$e.add(Fe))}if(!Ee)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:tt}of Be)_e.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${tt}`);let Pe=fe.filter(Fe=>$e.has(typeof Fe=="string"?Fe:Fe.name));return[Ee,new Proxy(se,{get:(Fe,tt)=>tt==="executionProviders"?Pe:Reflect.get(Fe,tt)})]}}),S=c(()=>{w()}),E,j=c(()=>{E="1.26.0"}),N,A,P=c(()=>{j(),N="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(se){if(se!==void 0){if(typeof se!="string"||["verbose","info","warning","error","fatal"].indexOf(se)===-1)throw new Error(`Unsupported logging level: ${se}`);N=se}},get logLevel(){return N}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),I,O=c(()=>{P(),I=A}),U,B,J=c(()=>{U=(se,fe)=>{let _e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_e.width=se.dims[3],_e.height=se.dims[2];let De=_e.getContext("2d");if(De!=null){let Ee,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=se.dims[2],Be=se.dims[3]):(Ee=se.dims[3],Be=se.dims[2]);let $e=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Pe=fe==null?void 0:fe.norm,Fe,tt;Pe===void 0||Pe.mean===void 0?Fe=[255,255,255,255]:typeof Pe.mean=="number"?Fe=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(Fe=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(Fe[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?tt=[0,0,0,0]:typeof Pe.bias=="number"?tt=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(tt=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(tt[3]=Pe.bias[3]));let st=Be*Ee,nt=0,Xe=st,$t=st*2,ze=-1;$e==="RGBA"?(nt=0,Xe=st,$t=st*2,ze=st*3):$e==="RGB"?(nt=0,Xe=st,$t=st*2):$e==="RBG"&&(nt=0,$t=st,Xe=st*2);for(let dt=0;dt<Be;dt++)for(let Rn=0;Rn<Ee;Rn++){let en=(se.data[nt++]-tt[0])*Fe[0],tn=(se.data[Xe++]-tt[1])*Fe[1],In=(se.data[$t++]-tt[2])*Fe[2],Bt=ze===-1?255:(se.data[ze++]-tt[3])*Fe[3];De.fillStyle="rgba("+en+","+tn+","+In+","+Bt+")",De.fillRect(Rn,dt,1,1)}if("toDataURL"in _e)return _e.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},B=(se,fe)=>{let _e=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(_e!=null){let Ee,Be,$e;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=se.dims[2],Be=se.dims[1],$e=se.dims[3]):(Ee=se.dims[3],Be=se.dims[2],$e=se.dims[1]);let Pe=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,tt,st;Fe===void 0||Fe.mean===void 0?tt=[255,255,255,255]:typeof Fe.mean=="number"?tt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(tt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(tt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?st=[0,0,0,0]:typeof Fe.bias=="number"?st=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(st=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(st[3]=Fe.bias[3]));let nt=Be*Ee;if(fe!==void 0&&(fe.format!==void 0&&$e===4&&fe.format!=="RGBA"||$e===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,$t=0,ze=1,dt=2,Rn=3,en=0,tn=nt,In=nt*2,Bt=-1;Pe==="RGBA"?(en=0,tn=nt,In=nt*2,Bt=nt*3):Pe==="RGB"?(en=0,tn=nt,In=nt*2):Pe==="RBG"&&(en=0,In=nt,tn=nt*2),De=_e.createImageData(Ee,Be);for(let Bn=0;Bn<Be*Ee;$t+=Xe,ze+=Xe,dt+=Xe,Rn+=Xe,Bn++)De.data[$t]=(se.data[en++]-st[0])*tt[0],De.data[ze]=(se.data[tn++]-st[1])*tt[1],De.data[dt]=(se.data[In++]-st[2])*tt[2],De.data[Rn]=Bt===-1?255:(se.data[Bt++]-st[3])*tt[3]}else throw new Error("Can not access image data");return De}}),Z,W,q,Q,oe,le,H=c(()=>{we(),Z=(se,fe)=>{if(se===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:_e,width:De}=fe,Ee=fe.norm??{mean:255,bias:0},Be,$e;typeof Ee.mean=="number"?Be=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Be=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?$e=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:$e=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Pe=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",tt=_e*De,st=Fe==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),nt=4,Xe=0,$t=1,ze=2,dt=3,Rn=0,en=tt,tn=tt*2,In=-1;Pe==="RGB"&&(nt=3,Xe=0,$t=1,ze=2,dt=-1),Fe==="RGBA"?In=tt*3:Fe==="RBG"?(Rn=0,tn=tt,en=tt*2):Fe==="BGR"&&(tn=0,en=tt,Rn=tt*2);for(let Bt=0;Bt<tt;Bt++,Xe+=nt,ze+=nt,$t+=nt,dt+=nt)st[Rn++]=(se[Xe]+$e[0])/Be[0],st[en++]=(se[$t]+$e[1])/Be[1],st[tn++]=(se[ze]+$e[2])/Be[2],In!==-1&&dt!==-1&&(st[In++]=(se[dt]+$e[3])/Be[3]);return Fe==="RGBA"?new te("float32",st,[1,4,_e,De]):new te("float32",st,[1,3,_e,De])},W=async(se,fe)=>{let _e=typeof HTMLImageElement<"u"&&se instanceof HTMLImageElement,De=typeof ImageData<"u"&&se instanceof ImageData,Ee=typeof ImageBitmap<"u"&&se instanceof ImageBitmap,Be=typeof se=="string",$e,Pe=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(_e){let st=Fe();st.width=se.width,st.height=se.height;let nt=tt(st);if(nt!=null){let Xe=se.height,$t=se.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,$t=fe.resizedWidth),fe!==void 0){if(Pe=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t;nt.drawImage(se,0,0),$e=nt.getImageData(0,0,$t,Xe).data}else throw new Error("Can not access image data")}else if(De){let st,nt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(st=fe.resizedHeight,nt=fe.resizedWidth):(st=se.height,nt=se.width),fe!==void 0&&(Pe=fe),Pe.format="RGBA",Pe.height=st,Pe.width=nt,fe!==void 0){let Xe=Fe();Xe.width=nt,Xe.height=st;let $t=tt(Xe);if($t!=null)$t.putImageData(se,0,0),$e=$t.getImageData(0,0,nt,st).data;else throw new Error("Can not access image data")}else $e=se.data}else if(Ee){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Fe();st.width=se.width,st.height=se.height;let nt=tt(st);if(nt!=null){let Xe=se.height,$t=se.width;return nt.drawImage(se,0,0,$t,Xe),$e=nt.getImageData(0,0,$t,Xe).data,Pe.height=Xe,Pe.width=$t,Z($e,Pe)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((st,nt)=>{let Xe=Fe(),$t=tt(Xe);if(!se||!$t)return nt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=se,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,$t.drawImage(ze,0,0,Xe.width,Xe.height);let dt=$t.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,st(Z(dt.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},q=(se,fe)=>{let{width:_e,height:De,download:Ee,dispose:Be}=fe,$e=[1,De,_e,4];return new te({location:"texture",type:"float32",texture:se,dims:$e,download:Ee,dispose:Be})},Q=(se,fe)=>{let{dataType:_e,dims:De,download:Ee,dispose:Be}=fe;return new te({location:"gpu-buffer",type:_e??"float32",gpuBuffer:se,dims:De,download:Ee,dispose:Be})},oe=(se,fe)=>{let{dataType:_e,dims:De,download:Ee,dispose:Be}=fe;return new te({location:"ml-tensor",type:_e??"float32",mlTensor:se,dims:De,download:Ee,dispose:Be})},le=(se,fe,_e)=>new te({location:"cpu-pinned",type:se,data:fe,dims:_e??[fe.length]})}),ee,Y,ce,ae,xe=c(()=>{ee=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ce=!1,ae=()=>{if(!ce){ce=!0;let se=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,_e=globalThis.Float16Array,De=typeof _e<"u"&&_e.from;se&&(ee.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),fe&&(ee.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),De?(ee.set("float16",_e),Y.set(_e,"float16")):ee.set("float16",Uint16Array)}}}),Ne,me,re=c(()=>{we(),Ne=se=>{let fe=1;for(let _e=0;_e<se.length;_e++){let De=se[_e];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${_e}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${_e}] must be a non-negative integer, got: ${De}`);fe*=De}return fe},me=(se,fe)=>{switch(se.location){case"cpu":return new te(se.type,se.data,fe);case"cpu-pinned":return new te({location:"cpu-pinned",data:se.data,type:se.type,dims:fe});case"texture":return new te({location:"texture",texture:se.texture,type:se.type,dims:fe});case"gpu-buffer":return new te({location:"gpu-buffer",gpuBuffer:se.gpuBuffer,type:se.type,dims:fe});case"ml-tensor":return new te({location:"ml-tensor",mlTensor:se.mlTensor,type:se.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${se.location} is not supported`)}}}),te,we=c(()=>{J(),H(),xe(),re(),te=class{constructor(se,fe,_e){ae();let De,Ee;if(typeof se=="object"&&"location"in se)switch(this.dataLocation=se.location,De=se.type,Ee=se.dims,se.location){case"cpu-pinned":{let $e=ee.get(De);if(!$e)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(se.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=se.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=se.texture,this.downloader=se.download,this.disposer=se.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=se.gpuBuffer,this.downloader=se.download,this.disposer=se.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=se.mlTensor,this.downloader=se.download,this.disposer=se.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Pe;if(typeof se=="string")if(De=se,Pe=_e,se==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");$e=fe}else{let Fe=ee.get(se);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${se}.`);if(Array.isArray(fe)){if(se==="float16"&&Fe===Uint16Array||se==="uint4"||se==="int4")throw new TypeError(`Creating a ${se} tensor from number array is not supported. Please use ${Fe.name} as data.`);se==="uint64"||se==="int64"?$e=Fe.from(fe,BigInt):$e=Fe.from(fe)}else if(fe instanceof Fe)$e=fe;else if(fe instanceof Uint8ClampedArray)if(se==="uint8")$e=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(se==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)$e=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if(Pe=fe,Array.isArray(se)){if(se.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof se[0];if(Fe==="string")De="string",$e=se;else if(Fe==="boolean")De="bool",$e=Uint8Array.from(se);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(se instanceof Uint8ClampedArray)De="uint8",$e=Uint8Array.from(se);else{let Fe=Y.get(se.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${se.constructor}.`);De=Fe,$e=se}if(Pe===void 0)Pe=[$e.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Ee=Pe,this.cpuData=$e,this.dataLocation="cpu"}let Be=Ne(Ee);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Ee,this.size=Be}static async fromImage(se,fe){return W(se,fe)}static fromTexture(se,fe){return q(se,fe)}static fromGpuBuffer(se,fe){return Q(se,fe)}static fromMLTensor(se,fe){return oe(se,fe)}static fromPinnedBuffer(se,fe,_e){return le(se,fe,_e)}toDataURL(se){return U(this,se)}toImageData(se){return B(this,se)}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(se){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 fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,se&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}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(se){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return me(this,se)}}}),be,Ue=c(()=>{we(),be=te}),et,ut,zt,pt,it,ot,Dt=c(()=>{P(),et=(se,fe)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${se}::ORT::${fe}`)},ut=(se,fe)=>{var Ee;let _e=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<_e.length;Be++){if(De&&!_e[Be].includes("TRACE_FUNC")){let $e=`FUNC_${se}::${_e[Be].trim().split(" ")[1]}`;fe&&($e+=`::${fe}`),et("CPU",$e);return}_e[Be].includes("TRACE_FUNC")&&(De=!0)}},zt=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||ut("BEGIN",se)},pt=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||ut("END",se)},it=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.time(`ORT::${se}`)},ot=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeEnd(`ORT::${se}`)}}),sn,gn=c(()=>{w(),Ue(),Dt(),sn=class GT{constructor(fe){this.handler=fe}async run(fe,_e,De){zt(),it("InferenceSession.run");let Ee={},Be={};if(typeof fe!="object"||fe===null||fe instanceof be||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof _e=="object"){if(_e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_e instanceof be)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_e)){if(_e.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of _e){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}.`);Ee[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,st=Object.getOwnPropertyNames(_e);for(let nt of this.outputNames)if(st.indexOf(nt)!==-1){let Xe=_e[nt];(Xe===null||Xe instanceof be)&&(tt=!0,$e=!1,Ee[nt]=Xe)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=_e}}else if(typeof _e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof fe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)Ee[tt]=null;let Pe=await this.handler.run(fe,Ee,Be),Fe={};for(let tt in Pe)if(Object.hasOwnProperty.call(Pe,tt)){let st=Pe[tt];st instanceof be?Fe[tt]=st:Fe[tt]=new be(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Fe}async release(){return this.handler.dispose()}static async create(fe,_e,De,Ee){zt(),it("InferenceSession.create");let Be,$e={};if(typeof fe=="string"){if(Be=fe,typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let st=fe,nt=0,Xe=fe.byteLength;if(typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e=="number"){if(nt=_e,!Number.isSafeInteger(nt))throw new RangeError("'byteOffset' must be an integer.");if(nt<0||nt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Xe=fe.byteLength-nt,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||nt+Xe>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-nt}].`);if(typeof Ee=="object"&&Ee!==null)$e=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof _e<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(st,nt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,Fe]=await x($e),tt=await Pe.createInferenceSessionHandler(Be,Fe);return ot("InferenceSession.create"),pt(),new GT(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}}}),Je,Ct=c(()=>{gn(),Je=sn}),xt=c(()=>{}),pn=c(()=>{}),$n=c(()=>{}),er=c(()=>{}),yr={};p(yr,{InferenceSession:()=>Je,TRACE:()=>et,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>be,env:()=>I,registerBackend:()=>y});var vn=c(()=>{S(),O(),Ct(),Ue(),xt(),pn(),Dt(),$n(),er()}),Hi=c(()=>{}),Xn={};p(Xn,{default:()=>Rs});var di,xn,Rs,tl=c(()=>{var se;Se(),ir(),nr(),di="ort-wasm-proxy-worker",xn=((se=globalThis.self)==null?void 0:se.name)===di,xn&&(self.onmessage=fe=>{let{type:_e,in:De}=fe.data;try{switch(_e){case"init-wasm":gs(De.wasm).then(()=>{ga(De).then(()=>{postMessage({type:_e})},Ee=>{postMessage({type:_e,err:Ee})})},Ee=>{postMessage({type:_e,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Be}=De;Fs(Be,Ee).then(()=>{postMessage({type:_e})},$e=>{postMessage({type:_e,err:$e})});break}case"copy-from":{let{buffer:Ee}=De,Be=dn(Ee);postMessage({type:_e,out:Be});break}case"create":{let{model:Ee,options:Be}=De;Cr(Ee,Be).then($e=>{postMessage({type:_e,out:$e})},$e=>{postMessage({type:_e,err:$e})});break}case"release":ao(De),postMessage({type:_e});break;case"run":{let{sessionId:Ee,inputIndices:Be,inputs:$e,outputIndices:Pe,options:Fe}=De;Ye(Ee,Be,$e,Pe,new Array(Pe.length).fill(null),Fe).then(tt=>{tt.some(st=>st[3]!=="cpu")?postMessage({type:_e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:_e,out:tt},mt([...$e,...tt]))},tt=>{postMessage({type:_e,err:tt})});break}case"end-profiling":sr(De),postMessage({type:_e});break;default:}}catch(Ee){postMessage({type:_e,err:Ee})}}),Rs=xn?null:fe=>new Worker(fe??kn,{type:"classic",name:di})}),fa,Is,kn,tr,ui,Ms,qr,wr,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),fa=typeof location>"u"?void 0:location.origin,Is=()=>{var se,fe;return typeof document<"u"?(se=document.currentScript)==null?void 0:se.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},ui=(se,fe)=>{try{let _e=fe??kn;return(_e?new URL(se,_e):new URL(se)).origin===fa}catch{return!1}},Ms=(se,fe)=>{let _e=fe??kn;try{return(_e?new URL(se,_e):new URL(se)).href}catch{return}},qr=(se,fe)=>`${fe??"./"}${se}`,wr=async se=>{let fe=await(await fetch(se,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},ro=async se=>(await import(se)).default,Os=(tl(),f(Xn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ui(kn))return[void 0,Os()];let se=await wr(kn);return[se,Os(se)]},Kr=void 0,Wi=async(se,fe,_e,De)=>{let Ee=Kr&&!(se||fe);if(Ee)if(kn)Ee=ui(kn)||De&&!_e;else if(De&&!_e)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let Be="ort-wasm-simd-threaded.mjs",$e=se??Ms(Be,fe),Pe=_e&&$e&&!ui($e,fe),Fe=Pe?await wr($e):$e??qr(Be,fe);return[Pe?Fe:void 0,await ro(Fe)]}}}),ps,Vi,_r,Br,Ao,fs,ms,gs,Gt,ir=c(()=>{nr(),Vi=!1,_r=!1,Br=!1,Ao=()=>{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}},fs=()=>{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}},ms=()=>{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}},gs=async se=>{if(Vi)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let fe=se.initTimeout,_e=se.numThreads;if(se.simd!==!1){if(se.simd==="relaxed"){if(!ms())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=Ao();_e>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+_e+", 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."),se.numThreads=_e=1);let Ee=se.wasmPaths,Be=typeof Ee=="string"?Ee:void 0,$e=Ee==null?void 0:Ee.mjs,Pe=($e==null?void 0:$e.href)??$e,Fe=Ee==null?void 0:Ee.wasm,tt=(Fe==null?void 0:Fe.href)??Fe,st=se.wasmBinary,[nt,Xe]=await Wi(Pe,Be,_e>1,!!st||!!tt),$t=!1,ze=[];if(fe>0&&ze.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},fe)})),ze.push(new Promise((dt,Rn)=>{let en={numThreads:_e};if(st)en.wasmBinary=st,en.locateFile=tn=>tn;else if(tt||Be)en.locateFile=tn=>tt??Be+tn;else if(Pe&&Pe.indexOf("blob:")!==0)en.locateFile=tn=>new URL(tn,Pe).href;else if(nt){let tn=tr();tn&&(en.locateFile=In=>tn+In)}Xe(en).then(tn=>{_r=!1,Vi=!0,ps=tn,dt(),nt&&URL.revokeObjectURL(nt)},tn=>{_r=!1,Br=!0,Rn(tn)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},Gt=()=>{if(Vi&&ps)return ps;throw new Error("WebAssembly is not initialized yet.")}}),Jn,jn,Et,so=c(()=>{ir(),Jn=(se,fe)=>{let _e=Gt(),De=_e.lengthBytesUTF8(se)+1,Ee=_e._malloc(De);return _e.stringToUTF8(se,Ee,De),fe.push(Ee),Ee},jn=(se,fe,_e,De)=>{if(typeof se=="object"&&se!==null){if(_e.has(se))throw new Error("Circular reference in options");_e.add(se)}Object.entries(se).forEach(([Ee,Be])=>{let $e=fe?fe+Ee:Ee;if(typeof Be=="object")jn(Be,$e+".",_e,De);else if(typeof Be=="string"||typeof Be=="number")De($e,Be.toString());else if(typeof Be=="boolean")De($e,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=se=>{let fe=Gt(),_e=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetLastError(Ee,Ee+De);let Be=Number(fe.getValue(Ee,De===4?"i32":"i64")),$e=fe.getValue(Ee+De,"*"),Pe=$e?fe.UTF8ToString($e):"";throw new Error(`${se} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Pe}`)}finally{fe.stackRestore(_e)}}}),$o,nl=c(()=>{ir(),so(),$o=se=>{let fe=Gt(),_e=0,De=[],Ee=se||{};try{if((se==null?void 0:se.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof se.logSeverityLevel!="number"||!Number.isInteger(se.logSeverityLevel)||se.logSeverityLevel<0||se.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${se.logSeverityLevel}`);if((se==null?void 0:se.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof se.logVerbosityLevel!="number"||!Number.isInteger(se.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${se.logVerbosityLevel}`);(se==null?void 0:se.terminate)===void 0&&(Ee.terminate=!1);let Be=0;return(se==null?void 0:se.tag)!==void 0&&(Be=Jn(se.tag,De)),_e=fe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Be),_e===0&&Et("Can't create run options."),(se==null?void 0:se.extra)!==void 0&&jn(se.extra,"",new WeakSet,($e,Pe)=>{let Fe=Jn($e,De),tt=Jn(Pe,De);fe._OrtAddRunConfigEntry(_e,Fe,tt)!==0&&Et(`Can't set a run config entry: ${$e} - ${Pe}.`)}),[_e,De]}catch(Be){throw _e!==0&&fe._OrtReleaseRunOptions(_e),De.forEach($e=>fe._free($e)),Be}}}),Po,Ro,ma,Li,il,rl,Nn=c(()=>{ir(),so(),Po=se=>{switch(se){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: ${se}`)}},Ro=se=>{switch(se){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${se}`)}},ma=se=>{se.extra||(se.extra={}),se.extra.session||(se.extra.session={});let fe=se.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),se.executionProviders&&se.executionProviders.some(_e=>(typeof _e=="string"?_e:_e.name)==="webgpu")&&(se.enableMemPattern=!1)},Li=(se,fe,_e,De)=>{let Ee=Jn(fe,De),Be=Jn(_e,De);Gt()._OrtAddSessionConfigEntry(se,Ee,Be)!==0&&Et(`Can't set a session config entry: ${fe} - ${_e}.`)},il=async(se,fe,_e)=>{let De=fe.executionProviders;for(let Ee of De){let Be=typeof Ee=="string"?Ee:Ee.name,$e=[];switch(Be){case"webnn":if(Be="WEBNN",Li(se,"session.disable_quant_qdq","1",_e),Li(se,"session.disable_qdq_constant_folding","1",_e),typeof Ee!="string"){let nt=Ee==null?void 0:Ee.deviceType;nt&&Li(se,"deviceType",nt,_e)}break;case"webgpu":if(Be="JS",typeof Ee!="string"){let nt=Ee;if(nt!=null&&nt.preferredLayout){if(nt.preferredLayout!=="NCHW"&&nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${nt.preferredLayout}`);Li(se,"preferredLayout",nt.preferredLayout,_e)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Pe=Jn(Be,_e),Fe=$e.length,tt=0,st=0;if(Fe>0){tt=Gt()._malloc(Fe*Gt().PTR_SIZE),_e.push(tt),st=Gt()._malloc(Fe*Gt().PTR_SIZE),_e.push(st);for(let nt=0;nt<Fe;nt++)Gt().setValue(tt+nt*Gt().PTR_SIZE,$e[nt][0],"*"),Gt().setValue(st+nt*Gt().PTR_SIZE,$e[nt][1],"*")}await Gt()._OrtAppendExecutionProvider(se,Pe,tt,st,Fe)!==0&&Et(`Can't append execution provider: ${Be}.`)}},rl=async se=>{let fe=Gt(),_e=0,De=[],Ee=se||{};ma(Ee);try{let Be=Po(Ee.graphOptimizationLevel??"all"),$e=Ro(Ee.executionMode??"sequential"),Pe=typeof Ee.logId=="string"?Jn(Ee.logId,De):0,Fe=Ee.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let tt=Ee.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let st=typeof Ee.optimizedModelFilePath=="string"?Jn(Ee.optimizedModelFilePath,De):0;if(_e=fe._OrtCreateSessionOptions(Be,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,$e,!!Ee.enableProfiling,0,Pe,Fe,tt,st),_e===0&&Et("Can't create session options."),Ee.executionProviders&&await il(_e,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Li(_e,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[nt,Xe]of Object.entries(Ee.freeDimensionOverrides)){if(typeof nt!="string")throw new Error(`free dimension override name must be a string: ${nt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let $t=Jn(nt,De);fe._OrtAddFreeDimensionOverride(_e,$t,Xe)!==0&&Et(`Can't set a free dimension override: ${nt} - ${Xe}.`)}return Ee.extra!==void 0&&jn(Ee.extra,"",new WeakSet,(nt,Xe)=>{Li(_e,nt,Xe,De)}),[_e,De]}catch(Be){throw _e!==0&&fe._OrtReleaseSessionOptions(_e)!==0&&Et("Can't release session options."),De.forEach($e=>fe._free($e)),Be}}}),qi,ei,Ki,vs,oo,zs,Sr,Ni,Ut=c(()=>{qi=se=>{switch(se){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: ${se}`)}},ei=se=>{switch(se){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: ${se}`)}},Ki=(se,fe)=>{let _e=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][se],De=typeof fe=="number"?fe:fe.reduce((Ee,Be)=>Ee*Be,1);return _e>0?Math.ceil(De*_e):void 0},vs=se=>{switch(se){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: ${se}`)}},oo=se=>{switch(se){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: ${se}`)}},zs=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Sr=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint64"||se==="int8"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Ni=se=>{switch(se){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: ${se}`)}}}),ti,Bs=c(()=>{Hi(),ti=async se=>{if(typeof se=="string"){let fe=await fetch(se);if(!fe.ok)throw new Error(`failed to load external data file: ${se}`);let _e=fe.headers.get("Content-Length"),De=_e?parseInt(_e,10):0;if(De<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${se}, no response body.`);let Ee=fe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let Fe=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Pe}let $e=0;for(;;){let{done:Pe,value:Fe}=await Ee.read();if(Pe)break;let tt=Fe.byteLength;new Uint8Array(Be,$e,tt).set(Fe),$e+=tt}return new Uint8Array(Be,0,De)}}else return se instanceof Blob?new Uint8Array(await se.arrayBuffer()):se instanceof Uint8Array?se:new Uint8Array(se)}}),kr,ga,Fs,rr,Yr,Gs,dn,Cr,ao,Fr,Ye,sr,mt,Se=c(()=>{vn(),nl(),Nn(),Ut(),ir(),so(),Bs(),kr=(se,fe)=>{Gt()._OrtInit(se,fe)!==0&&Et("Can't initialize onnxruntime.")},ga=async se=>{kr(se.wasm.numThreads,oo(se.logLevel))},Fs=async(se,fe)=>{var De,Ee;(Ee=(De=Gt()).asyncInit)==null||Ee.call(De);let _e=se.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(_e){if(typeof _e.limits!="object"||typeof _e.features!="object"||typeof _e.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=se.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let $e=se.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(_e=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:$e}),!_e)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rr=new Map,Yr=se=>{let fe=Gt(),_e=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetInputOutputCount(se,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(fe.getValue(Ee,Be)),Number(fe.getValue(Ee+De,Be))]}finally{fe.stackRestore(_e)}},Gs=(se,fe)=>{let _e=Gt(),De=_e.stackSave(),Ee=0;try{let Be=_e.PTR_SIZE,$e=_e.stackAlloc(2*Be);_e._OrtGetInputOutputMetadata(se,fe,$e,$e+Be)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(_e.getValue($e,"*"));Ee=Number(_e.getValue($e+Be,"*"));let Fe=_e.HEAP32[Ee/4];if(Fe===0)return[Pe,0];let tt=_e.HEAPU32[Ee/4+1],st=[];for(let nt=0;nt<tt;nt++){let Xe=Number(_e.getValue(Ee+8+nt*Be,"*"));st.push(Xe!==0?_e.UTF8ToString(Xe):Number(_e.getValue(Ee+8+(nt+tt)*Be,"*")))}return[Pe,Fe,st]}finally{_e.stackRestore(De),Ee!==0&&_e._OrtFree(Ee)}},dn=se=>{let fe=Gt(),_e=fe._malloc(se.byteLength);if(_e===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${se.byteLength}.`);return fe.HEAPU8.set(se,_e),[_e,se.byteLength]},Cr=async(se,fe)=>{var st,nt,Xe;let _e,De,Ee=Gt();Array.isArray(se)?[_e,De]=se:se.buffer===Ee.HEAPU8.buffer?[_e,De]=[se.byteOffset,se.byteLength]:[_e,De]=dn(se);let Be=0,$e=0,Pe=[],Fe=[],tt=[];try{if([$e,Pe]=await rl(fe),(fe==null?void 0:fe.externalData)&&Ee.mountExternalData){let Bn=[];for(let fn of fe.externalData){let Di=typeof fn=="string"?fn:fn.path;Bn.push(ti(typeof fn=="string"?fn:fn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let fn=Bn,Di=fn==null?void 0:fn.context,Yi=fn==null?void 0:fn.gpuDevice,or=fn==null?void 0:fn.deviceType,ol=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:ol})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Be=await Ee._OrtCreateSession(_e,De,$e),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,Be),Be===0&&Et("Can't create a session."),(nt=Ee.jsepOnCreateSession)==null||nt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Be,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,ze]=Yr(Be),dt=!!(fe!=null&&fe.enableGraphCapture),Rn=[],en=[],tn=[],In=[],Bt=[];for(let Bn=0;Bn<$t;Bn++){let[fn,Di,Yi]=Gs(Be,Bn);fn===0&&Et("Can't get an input name."),Fe.push(fn);let or=Ee.UTF8ToString(fn);Rn.push(or),tn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}for(let Bn=0;Bn<ze;Bn++){let[fn,Di,Yi]=Gs(Be,Bn+$t);fn===0&&Et("Can't get an output name."),tt.push(fn);let or=Ee.UTF8ToString(fn);en.push(or),In.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}return rr.set(Be,[Be,Fe,tt,null,dt,!1]),[Be,Rn,en,tn,In]}catch($t){throw Fe.forEach(ze=>Ee._OrtFree(ze)),tt.forEach(ze=>Ee._OrtFree(ze)),Be!==0&&Ee._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{Ee._free(_e),$e!==0&&Ee._OrtReleaseSessionOptions($e)!==0&&Et("Can't release session options."),Pe.forEach($t=>Ee._free($t)),(Xe=Ee.unmountExternalData)==null||Xe.call(Ee)}},ao=se=>{var Fe,tt,st;let fe=Gt(),_e=rr.get(se);if(!_e)throw new Error(`cannot release session. invalid session id: ${se}`);let[De,Ee,Be,$e,Pe]=_e;$e&&(Pe&&fe._OrtClearBoundOutputs($e.handle)!==0&&Et("Can't clear bound outputs."),fe._OrtReleaseBinding($e.handle)!==0&&Et("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,se),(tt=fe.webnnOnReleaseSession)==null||tt.call(fe,se),(st=fe.webgpuOnReleaseSession)==null||st.call(fe,se),Ee.forEach(nt=>fe._OrtFree(nt)),Be.forEach(nt=>fe._OrtFree(nt)),fe._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(se)},Fr=async(se,fe,_e,De,Ee,Be,$e=!1)=>{if(!se){fe.push(0);return}let Pe=Gt(),Fe=Pe.PTR_SIZE,tt=se[0],st=se[1],nt=se[3],Xe=nt,$t,ze;if(tt==="string"&&(nt==="gpu-buffer"||nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(nt==="gpu-buffer"){let en=se[2].gpuBuffer;ze=Ki(qi(tt),st);{let tn=Pe.jsepRegisterBuffer;if(!tn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=tn(De,Be,en,ze)}}else if(nt==="ml-tensor"){let en=se[2].mlTensor;ze=Ki(qi(tt),st);let tn=Pe.webnnRegisterMLTensor;if(!tn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=tn(De,en,qi(tt),st)}else{let en=se[2];if(Array.isArray(en)){ze=Fe*en.length,$t=Pe._malloc(ze),_e.push($t);for(let tn=0;tn<en.length;tn++){if(typeof en[tn]!="string")throw new TypeError(`tensor data at index ${tn} is not a string`);Pe.setValue($t+tn*Fe,Jn(en[tn],_e),"*")}}else{let tn=Pe.webnnIsGraphInput,In=Pe.webnnIsGraphOutput;if(tt!=="string"&&tn&&In){let Bt=Pe.UTF8ToString(Ee);if(tn(De,Bt)||In(De,Bt)){let Bn=qi(tt);ze=Ki(Bn,st),Xe="ml-tensor";let fn=Pe.webnnCreateTemporaryTensor,Di=Pe.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await fn(De,Bn,st);Di(Yi,new Uint8Array(en.buffer,en.byteOffset,en.byteLength)),$t=Yi}else ze=en.byteLength,$t=Pe._malloc(ze),_e.push($t),Pe.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,ze),$t)}else ze=en.byteLength,$t=Pe._malloc(ze),_e.push($t),Pe.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,ze),$t)}}let dt=Pe.stackSave(),Rn=Pe.stackAlloc(4*st.length);try{st.forEach((tn,In)=>Pe.setValue(Rn+In*Fe,tn,Fe===4?"i32":"i64"));let en=Pe._OrtCreateTensor(qi(tt),$t,ze,Rn,st.length,Ni(Xe));en===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),fe.push(en)}finally{Pe.stackRestore(dt)}},Ye=async(se,fe,_e,De,Ee,Be)=>{var ar,sc,pd;let $e=Gt(),Pe=$e.PTR_SIZE,Fe=rr.get(se);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${se}`);let tt=Fe[0],st=Fe[1],nt=Fe[2],Xe=Fe[3],$t=Fe[4];Fe[5];let ze=fe.length,dt=De.length,Rn=0,en=[],tn=[],In=[],Bt=[],Bn=[],fn=$e.stackSave(),Di=$e.stackAlloc(ze*Pe),Yi=$e.stackAlloc(ze*Pe),or=$e.stackAlloc(dt*Pe),ol=$e.stackAlloc(dt*Pe);try{[Rn,en]=$o(Be),it("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)await Fr(_e[hn],tn,Bt,se,st[fe[hn]],fe[hn],$t);for(let hn=0;hn<dt;hn++)await Fr(Ee[hn],In,Bt,se,nt[De[hn]],ze+De[hn],$t);ot("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)$e.setValue(Di+hn*Pe,tn[hn],"*"),$e.setValue(Yi+hn*Pe,st[fe[hn]],"*");for(let hn=0;hn<dt;hn++)$e.setValue(or+hn*Pe,In[hn],"*"),$e.setValue(ol+hn*Pe,nt[De[hn]],"*");(ar=$e.jsepOnRunStart)==null||ar.call($e,tt),(sc=$e.webnnOnRunStart)==null||sc.call($e,tt);let Ai;Ai=await $e._OrtRun(tt,Yi,Di,ze,ol,dt,or,Rn),Ai!==0&&Et("failed to call OrtRun().");let bs=[],fd=[];it("wasm ProcessOutputTensor");for(let hn=0;hn<dt;hn++){let Jr=Number($e.getValue(or+hn*Pe,"*"));if(Jr===In[hn]||Bn.includes(In[hn])){bs.push(Ee[hn]),Jr!==In[hn]&&$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let zu=$e.stackSave(),Ws=$e.stackAlloc(4*Pe),va=!1,vi,lr=0;try{$e._OrtGetTensorData(Jr,Ws,Ws+Pe,Ws+2*Pe,Ws+3*Pe)!==0&&Et(`Can't access output tensor data on index ${hn}.`);let oc=Pe===4?"i32":"i64",cr=Number($e.getValue(Ws,oc));lr=$e.getValue(Ws+Pe,"*");let md=$e.getValue(Ws+Pe*2,"*"),Bu=Number($e.getValue(Ws+Pe*3,oc)),Vs=[];for(let xi=0;xi<Bu;xi++)Vs.push(Number($e.getValue(md+xi*Pe,oc)));$e._OrtFree(md)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Zn)=>xi*Zn,1);vi=ei(cr);let ys=Xe==null?void 0:Xe.outputPreferredLocations[De[hn]];if(vi==="string"){if(ys==="gpu-buffer"||ys==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Zn=0;Zn<Zr;Zn++){let Qr=$e.getValue(lr+Zn*Pe,"*"),gd=$e.getValue(lr+(Zn+1)*Pe,"*"),vd=Zn===Zr-1?void 0:gd-Qr;xi.push($e.UTF8ToString(Qr,vd))}bs.push([vi,Vs,xi,"cpu"])}else if(ys==="gpu-buffer"&&Zr>0){let xi=$e.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);va=!0,bs.push([vi,Vs,{gpuBuffer:Zn,download:$e.jsepCreateDownloader(Zn,Qr,vi),dispose:()=>{$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(ys==="ml-tensor"&&Zr>0){let xi=$e.webnnEnsureTensor,Zn=$e.webnnIsGraphInputOutputTypeSupported;if(!xi||!Zn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Zn(se,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(se,lr,cr,Vs,!1);va=!0,bs.push([vi,Vs,{mlTensor:Qr,download:$e.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{$e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(ys==="ml-tensor-cpu-output"&&Zr>0){let xi=$e.webnnCreateMLTensorDownloader(lr,vi)(),Zn=bs.length;va=!0,fd.push((async()=>{let Qr=[Zn,await xi];return $e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr),Qr})()),bs.push([vi,Vs,[],"cpu"])}else{let xi=vs(vi),Zn=new xi(Zr);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set($e.HEAPU8.subarray(lr,lr+Zn.byteLength)),bs.push([vi,Vs,Zn,"cpu"])}}finally{$e.stackRestore(zu),vi==="string"&&lr&&$e._free(lr),va||$e._OrtReleaseTensor(Jr)}}Xe&&!$t&&($e._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),rr.set(se,[tt,st,nt,Xe,$t,!1]));for(let[hn,Jr]of await Promise.all(fd))bs[hn][2]=Jr;return ot("wasm ProcessOutputTensor"),bs}finally{(pd=$e.webnnOnRunEnd)==null||pd.call($e,tt),$e.stackRestore(fn),tn.forEach(Ai=>$e._OrtReleaseTensor(Ai)),In.forEach(Ai=>$e._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>$e._free(Ai)),Rn!==0&&$e._OrtReleaseRunOptions(Rn),en.forEach(Ai=>$e._free(Ai))}},sr=se=>{let fe=Gt(),_e=rr.get(se);if(!_e)throw new Error("invalid session id");let De=_e[0],Ee=fe._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),fe._OrtFree(Ee)},mt=se=>{let fe=[];for(let _e of se){let De=_e[2];!Array.isArray(De)&&"buffer"in De&&fe.push(De.buffer)}return fe}}),Me,Ze,jt,on,un,Ln,Mn,hi,Hn,gi,On,Xr,lo,Io,xs,Lu,Mo,Oo,dd=c(()=>{vn(),Se(),ir(),nr(),Me=()=>!!I.wasm.proxy&&typeof document<"u",jt=!1,on=!1,un=!1,hi=new Map,Hn=(se,fe)=>{let _e=hi.get(se);_e?_e.push(fe):hi.set(se,[fe])},gi=()=>{if(jt||!on||un||!Ze)throw new Error("worker not ready")},On=se=>{switch(se.data.type){case"init-wasm":jt=!1,se.data.err?(un=!0,Mn[1](se.data.err)):(on=!0,Mn[0]()),Ln&&(URL.revokeObjectURL(Ln),Ln=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=hi.get(se.data.type);se.data.err?fe.shift()[1](se.data.err):fe.shift()[0](se.data.out);break}}},Xr=async()=>{if(!on){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(un)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Me())return new Promise((se,fe)=>{Ze==null||Ze.terminate(),Ls().then(([_e,De])=>{try{Ze=De,Ze.onerror=Be=>fe(Be),Ze.onmessage=On,Mn=[se,fe];let Ee={type:"init-wasm",in:I};if(!Ee.in.wasm.wasmPaths&&_e){let Be=tr();Be&&(Ee.in.wasm.wasmPaths=Be)}Ze.postMessage(Ee),Ln=_e}catch(Ee){fe(Ee)}},fe)});try{await gs(I.wasm),await ga(I),on=!0}catch(se){throw un=!0,se}finally{jt=!1}}},lo=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("init-ep",[fe,_e]);let De={type:"init-ep",in:{epName:se,env:I}};Ze.postMessage(De)});await Fs(I,se)},Io=async se=>Me()?(gi(),new Promise((fe,_e)=>{Hn("copy-from",[fe,_e]);let De={type:"copy-from",in:{buffer:se}};Ze.postMessage(De,[se.buffer])})):dn(se),xs=async(se,fe)=>{if(Me()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((_e,De)=>{Hn("create",[_e,De]);let Ee={type:"create",in:{model:se,options:{...fe}}},Be=[];se instanceof Uint8Array&&Be.push(se.buffer),Ze.postMessage(Ee,Be)})}else return Cr(se,fe)},Lu=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("release",[fe,_e]);let De={type:"release",in:se};Ze.postMessage(De)});ao(se)},Mo=async(se,fe,_e,De,Ee,Be)=>{if(Me()){if(_e.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise(($e,Pe)=>{Hn("run",[$e,Pe]);let Fe=_e,tt={type:"run",in:{sessionId:se,inputIndices:fe,inputs:Fe,outputIndices:De,options:Be}};Ze.postMessage(tt,mt(Fe))})}else return Ye(se,fe,_e,De,Ee,Be)},Oo=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("end-profiling",[fe,_e]);let De={type:"end-profiling",in:se};Ze.postMessage(De)});sr(se)}}),tc,Lo,sl,nc=c(()=>{vn(),dd(),Ut(),Hi(),Bs(),tc=(se,fe)=>{switch(se.location){case"cpu":return[se.type,se.dims,se.data,"cpu"];case"gpu-buffer":return[se.type,se.dims,{gpuBuffer:se.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[se.type,se.dims,{mlTensor:se.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${se.location} for ${fe()}`)}},Lo=se=>{switch(se[3]){case"cpu":return new be(se[0],se[2],se[1]);case"gpu-buffer":{let fe=se[0];if(!zs(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:_e,download:De,dispose:Ee}=se[2];return be.fromGpuBuffer(_e,{dataType:fe,dims:se[1],download:De,dispose:Ee})}case"ml-tensor":{let fe=se[0];if(!Sr(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:_e,download:De,dispose:Ee}=se[2];return be.fromMLTensor(_e,{dataType:fe,dims:se[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${se[3]}`)}},sl=class{async fetchModelAndCopyToWasmMemory(se){return Io(await ti(se))}async loadModel(se,fe){zt();let _e;typeof se=="string"?_e=await this.fetchModelAndCopyToWasmMemory(se):_e=se,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xs(_e,fe),pt()}async dispose(){return Lu(this.sessionId)}async run(se,fe,_e){zt();let De=[],Ee=[];Object.entries(se).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);De.push($t),Ee.push(ze)});let Be=[],$e=[];Object.entries(fe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push($t),$e.push(ze)});let Pe=De.map((nt,Xe)=>tc(nt,()=>`input "${this.inputNames[Ee[Xe]]}"`)),Fe=Be.map((nt,Xe)=>nt?tc(nt,()=>`output "${this.outputNames[$e[Xe]]}"`):null),tt=await Mo(this.sessionId,Ee,Pe,$e,Fe,_e),st={};for(let nt=0;nt<tt.length;nt++)st[this.outputNames[$e[nt]]]=Be[nt]??Lo(tt[nt]);return pt(),st}startProfiling(){}endProfiling(){Oo(this.sessionId)}}}),Us={};p(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>zo});var co,Hs,zo,ud=c(()=>{vn(),dd(),nc(),co=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let se=I.wasm.simd;if(typeof se!="boolean"&&se!==void 0&&se!=="fixed"&&se!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${se}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Hs=class{async init(se){co(),await Xr(),await lo(se)}async createInferenceSessionHandler(se,fe){let _e=new sl;return await _e.loadModel(se,fe),_e}},zo=new Hs}),hd={};p(hd,{InferenceSession:()=>Je,TRACE:()=>et,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>be,default:()=>rc,env:()=>I,registerBackend:()=>y}),vn(),vn(),vn();var ic="1.26.0",rc=yr;{let se=(ud(),f(Us)).wasmBackend;y("cpu",se,10),y("wasm",se,10)}return Object.defineProperty(I.versions,"web",{value:ic,enumerable:!0}),f(hd)})();n.exports=i})(dw)),dw.exports}var ak;function CP(){return ak||(ak=1,(function(n){var e=Dl&&Dl.__createBinding||(Object.create?(function(E,j,N,A){A===void 0&&(A=N);var P=Object.getOwnPropertyDescriptor(j,N);(!P||("get"in P?!j.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return j[N]}}),Object.defineProperty(E,A,P)}):(function(E,j,N,A){A===void 0&&(A=N),E[A]=j[N]})),i=Dl&&Dl.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=Dl&&Dl.__importStar||function(E){if(E&&E.__esModule)return E;var j={};if(E!=null)for(var N in E)N!=="default"&&Object.prototype.hasOwnProperty.call(E,N)&&e(j,E,N);return i(j,E),j};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(kP()),a=K0(),d=Y0(),l=iv(),c=wy(),p=BT(),m=FT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",_="silero_vad_legacy.onnx",y=E=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:E,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async j=>{j.getTracks().forEach(N=>{N.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:j=>{j.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});n.getDefaultRealTimeVADOptions=y;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,N,A,P){await N.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:A};const I=new AudioWorkletNode(N,"vad-helper-worklet",j);return I.port.onmessage=async O=>{const U=O.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case c.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const B=new Float32Array(U.data);await P(B);break}}},I}async function w(E,j,N){const A=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const I=E.createScriptProcessor(4096,1,1);let O=!1;return I.onaudioprocess=async U=>{if(!O){O=!0;try{const B=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=A.process(B);for(const W of Z)await N(W)}catch(B){console.error("Error processing audio:",B)}finally{O=!1}}},I.connect(E.destination),I}class S{constructor(j,N,A,P,I=!1,O=null,U=null,B=null,J=null,Z=null,W=null,q="uninitialized",Q=!1){this.options=j,this.frameProcessor=N,this.model=A,this.frameSamples=P,this.listening=I,this.errored=O,this._stream=U,this._audioContext=B,this._vadNode=J,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=W,this.initializationState=q,this.ownsAudioContext=Q,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=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await w(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:le,vadNode:H}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const ee=new MediaStreamAudioSourceNode(le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ee,ee.connect(H);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:le}=this.getAudioInstances();await this.options.pauseStream(oe),le.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var le;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((le=this._audioContext)==null?void 0:le.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(j={}){const N={...(0,n.getDefaultRealTimeVADOptions)(j.model??n.DEFAULT_MODEL),...j};(0,d.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const A=N.model==="v5"?b:_,P=N.baseAssetPath+A,I=N.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let O;try{O=await I(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(W){throw console.error(`Encountered an error while loading model file ${P}`),W}const U=N.model==="v5"?512:1536,B=U/16,J=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},B),Z=new S(N,J,O,U);if(N.startOnLoad)try{await Z.start()}catch(W){throw console.error("Error starting micVad",W),W}return Z}}n.MicVAD=S})(Dl)),Dl}var lk;function EP(){return lk||(lk=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=OT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=K0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=Y0();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=wy();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=_P();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=SP();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=CP();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(aw)),aw}var TP=EP();function mx(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>mx(n,"debug",e,i),info:(n,e,i)=>mx(n,"info",e,i),warn:(n,e,i)=>mx(n,"warn",e,i),error:(n,e,i,r)=>mx(n,"error",e,i,r)},UT=16e3,jP=6,xp=UT*jP,NP=400,DP=UT*NP/1e3,ck=300,dk=2e3,uk=1500,hk=3e3,AP=600,HT=.5,WT=.35,pk=.85,fk=.7;let As=null,qa=!1,cs=!1;const __=new Set;function gx(n){for(const e of Array.from(__))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let uw=0;const mk=2;let Pp=!1,VT=!1;function qT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),$P(`error:${e.message||"unknown"}`)})}function Rb(){return As||(As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),qT(As),ht.info("speech","worker spawned"),As)}let vx=!1;function $P(n){if(!Pp){if(vx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(vx=!0,uw+=1,VT=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:uw}),gx({reason:n,respawned:!1,finalOnly:!0}),uw>mk){if(Pp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:mk}),As)try{As.terminate()}catch{}As=null,qa=!1,cs=!1,gx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),vx=!1;return}if(As)try{As.terminate()}catch{}As=null,qa=!1,cs=!1;try{As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),qT(As),cs=!0,As.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),gx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Pp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),gx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{vx=!1}}}function PP(n,e){if(qa||cs)return;cs=!0;const i=Rb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(qa=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function RP(){ht.info("speech","resetModel: clearing load flags"),qa=!1,cs=!1}function _y(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function IP(n){const e=Rb();return!qa&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(qa=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function KT(n){let e=Rb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],p=new Set;let m=null,f=0,b=!1,_=0,y=!1,k=!1,x=0,w=0,S=0,E=-1,j=ck,N=0,A=null,P="",I="",O=!1,U=0;function B(ae,xe){const Ne=Math.min(ae.length,xe.length);let me=0;for(;me<Ne&&ae.charCodeAt(me)===xe.charCodeAt(me);)me++;return me}function J(ae){const xe=B(P,ae);return P=ae,xe>I.length&&(I=ae.slice(0,xe)),I.length>ae.length&&(I=ae),I}const Z=()=>(m||(m=new Float32Array(xp)),m),W=()=>{f=0},q=ae=>{const xe=Z(),Ne=ae.length;if(Ne>=xp){xe.set(ae.subarray(Ne-xp)),f=xp;return}if(f+Ne<=xp){xe.set(ae,f),f+=Ne;return}const me=f+Ne-xp;xe.copyWithin(0,me,f),f-=me,xe.set(ae,f),f+=Ne},Q=()=>{A&&(clearTimeout(A),A=null)},oe=()=>{Q(),b=!1,y=!1,k=!1,j=ck,P="",I="",O=!1,U=0,W()},le=()=>{if(i||!b||k||y||A)return;if(f<DP){A=setTimeout(()=>{A=null,le()},j);return}const ae=performance.now()-x;if(ae<j&&x!==0){A=setTimeout(()=>{A=null,le()},j-ae);return}if(VT||Pp||n.partialsEnabled&&!n.partialsEnabled())return;const xe=Z(),Ne=new Float32Array(f);Ne.set(xe.subarray(0,f)),w+=1,S=w,y=!0,N=performance.now(),x=N,e.postMessage({type:"transcribe-partial",audio:Ne,seq:w},[Ne.buffer])},H=ae=>ae.length===0?Promise.resolve():Pp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(xe=>{c.push(xe),w+=1;const Ne=w;E=Ne,e.postMessage({type:"transcribe",audio:ae,seq:Ne},[ae.buffer])}),ee=ae=>{const xe=H(ae);return p.add(xe),xe.finally(()=>{p.delete(xe)}),xe},Y=ae=>{var xe,Ne,me,re,te;if(ae.data.type==="result"){const we=ae.data.text,be=ae.data.seq??0;be&&be<E&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:be,latestFinalSeq:E}),!i&&we&&n.onFinal(we),(xe=c.shift())==null||xe()}else if(ae.data.type==="partial"){const we=ae.data.seq??0,be=ae.data.text??"",Ue=performance.now()-N;y=!1,Ue>=hk?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ue),seq:we})):Ue>=uk&&(j=Math.min(j*2,dk),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ue),newIntervalMs:j,seq:we})),O||(O=!0,Ue>AP&&j<500&&(j=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ue),newIntervalMs:500})));const et=we!==S||we<=E;if(!i&&!et&&be){const ut=J(be);ut&&((Ne=n.onPartial)==null||Ne.call(n,ut),U===0&&(U=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-_)})))}le()}else if(ae.data.type==="partial-error"){const we=performance.now()-N;y=!1,we>=hk?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ae.data.seq})):we>=uk&&(j=Math.min(j*2,dk),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:j,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),le()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(me=c.shift())==null||me()):ae.data.type==="status"?(i||(re=n.onModelStatus)==null||re.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(qa=!0,cs=!1)):ae.data.type==="progress"&&(i||(te=n.onProgress)==null||te.call(n,ae.data.pct))};e.addEventListener("message",Y);const ce=ae=>{var xe,Ne;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(xe=n.onStatusChange)==null||xe.call(n,"restarting");c.length;)(Ne=c.shift())==null||Ne();if(p.clear(),Q(),y=!1,ae.respawned){try{e.removeEventListener("message",Y)}catch{}e=Rb(),e.addEventListener("message",Y)}}};return __.add(ce),{start:async()=>{if(!i){if(Pp){n.onError("Speech recognition disabled — please reload the app.");return}!qa&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:qa,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,xe=n.inputDeviceId||null,Ne={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};xe&&(Ne.deviceId={exact:xe}),ht.info("speech","getUserMedia",{hasDeviceId:!!xe,deviceIdPrefix:xe?xe.slice(0,8):null});const me=await navigator.mediaDevices.getUserMedia({audio:Ne});s=me,a=new AudioContext;for(const re of me.getAudioTracks())re.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(re){ht.warn("speech","analyser init failed",{error:re instanceof Error?re.message:String(re)}),l=null,d=null}r=await TP.MicVAD.new({audioContext:a,getStream:async()=>me,resumeStream:async()=>me,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:HT,negativeSpeechThreshold:WT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(re,te)=>{var we;i||((we=n.onFrame)==null||we.call(n,re),b&&(q(te),le()))},onSpeechStart:()=>{var re;i||(oe(),b=!0,_=performance.now(),(re=n.onSpeechStart)==null||re.call(n))},onSpeechEnd:re=>{var te;i||((te=n.onStatusChange)==null||te.call(n,"transcribing"),oe(),ee(re))},onVADMisfire:()=>{var re,te;i||((re=n.onStatusChange)==null||re.call(n,"idle"),oe(),(te=n.onMisfire)==null||te.call(n))}}),r.start()}catch(ae){const xe=ae instanceof Error?ae.message:"Microphone access denied",Ne=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:xe,stack:Ne}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(me=>me.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(xe)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(oe();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,xe)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:xe})}catch(Ne){ht.warn("speech","setVadThresholds failed",{error:Ne instanceof Error?Ne.message:String(Ne)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,oe(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}__.delete(ce),e.removeEventListener("message",Y)}}}let Tg=null;const S_=new Set,k_=new Set;function MP(){for(const n of S_)try{n()}catch{}}function C_(){for(const n of k_)try{n()}catch{}}function OP(n){return n.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function LP(n){if(!window.speechSynthesis)return;const e=OP(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Tg=performance.now(),MP()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Tg=null,C_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Tg=null,C_())},window.speechSynthesis.speak(i)}function YT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Tg=null,C_())}function XT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function zP(){return Tg}function BP(n){return S_.add(n),()=>{S_.delete(n)}}function FP(n){return k_.add(n),()=>{k_.delete(n)}}function GP(n){XT()&&(n.setVadThresholds(pk,fk),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=BP(()=>{n.setVadThresholds(pk,fk),ht.info("voice","tts.duck.on")}),i=FP(()=>{n.setVadThresholds(HT,WT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const UP=[{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 HP(n){const e=n.trim();return UP.find(i=>i.match.test(e))??null}const WP=4e4;let bu=null;function Rp(){bu&&clearTimeout(bu),bu=setTimeout(()=>{bu=null,kt.getState().stopRecording()},WP)}function xx(){bu&&(clearTimeout(bu),bu=null)}let ed=null,Jc=null;const VP=.04,qP=.3;let Ib=0,E_=0;function KP(n){Jc!==null&&cancelAnimationFrame(Jc);const e=()=>{if(ed===null||kt.getState().submitCountdownStartAt===null){Jc=null;return}const i=performance.now();if(i-E_<200&&Ib>qP){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Ib.toFixed(2),msIntoCountdown:Math.round(s)}),Vc(),Rp();return}const r=JT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>VP){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Vc(),Rp();return}}Jc=requestAnimationFrame(e)};Jc=requestAnimationFrame(e)}function gk(n){ed&&clearTimeout(ed);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),ed=setTimeout(()=>{var s;ed=null,kt.setState({submitCountdownStartAt:null});const r=vt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=An.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(An.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),An.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Rp()},e),KP(i)}function Vc(){Jc!==null&&(cancelAnimationFrame(Jc),Jc=null),ed&&(clearTimeout(ed),ed=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Wm=null;function JT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const bx=1e4;let jg=null;function yx(){jg&&(clearTimeout(jg),jg=null)}let ub=null,hb=null;function wx(){ub=null,hb&&(hb(),hb=null)}const YP=1500,XP=9e4;let _x=0,pb=null,T_=-1;function Sx(){pb&&(clearTimeout(pb),pb=null,T_=-1)}const JP=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=ji((n,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;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++_x,r=()=>{i===_x&&(Sx(),T_=i,pb=setTimeout(()=>{T_===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},XP))};r(),PP((s,a)=>{i===_x&&(s==="ready"?(Sx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Sx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===_x&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),Sx(),RP(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!_y()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=KT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Ib=l.isSpeech,E_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),xx(),Vc(),XT()){const c=zP(),p=c!==null?performance.now()-c:null;YT(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Rp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Rp();const c=l.trim();if(!c||JP.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Wm){Wm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=vt.getState().tabs.find(_=>_.id===i))==null?void 0:b.status)==="dormant"){An.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&gk(i);const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}const m=HP(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vc();const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&gk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Vc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,xx(),xr==null||xr.destroy(),xr=null,Wm=null,Re.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Wm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Rp(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=GP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Re.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(xx(),Vc(),Ib=0,E_=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Wm=null),e().hotkeyState==="stopping"&&(yx(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;xx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await nv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>J$);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Vc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=Mb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),yx(),jg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:bx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},bx),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),wx(),ub={tabId:a,source:r,mode:s},hb=kt.subscribe((p,m)=>{if(ub&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=ub;if(wx(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){wx(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),yx(),jg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:bx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},bx),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(wx(),Vc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(yx(),n({hotkeyState:"destroyed"}))}})),ZP=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Mb=n=>_y()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}const QP=6e4,eR=5e3,Ng=ji(()=>({data:null,refreshing:!1}));let vk=!1,fb=null,xk=null,bk=!1;async function X0(){Ng.setState({refreshing:!0});let n=QP;try{const e=await B0(window.api.billing.fetch(),eR,"billing.fetch");Ng.setState({data:e,refreshing:!1}),e.kind==="transient"?n=xk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),xk=e.kind}catch(e){if(Ng.setState({refreshing:!1}),!bk){bk=!0;const i=e instanceof Error?e.message:String(e);Re.warn(`Billing usage fetch failed: ${i}`)}}fb=setTimeout(X0,n)}function tR(){vk||(vk=!0,X0())}function ZT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function nR(){fb!==null&&(clearTimeout(fb),fb=null),X0()}function rv(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const kx=new Map,iR=3e4;function J0(n){const[e,i]=R.useState(()=>{var r;return n?((r=kx.get(n))==null?void 0:r.value)??null:null});return R.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=kx.get(n);if(a&&Date.now()-a.ts<iR){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;kx.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;kx.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function rR(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const j_="sm.almanac.sidebarWidth",QT=180,ej=480,N_=252;function sR(){try{const n=parseInt(localStorage.getItem(j_)??"",10);if(Number.isFinite(n))return Math.min(ej,Math.max(QT,n))}catch{}return N_}const oR=52,tj="sm.almanac.sidebarCollapsed";function aR(){try{return localStorage.getItem(tj)==="1"}catch{}return!1}const nj="sm.almanac.collapsedGroups";function lR(){try{const n=localStorage.getItem(nj);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function cR(){const n=vt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function dR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=R.useState(()=>lR()),a=R.useCallback(P=>{s(I=>{const O=new Set(I);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(nj,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=R.useState(()=>aR()),c=R.useCallback(()=>{l(P=>{const I=!P;try{localStorage.setItem(tj,I?"1":"0")}catch{}return I})},[]),p=vt(P=>P.tabs),m=vt(P=>P.activeTabId),f=p.find(P=>P.id===m)??null,b=cR(),_=mn(P=>P.navFace),y=oP(_),k=y.filter(P=>P.group==="Workspace"),x=y.filter(P=>P.group==="Configure"),w=rR(y),[S,E]=R.useState(()=>sR()),j=R.useRef(S);j.current=S;const N=R.useCallback(P=>{P.preventDefault();const I=P.clientX,O=j.current;let U=O;const B=Z=>{U=Math.min(ej,Math.max(QT,O+(Z.clientX-I))),E(U)},J=()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",J),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(j_,String(U))}catch{}};window.addEventListener("pointermove",B),window.addEventListener("pointerup",J),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),A=R.useCallback(()=>{E(N_);try{localStorage.setItem(j_,String(N_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?oR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(uR,{tab:f,navFace:_,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(hw,{label:"Workspace",desc:ow.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(yk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(hw,{label:"Configure",desc:ow.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(yk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(hw,{label:"Tools",desc:ow.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(hR,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(pR,{rail:d,navFace:_}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:A,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 uR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=J0((n==null?void 0:n.cwd)??null);return r?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:i,"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:o.jsx(an,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(an,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),o.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function hw({label:n,desc:e,collapsed:i,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!i,title:i?`Expand ${n}`:`Collapse ${n}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&o.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 yk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(an,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&o.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 hR({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"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&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(an,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function pR({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=vt(c=>c.tabs),s=vt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=R.useState(null);return R.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return ET(a.presetId).then(p=>{c||l((p==null?void 0:p.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"})}):o.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:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${rv(d)}`:"Claude Code"})]})}function fR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function mR(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const mb=ji((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:mR(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await nv(async()=>{const{toast:f}=await Promise.resolve().then(()=>DT);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],p=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const _ of["command","file_path","pattern","url","query","subagent_type","description"])f&&_ in f&&(b[_]=f[_]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const _=m.input,y=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(_==null?void 0:_.file_path)=="string"?_.file_path:void 0,x=typeof(_==null?void 0:_.command)=="string"?_.command:void 0,w=k?k.split("/").pop()??k:x?p(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),y&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${p(k.split("/").pop()??k,34)}`,target:k,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,_=m.output_tokens??m.outputTokens??0,y=f+b+_;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+_,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(y/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(y/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=fR(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function gR(n){const e=mb(s=>s.subscribe),i=mb(s=>s.unsubscribe),r=mb(s=>n?s.tabs[n.id]:void 0);return R.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function vR({onNavigate:n}){const e=vt(E=>E.tabs),i=vt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=gR(r),a=(s==null?void 0:s.lastEventAt)??0,d=Ng(E=>E.data),l=to(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),c=J0((r==null?void 0:r.cwd)??null),[,p]=R.useState(0);R.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=R.useState(!1),_=R.useRef(null);R.useEffect(()=>{if(!f)return;const E=j=>{_.current&&!_.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),R.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const y=ZT(d),k=(y==null?void 0:y.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?yR(Date.now()-a):"—";return o.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:[o.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(xR,{ref:_,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.55.0"]})]})}const xR=R.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",i?"▾":"▴"]})]}),i&&o.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 z-50","data-testid":"footer-todos-popover",children:o.jsx("ul",{className:"space-y-0.5",children:e.map((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(bR,{status:d.status}),o.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},l))})})]})});function bR({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function yR(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function wR({onClose:n,onSent:e}){const i=vt(P=>P.tabs),[r,s]=R.useState(""),[a,d]=R.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=R.useState(!1),[p,m]=R.useState({}),f=R.useRef(null),b=R.useRef(e);R.useEffect(()=>{b.current=e},[e]),R.useEffect(()=>{d(P=>{const I={};for(const O of i)I[O.id]=P[O.id]??!0;return I})},[i]),R.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(I=>{m(O=>I.tabId in O?{...O,[I.tabId]:"skipped"}:O)}),[]),R.useEffect(()=>{if(Object.keys(p).length===0)return;const P=Object.values(p).filter(O=>O==="sent").length,I=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(I)},[p]);const _=i.filter(P=>a[P.id]).map(P=>P.id),y=_.length,k=Object.keys(p).length>0,x=r.length>0&&y>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=vt.getState().tabs,I=new Set(P.map(U=>U.id)),O={};for(const U of _)I.has(U)?(window.api.pty.write({tabId:U,data:r+"\r"}),O[U]="sent"):O[U]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},E=i.length>0&&i.every(P=>a[P.id]),j=()=>{const P=!E;d(Object.fromEntries(i.map(I=>[I.id,P])))},N=Object.values(p).some(P=>P==="skipped"),A=k?N?"Sent (some skipped)":"Sent":`Send to ${y} tab${y===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:P=>s(P.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"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:E,onChange:j,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",y,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[P.id],onChange:I=>d(O=>({...O,[P.id]:I.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),p[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:w,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:A})]})]})}function _R({tabId:n,cwd:e,onClose:i}){const r=Eg(y=>y.watchersForTab(n)),s=Eg(y=>y.add),a=Eg(y=>y.remove),d=R.useRef(null),[l,c]=R.useState(""),[p,m]=R.useState(""),[f,b]=R.useState(!1);R.useEffect(()=>{const y=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),R.useEffect(()=>{const y=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[i]);const _=async()=>{const y=p.trim();if(!y||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:y,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,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:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:i,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:y=>c(y.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"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:p,onChange:y=>m(y.target.value),onKeyDown:y=>{y.key==="Enter"&&_()},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"}),o.jsx("button",{onClick:_,disabled:!p.trim()||f,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"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(y=>{const k=y.lines[y.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:y.label}),o.jsxs("span",{className:"text-fg-faint",children:[y.lineCount," line",y.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(y.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${y.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:y.command,children:y.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},y.watcherId)})})]})}/**
|
|
2901
|
+
*/var ok;function kP(){return ok||(ok=1,(function(n,e){var i=(()=>{var r=Object.defineProperty,s=Object.getOwnPropertyDescriptor,a=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,l=(se=>typeof Eo<"u"?Eo:typeof Proxy<"u"?new Proxy(se,{get:(fe,_e)=>(typeof Eo<"u"?Eo:fe)[_e]}):se)(function(se){if(typeof Eo<"u")return Eo.apply(this,arguments);throw Error('Dynamic require of "'+se+'" is not supported')}),c=(se,fe)=>()=>(se&&(fe=se(se=0)),fe),p=(se,fe)=>{for(var _e in fe)r(se,_e,{get:fe[_e],enumerable:!0})},m=(se,fe,_e,De)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ee of a(fe))!d.call(se,Ee)&&Ee!==_e&&r(se,Ee,{get:()=>fe[Ee],enumerable:!(De=s(fe,Ee))||De.enumerable});return se},f=se=>m(r({},"__esModule",{value:!0}),se),b,_,y,k,x,w=c(()=>{b=new Map,_=[],y=(se,fe,_e)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let De=b.get(se);if(De===void 0)b.set(se,{backend:fe,priority:_e});else{if(De.priority>_e)return;if(De.priority===_e&&De.backend!==fe)throw new Error(`cannot register backend "${se}" using priority ${_e}`)}if(_e>=0){let Ee=_.indexOf(se);Ee!==-1&&_.splice(Ee,1);for(let Be=0;Be<_.length;Be++)if(b.get(_[Be]).priority<=_e){_.splice(Be,0,se);return}_.push(se)}return}throw new TypeError("not a valid backend")},k=async se=>{let fe=b.get(se);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let _e=!!fe.initPromise;try{return _e||(fe.initPromise=fe.backend.init(se)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(De){return _e||(fe.error=`${De}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},x=async se=>{let fe=se.executionProviders||[],_e=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),De=_e.length===0?_:_e,Ee,Be=[],$e=new Set;for(let Fe of De){let tt=await k(Fe);typeof tt=="string"?Be.push({name:Fe,err:tt}):(Ee||(Ee=tt),Ee===tt&&$e.add(Fe))}if(!Ee)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:tt}of Be)_e.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${tt}`);let Pe=fe.filter(Fe=>$e.has(typeof Fe=="string"?Fe:Fe.name));return[Ee,new Proxy(se,{get:(Fe,tt)=>tt==="executionProviders"?Pe:Reflect.get(Fe,tt)})]}}),S=c(()=>{w()}),E,j=c(()=>{E="1.26.0"}),N,A,P=c(()=>{j(),N="warning",A={wasm:{},webgl:{},webgpu:{},versions:{common:E},set logLevel(se){if(se!==void 0){if(typeof se!="string"||["verbose","info","warning","error","fatal"].indexOf(se)===-1)throw new Error(`Unsupported logging level: ${se}`);N=se}},get logLevel(){return N}},Object.defineProperty(A,"logLevel",{enumerable:!0})}),I,O=c(()=>{P(),I=A}),U,B,J=c(()=>{U=(se,fe)=>{let _e=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_e.width=se.dims[3],_e.height=se.dims[2];let De=_e.getContext("2d");if(De!=null){let Ee,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=se.dims[2],Be=se.dims[3]):(Ee=se.dims[3],Be=se.dims[2]);let $e=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Pe=fe==null?void 0:fe.norm,Fe,tt;Pe===void 0||Pe.mean===void 0?Fe=[255,255,255,255]:typeof Pe.mean=="number"?Fe=[Pe.mean,Pe.mean,Pe.mean,Pe.mean]:(Fe=[Pe.mean[0],Pe.mean[1],Pe.mean[2],0],Pe.mean[3]!==void 0&&(Fe[3]=Pe.mean[3])),Pe===void 0||Pe.bias===void 0?tt=[0,0,0,0]:typeof Pe.bias=="number"?tt=[Pe.bias,Pe.bias,Pe.bias,Pe.bias]:(tt=[Pe.bias[0],Pe.bias[1],Pe.bias[2],0],Pe.bias[3]!==void 0&&(tt[3]=Pe.bias[3]));let st=Be*Ee,nt=0,Xe=st,$t=st*2,ze=-1;$e==="RGBA"?(nt=0,Xe=st,$t=st*2,ze=st*3):$e==="RGB"?(nt=0,Xe=st,$t=st*2):$e==="RBG"&&(nt=0,$t=st,Xe=st*2);for(let dt=0;dt<Be;dt++)for(let Rn=0;Rn<Ee;Rn++){let en=(se.data[nt++]-tt[0])*Fe[0],tn=(se.data[Xe++]-tt[1])*Fe[1],In=(se.data[$t++]-tt[2])*Fe[2],Bt=ze===-1?255:(se.data[ze++]-tt[3])*Fe[3];De.fillStyle="rgba("+en+","+tn+","+In+","+Bt+")",De.fillRect(Rn,dt,1,1)}if("toDataURL"in _e)return _e.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},B=(se,fe)=>{let _e=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),De;if(_e!=null){let Ee,Be,$e;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ee=se.dims[2],Be=se.dims[1],$e=se.dims[3]):(Ee=se.dims[3],Be=se.dims[2],$e=se.dims[1]);let Pe=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,tt,st;Fe===void 0||Fe.mean===void 0?tt=[255,255,255,255]:typeof Fe.mean=="number"?tt=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(tt=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(tt[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?st=[0,0,0,0]:typeof Fe.bias=="number"?st=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(st=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(st[3]=Fe.bias[3]));let nt=Be*Ee;if(fe!==void 0&&(fe.format!==void 0&&$e===4&&fe.format!=="RGBA"||$e===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,$t=0,ze=1,dt=2,Rn=3,en=0,tn=nt,In=nt*2,Bt=-1;Pe==="RGBA"?(en=0,tn=nt,In=nt*2,Bt=nt*3):Pe==="RGB"?(en=0,tn=nt,In=nt*2):Pe==="RBG"&&(en=0,In=nt,tn=nt*2),De=_e.createImageData(Ee,Be);for(let Bn=0;Bn<Be*Ee;$t+=Xe,ze+=Xe,dt+=Xe,Rn+=Xe,Bn++)De.data[$t]=(se.data[en++]-st[0])*tt[0],De.data[ze]=(se.data[tn++]-st[1])*tt[1],De.data[dt]=(se.data[In++]-st[2])*tt[2],De.data[Rn]=Bt===-1?255:(se.data[Bt++]-st[3])*tt[3]}else throw new Error("Can not access image data");return De}}),Z,W,q,Q,oe,le,H=c(()=>{we(),Z=(se,fe)=>{if(se===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:_e,width:De}=fe,Ee=fe.norm??{mean:255,bias:0},Be,$e;typeof Ee.mean=="number"?Be=[Ee.mean,Ee.mean,Ee.mean,Ee.mean]:Be=[Ee.mean[0],Ee.mean[1],Ee.mean[2],Ee.mean[3]??255],typeof Ee.bias=="number"?$e=[Ee.bias,Ee.bias,Ee.bias,Ee.bias]:$e=[Ee.bias[0],Ee.bias[1],Ee.bias[2],Ee.bias[3]??0];let Pe=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",tt=_e*De,st=Fe==="RGBA"?new Float32Array(tt*4):new Float32Array(tt*3),nt=4,Xe=0,$t=1,ze=2,dt=3,Rn=0,en=tt,tn=tt*2,In=-1;Pe==="RGB"&&(nt=3,Xe=0,$t=1,ze=2,dt=-1),Fe==="RGBA"?In=tt*3:Fe==="RBG"?(Rn=0,tn=tt,en=tt*2):Fe==="BGR"&&(tn=0,en=tt,Rn=tt*2);for(let Bt=0;Bt<tt;Bt++,Xe+=nt,ze+=nt,$t+=nt,dt+=nt)st[Rn++]=(se[Xe]+$e[0])/Be[0],st[en++]=(se[$t]+$e[1])/Be[1],st[tn++]=(se[ze]+$e[2])/Be[2],In!==-1&&dt!==-1&&(st[In++]=(se[dt]+$e[3])/Be[3]);return Fe==="RGBA"?new te("float32",st,[1,4,_e,De]):new te("float32",st,[1,3,_e,De])},W=async(se,fe)=>{let _e=typeof HTMLImageElement<"u"&&se instanceof HTMLImageElement,De=typeof ImageData<"u"&&se instanceof ImageData,Ee=typeof ImageBitmap<"u"&&se instanceof ImageBitmap,Be=typeof se=="string",$e,Pe=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},tt=st=>typeof HTMLCanvasElement<"u"&&st instanceof HTMLCanvasElement||st instanceof OffscreenCanvas?st.getContext("2d"):null;if(_e){let st=Fe();st.width=se.width,st.height=se.height;let nt=tt(st);if(nt!=null){let Xe=se.height,$t=se.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,$t=fe.resizedWidth),fe!==void 0){if(Pe=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t}else Pe.tensorFormat="RGBA",Pe.height=Xe,Pe.width=$t;nt.drawImage(se,0,0),$e=nt.getImageData(0,0,$t,Xe).data}else throw new Error("Can not access image data")}else if(De){let st,nt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(st=fe.resizedHeight,nt=fe.resizedWidth):(st=se.height,nt=se.width),fe!==void 0&&(Pe=fe),Pe.format="RGBA",Pe.height=st,Pe.width=nt,fe!==void 0){let Xe=Fe();Xe.width=nt,Xe.height=st;let $t=tt(Xe);if($t!=null)$t.putImageData(se,0,0),$e=$t.getImageData(0,0,nt,st).data;else throw new Error("Can not access image data")}else $e=se.data}else if(Ee){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let st=Fe();st.width=se.width,st.height=se.height;let nt=tt(st);if(nt!=null){let Xe=se.height,$t=se.width;return nt.drawImage(se,0,0,$t,Xe),$e=nt.getImageData(0,0,$t,Xe).data,Pe.height=Xe,Pe.width=$t,Z($e,Pe)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((st,nt)=>{let Xe=Fe(),$t=tt(Xe);if(!se||!$t)return nt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=se,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,$t.drawImage(ze,0,0,Xe.width,Xe.height);let dt=$t.getImageData(0,0,Xe.width,Xe.height);Pe.height=Xe.height,Pe.width=Xe.width,st(Z(dt.data,Pe))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if($e!==void 0)return Z($e,Pe);throw new Error("Input data provided is not supported - aborted tensor creation")},q=(se,fe)=>{let{width:_e,height:De,download:Ee,dispose:Be}=fe,$e=[1,De,_e,4];return new te({location:"texture",type:"float32",texture:se,dims:$e,download:Ee,dispose:Be})},Q=(se,fe)=>{let{dataType:_e,dims:De,download:Ee,dispose:Be}=fe;return new te({location:"gpu-buffer",type:_e??"float32",gpuBuffer:se,dims:De,download:Ee,dispose:Be})},oe=(se,fe)=>{let{dataType:_e,dims:De,download:Ee,dispose:Be}=fe;return new te({location:"ml-tensor",type:_e??"float32",mlTensor:se,dims:De,download:Ee,dispose:Be})},le=(se,fe,_e)=>new te({location:"cpu-pinned",type:se,data:fe,dims:_e??[fe.length]})}),ee,Y,ce,ae,xe=c(()=>{ee=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Y=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ce=!1,ae=()=>{if(!ce){ce=!0;let se=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,_e=globalThis.Float16Array,De=typeof _e<"u"&&_e.from;se&&(ee.set("int64",BigInt64Array),Y.set(BigInt64Array,"int64")),fe&&(ee.set("uint64",BigUint64Array),Y.set(BigUint64Array,"uint64")),De?(ee.set("float16",_e),Y.set(_e,"float16")):ee.set("float16",Uint16Array)}}}),Ne,me,re=c(()=>{we(),Ne=se=>{let fe=1;for(let _e=0;_e<se.length;_e++){let De=se[_e];if(typeof De!="number"||!Number.isSafeInteger(De))throw new TypeError(`dims[${_e}] must be an integer, got: ${De}`);if(De<0)throw new RangeError(`dims[${_e}] must be a non-negative integer, got: ${De}`);fe*=De}return fe},me=(se,fe)=>{switch(se.location){case"cpu":return new te(se.type,se.data,fe);case"cpu-pinned":return new te({location:"cpu-pinned",data:se.data,type:se.type,dims:fe});case"texture":return new te({location:"texture",texture:se.texture,type:se.type,dims:fe});case"gpu-buffer":return new te({location:"gpu-buffer",gpuBuffer:se.gpuBuffer,type:se.type,dims:fe});case"ml-tensor":return new te({location:"ml-tensor",mlTensor:se.mlTensor,type:se.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${se.location} is not supported`)}}}),te,we=c(()=>{J(),H(),xe(),re(),te=class{constructor(se,fe,_e){ae();let De,Ee;if(typeof se=="object"&&"location"in se)switch(this.dataLocation=se.location,De=se.type,Ee=se.dims,se.location){case"cpu-pinned":{let $e=ee.get(De);if(!$e)throw new TypeError(`unsupported type "${De}" to create tensor from pinned buffer`);if(!(se.data instanceof $e))throw new TypeError(`buffer should be of type ${$e.name}`);this.cpuData=se.data;break}case"texture":{if(De!=="float32")throw new TypeError(`unsupported type "${De}" to create tensor from texture`);this.gpuTextureData=se.texture,this.downloader=se.download,this.disposer=se.dispose;break}case"gpu-buffer":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from gpu buffer`);this.gpuBufferData=se.gpuBuffer,this.downloader=se.download,this.disposer=se.dispose;break}case"ml-tensor":{if(De!=="float32"&&De!=="float16"&&De!=="int32"&&De!=="int64"&&De!=="uint32"&&De!=="uint64"&&De!=="int8"&&De!=="uint8"&&De!=="bool"&&De!=="uint4"&&De!=="int4")throw new TypeError(`unsupported type "${De}" to create tensor from MLTensor`);this.mlTensorData=se.mlTensor,this.downloader=se.download,this.disposer=se.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $e,Pe;if(typeof se=="string")if(De=se,Pe=_e,se==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");$e=fe}else{let Fe=ee.get(se);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${se}.`);if(Array.isArray(fe)){if(se==="float16"&&Fe===Uint16Array||se==="uint4"||se==="int4")throw new TypeError(`Creating a ${se} tensor from number array is not supported. Please use ${Fe.name} as data.`);se==="uint64"||se==="int64"?$e=Fe.from(fe,BigInt):$e=Fe.from(fe)}else if(fe instanceof Fe)$e=fe;else if(fe instanceof Uint8ClampedArray)if(se==="uint8")$e=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(se==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)$e=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${De} tensor's data must be type of ${Fe}`)}else if(Pe=fe,Array.isArray(se)){if(se.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof se[0];if(Fe==="string")De="string",$e=se;else if(Fe==="boolean")De="bool",$e=Uint8Array.from(se);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(se instanceof Uint8ClampedArray)De="uint8",$e=Uint8Array.from(se);else{let Fe=Y.get(se.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${se.constructor}.`);De=Fe,$e=se}if(Pe===void 0)Pe=[$e.length];else if(!Array.isArray(Pe))throw new TypeError("A tensor's dims must be a number array");Ee=Pe,this.cpuData=$e,this.dataLocation="cpu"}let Be=Ne(Ee);if(this.cpuData&&Be!==this.cpuData.length&&!((De==="uint4"||De==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=De,this.dims=Ee,this.size=Be}static async fromImage(se,fe){return W(se,fe)}static fromTexture(se,fe){return q(se,fe)}static fromGpuBuffer(se,fe){return Q(se,fe)}static fromMLTensor(se,fe){return oe(se,fe)}static fromPinnedBuffer(se,fe,_e){return le(se,fe,_e)}toDataURL(se){return U(this,se)}toImageData(se){return B(this,se)}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(se){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 fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,se&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}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(se){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return me(this,se)}}}),be,Ue=c(()=>{we(),be=te}),et,ut,zt,pt,it,ot,Dt=c(()=>{P(),et=(se,fe)=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeStamp(`${se}::ORT::${fe}`)},ut=(se,fe)=>{var Ee;let _e=((Ee=new Error().stack)==null?void 0:Ee.split(/\r\n|\r|\n/g))||[],De=!1;for(let Be=0;Be<_e.length;Be++){if(De&&!_e[Be].includes("TRACE_FUNC")){let $e=`FUNC_${se}::${_e[Be].trim().split(" ")[1]}`;fe&&($e+=`::${fe}`),et("CPU",$e);return}_e[Be].includes("TRACE_FUNC")&&(De=!0)}},zt=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||ut("BEGIN",se)},pt=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||ut("END",se)},it=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.time(`ORT::${se}`)},ot=se=>{(typeof A.trace>"u"?!A.wasm.trace:!A.trace)||console.timeEnd(`ORT::${se}`)}}),sn,gn=c(()=>{w(),Ue(),Dt(),sn=class GT{constructor(fe){this.handler=fe}async run(fe,_e,De){zt(),it("InferenceSession.run");let Ee={},Be={};if(typeof fe!="object"||fe===null||fe instanceof be||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let $e=!0;if(typeof _e=="object"){if(_e===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_e instanceof be)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_e)){if(_e.length===0)throw new TypeError("'fetches' cannot be an empty array.");$e=!1;for(let tt of _e){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}.`);Ee[tt]=null}if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else{let tt=!1,st=Object.getOwnPropertyNames(_e);for(let nt of this.outputNames)if(st.indexOf(nt)!==-1){let Xe=_e[nt];(Xe===null||Xe instanceof be)&&(tt=!0,$e=!1,Ee[nt]=Xe)}if(tt){if(typeof De=="object"&&De!==null)Be=De;else if(typeof De<"u")throw new TypeError("'options' must be an object.")}else Be=_e}}else if(typeof _e<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let tt of this.inputNames)if(typeof fe[tt]>"u")throw new Error(`input '${tt}' is missing in 'feeds'.`);if($e)for(let tt of this.outputNames)Ee[tt]=null;let Pe=await this.handler.run(fe,Ee,Be),Fe={};for(let tt in Pe)if(Object.hasOwnProperty.call(Pe,tt)){let st=Pe[tt];st instanceof be?Fe[tt]=st:Fe[tt]=new be(st.type,st.data,st.dims)}return ot("InferenceSession.run"),pt(),Fe}async release(){return this.handler.dispose()}static async create(fe,_e,De,Ee){zt(),it("InferenceSession.create");let Be,$e={};if(typeof fe=="string"){if(Be=fe,typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let st=fe,nt=0,Xe=fe.byteLength;if(typeof _e=="object"&&_e!==null)$e=_e;else if(typeof _e=="number"){if(nt=_e,!Number.isSafeInteger(nt))throw new RangeError("'byteOffset' must be an integer.");if(nt<0||nt>=st.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${st.byteLength}).`);if(Xe=fe.byteLength-nt,typeof De=="number"){if(Xe=De,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||nt+Xe>st.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${st.byteLength-nt}].`);if(typeof Ee=="object"&&Ee!==null)$e=Ee;else if(typeof Ee<"u")throw new TypeError("'options' must be an object.")}else if(typeof De<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof _e<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(st,nt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Pe,Fe]=await x($e),tt=await Pe.createInferenceSessionHandler(Be,Fe);return ot("InferenceSession.create"),pt(),new GT(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}}}),Je,Ct=c(()=>{gn(),Je=sn}),xt=c(()=>{}),pn=c(()=>{}),$n=c(()=>{}),er=c(()=>{}),yr={};p(yr,{InferenceSession:()=>Je,TRACE:()=>et,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>be,env:()=>I,registerBackend:()=>y});var vn=c(()=>{S(),O(),Ct(),Ue(),xt(),pn(),Dt(),$n(),er()}),Hi=c(()=>{}),Xn={};p(Xn,{default:()=>Rs});var di,xn,Rs,tl=c(()=>{var se;Se(),ir(),nr(),di="ort-wasm-proxy-worker",xn=((se=globalThis.self)==null?void 0:se.name)===di,xn&&(self.onmessage=fe=>{let{type:_e,in:De}=fe.data;try{switch(_e){case"init-wasm":gs(De.wasm).then(()=>{ga(De).then(()=>{postMessage({type:_e})},Ee=>{postMessage({type:_e,err:Ee})})},Ee=>{postMessage({type:_e,err:Ee})});break;case"init-ep":{let{epName:Ee,env:Be}=De;Fs(Be,Ee).then(()=>{postMessage({type:_e})},$e=>{postMessage({type:_e,err:$e})});break}case"copy-from":{let{buffer:Ee}=De,Be=dn(Ee);postMessage({type:_e,out:Be});break}case"create":{let{model:Ee,options:Be}=De;Cr(Ee,Be).then($e=>{postMessage({type:_e,out:$e})},$e=>{postMessage({type:_e,err:$e})});break}case"release":ao(De),postMessage({type:_e});break;case"run":{let{sessionId:Ee,inputIndices:Be,inputs:$e,outputIndices:Pe,options:Fe}=De;Ye(Ee,Be,$e,Pe,new Array(Pe.length).fill(null),Fe).then(tt=>{tt.some(st=>st[3]!=="cpu")?postMessage({type:_e,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:_e,out:tt},mt([...$e,...tt]))},tt=>{postMessage({type:_e,err:tt})});break}case"end-profiling":sr(De),postMessage({type:_e});break;default:}}catch(Ee){postMessage({type:_e,err:Ee})}}),Rs=xn?null:fe=>new Worker(fe??kn,{type:"classic",name:di})}),fa,Is,kn,tr,ui,Ms,qr,wr,ro,Os,Ls,Kr,Wi,nr=c(()=>{Hi(),fa=typeof location>"u"?void 0:location.origin,Is=()=>{var se,fe;return typeof document<"u"?(se=document.currentScript)==null?void 0:se.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},kn=Is(),tr=()=>{if(kn&&!kn.startsWith("blob:"))return kn.substring(0,kn.lastIndexOf("/")+1)},ui=(se,fe)=>{try{let _e=fe??kn;return(_e?new URL(se,_e):new URL(se)).origin===fa}catch{return!1}},Ms=(se,fe)=>{let _e=fe??kn;try{return(_e?new URL(se,_e):new URL(se)).href}catch{return}},qr=(se,fe)=>`${fe??"./"}${se}`,wr=async se=>{let fe=await(await fetch(se,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},ro=async se=>(await import(se)).default,Os=(tl(),f(Xn)).default,Ls=async()=>{if(!kn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(ui(kn))return[void 0,Os()];let se=await wr(kn);return[se,Os(se)]},Kr=void 0,Wi=async(se,fe,_e,De)=>{let Ee=Kr&&!(se||fe);if(Ee)if(kn)Ee=ui(kn)||De&&!_e;else if(De&&!_e)Ee=!0;else throw new Error("cannot determine the script source URL.");if(Ee)return[void 0,Kr];{let Be="ort-wasm-simd-threaded.mjs",$e=se??Ms(Be,fe),Pe=_e&&$e&&!ui($e,fe),Fe=Pe?await wr($e):$e??qr(Be,fe);return[Pe?Fe:void 0,await ro(Fe)]}}}),ps,Vi,_r,Br,Ao,fs,ms,gs,Gt,ir=c(()=>{nr(),Vi=!1,_r=!1,Br=!1,Ao=()=>{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}},fs=()=>{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}},ms=()=>{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}},gs=async se=>{if(Vi)return Promise.resolve();if(_r)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(Br)throw new Error("previous call to 'initializeWebAssembly()' failed.");_r=!0;let fe=se.initTimeout,_e=se.numThreads;if(se.simd!==!1){if(se.simd==="relaxed"){if(!ms())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!fs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let De=Ao();_e>1&&!De&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+_e+", 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."),se.numThreads=_e=1);let Ee=se.wasmPaths,Be=typeof Ee=="string"?Ee:void 0,$e=Ee==null?void 0:Ee.mjs,Pe=($e==null?void 0:$e.href)??$e,Fe=Ee==null?void 0:Ee.wasm,tt=(Fe==null?void 0:Fe.href)??Fe,st=se.wasmBinary,[nt,Xe]=await Wi(Pe,Be,_e>1,!!st||!!tt),$t=!1,ze=[];if(fe>0&&ze.push(new Promise(dt=>{setTimeout(()=>{$t=!0,dt()},fe)})),ze.push(new Promise((dt,Rn)=>{let en={numThreads:_e};if(st)en.wasmBinary=st,en.locateFile=tn=>tn;else if(tt||Be)en.locateFile=tn=>tt??Be+tn;else if(Pe&&Pe.indexOf("blob:")!==0)en.locateFile=tn=>new URL(tn,Pe).href;else if(nt){let tn=tr();tn&&(en.locateFile=In=>tn+In)}Xe(en).then(tn=>{_r=!1,Vi=!0,ps=tn,dt(),nt&&URL.revokeObjectURL(nt)},tn=>{_r=!1,Br=!0,Rn(tn)})})),await Promise.race(ze),$t)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},Gt=()=>{if(Vi&&ps)return ps;throw new Error("WebAssembly is not initialized yet.")}}),Jn,jn,Et,so=c(()=>{ir(),Jn=(se,fe)=>{let _e=Gt(),De=_e.lengthBytesUTF8(se)+1,Ee=_e._malloc(De);return _e.stringToUTF8(se,Ee,De),fe.push(Ee),Ee},jn=(se,fe,_e,De)=>{if(typeof se=="object"&&se!==null){if(_e.has(se))throw new Error("Circular reference in options");_e.add(se)}Object.entries(se).forEach(([Ee,Be])=>{let $e=fe?fe+Ee:Ee;if(typeof Be=="object")jn(Be,$e+".",_e,De);else if(typeof Be=="string"||typeof Be=="number")De($e,Be.toString());else if(typeof Be=="boolean")De($e,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Et=se=>{let fe=Gt(),_e=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetLastError(Ee,Ee+De);let Be=Number(fe.getValue(Ee,De===4?"i32":"i64")),$e=fe.getValue(Ee+De,"*"),Pe=$e?fe.UTF8ToString($e):"";throw new Error(`${se} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Pe}`)}finally{fe.stackRestore(_e)}}}),$o,nl=c(()=>{ir(),so(),$o=se=>{let fe=Gt(),_e=0,De=[],Ee=se||{};try{if((se==null?void 0:se.logSeverityLevel)===void 0)Ee.logSeverityLevel=2;else if(typeof se.logSeverityLevel!="number"||!Number.isInteger(se.logSeverityLevel)||se.logSeverityLevel<0||se.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${se.logSeverityLevel}`);if((se==null?void 0:se.logVerbosityLevel)===void 0)Ee.logVerbosityLevel=0;else if(typeof se.logVerbosityLevel!="number"||!Number.isInteger(se.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${se.logVerbosityLevel}`);(se==null?void 0:se.terminate)===void 0&&(Ee.terminate=!1);let Be=0;return(se==null?void 0:se.tag)!==void 0&&(Be=Jn(se.tag,De)),_e=fe._OrtCreateRunOptions(Ee.logSeverityLevel,Ee.logVerbosityLevel,!!Ee.terminate,Be),_e===0&&Et("Can't create run options."),(se==null?void 0:se.extra)!==void 0&&jn(se.extra,"",new WeakSet,($e,Pe)=>{let Fe=Jn($e,De),tt=Jn(Pe,De);fe._OrtAddRunConfigEntry(_e,Fe,tt)!==0&&Et(`Can't set a run config entry: ${$e} - ${Pe}.`)}),[_e,De]}catch(Be){throw _e!==0&&fe._OrtReleaseRunOptions(_e),De.forEach($e=>fe._free($e)),Be}}}),Po,Ro,ma,Li,il,rl,Nn=c(()=>{ir(),so(),Po=se=>{switch(se){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: ${se}`)}},Ro=se=>{switch(se){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${se}`)}},ma=se=>{se.extra||(se.extra={}),se.extra.session||(se.extra.session={});let fe=se.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),se.executionProviders&&se.executionProviders.some(_e=>(typeof _e=="string"?_e:_e.name)==="webgpu")&&(se.enableMemPattern=!1)},Li=(se,fe,_e,De)=>{let Ee=Jn(fe,De),Be=Jn(_e,De);Gt()._OrtAddSessionConfigEntry(se,Ee,Be)!==0&&Et(`Can't set a session config entry: ${fe} - ${_e}.`)},il=async(se,fe,_e)=>{let De=fe.executionProviders;for(let Ee of De){let Be=typeof Ee=="string"?Ee:Ee.name,$e=[];switch(Be){case"webnn":if(Be="WEBNN",Li(se,"session.disable_quant_qdq","1",_e),Li(se,"session.disable_qdq_constant_folding","1",_e),typeof Ee!="string"){let nt=Ee==null?void 0:Ee.deviceType;nt&&Li(se,"deviceType",nt,_e)}break;case"webgpu":if(Be="JS",typeof Ee!="string"){let nt=Ee;if(nt!=null&&nt.preferredLayout){if(nt.preferredLayout!=="NCHW"&&nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${nt.preferredLayout}`);Li(se,"preferredLayout",nt.preferredLayout,_e)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Pe=Jn(Be,_e),Fe=$e.length,tt=0,st=0;if(Fe>0){tt=Gt()._malloc(Fe*Gt().PTR_SIZE),_e.push(tt),st=Gt()._malloc(Fe*Gt().PTR_SIZE),_e.push(st);for(let nt=0;nt<Fe;nt++)Gt().setValue(tt+nt*Gt().PTR_SIZE,$e[nt][0],"*"),Gt().setValue(st+nt*Gt().PTR_SIZE,$e[nt][1],"*")}await Gt()._OrtAppendExecutionProvider(se,Pe,tt,st,Fe)!==0&&Et(`Can't append execution provider: ${Be}.`)}},rl=async se=>{let fe=Gt(),_e=0,De=[],Ee=se||{};ma(Ee);try{let Be=Po(Ee.graphOptimizationLevel??"all"),$e=Ro(Ee.executionMode??"sequential"),Pe=typeof Ee.logId=="string"?Jn(Ee.logId,De):0,Fe=Ee.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let tt=Ee.logVerbosityLevel??0;if(!Number.isInteger(tt)||tt<0||tt>4)throw new Error(`log verbosity level is not valid: ${tt}`);let st=typeof Ee.optimizedModelFilePath=="string"?Jn(Ee.optimizedModelFilePath,De):0;if(_e=fe._OrtCreateSessionOptions(Be,!!Ee.enableCpuMemArena,!!Ee.enableMemPattern,$e,!!Ee.enableProfiling,0,Pe,Fe,tt,st),_e===0&&Et("Can't create session options."),Ee.executionProviders&&await il(_e,Ee,De),Ee.enableGraphCapture!==void 0){if(typeof Ee.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ee.enableGraphCapture}`);Li(_e,"enableGraphCapture",Ee.enableGraphCapture.toString(),De)}if(Ee.freeDimensionOverrides)for(let[nt,Xe]of Object.entries(Ee.freeDimensionOverrides)){if(typeof nt!="string")throw new Error(`free dimension override name must be a string: ${nt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let $t=Jn(nt,De);fe._OrtAddFreeDimensionOverride(_e,$t,Xe)!==0&&Et(`Can't set a free dimension override: ${nt} - ${Xe}.`)}return Ee.extra!==void 0&&jn(Ee.extra,"",new WeakSet,(nt,Xe)=>{Li(_e,nt,Xe,De)}),[_e,De]}catch(Be){throw _e!==0&&fe._OrtReleaseSessionOptions(_e)!==0&&Et("Can't release session options."),De.forEach($e=>fe._free($e)),Be}}}),qi,ei,Ki,vs,oo,zs,Sr,Ni,Ut=c(()=>{qi=se=>{switch(se){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: ${se}`)}},ei=se=>{switch(se){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: ${se}`)}},Ki=(se,fe)=>{let _e=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][se],De=typeof fe=="number"?fe:fe.reduce((Ee,Be)=>Ee*Be,1);return _e>0?Math.ceil(De*_e):void 0},vs=se=>{switch(se){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: ${se}`)}},oo=se=>{switch(se){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: ${se}`)}},zs=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Sr=se=>se==="float32"||se==="float16"||se==="int32"||se==="int64"||se==="uint32"||se==="uint64"||se==="int8"||se==="uint8"||se==="bool"||se==="uint4"||se==="int4",Ni=se=>{switch(se){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: ${se}`)}}}),ti,Bs=c(()=>{Hi(),ti=async se=>{if(typeof se=="string"){let fe=await fetch(se);if(!fe.ok)throw new Error(`failed to load external data file: ${se}`);let _e=fe.headers.get("Content-Length"),De=_e?parseInt(_e,10):0;if(De<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${se}, no response body.`);let Ee=fe.body.getReader(),Be;try{Be=new ArrayBuffer(De)}catch(Pe){if(Pe instanceof RangeError){let Fe=Math.ceil(De/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Pe}let $e=0;for(;;){let{done:Pe,value:Fe}=await Ee.read();if(Pe)break;let tt=Fe.byteLength;new Uint8Array(Be,$e,tt).set(Fe),$e+=tt}return new Uint8Array(Be,0,De)}}else return se instanceof Blob?new Uint8Array(await se.arrayBuffer()):se instanceof Uint8Array?se:new Uint8Array(se)}}),kr,ga,Fs,rr,Yr,Gs,dn,Cr,ao,Fr,Ye,sr,mt,Se=c(()=>{vn(),nl(),Nn(),Ut(),ir(),so(),Bs(),kr=(se,fe)=>{Gt()._OrtInit(se,fe)!==0&&Et("Can't initialize onnxruntime.")},ga=async se=>{kr(se.wasm.numThreads,oo(se.logLevel))},Fs=async(se,fe)=>{var De,Ee;(Ee=(De=Gt()).asyncInit)==null||Ee.call(De);let _e=se.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(_e){if(typeof _e.limits!="object"||typeof _e.features!="object"||typeof _e.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=se.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let $e=se.webgpu.forceFallbackAdapter;if($e!==void 0&&typeof $e!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${$e}"`);if(_e=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:$e}),!_e)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},rr=new Map,Yr=se=>{let fe=Gt(),_e=fe.stackSave();try{let De=fe.PTR_SIZE,Ee=fe.stackAlloc(2*De);fe._OrtGetInputOutputCount(se,Ee,Ee+De)!==0&&Et("Can't get session input/output count.");let Be=De===4?"i32":"i64";return[Number(fe.getValue(Ee,Be)),Number(fe.getValue(Ee+De,Be))]}finally{fe.stackRestore(_e)}},Gs=(se,fe)=>{let _e=Gt(),De=_e.stackSave(),Ee=0;try{let Be=_e.PTR_SIZE,$e=_e.stackAlloc(2*Be);_e._OrtGetInputOutputMetadata(se,fe,$e,$e+Be)!==0&&Et("Can't get session input/output metadata.");let Pe=Number(_e.getValue($e,"*"));Ee=Number(_e.getValue($e+Be,"*"));let Fe=_e.HEAP32[Ee/4];if(Fe===0)return[Pe,0];let tt=_e.HEAPU32[Ee/4+1],st=[];for(let nt=0;nt<tt;nt++){let Xe=Number(_e.getValue(Ee+8+nt*Be,"*"));st.push(Xe!==0?_e.UTF8ToString(Xe):Number(_e.getValue(Ee+8+(nt+tt)*Be,"*")))}return[Pe,Fe,st]}finally{_e.stackRestore(De),Ee!==0&&_e._OrtFree(Ee)}},dn=se=>{let fe=Gt(),_e=fe._malloc(se.byteLength);if(_e===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${se.byteLength}.`);return fe.HEAPU8.set(se,_e),[_e,se.byteLength]},Cr=async(se,fe)=>{var st,nt,Xe;let _e,De,Ee=Gt();Array.isArray(se)?[_e,De]=se:se.buffer===Ee.HEAPU8.buffer?[_e,De]=[se.byteOffset,se.byteLength]:[_e,De]=dn(se);let Be=0,$e=0,Pe=[],Fe=[],tt=[];try{if([$e,Pe]=await rl(fe),(fe==null?void 0:fe.externalData)&&Ee.mountExternalData){let Bn=[];for(let fn of fe.externalData){let Di=typeof fn=="string"?fn:fn.path;Bn.push(ti(typeof fn=="string"?fn:fn.data).then(Yi=>{Ee.mountExternalData(Di,Yi)}))}await Promise.all(Bn)}for(let Bn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Bn=="string"?Bn:Bn.name)==="webnn"){if(Ee.shouldTransferToMLTensor=!1,typeof Bn!="string"){let fn=Bn,Di=fn==null?void 0:fn.context,Yi=fn==null?void 0:fn.gpuDevice,or=fn==null?void 0:fn.deviceType,ol=fn==null?void 0:fn.powerPreference;Di?Ee.currentContext=Di:Yi?Ee.currentContext=await Ee.webnnCreateMLContext(Yi):Ee.currentContext=await Ee.webnnCreateMLContext({deviceType:or,powerPreference:ol})}else Ee.currentContext=await Ee.webnnCreateMLContext();break}Be=await Ee._OrtCreateSession(_e,De,$e),(st=Ee.webgpuOnCreateSession)==null||st.call(Ee,Be),Be===0&&Et("Can't create a session."),(nt=Ee.jsepOnCreateSession)==null||nt.call(Ee),Ee.currentContext&&(Ee.webnnRegisterMLContext(Be,Ee.currentContext),Ee.currentContext=void 0,Ee.shouldTransferToMLTensor=!0);let[$t,ze]=Yr(Be),dt=!!(fe!=null&&fe.enableGraphCapture),Rn=[],en=[],tn=[],In=[],Bt=[];for(let Bn=0;Bn<$t;Bn++){let[fn,Di,Yi]=Gs(Be,Bn);fn===0&&Et("Can't get an input name."),Fe.push(fn);let or=Ee.UTF8ToString(fn);Rn.push(or),tn.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}for(let Bn=0;Bn<ze;Bn++){let[fn,Di,Yi]=Gs(Be,Bn+$t);fn===0&&Et("Can't get an output name."),tt.push(fn);let or=Ee.UTF8ToString(fn);en.push(or),In.push(Di===0?{name:or,isTensor:!1}:{name:or,isTensor:!0,type:ei(Di),shape:Yi})}return rr.set(Be,[Be,Fe,tt,null,dt,!1]),[Be,Rn,en,tn,In]}catch($t){throw Fe.forEach(ze=>Ee._OrtFree(ze)),tt.forEach(ze=>Ee._OrtFree(ze)),Be!==0&&Ee._OrtReleaseSession(Be)!==0&&Et("Can't release session."),$t}finally{Ee._free(_e),$e!==0&&Ee._OrtReleaseSessionOptions($e)!==0&&Et("Can't release session options."),Pe.forEach($t=>Ee._free($t)),(Xe=Ee.unmountExternalData)==null||Xe.call(Ee)}},ao=se=>{var Fe,tt,st;let fe=Gt(),_e=rr.get(se);if(!_e)throw new Error(`cannot release session. invalid session id: ${se}`);let[De,Ee,Be,$e,Pe]=_e;$e&&(Pe&&fe._OrtClearBoundOutputs($e.handle)!==0&&Et("Can't clear bound outputs."),fe._OrtReleaseBinding($e.handle)!==0&&Et("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,se),(tt=fe.webnnOnReleaseSession)==null||tt.call(fe,se),(st=fe.webgpuOnReleaseSession)==null||st.call(fe,se),Ee.forEach(nt=>fe._OrtFree(nt)),Be.forEach(nt=>fe._OrtFree(nt)),fe._OrtReleaseSession(De)!==0&&Et("Can't release session."),rr.delete(se)},Fr=async(se,fe,_e,De,Ee,Be,$e=!1)=>{if(!se){fe.push(0);return}let Pe=Gt(),Fe=Pe.PTR_SIZE,tt=se[0],st=se[1],nt=se[3],Xe=nt,$t,ze;if(tt==="string"&&(nt==="gpu-buffer"||nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if($e&&nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(nt==="gpu-buffer"){let en=se[2].gpuBuffer;ze=Ki(qi(tt),st);{let tn=Pe.jsepRegisterBuffer;if(!tn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');$t=tn(De,Be,en,ze)}}else if(nt==="ml-tensor"){let en=se[2].mlTensor;ze=Ki(qi(tt),st);let tn=Pe.webnnRegisterMLTensor;if(!tn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');$t=tn(De,en,qi(tt),st)}else{let en=se[2];if(Array.isArray(en)){ze=Fe*en.length,$t=Pe._malloc(ze),_e.push($t);for(let tn=0;tn<en.length;tn++){if(typeof en[tn]!="string")throw new TypeError(`tensor data at index ${tn} is not a string`);Pe.setValue($t+tn*Fe,Jn(en[tn],_e),"*")}}else{let tn=Pe.webnnIsGraphInput,In=Pe.webnnIsGraphOutput;if(tt!=="string"&&tn&&In){let Bt=Pe.UTF8ToString(Ee);if(tn(De,Bt)||In(De,Bt)){let Bn=qi(tt);ze=Ki(Bn,st),Xe="ml-tensor";let fn=Pe.webnnCreateTemporaryTensor,Di=Pe.webnnUploadTensor;if(!fn||!Di)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Yi=await fn(De,Bn,st);Di(Yi,new Uint8Array(en.buffer,en.byteOffset,en.byteLength)),$t=Yi}else ze=en.byteLength,$t=Pe._malloc(ze),_e.push($t),Pe.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,ze),$t)}else ze=en.byteLength,$t=Pe._malloc(ze),_e.push($t),Pe.HEAPU8.set(new Uint8Array(en.buffer,en.byteOffset,ze),$t)}}let dt=Pe.stackSave(),Rn=Pe.stackAlloc(4*st.length);try{st.forEach((tn,In)=>Pe.setValue(Rn+In*Fe,tn,Fe===4?"i32":"i64"));let en=Pe._OrtCreateTensor(qi(tt),$t,ze,Rn,st.length,Ni(Xe));en===0&&Et(`Can't create tensor for input/output. session=${De}, index=${Be}.`),fe.push(en)}finally{Pe.stackRestore(dt)}},Ye=async(se,fe,_e,De,Ee,Be)=>{var ar,sc,pd;let $e=Gt(),Pe=$e.PTR_SIZE,Fe=rr.get(se);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${se}`);let tt=Fe[0],st=Fe[1],nt=Fe[2],Xe=Fe[3],$t=Fe[4];Fe[5];let ze=fe.length,dt=De.length,Rn=0,en=[],tn=[],In=[],Bt=[],Bn=[],fn=$e.stackSave(),Di=$e.stackAlloc(ze*Pe),Yi=$e.stackAlloc(ze*Pe),or=$e.stackAlloc(dt*Pe),ol=$e.stackAlloc(dt*Pe);try{[Rn,en]=$o(Be),it("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)await Fr(_e[hn],tn,Bt,se,st[fe[hn]],fe[hn],$t);for(let hn=0;hn<dt;hn++)await Fr(Ee[hn],In,Bt,se,nt[De[hn]],ze+De[hn],$t);ot("wasm prepareInputOutputTensor");for(let hn=0;hn<ze;hn++)$e.setValue(Di+hn*Pe,tn[hn],"*"),$e.setValue(Yi+hn*Pe,st[fe[hn]],"*");for(let hn=0;hn<dt;hn++)$e.setValue(or+hn*Pe,In[hn],"*"),$e.setValue(ol+hn*Pe,nt[De[hn]],"*");(ar=$e.jsepOnRunStart)==null||ar.call($e,tt),(sc=$e.webnnOnRunStart)==null||sc.call($e,tt);let Ai;Ai=await $e._OrtRun(tt,Yi,Di,ze,ol,dt,or,Rn),Ai!==0&&Et("failed to call OrtRun().");let bs=[],fd=[];it("wasm ProcessOutputTensor");for(let hn=0;hn<dt;hn++){let Jr=Number($e.getValue(or+hn*Pe,"*"));if(Jr===In[hn]||Bn.includes(In[hn])){bs.push(Ee[hn]),Jr!==In[hn]&&$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.");continue}let zu=$e.stackSave(),Ws=$e.stackAlloc(4*Pe),va=!1,vi,lr=0;try{$e._OrtGetTensorData(Jr,Ws,Ws+Pe,Ws+2*Pe,Ws+3*Pe)!==0&&Et(`Can't access output tensor data on index ${hn}.`);let oc=Pe===4?"i32":"i64",cr=Number($e.getValue(Ws,oc));lr=$e.getValue(Ws+Pe,"*");let md=$e.getValue(Ws+Pe*2,"*"),Bu=Number($e.getValue(Ws+Pe*3,oc)),Vs=[];for(let xi=0;xi<Bu;xi++)Vs.push(Number($e.getValue(md+xi*Pe,oc)));$e._OrtFree(md)!==0&&Et("Can't free memory for tensor dims.");let Zr=Vs.reduce((xi,Zn)=>xi*Zn,1);vi=ei(cr);let ys=Xe==null?void 0:Xe.outputPreferredLocations[De[hn]];if(vi==="string"){if(ys==="gpu-buffer"||ys==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let xi=[];for(let Zn=0;Zn<Zr;Zn++){let Qr=$e.getValue(lr+Zn*Pe,"*"),gd=$e.getValue(lr+(Zn+1)*Pe,"*"),vd=Zn===Zr-1?void 0:gd-Qr;xi.push($e.UTF8ToString(Qr,vd))}bs.push([vi,Vs,xi,"cpu"])}else if(ys==="gpu-buffer"&&Zr>0){let xi=$e.jsepGetBuffer;if(!xi)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Zn=xi(lr),Qr=Ki(cr,Zr);if(Qr===void 0||!zs(vi))throw new Error(`Unsupported data type: ${vi}`);va=!0,bs.push([vi,Vs,{gpuBuffer:Zn,download:$e.jsepCreateDownloader(Zn,Qr,vi),dispose:()=>{$e._OrtReleaseTensor(Jr)!==0&&Et("Can't release tensor.")}},"gpu-buffer"])}else if(ys==="ml-tensor"&&Zr>0){let xi=$e.webnnEnsureTensor,Zn=$e.webnnIsGraphInputOutputTypeSupported;if(!xi||!Zn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ki(cr,Zr)===void 0||!Sr(vi))throw new Error(`Unsupported data type: ${vi}`);if(!Zn(se,vi,!1))throw new Error(`preferredLocation "ml-tensor" for ${vi} output is not supported by current WebNN Context.`);let Qr=await xi(se,lr,cr,Vs,!1);va=!0,bs.push([vi,Vs,{mlTensor:Qr,download:$e.webnnCreateMLTensorDownloader(lr,vi),dispose:()=>{$e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr)}},"ml-tensor"])}else if(ys==="ml-tensor-cpu-output"&&Zr>0){let xi=$e.webnnCreateMLTensorDownloader(lr,vi)(),Zn=bs.length;va=!0,fd.push((async()=>{let Qr=[Zn,await xi];return $e.webnnReleaseTensorId(lr),$e._OrtReleaseTensor(Jr),Qr})()),bs.push([vi,Vs,[],"cpu"])}else{let xi=vs(vi),Zn=new xi(Zr);new Uint8Array(Zn.buffer,Zn.byteOffset,Zn.byteLength).set($e.HEAPU8.subarray(lr,lr+Zn.byteLength)),bs.push([vi,Vs,Zn,"cpu"])}}finally{$e.stackRestore(zu),vi==="string"&&lr&&$e._free(lr),va||$e._OrtReleaseTensor(Jr)}}Xe&&!$t&&($e._OrtClearBoundOutputs(Xe.handle)!==0&&Et("Can't clear bound outputs."),rr.set(se,[tt,st,nt,Xe,$t,!1]));for(let[hn,Jr]of await Promise.all(fd))bs[hn][2]=Jr;return ot("wasm ProcessOutputTensor"),bs}finally{(pd=$e.webnnOnRunEnd)==null||pd.call($e,tt),$e.stackRestore(fn),tn.forEach(Ai=>$e._OrtReleaseTensor(Ai)),In.forEach(Ai=>$e._OrtReleaseTensor(Ai)),Bt.forEach(Ai=>$e._free(Ai)),Rn!==0&&$e._OrtReleaseRunOptions(Rn),en.forEach(Ai=>$e._free(Ai))}},sr=se=>{let fe=Gt(),_e=rr.get(se);if(!_e)throw new Error("invalid session id");let De=_e[0],Ee=fe._OrtEndProfiling(De);Ee===0&&Et("Can't get an profile file name."),fe._OrtFree(Ee)},mt=se=>{let fe=[];for(let _e of se){let De=_e[2];!Array.isArray(De)&&"buffer"in De&&fe.push(De.buffer)}return fe}}),Me,Ze,jt,on,un,Ln,Mn,hi,Hn,gi,On,Xr,lo,Io,xs,Lu,Mo,Oo,dd=c(()=>{vn(),Se(),ir(),nr(),Me=()=>!!I.wasm.proxy&&typeof document<"u",jt=!1,on=!1,un=!1,hi=new Map,Hn=(se,fe)=>{let _e=hi.get(se);_e?_e.push(fe):hi.set(se,[fe])},gi=()=>{if(jt||!on||un||!Ze)throw new Error("worker not ready")},On=se=>{switch(se.data.type){case"init-wasm":jt=!1,se.data.err?(un=!0,Mn[1](se.data.err)):(on=!0,Mn[0]()),Ln&&(URL.revokeObjectURL(Ln),Ln=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=hi.get(se.data.type);se.data.err?fe.shift()[1](se.data.err):fe.shift()[0](se.data.out);break}}},Xr=async()=>{if(!on){if(jt)throw new Error("multiple calls to 'initWasm()' detected.");if(un)throw new Error("previous call to 'initWasm()' failed.");if(jt=!0,Me())return new Promise((se,fe)=>{Ze==null||Ze.terminate(),Ls().then(([_e,De])=>{try{Ze=De,Ze.onerror=Be=>fe(Be),Ze.onmessage=On,Mn=[se,fe];let Ee={type:"init-wasm",in:I};if(!Ee.in.wasm.wasmPaths&&_e){let Be=tr();Be&&(Ee.in.wasm.wasmPaths=Be)}Ze.postMessage(Ee),Ln=_e}catch(Ee){fe(Ee)}},fe)});try{await gs(I.wasm),await ga(I),on=!0}catch(se){throw un=!0,se}finally{jt=!1}}},lo=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("init-ep",[fe,_e]);let De={type:"init-ep",in:{epName:se,env:I}};Ze.postMessage(De)});await Fs(I,se)},Io=async se=>Me()?(gi(),new Promise((fe,_e)=>{Hn("copy-from",[fe,_e]);let De={type:"copy-from",in:{buffer:se}};Ze.postMessage(De,[se.buffer])})):dn(se),xs=async(se,fe)=>{if(Me()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return gi(),new Promise((_e,De)=>{Hn("create",[_e,De]);let Ee={type:"create",in:{model:se,options:{...fe}}},Be=[];se instanceof Uint8Array&&Be.push(se.buffer),Ze.postMessage(Ee,Be)})}else return Cr(se,fe)},Lu=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("release",[fe,_e]);let De={type:"release",in:se};Ze.postMessage(De)});ao(se)},Mo=async(se,fe,_e,De,Ee,Be)=>{if(Me()){if(_e.some($e=>$e[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ee.some($e=>$e))throw new Error("pre-allocated output tensor is not supported for proxy.");return gi(),new Promise(($e,Pe)=>{Hn("run",[$e,Pe]);let Fe=_e,tt={type:"run",in:{sessionId:se,inputIndices:fe,inputs:Fe,outputIndices:De,options:Be}};Ze.postMessage(tt,mt(Fe))})}else return Ye(se,fe,_e,De,Ee,Be)},Oo=async se=>{if(Me())return gi(),new Promise((fe,_e)=>{Hn("end-profiling",[fe,_e]);let De={type:"end-profiling",in:se};Ze.postMessage(De)});sr(se)}}),tc,Lo,sl,nc=c(()=>{vn(),dd(),Ut(),Hi(),Bs(),tc=(se,fe)=>{switch(se.location){case"cpu":return[se.type,se.dims,se.data,"cpu"];case"gpu-buffer":return[se.type,se.dims,{gpuBuffer:se.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[se.type,se.dims,{mlTensor:se.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${se.location} for ${fe()}`)}},Lo=se=>{switch(se[3]){case"cpu":return new be(se[0],se[2],se[1]);case"gpu-buffer":{let fe=se[0];if(!zs(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:_e,download:De,dispose:Ee}=se[2];return be.fromGpuBuffer(_e,{dataType:fe,dims:se[1],download:De,dispose:Ee})}case"ml-tensor":{let fe=se[0];if(!Sr(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:_e,download:De,dispose:Ee}=se[2];return be.fromMLTensor(_e,{dataType:fe,dims:se[1],download:De,dispose:Ee})}default:throw new Error(`invalid data location: ${se[3]}`)}},sl=class{async fetchModelAndCopyToWasmMemory(se){return Io(await ti(se))}async loadModel(se,fe){zt();let _e;typeof se=="string"?_e=await this.fetchModelAndCopyToWasmMemory(se):_e=se,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await xs(_e,fe),pt()}async dispose(){return Lu(this.sessionId)}async run(se,fe,_e){zt();let De=[],Ee=[];Object.entries(se).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);De.push($t),Ee.push(ze)});let Be=[],$e=[];Object.entries(fe).forEach(nt=>{let Xe=nt[0],$t=nt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push($t),$e.push(ze)});let Pe=De.map((nt,Xe)=>tc(nt,()=>`input "${this.inputNames[Ee[Xe]]}"`)),Fe=Be.map((nt,Xe)=>nt?tc(nt,()=>`output "${this.outputNames[$e[Xe]]}"`):null),tt=await Mo(this.sessionId,Ee,Pe,$e,Fe,_e),st={};for(let nt=0;nt<tt.length;nt++)st[this.outputNames[$e[nt]]]=Be[nt]??Lo(tt[nt]);return pt(),st}startProfiling(){}endProfiling(){Oo(this.sessionId)}}}),Us={};p(Us,{OnnxruntimeWebAssemblyBackend:()=>Hs,initializeFlags:()=>co,wasmBackend:()=>zo});var co,Hs,zo,ud=c(()=>{vn(),dd(),nc(),co=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let se=I.wasm.simd;if(typeof se!="boolean"&&se!==void 0&&se!=="fixed"&&se!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${se}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Hs=class{async init(se){co(),await Xr(),await lo(se)}async createInferenceSessionHandler(se,fe){let _e=new sl;return await _e.loadModel(se,fe),_e}},zo=new Hs}),hd={};p(hd,{InferenceSession:()=>Je,TRACE:()=>et,TRACE_EVENT_BEGIN:()=>it,TRACE_EVENT_END:()=>ot,TRACE_FUNC_BEGIN:()=>zt,TRACE_FUNC_END:()=>pt,Tensor:()=>be,default:()=>rc,env:()=>I,registerBackend:()=>y}),vn(),vn(),vn();var ic="1.26.0",rc=yr;{let se=(ud(),f(Us)).wasmBackend;y("cpu",se,10),y("wasm",se,10)}return Object.defineProperty(I.versions,"web",{value:ic,enumerable:!0}),f(hd)})();n.exports=i})(dw)),dw.exports}var ak;function CP(){return ak||(ak=1,(function(n){var e=Dl&&Dl.__createBinding||(Object.create?(function(E,j,N,A){A===void 0&&(A=N);var P=Object.getOwnPropertyDescriptor(j,N);(!P||("get"in P?!j.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return j[N]}}),Object.defineProperty(E,A,P)}):(function(E,j,N,A){A===void 0&&(A=N),E[A]=j[N]})),i=Dl&&Dl.__setModuleDefault||(Object.create?(function(E,j){Object.defineProperty(E,"default",{enumerable:!0,value:j})}):function(E,j){E.default=j}),r=Dl&&Dl.__importStar||function(E){if(E&&E.__esModule)return E;var j={};if(E!=null)for(var N in E)N!=="default"&&Object.prototype.hasOwnProperty.call(E,N)&&e(j,E,N);return i(j,E),j};Object.defineProperty(n,"__esModule",{value:!0}),n.MicVAD=n.getDefaultRealTimeVADOptions=n.ort=n.DEFAULT_MODEL=void 0;const s=r(kP()),a=K0(),d=Y0(),l=iv(),c=wy(),p=BT(),m=FT();n.DEFAULT_MODEL="legacy",n.ort=s;const f="vad.worklet.bundle.min.js",b="silero_vad_v5.onnx",_="silero_vad_legacy.onnx",y=E=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:E,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async j=>{j.getTracks().forEach(N=>{N.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:j=>{j.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});n.getDefaultRealTimeVADOptions=y;const k=E=>"audioWorklet"in E&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function x(E,j,N,A,P){await N.audioWorklet.addModule(E),j.processorOptions={...j.processorOptions??{},frameSamples:A};const I=new AudioWorkletNode(N,"vad-helper-worklet",j);return I.port.onmessage=async O=>{const U=O.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case c.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const B=new Float32Array(U.data);await P(B);break}}},I}async function w(E,j,N){const A=new m.Resampler({nativeSampleRate:E.sampleRate,targetSampleRate:16e3,targetFrameSize:j});l.log.debug("using script processor");const I=E.createScriptProcessor(4096,1,1);let O=!1;return I.onaudioprocess=async U=>{if(!O){O=!0;try{const B=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const Z=A.process(B);for(const W of Z)await N(W)}catch(B){console.error("Error processing audio:",B)}finally{O=!1}}},I.connect(E.destination),I}class S{constructor(j,N,A,P,I=!1,O=null,U=null,B=null,J=null,Z=null,W=null,q="uninitialized",Q=!1){this.options=j,this.frameProcessor=N,this.model=A,this.frameSamples=P,this.listening=I,this.errored=O,this._stream=U,this._audioContext=B,this._vadNode=J,this._mediaStreamAudioSourceNode=Z,this._audioProcessorAdapterType=W,this.initializationState=q,this.ownsAudioContext=Q,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=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?k(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await x(this.options.baseAssetPath+f,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await w(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:le,vadNode:H}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const ee=new MediaStreamAudioSourceNode(le,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=ee,ee.connect(H);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:le}=this.getAudioInstances();await this.options.pauseStream(oe),le.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var le;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((le=this._audioContext)==null?void 0:le.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(j={}){const N={...(0,n.getDefaultRealTimeVADOptions)(j.model??n.DEFAULT_MODEL),...j};(0,d.validateOptions)(N),n.ort.env.wasm.wasmPaths=N.onnxWASMBasePath,N.ortConfig!==void 0&&N.ortConfig(n.ort);const A=N.model==="v5"?b:_,P=N.baseAssetPath+A,I=N.model==="v5"?p.SileroV5.new:p.SileroLegacy.new;let O;try{O=await I(n.ort,()=>(0,a.defaultModelFetcher)(P))}catch(W){throw console.error(`Encountered an error while loading model file ${P}`),W}const U=N.model==="v5"?512:1536,B=U/16,J=new d.FrameProcessor(O.process,O.reset_state,{positiveSpeechThreshold:N.positiveSpeechThreshold,negativeSpeechThreshold:N.negativeSpeechThreshold,redemptionMs:N.redemptionMs,preSpeechPadMs:N.preSpeechPadMs,minSpeechMs:N.minSpeechMs,submitUserSpeechOnPause:N.submitUserSpeechOnPause},B),Z=new S(N,J,O,U);if(N.startOnLoad)try{await Z.start()}catch(W){throw console.error("Error starting micVad",W),W}return Z}}n.MicVAD=S})(Dl)),Dl}var lk;function EP(){return lk||(lk=1,(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.getDefaultRealTimeVADOptions=n.MicVAD=n.DEFAULT_MODEL=n.utils=n.NonRealTimeVAD=n.Message=n.FrameProcessor=n.defaultModelFetcher=n.baseAssetPath=void 0;var e=OT();Object.defineProperty(n,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=K0();Object.defineProperty(n,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var r=Y0();Object.defineProperty(n,"FrameProcessor",{enumerable:!0,get:function(){return r.FrameProcessor}});var s=wy();Object.defineProperty(n,"Message",{enumerable:!0,get:function(){return s.Message}});var a=_P();Object.defineProperty(n,"NonRealTimeVAD",{enumerable:!0,get:function(){return a.NonRealTimeVAD}});const d=SP();n.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var l=CP();Object.defineProperty(n,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(n,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(n,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(aw)),aw}var TP=EP();function mx(n,e,i,r,s){var d,l;try{(l=(d=window.api)==null?void 0:d.logs)==null||l.write(n,e,i,r,s)}catch{}const a=e==="error"?console.error:e==="warn"?console.warn:console.log;r!==void 0?a(`[${n}]`,i,r):a(`[${n}]`,i)}const ht={debug:(n,e,i)=>mx(n,"debug",e,i),info:(n,e,i)=>mx(n,"info",e,i),warn:(n,e,i)=>mx(n,"warn",e,i),error:(n,e,i,r)=>mx(n,"error",e,i,r)},UT=16e3,jP=6,xp=UT*jP,NP=400,DP=UT*NP/1e3,ck=300,dk=2e3,uk=1500,hk=3e3,AP=600,HT=.5,WT=.35,pk=.85,fk=.7;let As=null,qa=!1,cs=!1;const __=new Set;function gx(n){for(const e of Array.from(__))try{e(n)}catch(i){ht.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let uw=0;const mk=2;let Pp=!1,VT=!1;function qT(n){n.addEventListener("message",e=>{var r;if(((r=e.data)==null?void 0:r.type)!=="log")return;const i=e.data.level||"info";ht[i]("whisperWorker",e.data.message??"",e.data.meta)}),n.addEventListener("error",e=>{ht.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),$P(`error:${e.message||"unknown"}`)})}function Rb(){return As||(As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),qT(As),ht.info("speech","worker spawned"),As)}let vx=!1;function $P(n){if(!Pp){if(vx){ht.warn("speech","respawnWorker: already in flight, ignoring",{reason:n});return}if(vx=!0,uw+=1,VT=!0,ht.warn("speech","respawnWorker: starting",{reason:n,attempt:uw}),gx({reason:n,respawned:!1,finalOnly:!0}),uw>mk){if(Pp=!0,ht.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:mk}),As)try{As.terminate()}catch{}As=null,qa=!1,cs=!1,gx({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),vx=!1;return}if(As)try{As.terminate()}catch{}As=null,qa=!1,cs=!1;try{As=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),qT(As),cs=!0,As.postMessage({type:"load"}),ht.info("speech","respawnWorker: new worker spawned, load posted"),gx({reason:n,respawned:!0,finalOnly:!0})}catch(e){Pp=!0,ht.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),gx({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{vx=!1}}}function PP(n,e){if(qa||cs)return;cs=!0;const i=Rb();ht.info("speech","preloadModel: posting load");const r=s=>{s.data.type==="status"?(n==null||n(s.data.status,s.data.message),s.data.status==="ready"&&(qa=!0,cs=!1,ht.info("speech","preloadModel: ready"),i.removeEventListener("message",r))):s.data.type==="progress"?e==null||e(s.data.pct):s.data.type==="error"&&(cs=!1,ht.error("speech","preloadModel: worker reported error",{error:s.data.error}),n==null||n("error",s.data.error),i.removeEventListener("message",r))};i.addEventListener("message",r),i.postMessage({type:"load"})}function RP(){ht.info("speech","resetModel: clearing load flags"),qa=!1,cs=!1}function _y(){var n;return typeof Worker<"u"&&!!((n=navigator.mediaDevices)!=null&&n.getUserMedia)&&typeof AudioWorkletNode<"u"}function IP(n){const e=Rb();return!qa&&!cs&&(cs=!0,e.postMessage({type:"load"})),new Promise((i,r)=>{const s=a=>{var d,l,c;((d=a.data)==null?void 0:d.type)==="result"?(e.removeEventListener("message",s),i((a.data.text??"").trim())):((l=a.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",s),r(new Error(String(a.data.error??"Transcription failed")))):((c=a.data)==null?void 0:c.type)==="status"&&a.data.status==="ready"&&(qa=!0,cs=!1)};e.addEventListener("message",s),e.postMessage({type:"transcribe",audio:n},[n.buffer])})}function KT(n){let e=Rb(),i=!1,r=null,s=null,a=null,d=null,l=null;const c=[],p=new Set;let m=null,f=0,b=!1,_=0,y=!1,k=!1,x=0,w=0,S=0,E=-1,j=ck,N=0,A=null,P="",I="",O=!1,U=0;function B(ae,xe){const Ne=Math.min(ae.length,xe.length);let me=0;for(;me<Ne&&ae.charCodeAt(me)===xe.charCodeAt(me);)me++;return me}function J(ae){const xe=B(P,ae);return P=ae,xe>I.length&&(I=ae.slice(0,xe)),I.length>ae.length&&(I=ae),I}const Z=()=>(m||(m=new Float32Array(xp)),m),W=()=>{f=0},q=ae=>{const xe=Z(),Ne=ae.length;if(Ne>=xp){xe.set(ae.subarray(Ne-xp)),f=xp;return}if(f+Ne<=xp){xe.set(ae,f),f+=Ne;return}const me=f+Ne-xp;xe.copyWithin(0,me,f),f-=me,xe.set(ae,f),f+=Ne},Q=()=>{A&&(clearTimeout(A),A=null)},oe=()=>{Q(),b=!1,y=!1,k=!1,j=ck,P="",I="",O=!1,U=0,W()},le=()=>{if(i||!b||k||y||A)return;if(f<DP){A=setTimeout(()=>{A=null,le()},j);return}const ae=performance.now()-x;if(ae<j&&x!==0){A=setTimeout(()=>{A=null,le()},j-ae);return}if(VT||Pp||n.partialsEnabled&&!n.partialsEnabled())return;const xe=Z(),Ne=new Float32Array(f);Ne.set(xe.subarray(0,f)),w+=1,S=w,y=!0,N=performance.now(),x=N,e.postMessage({type:"transcribe-partial",audio:Ne,seq:w},[Ne.buffer])},H=ae=>ae.length===0?Promise.resolve():Pp?(ht.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||n.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(xe=>{c.push(xe),w+=1;const Ne=w;E=Ne,e.postMessage({type:"transcribe",audio:ae,seq:Ne},[ae.buffer])}),ee=ae=>{const xe=H(ae);return p.add(xe),xe.finally(()=>{p.delete(xe)}),xe},Y=ae=>{var xe,Ne,me,re,te;if(ae.data.type==="result"){const we=ae.data.text,be=ae.data.seq??0;be&&be<E&&ht.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:be,latestFinalSeq:E}),!i&&we&&n.onFinal(we),(xe=c.shift())==null||xe()}else if(ae.data.type==="partial"){const we=ae.data.seq??0,be=ae.data.text??"",Ue=performance.now()-N;y=!1,Ue>=hk?(k=!0,ht.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Ue),seq:we})):Ue>=uk&&(j=Math.min(j*2,dk),ht.warn("speech","partials.slowdown",{elapsedMs:Math.round(Ue),newIntervalMs:j,seq:we})),O||(O=!0,Ue>AP&&j<500&&(j=500,ht.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Ue),newIntervalMs:500})));const et=we!==S||we<=E;if(!i&&!et&&be){const ut=J(be);ut&&((Ne=n.onPartial)==null||Ne.call(n,ut),U===0&&(U=performance.now(),ht.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-_)})))}le()}else if(ae.data.type==="partial-error"){const we=performance.now()-N;y=!1,we>=hk?(k=!0,ht.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ae.data.seq})):we>=uk&&(j=Math.min(j*2,dk),ht.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:j,seq:ae.data.seq})),ht.warn("speech","partial encode failed",{error:ae.data.error,seq:ae.data.seq}),le()}else ae.data.type==="error"?(i||n.onError(ae.data.error),(me=c.shift())==null||me()):ae.data.type==="status"?(i||(re=n.onModelStatus)==null||re.call(n,ae.data.status,ae.data.message),ae.data.status==="ready"&&(qa=!0,cs=!1)):ae.data.type==="progress"&&(i||(te=n.onProgress)==null||te.call(n,ae.data.pct))};e.addEventListener("message",Y);const ce=ae=>{var xe,Ne;if(!i){for(ht.warn("speech","createRecognition: worker death event",ae),(xe=n.onStatusChange)==null||xe.call(n,"restarting");c.length;)(Ne=c.shift())==null||Ne();if(p.clear(),Q(),y=!1,ae.respawned){try{e.removeEventListener("message",Y)}catch{}e=Rb(),e.addEventListener("message",Y)}}};return __.add(ce),{start:async()=>{if(!i){if(Pp){n.onError("Speech recognition disabled — please reload the app.");return}!qa&&!cs&&(cs=!0,ht.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ht.info("speech","createRecognition.start: initializing VAD",{modelReady:qa,modelLoading:cs});try{const ae=new URL("vad/",document.baseURI).href,xe=n.inputDeviceId||null,Ne={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};xe&&(Ne.deviceId={exact:xe}),ht.info("speech","getUserMedia",{hasDeviceId:!!xe,deviceIdPrefix:xe?xe.slice(0,8):null});const me=await navigator.mediaDevices.getUserMedia({audio:Ne});s=me,a=new AudioContext;for(const re of me.getAudioTracks())re.addEventListener("ended",()=>{i||(ht.warn("speech","mic track ended (permission revoked or device removed)"),n.onError("Microphone disconnected or permission revoked"))});try{l=a.createMediaStreamSource(s),d=a.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,l.connect(d)}catch(re){ht.warn("speech","analyser init failed",{error:re instanceof Error?re.message:String(re)}),l=null,d=null}r=await TP.MicVAD.new({audioContext:a,getStream:async()=>me,resumeStream:async()=>me,pauseStream:async()=>{},baseAssetPath:ae,onnxWASMBasePath:ae,model:"v5",positiveSpeechThreshold:HT,negativeSpeechThreshold:WT,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(re,te)=>{var we;i||((we=n.onFrame)==null||we.call(n,re),b&&(q(te),le()))},onSpeechStart:()=>{var re;i||(oe(),b=!0,_=performance.now(),(re=n.onSpeechStart)==null||re.call(n))},onSpeechEnd:re=>{var te;i||((te=n.onStatusChange)==null||te.call(n,"transcribing"),oe(),ee(re))},onVADMisfire:()=>{var re,te;i||((re=n.onStatusChange)==null||re.call(n,"idle"),oe(),(te=n.onMisfire)==null||te.call(n))}}),r.start()}catch(ae){const xe=ae instanceof Error?ae.message:"Microphone access denied",Ne=ae instanceof Error?ae.stack:"";if(ht.error("speech","createRecognition.start: VAD init failed",{error:xe,stack:Ne}),d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(me=>me.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}n.onError(xe)}}},stop:async()=>{if(r)try{await r.pause()}catch{}for(oe();p.size>0;)await Promise.all(Array.from(p));if(r){try{await r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}if(a){try{await a.close()}catch{}a=null}},setVadThresholds:(ae,xe)=>{if(r)try{r.setOptions({positiveSpeechThreshold:ae,negativeSpeechThreshold:xe})}catch(Ne){ht.warn("speech","setVadThresholds failed",{error:Ne instanceof Error?Ne.message:String(Ne)})}},getAnalyser:()=>d,destroy:()=>{if(i=!0,oe(),r){try{r.destroy()}catch{}r=null}if(d){try{d.disconnect()}catch{}d=null}if(l){try{l.disconnect()}catch{}l=null}if(a){try{a.close()}catch{}a=null}if(s){try{s.getTracks().forEach(ae=>ae.stop())}catch{}s=null}__.delete(ce),e.removeEventListener("message",Y)}}}let Tg=null;const S_=new Set,k_=new Set;function MP(){for(const n of S_)try{n()}catch{}}function C_(){for(const n of k_)try{n()}catch{}}function OP(n){return n.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function LP(n){if(!window.speechSynthesis)return;const e=OP(n);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{Tg=performance.now(),MP()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Tg=null,C_())},i.onerror=r=>{r.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Tg=null,C_())},window.speechSynthesis.speak(i)}function YT(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Tg=null,C_())}function XT(){var n;return((n=window.speechSynthesis)==null?void 0:n.speaking)??!1}function zP(){return Tg}function BP(n){return S_.add(n),()=>{S_.delete(n)}}function FP(n){return k_.add(n),()=>{k_.delete(n)}}function GP(n){XT()&&(n.setVadThresholds(pk,fk),ht.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=BP(()=>{n.setVadThresholds(pk,fk),ht.info("voice","tts.duck.on")}),i=FP(()=>{n.setVadThresholds(HT,WT),ht.info("voice","tts.duck.off")});return()=>{e(),i()}}const UP=[{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 HP(n){const e=n.trim();return UP.find(i=>i.match.test(e))??null}const WP=4e4;let bu=null;function Rp(){bu&&clearTimeout(bu),bu=setTimeout(()=>{bu=null,kt.getState().stopRecording()},WP)}function xx(){bu&&(clearTimeout(bu),bu=null)}let ed=null,Jc=null;const VP=.04,qP=.3;let Ib=0,E_=0;function KP(n){Jc!==null&&cancelAnimationFrame(Jc);const e=()=>{if(ed===null||kt.getState().submitCountdownStartAt===null){Jc=null;return}const i=performance.now();if(i-E_<200&&Ib>qP){const s=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"vad",prob:Ib.toFixed(2),msIntoCountdown:Math.round(s)}),Vc(),Rp();return}const r=JT();if(r){const s=new Uint8Array(r.fftSize);r.getByteTimeDomainData(s);let a=0;for(let l=0;l<s.length;l++){const c=(s[l]-128)/128;a+=c*c}const d=Math.sqrt(a/s.length);if(d>VP){const l=i-n;ht.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(l)}),Vc(),Rp();return}}Jc=requestAnimationFrame(e)};Jc=requestAnimationFrame(e)}function gk(n){ed&&clearTimeout(ed);const e=kt.getState().submitDelayMs,i=performance.now();kt.setState({submitCountdownStartAt:i}),ed=setTimeout(()=>{var s;ed=null,kt.setState({submitCountdownStartAt:null});const r=vt.getState().tabs.find(a=>a.id===n);if((r==null?void 0:r.status)==="dormant"){const a=(s=An.getState().chats[n])==null?void 0:s.pendingVoiceText;a&&(An.getState().send({tabId:n,sessionId:r.sessionId,cwd:r.cwd,prompt:a}),An.getState().clearPendingVoiceText(n))}else try{window.api.pty.write({tabId:n,data:"\r"})}catch(a){ht.warn("voice","submit pty.write failed",{error:a instanceof Error?a.message:String(a)})}Rp()},e),KP(i)}function Vc(){Jc!==null&&(cancelAnimationFrame(Jc),Jc=null),ed&&(clearTimeout(ed),ed=null),kt.getState().submitCountdownStartAt!==null&&kt.setState({submitCountdownStartAt:null})}let xr=null,Wr=null,Wm=null;function JT(){var n;return((n=xr==null?void 0:xr.getAnalyser)==null?void 0:n.call(xr))??null}const bx=1e4;let jg=null;function yx(){jg&&(clearTimeout(jg),jg=null)}let ub=null,hb=null;function wx(){ub=null,hb&&(hb(),hb=null)}const YP=1500,XP=9e4;let _x=0,pb=null,T_=-1;function Sx(){pb&&(clearTimeout(pb),pb=null,T_=-1)}const JP=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),kt=ji((n,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;ht.info("voice","initModel: kicking off preload"),n({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++_x,r=()=>{i===_x&&(Sx(),T_=i,pb=setTimeout(()=>{T_===i&&e().modelStatus==="loading"&&(ht.warn("voice","mic.gate.timeout: no progress within 90s"),n({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},XP))};r(),PP((s,a)=>{i===_x&&(s==="ready"?(Sx(),ht.info("voice","modelStatus -> ready"),n({modelStatus:"ready",loadingProgress:100,errorKind:null})):s==="error"?(Sx(),ht.error("voice","modelStatus -> error",{msg:a}),n({modelStatus:"error",error:a,errorKind:"load"})):(r(),n({modelStatus:"loading"})))},s=>{i===_x&&(r(),n({loadingProgress:Math.round(s)}))})},resetAndRetryModel:()=>{ht.info("voice","mic.gate.retry"),Sx(),RP(),n({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:(i,r)=>{if(e().isRecording)return;if(xr){ht.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!_y()){n({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const s=a=>{try{const d=KT({inputDeviceId:a,onStatusChange:l=>{n(l==="transcribing"?{statusPill:"transcribing"}:l==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:l=>{e().partialsEnabled&&n({lastPartial:l})},partialsEnabled:()=>e().partialsEnabled,onFrame:l=>{Ib=l.isSpeech,E_=performance.now()},onSpeechStart:()=>{if(n({statusPill:"listening",lastPartial:""}),xx(),Vc(),XT()){const c=zP(),p=c!==null?performance.now()-c:null;YT(),n({lastBargeInAt:performance.now()}),ht.info("voice","barge-in",{tabId:i,utteranceOffsetMs:p})}else ht.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{n({lastPartial:"",statusPill:"idle"}),Rp();const l=e().lastBargeInAt;l!==null&&performance.now()-l<600&&ht.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-l)})},onFinal:l=>{var b;Rp();const c=l.trim();if(!c||JP.has(c)){n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(Wm){Wm(c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}if(((b=vt.getState().tabs.find(_=>_.id===i))==null?void 0:b.status)==="dormant"){An.getState().setPendingVoiceText(i,c),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&gk(i);const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}const m=HP(c);if(m){ht.info("voice","voice-command",{tabId:i,label:m.label,transcript:c}),window.api.pty.write({tabId:i,data:m.data}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vc();const _=window;_.__transcripts&&(_.__transcripts.push({tabId:i,text:c}),_.__transcripts.length>500&&_.__transcripts.shift());return}window.api.pty.write({tabId:i,data:c}),n({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&gk(i);const f=window;f.__transcripts&&(f.__transcripts.push({tabId:i,text:c}),f.__transcripts.length>500&&f.__transcripts.shift())},onError:l=>{ht.error("voice","recognition error",{err:l}),Vc(),n({error:l,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),Wr==null||Wr(),Wr=null,xx(),xr==null||xr.destroy(),xr=null,Wm=null,Re.error(`Microphone error: ${l}`)},onModelStatus:l=>{l==="ready"?n({modelStatus:"ready",loadingProgress:100}):l==="loading"&&n({modelStatus:"loading"})},onProgress:l=>n({loadingProgress:Math.round(l)})});xr=d,Wm=(r==null?void 0:r.sink)??null,n({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Rp(),d.start().then(()=>{xr===d&&(Wr==null||Wr(),Wr=GP(d))}).catch(l=>{const c=l instanceof Error?l.message:String(l);ht.error("voice","handle.start() failed",{error:c}),Re.error(`Could not start mic: ${c}`)})}catch(d){n({error:d instanceof Error?d.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var a,d,l;return((l=(d=(a=window.api)==null?void 0:a.voice)==null?void 0:d.getDevicePref)==null?void 0:l.call(d))??Promise.resolve(null)}).then(a=>s((a==null?void 0:a.selectedDeviceId)??null)).catch(a=>{ht.warn("voice","getDevicePref failed; using default device",{error:a instanceof Error?a.message:String(a)}),s(null)})},stopRecording:()=>{const i=xr;i&&(xx(),Vc(),Ib=0,E_=0,Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),xr===i&&(xr=null,Wm=null),e().hotkeyState==="stopping"&&(yx(),n({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=xr;if(!i)return;xx(),Wr==null||Wr(),Wr=null,n({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(a){ht.warn("voice","restartWithDevice: drain rejected",{error:a instanceof Error?a.message:String(a)})}i.destroy(),xr===i&&(xr=null);const{useSessions:r}=await nv(async()=>{const{useSessions:a}=await Promise.resolve().then(()=>J$);return{useSessions:a}},[],import.meta.url),s=r.getState().activeTabId;s&&e().startRecording(s)},setExternalRecording:i=>n({externalRecording:i}),toggleTTS:()=>n(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>n({autoSubmit:i}),setSubmitDelayMs:i=>n({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Vc(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(n({partialsEnabled:i}),i||n({lastPartial:""}))},clearError:()=>n({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ht.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),n({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&n({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(n({turnDetectorState:i}),i==="load_failed"?ht.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ht.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ht.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&n({wizardArmed:i})},openWizard:()=>{e().wizardOpen||n({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&n({wizardOpen:!1})},armHotkey:({phase:i,source:r,mode:s,tabId:a})=>{const d=e(),{canRecord:l,reason:c}=Mb(d);if(i==="down"){if(c==="error"||c==="load-timeout"){d.resetAndRetryModel(),ht.info("voice-hotkey","down.retry",{source:r,reason:c});return}if(!l&&c!=="loading"){ht.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:c});return}if(d.hotkeyState==="recording"||d.isRecording){(s==="toggle"||r==="global")&&(n({hotkeyState:"stopping"}),yx(),jg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:bx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},bx),d.stopRecording());return}if(c==="loading"){d.hotkeyState!=="armed"&&(n({hotkeyState:"armed"}),ht.info("voice-hotkey","armed",{source:r,modelStatus:d.modelStatus})),wx(),ub={tabId:a,source:r,mode:s},hb=kt.subscribe((p,m)=>{if(ub&&p.modelStatus==="ready"&&m.modelStatus!=="ready"&&p.hotkeyState==="armed"){const f=ub;if(wx(),!f.tabId){ht.warn("voice-hotkey","armed-promote-no-tab",{source:f.source}),n({hotkeyState:"idle"});return}ht.info("voice-hotkey","armed-promote",f),n({hotkeyState:"recording"}),kt.getState().startRecording(f.tabId)}});return}if(!a){ht.warn("voice-hotkey","no-active-tab",{source:r});return}ht.info("voice-hotkey","start",{source:r,mode:s,tabId:a}),d.startRecording(a),e().isRecording?n({hotkeyState:"recording"}):(ht.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),n({hotkeyState:"idle"}));return}if(!(s!=="hold"||r==="global")){if(d.hotkeyState==="armed"){wx(),ht.info("voice-hotkey","miss-model-loading-armed-up"),n({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(n({hotkeyState:"stopping"}),yx(),jg=setTimeout(()=>{e().hotkeyState==="stopping"&&(ht.warn("voice-hotkey","drain-timeout",{durationMs:bx}),n({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&n({hotkeyState:"idle"})},0))},bx),d.stopRecording())}},destroyHotkey:()=>{const i=e();if(wx(),Vc(),i.hotkeyState==="recording"){ht.warn("voice-hotkey","destroyed-mid-recording"),n({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(yx(),n({hotkeyState:"destroyed"}))}})),ZP=n=>({isRecording:n.isRecording,statusPill:n.statusPill,lastPartial:n.lastPartial,lastTranscript:n.lastTranscript,submitCountdownStartAt:n.submitCountdownStartAt}),Mb=n=>_y()?n.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:n.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:n.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:n.modelStatus==="error"?{canRecord:!1,reason:n.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const n=window;n.__voice=kt,n.__transcripts=[]}const QP=6e4,eR=5e3,Ng=ji(()=>({data:null,refreshing:!1}));let vk=!1,fb=null,xk=null,bk=!1;async function X0(){Ng.setState({refreshing:!0});let n=QP;try{const e=await B0(window.api.billing.fetch(),eR,"billing.fetch");Ng.setState({data:e,refreshing:!1}),e.kind==="transient"?n=xk==="transient"?3e4:5e3:(e.kind==="auth"||e.kind==="meter_rate_limited")&&(n=3e4),xk=e.kind}catch(e){if(Ng.setState({refreshing:!1}),!bk){bk=!0;const i=e instanceof Error?e.message:String(e);Re.warn(`Billing usage fetch failed: ${i}`)}}fb=setTimeout(X0,n)}function tR(){vk||(vk=!0,X0())}function ZT(n){return n?n.kind==="ok"||n.kind==="ok-stale"?n.data:(n.kind==="auth"||n.kind==="meter_rate_limited")&&n.cached?n.cached:null:null}function nR(){fb!==null&&(clearTimeout(fb),fb=null),X0()}function rv(n){if(!n||n==="—"||n==="unknown")return n;const e=/\[(\dm)\]/.exec(n),i=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(n);if(!i)return n;const r=i[1].charAt(0).toUpperCase()+i[1].slice(1).toLowerCase(),s=i[3]?`${i[2]}.${i[3]}`:i[2];return e?`${r} ${s} ${e[1]}`:`${r} ${s}`}const kx=new Map,iR=3e4;function J0(n){const[e,i]=R.useState(()=>{var r;return n?((r=kx.get(n))==null?void 0:r.value)??null:null});return R.useEffect(()=>{if(!n){i(null);return}let r=!1;return(async()=>{const a=kx.get(n);if(a&&Date.now()-a.ts<iR){r||i(a.value);return}try{const d=await window.api.app.gitBranch(n);if(r)return;kx.set(n,{value:d,ts:Date.now()}),i(d)}catch{if(r)return;kx.set(n,{value:null,ts:Date.now()}),i(null)}})(),()=>{r=!0}},[n]),e}function rR(n){return n.filter(e=>e.group==="Tools").map(({key:e,label:i,icon:r,hint:s})=>({key:e,label:i,icon:r,hint:s}))}const j_="sm.almanac.sidebarWidth",QT=180,ej=480,N_=252;function sR(){try{const n=parseInt(localStorage.getItem(j_)??"",10);if(Number.isFinite(n))return Math.min(ej,Math.max(QT,n))}catch{}return N_}const oR=52,tj="sm.almanac.sidebarCollapsed";function aR(){try{return localStorage.getItem(tj)==="1"}catch{}return!1}const nj="sm.almanac.collapsedGroups";function lR(){try{const n=localStorage.getItem(nj);if(!n)return new Set;const e=JSON.parse(n);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function cR(){const n=vt(i=>{var r;return((r=i.tabs.find(s=>s.id===i.activeTabId))==null?void 0:r.cwd)??null});return{scheduler:to(i=>{var r;return(((r=i.snapshot)==null?void 0:r.jobs)??[]).some(s=>s.status==="running"&&(!n||s.cwd===n))})}}function dR({active:n,onNavigate:e,onNewSession:i}){const[r,s]=R.useState(()=>lR()),a=R.useCallback(P=>{s(I=>{const O=new Set(I);O.has(P)?O.delete(P):O.add(P);try{localStorage.setItem(nj,JSON.stringify(Array.from(O)))}catch{}return O})},[]),[d,l]=R.useState(()=>aR()),c=R.useCallback(()=>{l(P=>{const I=!P;try{localStorage.setItem(tj,I?"1":"0")}catch{}return I})},[]),p=vt(P=>P.tabs),m=vt(P=>P.activeTabId),f=p.find(P=>P.id===m)??null,b=cR(),_=mn(P=>P.navFace),y=oP(_),k=y.filter(P=>P.group==="Workspace"),x=y.filter(P=>P.group==="Configure"),w=rR(y),[S,E]=R.useState(()=>sR()),j=R.useRef(S);j.current=S;const N=R.useCallback(P=>{P.preventDefault();const I=P.clientX,O=j.current;let U=O;const B=Z=>{U=Math.min(ej,Math.max(QT,O+(Z.clientX-I))),E(U)},J=()=>{window.removeEventListener("pointermove",B),window.removeEventListener("pointerup",J),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(j_,String(U))}catch{}};window.addEventListener("pointermove",B),window.addEventListener("pointerup",J),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),A=R.useCallback(()=>{E(N_);try{localStorage.setItem(j_,String(N_))}catch{}},[]);return o.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?oR:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[o.jsx(uR,{tab:f,navFace:_,onNewSession:i,rail:d,onToggleRail:c}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:o.jsxs(o.Fragment,{children:[!d&&o.jsx(hw,{label:"Workspace",desc:ow.Workspace,collapsed:r.has("Workspace"),count:k.length,onToggle:()=>a("Workspace")}),(d||!r.has("Workspace"))&&k.map(P=>o.jsx(yk,{item:P,active:n===P.key,live:P.liveKind?b[P.liveKind]:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(hw,{label:"Configure",desc:ow.Configure,collapsed:r.has("Configure"),count:x.length,onToggle:()=>a("Configure")}),(d||!r.has("Configure"))&&x.map(P=>o.jsx(yk,{item:P,active:n===P.key,live:!1,onClick:()=>e(P.key),rail:d},P.key)),!d&&o.jsx(hw,{label:"Tools",desc:ow.Tools,collapsed:r.has("Tools"),count:w.length,onToggle:()=>a("Tools")}),(d||!r.has("Tools"))&&w.map(P=>o.jsx(hR,{tool:P,active:n===P.key,onClick:()=>e(P.key),rail:d},P.key))]})}),o.jsx(pR,{rail:d,navFace:_}),!d&&o.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:N,onDoubleClick:A,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 uR({tab:n,navFace:e,onNewSession:i,rail:r,onToggleRail:s}){const a=(n==null?void 0:n.label)??"no session",d=J0((n==null?void 0:n.cwd)??null);return r?o.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[o.jsx("button",{onClick:i,"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:o.jsx(an,{name:"plus",size:15,stroke:1.8})}),o.jsx("button",{onClick:s,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:o.jsx(an,{name:"chevron",size:15,stroke:1.8})})})]}):e==="home"?o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Session Manager"}),o.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]}):o.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),o.jsx("button",{onClick:s,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:o.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:o.jsx(an,{name:"chevron",size:13,stroke:1.8})})})]}),o.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[o.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),o.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(n==null?void 0:n.cwd)??"",children:a})]}),o.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:d?`⌥${d}`:n?n.cwd:"—"}),o.jsx("div",{className:"mt-3 flex items-stretch gap-1.5",children:o.jsxs("button",{onClick:i,"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:[o.jsx(an,{name:"plus",size:13,stroke:1.8}),"Open / Start Project"]})})]})}function hw({label:n,desc:e,collapsed:i,count:r,onToggle:s}){return o.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[o.jsxs("button",{onClick:s,"aria-expanded":!i,title:i?`Expand ${n}`:`Collapse ${n}`,className:"group w-full flex items-center gap-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[o.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:i?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),o.jsx("span",{className:"flex-1",children:n}),i&&o.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:r})]}),!i&&o.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 yk({item:n,active:e,live:i,onClick:r,rail:s}){return o.jsxs("button",{onClick:r,title:n.hint,"data-testid":n.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${s?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${s?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(an,{name:n.icon,size:17,stroke:1.6})}),!s&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]}),!s&&i&&o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),s&&i&&o.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 hR({tool:n,active:e,onClick:i,rail:r}){return o.jsxs("button",{onClick:i,title:n.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${r?"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&&o.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${r?"-left-[4px]":"-left-[10px]"}`}),o.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:o.jsx(an,{name:n.icon,size:15,stroke:1.6})}),!r&&o.jsxs("span",{className:"flex-1 min-w-0",children:[o.jsx("span",{className:"block truncate",children:n.label}),n.hint&&o.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:n.hint})]})]})}function pR({rail:n,navFace:e}){const i=kt(c=>c.isRecording),r=vt(c=>c.tabs),s=vt(c=>c.activeTabId),a=r.find(c=>c.id===s)??null,[d,l]=R.useState(null);return R.useEffect(()=>{let c=!1;if(!(a!=null&&a.presetId)){l(null);return}return ET(a.presetId).then(p=>{c||l((p==null?void 0:p.model)??null)}).catch(()=>{c||l(null)}),()=>{c=!0}},[a==null?void 0:a.presetId]),n?o.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"})}):o.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:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${i?"bg-red-500 animate-pulse":"bg-sage"}`,title:i?"recording":"idle"}),(i||e==="project")&&o.jsx("span",{className:"truncate",title:d??"",children:i?"recording…":d?`Claude · ${rv(d)}`:"Claude Code"})]})}function fR(n,e,i){return e?n.map(r=>r.id===e?{...r,lastActivityAt:i}:r):n}function mR(n,e,i){return{tabId:n,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const mb=ji((n,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,r,s)=>{const a={...e().refs};if(a[i]=(a[i]??0)+1,n({refs:a}),a[i]>1)return;n({tabs:{...e().tabs,[i]:mR(i,r,s)}});const d=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));n({unsubs:{...e().unsubs,[i]:d}}),window.api.transcripts.subscribe({tabId:i,cwd:r,sessionUuid:s}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:m}=await nv(async()=>{const{toast:f}=await Promise.resolve().then(()=>DT);return{toast:f}},void 0,import.meta.url);m.error(`Live view unavailable: ${l.error??"subscribe failed"}`),n({tabs:{...e().tabs,[i]:{...c,path:null}}});return}n({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const p=await window.api.transcripts.buffer(i);for(const m of p)e().ingest(i,m,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const r={...e().refs};if(!r[i])return;if(r[i]--,r[i]>0){n({refs:r});return}delete r[i];const s=e().unsubs[i];s==null||s();const a={...e().unsubs};delete a[i];const d={...e().tabs};delete d[i],window.api.transcripts.unsubscribe(i),n({refs:r,unsubs:a,tabs:d})},ingest:(i,r,s)=>{const a=e().tabs[i];if(!a)return;const d=Date.now(),l={...a,lastEventAt:s!=null&&s.replay?a.lastEventAt:d},c=[],p=(m,f)=>m.length>f?m.slice(0,f-1)+"…":m;switch(r.kind){case"todo_write":{const m=Array.isArray(r.data)?r.data:[];l.todos=m,s!=null&&s.replay||c.push({id:0,kind:"todo-update",at:d,label:`Todos · ${m.length} item${m.length!==1?"s":""}`});break}case"tool_use":{const m=r.data,f=m.input,b={};for(const _ of["command","file_path","pattern","url","query","subagent_type","description"])f&&_ in f&&(b[_]=f[_]);if(l.lastToolUses=[{id:m.id,name:m.name,input:b,at:d},...a.lastToolUses].slice(0,50),!(s!=null&&s.replay)){const _=m.input,y=["Edit","Write","NotebookEdit"].includes(m.name),k=typeof(_==null?void 0:_.file_path)=="string"?_.file_path:void 0,x=typeof(_==null?void 0:_.command)=="string"?_.command:void 0,w=k?k.split("/").pop()??k:x?p(x,28):"";c.push({id:0,kind:"tool-use",at:d,label:w?`${m.name} · ${w}`:m.name,target:k??x,toolName:m.name}),y&&k&&c.push({id:0,kind:"file-edit",at:d,label:`${m.name} · ${p(k.split("/").pop()??k,34)}`,target:k,toolName:m.name})}break}case"plan":{const m=r.data,f=typeof m=="string"?m:(m==null?void 0:m.plan)??JSON.stringify(m);l.plans=[{at:d,content:f??""},...a.plans].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const m=r.data;l.agents=[{id:m==null?void 0:m.toolUseId,at:d,subagentType:m==null?void 0:m.subagent_type,description:m==null?void 0:m.description,lastActivityAt:d},...a.agents].slice(0,50),s!=null&&s.replay||c.push({id:0,kind:"agent-spawn",at:d,label:m!=null&&m.subagent_type?`Agent: ${p(m.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const m=r.data,f=(a.usage.inputTokens||0)+(a.usage.outputTokens||0),b=m.input_tokens??m.inputTokens??0,_=m.output_tokens??m.outputTokens??0,y=f+b+_;l.usage={inputTokens:(a.usage.inputTokens||0)+b,outputTokens:(a.usage.outputTokens||0)+_,cacheCreationInputTokens:(a.usage.cacheCreationInputTokens||0)+(m.cache_creation_input_tokens??m.cacheCreationInputTokens??0),cacheReadInputTokens:(a.usage.cacheReadInputTokens||0)+(m.cache_read_input_tokens??m.cacheReadInputTokens??0)},!(s!=null&&s.replay)&&Math.floor(y/1e3)>Math.floor(f/1e3)&&c.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(y/1e3)}k tokens`});break}case"tool_result":{const m=r.data;l.agents=fR(a.agents,m==null?void 0:m.toolUseId,d);break}}if(c.length>0){let m=a.activitySeq;const f=c.map(b=>({...b,id:++m}));l.activitySeq=m,l.activityRing=[...a.activityRing,...f].slice(-32)}n({tabs:{...e().tabs,[i]:l}})}}));function gR(n){const e=mb(s=>s.subscribe),i=mb(s=>s.unsubscribe),r=mb(s=>n?s.tabs[n.id]:void 0);return R.useEffect(()=>{if(n)return e(n.id,n.cwd,n.sessionId),()=>i(n.id)},[n==null?void 0:n.id,n==null?void 0:n.cwd,n==null?void 0:n.sessionId,e,i]),r}function vR({onNavigate:n}){const e=vt(E=>E.tabs),i=vt(E=>E.activeTabId),r=e.find(E=>E.id===i)??null,s=gR(r),a=(s==null?void 0:s.lastEventAt)??0,d=Ng(E=>E.data),l=to(E=>{var j;return((j=E.snapshot)==null?void 0:j.paused)??null}),c=J0((r==null?void 0:r.cwd)??null),[,p]=R.useState(0);R.useEffect(()=>{const E=setInterval(()=>p(j=>j+1),6e4);return()=>clearInterval(E)},[]);const m=(s==null?void 0:s.todos)??[],[f,b]=R.useState(!1),_=R.useRef(null);R.useEffect(()=>{if(!f)return;const E=j=>{_.current&&!_.current.contains(j.target)&&b(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[f]),R.useEffect(()=>{m.length===0&&b(!1)},[m.length]);const y=ZT(d),k=(y==null?void 0:y.usage.five_hour)??null,x=k?Math.round(k.utilization):null,w=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",S=a>0?yR(Date.now()-a):"—";return o.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:[o.jsxs("button",{onClick:()=>n==null?void 0:n("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:w?"Connected to Anthropic":"Disconnected",children:[o.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${w?"bg-sage":"bg-fg-faint"}`}),o.jsx("span",{children:w?"connected":"offline"})]}),o.jsx("button",{onClick:()=>n==null?void 0:n("overview"),className:"hover:text-fg transition-colors",title:"Open Home",children:x!=null?`${x}% of 5h window used`:"5h —"}),l&&o.jsxs("button",{onClick:()=>n==null?void 0:n("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${l.reason==="auth"||l.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[o.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",l.reason]}),r&&o.jsxs("span",{className:"text-fg-faint",title:r.cwd,children:[r.label,c&&o.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",c]})]}),o.jsxs("span",{className:"text-fg-faint",children:["last activity: ",o.jsx("span",{className:"text-fg-dim",children:S})]}),m.length>0&&o.jsx(xR,{ref:_,todos:m,open:f,onToggle:()=>b(E=>!E)}),o.jsx("span",{className:"flex-1"}),o.jsxs("span",{className:"text-fg-faint",children:["v","0.55.1"]})]})}const xR=R.forwardRef(function({todos:e,open:i,onToggle:r},s){const a={completed:e.filter(d=>d.status==="completed").length,in_progress:e.filter(d=>d.status==="in_progress").length,pending:e.filter(d=>d.status==="pending").length};return o.jsxs("div",{ref:s,className:"relative",children:[o.jsxs("button",{onClick:r,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[o.jsxs("span",{className:"text-green-400",children:["✓",a.completed]}),o.jsxs("span",{className:"text-accent",children:["●",a.in_progress]}),o.jsxs("span",{className:"text-fg-dim",children:["○",a.pending]}),o.jsxs("span",{className:"text-fg-faint",children:["todos ",i?"▾":"▴"]})]}),i&&o.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 z-50","data-testid":"footer-todos-popover",children:o.jsx("ul",{className:"space-y-0.5",children:e.map((d,l)=>o.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[o.jsx(bR,{status:d.status}),o.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},l))})})]})});function bR({status:n}){return n==="completed"?o.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):n==="in_progress"?o.jsx("span",{className:"w-3 shrink-0",children:o.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function yR(n){const e=Math.max(0,Math.floor(n/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}function wR({onClose:n,onSent:e}){const i=vt(P=>P.tabs),[r,s]=R.useState(""),[a,d]=R.useState(()=>Object.fromEntries(i.map(P=>[P.id,!0]))),[l,c]=R.useState(!1),[p,m]=R.useState({}),f=R.useRef(null),b=R.useRef(e);R.useEffect(()=>{b.current=e},[e]),R.useEffect(()=>{d(P=>{const I={};for(const O of i)I[O.id]=P[O.id]??!0;return I})},[i]),R.useEffect(()=>{var P;(P=f.current)==null||P.focus()},[]),R.useEffect(()=>window.api.pty.onWriteError(I=>{m(O=>I.tabId in O?{...O,[I.tabId]:"skipped"}:O)}),[]),R.useEffect(()=>{if(Object.keys(p).length===0)return;const P=Object.values(p).filter(O=>O==="sent").length,I=window.setTimeout(()=>b.current(P),1500);return()=>window.clearTimeout(I)},[p]);const _=i.filter(P=>a[P.id]).map(P=>P.id),y=_.length,k=Object.keys(p).length>0,x=r.length>0&&y>0&&!l&&!k,w=()=>{if(!x)return;c(!0);const P=vt.getState().tabs,I=new Set(P.map(U=>U.id)),O={};for(const U of _)I.has(U)?(window.api.pty.write({tabId:U,data:r+"\r"}),O[U]="sent"):O[U]="skipped";m(O),c(!1)},S=P=>{if(P.key==="Escape"){P.preventDefault(),P.stopPropagation(),n();return}P.key==="Enter"&&(P.metaKey||P.ctrlKey)&&(P.preventDefault(),w())},E=i.length>0&&i.every(P=>a[P.id]),j=()=>{const P=!E;d(Object.fromEntries(i.map(I=>[I.id,P])))},N=Object.values(p).some(P=>P==="skipped"),A=k?N?"Sent (some skipped)":"Sent":`Send to ${y} tab${y===1?"":"s"}`;return o.jsxs("div",{className:"border-b border-line bg-bg-elev px-4 py-3 flex flex-col gap-2 shrink-0",onKeyDown:S,"data-testid":"broadcast-bar",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-xs text-fg-dim uppercase tracking-wider",children:"Broadcast"}),o.jsx("div",{className:"text-[10px] text-fg-faint",children:"Esc to close · Cmd/Ctrl+Enter to send"})]}),o.jsx("textarea",{ref:f,value:r,onChange:P=>s(P.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"}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsxs("label",{className:"flex items-center gap-2 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:E,onChange:j,className:"accent-accent"}),o.jsxs("span",{children:["All tabs (",y,"/",i.length,")"]})]}),o.jsx("div",{className:"flex flex-wrap gap-x-3 gap-y-1 max-h-24 overflow-y-auto pl-4",children:i.map(P=>o.jsxs("label",{className:"flex items-center gap-1.5 text-[11px] text-fg-dim cursor-pointer select-none",children:[o.jsx("input",{type:"checkbox",checked:!!a[P.id],onChange:I=>d(O=>({...O,[P.id]:I.target.checked})),className:"accent-accent"}),o.jsx("span",{className:"truncate max-w-[12rem]",children:P.label}),p[P.id]==="sent"&&o.jsx("span",{"data-testid":"broadcast-row-sent",className:"text-[10px] text-green-500",children:"✓"}),p[P.id]==="skipped"&&o.jsx("span",{"data-testid":"broadcast-row-skipped",className:"text-[10px] text-red-400",children:"×"})]},P.id))})]}),o.jsxs("div",{className:"flex items-center gap-2 justify-end",children:[o.jsx("button",{onClick:n,className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line hover:border-fg-faint rounded transition-colors",children:"Cancel"}),o.jsx("button",{onClick:w,disabled:!x,className:"px-2 py-0.5 text-[10px] text-fg border border-accent-muted hover:border-accent rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:A})]})]})}function _R({tabId:n,cwd:e,onClose:i}){const r=Eg(y=>y.watchersForTab(n)),s=Eg(y=>y.add),a=Eg(y=>y.remove),d=R.useRef(null),[l,c]=R.useState(""),[p,m]=R.useState(""),[f,b]=R.useState(!1);R.useEffect(()=>{const y=k=>{k.key==="Escape"&&i()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[i]),R.useEffect(()=>{const y=k=>{d.current&&!d.current.contains(k.target)&&i()};return document.addEventListener("mousedown",y),()=>document.removeEventListener("mousedown",y)},[i]);const _=async()=>{const y=p.trim();if(!y||f)return;b(!0);const k=await s({tabId:n,label:l.trim(),command:y,cwd:e});b(!1),k&&(c(""),m(""))};return o.jsxs("div",{ref:d,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:[o.jsxs("div",{className:"flex items-center mb-2",children:[o.jsx("span",{className:"text-fg-dim uppercase tracking-wider",children:"Watchers"}),o.jsxs("span",{className:"text-fg-faint ml-2",children:[r.length," active"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:i,className:"text-fg-faint hover:text-fg",title:"Close",children:"×"})]}),o.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[o.jsx("input",{value:l,onChange:y=>c(y.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"}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("input",{value:p,onChange:y=>m(y.target.value),onKeyDown:y=>{y.key==="Enter"&&_()},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"}),o.jsx("button",{onClick:_,disabled:!p.trim()||f,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"})]}),o.jsxs("span",{className:"text-fg-faint",children:["cwd: ",o.jsx("span",{className:"font-mono",children:e})]})]}),r.length===0?o.jsx("div",{className:"text-fg-faint italic py-2",children:"no watchers — add one above"}):o.jsx("ul",{className:"flex flex-col gap-2 max-h-64 overflow-y-auto",children:r.map(y=>{const k=y.lines[y.lines.length-1];return o.jsxs("li",{className:"border border-line rounded p-2 bg-bg",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"font-medium text-fg truncate",children:y.label}),o.jsxs("span",{className:"text-fg-faint",children:[y.lineCount," line",y.lineCount===1?"":"s"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{onClick:()=>a(y.watcherId),className:"text-fg-faint hover:text-red-400",title:"Stop watcher","data-testid":`watcher-remove-${y.watcherId}`,children:"stop"})]}),o.jsx("div",{className:"text-fg-faint font-mono text-[10px] truncate mt-0.5",title:y.command,children:y.command}),o.jsx("div",{className:"text-fg-dim font-mono text-[10px] truncate mt-1",title:(k==null?void 0:k.line)??"",children:k?k.line:o.jsx("span",{className:"italic text-fg-faint",children:"waiting for output…"})})]},y.watcherId)})})]})}/**
|
|
2902
2902
|
* dockview-core
|
|
2903
2903
|
* @version 6.6.1
|
|
2904
2904
|
* @link https://github.com/mathuo/dockview
|
|
@@ -3070,7 +3070,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3070
3070
|
|
|
3071
3071
|
${i}`}const yg={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},y4=["popover","review","diff"],IN=["popover","review"];function w4(n,e){switch(e.type){case"SELECT":return{...yg,editCount:n.editCount,phase:"popover",selection:e.selection};case"CANCEL":return{...yg,editCount:n.editCount};case"LISTEN":return IN.includes(n.phase)?{...n,phase:"listening",transcript:"",modelStatus:null}:n;case"HEARD":return n.phase!=="listening"?n:{...n,phase:"review",transcript:e.transcript,modelStatus:null};case"RUN":return y4.includes(n.phase)?{...n,phase:"thinking",instruction:e.recordInstruction?e.instruction:n.instruction}:n;case"RUN_OK":return n.phase!=="thinking"?n:{...n,phase:"diff",diff:e.diff};case"RUN_ERR":return n.phase!=="thinking"?n:{...n,phase:"popover",transcript:"",diff:null};case"ACCEPT":return n.phase!=="diff"?n:{...yg,editCount:n.editCount+1};case"RESET_FILE":return{...yg,editCount:0};case"MODEL_STATUS":return n.phase!=="listening"?n:{...n,modelStatus:`${e.status}: ${e.message}`};default:return n}}function _4(n,e){let i=null;for(const r of e){const s=r.cwd;!s||!(n===s||n.startsWith(s.endsWith("/")?s:`${s}/`))||(i===null||s.length>i.length)&&(i=s)}return i}function S4(n,e,i){var a;let r=null,s=-1/0;for(const d of e){if(d.cwd!==n||d.status!=="dormant")continue;const l=((a=i[d.id])==null?void 0:a.lastEventAt)??0;(r===null||l>s)&&(r=d,s=l)}return r}const k4="sonnet";function C4(n,e){const[i,r]=R.useReducer(w4,yg),s=R.useRef(0),a=R.useRef(null),d=R.useRef(n),l=R.useRef(new Map);R.useEffect(()=>window.api.docEdit.onSessionResult(E=>{const j=l.current.get(E.requestId);j&&(l.current.delete(E.requestId),j(E))}),[]),R.useEffect(()=>{d.current!==n&&(d.current=n,s.current+=1,c(),r({type:"RESET_FILE"}))},[n]);function c(){const E=a.current;E&&(a.current=null,E.stop().catch(()=>{}),E.destroy(),kt.setState({externalRecording:!1}))}const p=R.useCallback(E=>{s.current+=1,c(),r({type:"SELECT",selection:E})},[]),m=R.useCallback(()=>{s.current+=1,c(),r({type:"CANCEL"})},[]),f=R.useCallback(()=>{if(!IN.includes(i.phase))return;if(kt.getState().isRecording){Re.error("Microphone is already in use");return}if(!_y()){Re.error("Microphone or Web Worker not available");return}const E=++s.current;r({type:"LISTEN"}),kt.setState({externalRecording:!0});const j=()=>{a.current===N&&(a.current=null),kt.setState({externalRecording:!1})},N=KT({onFinal:A=>{if(s.current!==E)return;N.stop().catch(()=>{}),N.destroy(),j();const P=A.trim();if(!P){r({type:"CANCEL"});return}r({type:"HEARD",transcript:P})},onError:A=>{s.current===E&&(N.destroy(),j(),Re.error(`Microphone error: ${A}`),r({type:"CANCEL"}))},onModelStatus:(A,P)=>{s.current===E&&r({type:"MODEL_STATUS",status:A,message:P})},onProgress:A=>{s.current===E&&r({type:"MODEL_STATUS",status:"loading",message:`${A}%`})}});a.current=N,N.start().catch(A=>{s.current===E&&(N.destroy(),j(),Re.error(`Could not start mic: ${A instanceof Error?A.message:String(A)}`),r({type:"CANCEL"}))})},[i.phase]),b=R.useCallback(()=>{const E=_4(n,vt.getState().tabs);if(!E)return null;const j=S4(E,vt.getState().tabs,mb.getState().tabs);return!j||An.getState().get(j.id).running?null:j},[n]),_=R.useCallback((E,j,N,A,P,I)=>{const O=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{l.current.set(O,U),window.api.docEdit.runInSession({tabId:E,sessionId:j,cwd:N,before:A,instruction:P,documentText:I,requestId:O})})},[]),y=R.useCallback(async(E,j)=>{const N=i.selection;if(!N)return;const A=++s.current;r({type:"RUN",instruction:E,recordInstruction:j});const P=b4(e);try{const I=b(),O=I?await _(I.id,I.sessionId,I.cwd,N.text,E,P):await window.api.docEdit.run({path:n,before:N.text,instruction:E,documentText:P});if(s.current!==A)return;if(!O.ok){Re.error(O.error||"Edit failed"),r({type:"RUN_ERR"});return}r({type:"RUN_OK",diff:{before:N.text,after:O.after??""}})}catch(I){if(s.current!==A)return;Re.error(I instanceof Error?I.message:"Edit failed"),r({type:"RUN_ERR"})}},[n,i.selection,e,b,_]),k=R.useCallback(E=>{y(E,!0)},[y]),x=R.useCallback(()=>{i.phase==="review"&&y(i.transcript,!0)},[y,i.phase,i.transcript]),w=R.useCallback(()=>{const E=i.instruction;E&&y(`${E}
|
|
3072
3072
|
|
|
3073
|
-
(Give a different rewrite than the last one.)`,!1)},[y,i.instruction]),S=R.useCallback(E=>{const j=i.diff;if(!j)return{ok:!1,reason:"not-found"};const N=v4(E,j.before,j.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Re.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[i.diff]);return{state:i,select:p,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const E4=[{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."}],YC=320,ng=8;function T4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function j4(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,ng),Math.max(ng,e-YC-ng)),r=Math.max(n.top-ng,ng);return{position:"fixed",left:i,top:r,width:YC,transform:"translateY(-100%)",zIndex:50}}function N4({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[_,y]=R.useState(""),k=()=>{const x=_.trim();x&&(d(x),y(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:j4(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"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"}),E4.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:_,onChange:x=>y(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():x.key==="Escape"&&p()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(T4,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function D4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function XC({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,onReject:p,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:rv(k4)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(D4,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function JC(n){return n.split("/").filter(Boolean).pop()||n}function A4({path:n,onRenamed:e,onDeleted:i}){const[r,s]=R.useState(!1),[a,d]=R.useState(!1),[l,c]=R.useState(""),[p,m]=R.useState(!1),f=Pn(U=>U.buffers[n]),b=Pn(U=>U.openFile),_=Pn(U=>U.renameOpenFile),y=Pn(U=>U.closeFile),k=cd(),x=JC(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},E=async()=>{const U=l.trim();if(!U||U===x){d(!1);return}try{const B=await window.api.files.rename(n,U);if(B.ok){const J=n.slice(0,n.lastIndexOf("/")),Z=B.newPath??`${J}/${U}`;_(n,Z),e==null||e(n,Z),Re.info(`Renamed to ${U}`)}else Re.error(B.error??`Couldn't rename ${x}`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't rename ${x}`)}d(!1)},j=async()=>{w();try{const U=await window.api.files.duplicate(n);U.ok&&U.path?(b(U.path),Re.info(`Duplicated as ${JC(U.path)}`)):Re.error(U.error??`Couldn't duplicate ${x}`)}catch(U){Re.error(U instanceof Error?U.message:`Couldn't duplicate ${x}`)}},N=async()=>{try{const U=await window.api.files.delete(n);U.ok?(y(n),i==null||i(n),Re.info(`Deleted ${x}`)):Re.error(U.error??`Couldn't delete ${x}`)}catch(U){Re.error(U instanceof Error?U.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{w();const U=f??"";try{await navigator.clipboard.writeText(U),Re.info(`Copied ${U.length} chars`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Re.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Re.info(`Added ${x} to Claude context`)},I=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(U=>{U.ok||Re.error(U.error??`Couldn't open ${x}`)}).catch(U=>Re.error(U instanceof Error?U.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(U=>{U.ok||Re.error(U.error??`Couldn't reveal ${x}`)}).catch(U=>Re.error(U instanceof Error?U.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:w}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[o.jsx(Pw,{children:"Edit"}),o.jsx(cu,{label:"Rename",onClick:S}),o.jsx(cu,{label:"Duplicate",onClick:j}),o.jsx(cu,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(ZC,{}),o.jsx(Pw,{children:"Open"}),o.jsx(cu,{label:"Open in default app",onClick:I}),o.jsx(cu,{label:"Reveal in OS",onClick:O}),o.jsx(ZC,{}),o.jsx(Pw,{children:"Export"}),o.jsx(cu,{label:"Copy as Markdown",onClick:A}),o.jsx(cu,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx($4,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void E()}),p&&o.jsx(P4,{name:x,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function Pw({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function cu({label:n,onClick:e,danger:i,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function ZC(){return o.jsx("div",{className:"my-1 border-t border-line"})}function $4({value:n,onChange:e,onCancel:i,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&i()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function P4({name:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function R4(){const[n,e]=R.useState(!1),i=Ap();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[o.jsx(Sp,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(Sp,{label:"Word wrap",children:o.jsx(Fx,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(Sp,{label:"Minimap",children:o.jsx(Fx,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(Sp,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(Sp,{label:"Autosave",children:o.jsx(Fx,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(Sp,{label:"Wide measure",children:o.jsx(Fx,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function Sp({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Fx({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const I4=R.lazy(()=>nv(()=>import("./TiptapBody-6GmgSP5x.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Gx(n){return n.split("/").filter(Boolean).pop()||n}function Ux(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Hx(n){return pN(n)||fN(n)}function Yb(){const n=cv(),e=Pn(Je=>Je.openFiles),i=Pn(Je=>Je.activeFilePath),r=Pn(Je=>Je.dirty),s=Pn(Je=>Je.viewMode),a=Pn(Je=>Je.buffers),d=Pn(Je=>Je.setActive),l=Pn(Je=>Je.closeFile),c=Pn(Je=>Je.closeOthers),p=Pn(Je=>Je.closeToTheRight),m=Pn(Je=>Je.closeAll),f=Pn(Je=>Je.loadBuffer),b=Pn(Je=>Je.setBuffer),_=Pn(Je=>Je.markSaved),y=Pn(Je=>Je.setViewMode),k=Ap(),[x,w]=R.useState({}),[S,E]=R.useState({}),[j,N]=R.useState(null),[A,P]=R.useState(null),[I,O]=R.useState(!1),[U,B]=R.useState(!1),[J,Z]=R.useState(!0),W=R.useRef(null),q=R.useRef(null),Q=R.useRef(void 0),oe=R.useRef(null),le=R.useRef(null),H=C4(i??"",a[i??""]??""),ee=R.useCallback(Je=>{W.current=Je},[]),Y=R.useCallback(()=>W.current,[]);R.useEffect(()=>{const Je=i;if(!Je||Hx(Je))return;if(Pn.getState().hasBuffer(Je)){w(xt=>xt[Je]==="ready"?xt:{...xt,[Je]:"ready"});return}let Ct=!1;return w(xt=>({...xt,[Je]:"loading"})),window.api.files.read(Je).then(xt=>{Ct||(xt.binary?w(pn=>({...pn,[Je]:{binary:!0,size:xt.size??0,mime:xt.mime??"application/octet-stream",reason:xt.error??"Binary file"}})):xt.ok?(f(Je,xt.text),w(pn=>({...pn,[Je]:"ready"}))):w(pn=>({...pn,[Je]:{error:xt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),R.useEffect(()=>{P(null)},[i]);const ce=R.useCallback(async(Je,Ct=!1)=>{const xt=Pn.getState().buffers[Je];if(xt==null)return;Ct&&O(!0);const pn=await window.api.files.write(Je,xt);pn.ok?(_(Je),E($n=>({...$n,[Je]:($n[Je]??0)+1})),Ct||Re.info(`Saved ${Gx(Je)}`)):Re.error(pn.error??`Couldn't save ${Gx(Je)}`),Ct&&O(!1)},[_]);R.useEffect(()=>{if(!k.autosave)return;const Je=i;if(!(!Je||Hx(Je)||!r[Je]))return window.clearTimeout(Q.current),Q.current=window.setTimeout(()=>{ce(Je,!0)},1200),()=>window.clearTimeout(Q.current)},[k.autosave,i,r,a,ce]);const ae=R.useCallback(Je=>{Je.length&&(w(Ct=>Ux(Ct,Je)),E(Ct=>Ux(Ct,Je)))},[]),xe=R.useCallback((Je,Ct)=>{w(xt=>Je in xt?{...Ux(xt,[Je]),[Ct]:xt[Je]}:xt),E(xt=>Je in xt?{...Ux(xt,[Je]),[Ct]:xt[Je]}:xt)},[]),Ne=R.useCallback(Je=>{r[Je]?N({kind:"one",path:Je}):(l(Je),ae([Je]))},[r,l,ae]),me=R.useCallback(Je=>{e.some(xt=>xt.path!==Je&&r[xt.path])?N({kind:"others",path:Je}):(c(Je),ae(e.filter(xt=>xt.path!==Je).map(xt=>xt.path)))},[e,r,c,ae]),re=R.useCallback(Je=>{const Ct=e.findIndex(pn=>pn.path===Je);Ct!==-1&&e.slice(Ct+1).some(pn=>r[pn.path])?N({kind:"right",path:Je}):(p(Je),ae(Ct!==-1?e.slice(Ct+1).map(pn=>pn.path):[]))},[e,r,p,ae]);R.useEffect(()=>{const Je=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const xt=Pn.getState().activeFilePath;xt&&!Hx(xt)&&(Ct.preventDefault(),ce(xt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),B(xt=>!xt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const xt=Pn.getState().activeFilePath;xt&&Pn.getState().openFiles.length>1&&(Ct.preventDefault(),me(xt))}else Ct.key==="Escape"&&H.state.phase!=="idle"?H.cancel():Ct.key==="Escape"&&U&&B(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ce,U,me,H.state.phase,H.cancel]),R.useEffect(()=>{if(H.state.phase==="idle")return;const Je=Ct=>{var pn,$n;const xt=Ct.target;(pn=le.current)!=null&&pn.contains(xt)||($n=oe.current)!=null&&$n.contains(xt)||H.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[H.state.phase,H.cancel]),R.useEffect(()=>{H.cancel()},[i,H.cancel]);const te=R.useCallback(()=>{e.some(Ct=>r[Ct.path])?N({kind:"all",path:""}):(m(),w({}),E({}))},[e,r,m]),we=()=>{if(j){if(j.kind==="one")l(j.path),ae([j.path]);else if(j.kind==="others"){const Je=e.filter(Ct=>Ct.path!==j.path).map(Ct=>Ct.path);c(j.path),ae(Je)}else if(j.kind==="right"){const Je=e.findIndex(xt=>xt.path===j.path),Ct=Je!==-1?e.slice(Je+1).map(xt=>xt.path):[];p(j.path),ae(Ct)}else m(),w({}),E({});N(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const be=i,Ue=be?Gx(be):"",et=be?x[be]:void 0,ut=be?vN(be):!1,zt=be?D5(be):!1,pt=be&&ut?s[be]??A5(be):"edit",it=!!be&&!Hx(be)&&et==="ready",ot=it,Dt=zt?["edit","wysiwyg","preview","split"]:ut?["edit","preview"]:[],sn=be&&o.jsx(z5,{path:be,name:Ue,value:a[be]??"",onChange:Je=>b(be,Je),onSave:()=>void ce(be),onReady:ee,onCursor:P}),gn=I?"Saving…":be&&r[be]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&o.jsx(I5,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:Ne,onCloseOthers:me,onCloseToTheRight:re,onCloseAll:te}),be&&!U&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ue}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:be}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",gn]}),Ml(be)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Z(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${J?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ml(be)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Je=>o.jsx("button",{onClick:()=>y(be,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),o.jsx("div",{className:"flex-1"}),o.jsx(A4,{path:be,onRenamed:xe,onDeleted:Je=>ae([Je])}),it&&o.jsx(R4,{}),o.jsx("button",{onClick:()=>B(!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&&o.jsx("button",{onClick:()=>B(!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"}),o.jsx("div",{className:"flex-1 min-h-0",children:be?pN(be)?o.jsx(l4,{path:be,name:Ue}):fN(be)?o.jsx(c4,{path:be}):et&&typeof et=="object"&&"binary"in et?o.jsx(g4,{path:be,name:Ue,size:et.size,mime:et.mime,reason:et.reason}):et&&typeof et=="object"&&"error"in et?o.jsx("div",{className:"p-6 text-xs text-red-400",children:et.error}):et!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ml(be)?o.jsx(R.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(I4,{value:a[be]??"",onChange:Je=>b(be,Je)},be)}):pt==="split"&&Ml(be)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(VC,{text:a[be]??"",scrollRef:q}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(WC,{getEditor:Y}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),o.jsx("div",{ref:oe,className:"flex-1 min-w-0",children:o.jsx(X_,{ref:q,text:a[be]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:H.select,onDismissSelection:H.cancel})}),!U&&k.assistantRail&&o.jsx(XC,{phase:H.state.phase,transcript:H.state.transcript,diff:H.state.diff,editCount:H.state.editCount,modelStatus:H.state.modelStatus,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)},onReject:H.cancel,onRetry:H.retry})]}):pt==="preview"&&Ml(be)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(VC,{text:a[be]??"",scrollRef:q}),o.jsx("div",{ref:oe,className:"flex-1 min-w-0",children:o.jsx(X_,{ref:q,text:a[be]??"",wideMeasure:k.wideMeasure,onSelect:H.select,onDismissSelection:H.cancel})}),!U&&k.assistantRail&&o.jsx(XC,{phase:H.state.phase,transcript:H.state.transcript,diff:H.state.diff,editCount:H.state.editCount,modelStatus:H.state.modelStatus,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)},onReject:H.cancel,onRetry:H.retry})]}):pt==="preview"&&hN(be)?o.jsx(o4,{path:be,dirty:!!r[be],reloadToken:S[be]??0}):pt==="preview"&&mN(be)?o.jsx(u4,{path:be,text:a[be]??""}):pt==="preview"&&gN(be)?o.jsx(f4,{path:be,text:a[be]??""}):Ml(be)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(WC,{getEditor:Y}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),ot&&o.jsx(s4,{text:a[be]??"",cursor:A,language:no(be)||void 0}),be&&Ml(be)&&(pt==="preview"||pt==="split")&&H.state.phase!=="idle"&&H.state.selection&&o.jsx("div",{ref:le,children:o.jsx(N4,{phase:H.state.phase,rect:H.state.selection.rect,diff:H.state.diff,transcript:H.state.transcript,modelStatus:H.state.modelStatus,onQuickAction:H.run,onRunCustom:H.run,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onReject:H.cancel,onRetry:H.retry,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)}})}),j&&o.jsx(M4,{message:j.kind==="one"?`Discard unsaved changes to ${Gx(j.path)}?`:j.kind==="others"?"Discard unsaved changes in the other open files?":j.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:we})]})}function M4({message:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const QC={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},O4={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function Rw(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function L4({open:n,onClose:e,variant:i="overlay"}){const r=vt(N=>N.tabs.find(A=>A.id===N.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=R.useState(null),[l,c]=R.useState(!1),[p,m]=R.useState(null),f=R.useRef(null),b=R.useCallback(async N=>{c(!0),m(null);try{const A=await window.api.repo.analyze(N);A.ok?d(A):(m(A.error||"Analysis failed"),d(null))}catch(A){m(A instanceof Error?A.message:String(A)),d(null)}finally{c(!1)}},[]);R.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),R.useEffect(()=>{var A;if(!n)return;const N=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",N),(A=f.current)==null||A.focus(),()=>window.removeEventListener("keydown",N)},[n,e]);const _=R.useCallback(()=>{s&&b(s)},[s,b]),y=R.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([A,P])=>[A,P.files,P.lines]).sort((A,P)=>P[1]-A[1]).slice(0,12):[],[a]),k=R.useMemo(()=>y.length===0?1:y[0][1],[y]),x=R.useMemo(()=>{if(!a)return[];const N=a.topDirectories;if(N.length===0)return[];const A=N.map(I=>Math.sqrt(Math.max(1,I.fileCount))),P=A.reduce((I,O)=>I+O,0)||1;return N.map((I,O)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:A[O]/P*100}))},[a]);if(!n)return null;const w=N=>{N.target===N.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=i==="page",j=o.jsx("div",{className:E?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:E?void 0:w,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,role:E?void 0:"dialog","aria-modal":E?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:E?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[S,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:_,disabled:l||!s,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):p?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:p})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Iw,{label:"Files",value:Rw(a.totalFiles)}),o.jsx(Iw,{label:"Lines of code",value:Rw(a.totalLines)}),o.jsx(Iw,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),y.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:y.map(([N,A,P])=>{const I=QC[N]??QC.other,O=O4[N]??N,U=A/k*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:O,children:O}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[A," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[Rw(P)," L"]})]},N)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(N=>o.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max(N.basis,6)}%`,flexGrow:N.basis>15?1:0},title:`${N.path} — ${N.fileCount} files, ${N.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:N.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[N.fileCount," files"]})]},N.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!E&&typeof document<"u"&&document.body?Iu.createPortal(j,document.body):j}function Iw({label:n,value:e,tone:i="neutral"}){const r=i==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:n})]})}const e2=n=>/[/\\\-_.\s]/.test(n),t2=n=>n>="A"&&n<="Z";function z4(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||e2(l[p-1])||t2(d[p])?650:600,matched:Array.from({length:n.length},(S,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,_=-1,y=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,_===w-1?(b++,f+=b*8):b=0,(w===0||e2(s[w-1])||t2(e[w]))&&(y++,f+=15,w===0&&(f+=10)),_=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,y>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function Mw(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function n2(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const i2="session-manager.quickopen.recent",B4=8;function F4({open:n,onClose:e,variant:i="overlay"}){const r=vt(O=>O.tabs.find(U=>U.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState([]),[p,m]=R.useState(!1),[f,b]=R.useState(0),[_,y]=R.useState([]),k=R.useRef(null),x=R.useRef(null);R.useEffect(()=>{if(n)try{const O=localStorage.getItem(i2);O&&y(JSON.parse(O))}catch{}},[n]),R.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var U;return(U=k.current)==null?void 0:U.focus()},0);return()=>clearTimeout(O)},[n]),R.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(U=>{if(!O){if(!U.ok){Re.error(`File search failed: ${U.error??"unknown error"}`),c([]);return}c(U.files)}}).catch(U=>{const B=U instanceof Error?U.message:String(U);ht.error("quick-open","search.files threw",{error:B},{cwd:s,tabId:r==null?void 0:r.id}),Re.error(`File search failed: ${B}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=R.useMemo(()=>{if(!a.trim())return[...l].sort((J,Z)=>J.name.localeCompare(Z.name)).slice(0,100).map(J=>({file:J,score:0,matched:[]}));const O=a.trim(),U=[];for(const B of l){const J=z4(O,B.name,B.path);J.match&&U.push({file:B,score:J.score,matched:J.matched})}return U.sort((B,J)=>J.score-B.score),U.slice(0,100)},[l,a]),S=R.useMemo(()=>a.trim()?[]:_.map(O=>l.find(U=>U.path===O)||null).filter(O=>O!==null).slice(0,5),[_,l,a]);R.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),R.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const E=R.useCallback(O=>{try{const Z=[O,..._.filter(W=>W!==O)].slice(0,B4);y(Z),localStorage.setItem(i2,JSON.stringify(Z))}catch{}const U=r==null?void 0:r.id;if(!U){Re.error("No active tab to receive file path");return}const J=(s?Mw(O,s):O)||O;try{window.api.pty.write({tabId:U,data:J})}catch(Z){const W=Z instanceof Error?Z.message:String(Z);ht.error("quick-open","pty.write failed",{error:W},{cwd:s,tabId:U}),Re.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,_,e]),j=R.useCallback(O=>{const U=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),U===0)return;b(B=>Math.min(U-1,B+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),U===0)return;b(B=>Math.max(0,B-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Z=S[f];Z&&E(Z.path);return}const B=f-S.length,J=w[B];J&&E(J.file.path)}},[f,w,S,E,e]);if(!n)return null;const N=(O,U)=>{if(U.length===0)return O;const B=new Set(U);return O.split("").map((J,Z)=>o.jsx("span",{className:B.has(Z)?"text-accent font-semibold":"",children:J},Z))};let A=-1;const P=i==="page",I=o.jsx("div",{className:P?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:j,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:k,type:"text",value:a,onChange:O=>{d(O.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:p?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?S.length===0&&w.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[S.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),S.map(O=>{A++;const U=A,B=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":B,onClick:()=>E(O.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${B?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Mw(n2(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),w.map(({file:O,matched:U})=>{A++;const B=A,J=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":J,onClick:()=>E(O.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${J?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:N(O.name,U)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Mw(n2(O.path),s)})]},O.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Iu.createPortal(I,document.body):I}function r2(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function G4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function U4({open:n,onClose:e,variant:i="overlay"}){const r=vt(Z=>Z.tabs.find(W=>W.id===Z.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState(!1),[p,m]=R.useState([]),[f,b]=R.useState(!1),[_,y]=R.useState(null),[k,x]=R.useState(0),[w,S]=R.useState(null),E=R.useRef(null),j=R.useRef(null),N=R.useRef(0);R.useEffect(()=>{if(!n){d(""),m([]),y(null),x(0);return}const Z=setTimeout(()=>{var W;return(W=E.current)==null?void 0:W.focus()},0);return()=>clearTimeout(Z)},[n]),R.useEffect(()=>{if(!n||!s)return;const Z=a.trim();if(!Z){m([]),y(null),b(!1);return}const W=++N.current;b(!0);const q=setTimeout(()=>{window.api.search.text(s,Z,{caseSensitive:l,limit:500}).then(Q=>{W===N.current&&(Q.ok?(m(Q.matches),y(null)):(y(Q.error??"unknown error"),m([])),S(Q.usedRipgrep))}).catch(Q=>{if(W!==N.current)return;const oe=Q instanceof Error?Q.message:String(Q);ht.error("global-search","search.text threw",{error:oe},{cwd:s,tabId:r==null?void 0:r.id}),y(oe),m([])}).finally(()=>{W===N.current&&b(!1)})},250);return()=>clearTimeout(q)},[n,s,a,l]);const A=R.useMemo(()=>{const Z=new Map;for(const q of p){const Q=Z.get(q.path);Q?Q.push(q):Z.set(q.path,[q])}const W=[];for(const[q,Q]of Z)W.push({path:q,matches:Q});return W.sort((q,Q)=>Q.matches.length-q.matches.length||q.path.localeCompare(Q.path)),W},[p]),P=R.useMemo(()=>p,[p]);R.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),R.useEffect(()=>{if(!j.current)return;const Z=j.current.querySelector(`[data-match="${k}"]`);Z&&Z.scrollIntoView({block:"nearest"})},[k]);const I=R.useCallback(Z=>{const W=r==null?void 0:r.id;if(!W){Re.error("No active tab to receive path");return}const Q=`${(s?r2(Z.path,s):Z.path)||Z.path}:${Z.line}`;try{window.api.pty.write({tabId:W,data:Q})}catch(oe){const le=oe instanceof Error?oe.message:String(oe);ht.error("global-search","pty.write failed",{error:le},{cwd:s,tabId:W}),Re.error(`Failed to write to terminal: ${le}`);return}e()},[r==null?void 0:r.id,s,e]),O=R.useCallback(Z=>{if(Z.key==="Escape"){Z.preventDefault(),e();return}if(Z.key==="ArrowDown"){if(Z.preventDefault(),P.length===0)return;x(W=>Math.min(P.length-1,W+1));return}if(Z.key==="ArrowUp"){if(Z.preventDefault(),P.length===0)return;x(W=>Math.max(0,W-1));return}if(Z.key==="Enter"){Z.preventDefault();const W=P[k];W&&I(W)}},[P,k,I,e]);if(!n)return null;const U=i==="page";let B=-1;const J=o.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:Z=>{Z.target===Z.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:O,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:E,type:"text",value:a,onChange:Z=>{d(Z.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),o.jsx("button",{type:"button",onClick:()=>c(Z=>!Z),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:j,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):_?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:_}):P.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:A.map(Z=>o.jsxs("div",{children:[o.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[r2(Z.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Z.matches.length,")"]})]}),Z.matches.map(W=>{B++;const q=B,Q=q===k;return o.jsxs("button",{"data-match":q,role:"option","aria-selected":Q,onClick:()=>I(W),onMouseEnter:()=>x(q),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${Q?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:G4(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${q}`)})]},Z.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Iu.createPortal(J,document.body):J}const H4=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function W4({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=R.useState(r);return R.useEffect(()=>{a(r)},[r]),n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(Ql,{options:H4,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(F4,{open:!0,onClose:e,variant:"page"}):o.jsx(U4,{open:!0,onClose:e,variant:"page"})})]}):null}const V4={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},s2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function ef({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${d?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=R.useRef(null),p=R.useRef(null),m=R.useRef(e);if(m.current=e,R.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const y=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(s2);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(s2)).filter(A=>!A.hasAttribute("disabled")&&A.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const E=S[0],j=S[S.length-1],N=document.activeElement;x.shiftKey?(N===E||!w.contains(N))&&(x.preventDefault(),j.focus()):(N===j||!w.contains(N))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(y),document.removeEventListener("keydown",k);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[n]),!n)return null;const f=_=>{_.target===_.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":r??"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 ${V4[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:i}):i]})});return typeof document<"u"&&document.body?Iu.createPortal(b,document.body):b}class MN extends R.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.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 q4({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(ef,{open:n,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:i}),o.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:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(MN,{children:r})})]})}function ON(n,e={}){switch(n){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 o2=n=>Symbol.iterator in n,a2=n=>"entries"in n,l2=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},K4=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function Y4(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:o2(n)&&o2(e)?a2(n)&&a2(e)?l2(n,e):K4(n,e):l2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function A1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return Y4(e.current,r)?e.current:e.current=r}}let c2=0;const X4=1e3;function J4(n){const e=performance.now();e-c2<X4||(c2=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function LN(){const n=kt(p=>p.isRecording),e=kt(p=>p.error),i=kt(p=>p.loadingProgress),r=kt(A1(Mb)),s=()=>{const p=kt.getState(),{canRecord:m,reason:f}=Mb(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return J4(f);const b=vt.getState().activeTabId;b&&p.startRecording(b)},a=ON(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function Z4(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Q4(n){return/^monitor of /i.test(n.trim())}function d2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function u2(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=d2(e),a=i.filter(d=>d.label&&d2(d.label)===s);return a.length===1?a[0]:null}async function h2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&Q4(r.label))):[]}const p2=!1;function zN(){const n=kt(p=>p.isRecording);kt(p=>p.startRecording),kt(p=>p.stopRecording);const[e,i]=R.useState([]),[r,s]=R.useState(null),[a,d]=R.useState(null);R.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await h2(p2);if(p)return;i(f),d(m.selectedLabel);const b=u2(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=R.useCallback(async()=>{try{const p=await h2(p2);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=u2(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){ht.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);R.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const c=async p=>{var _;const m=p.target.value,f=m===""?null:m,b=f?((_=e.find(y=>y.deviceId===f))==null?void 0:_.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(y){ht.warn("voice","setDevicePref failed",{error:y instanceof Error?y.message:String(y)})}if(n)try{await kt.getState().restartWithDevice()}catch(y){ht.warn("voice","device-picker restart failed",{error:y instanceof Error?y.message:String(y)})}};return o.jsxs("select",{value:r??"",onChange:c,onFocus:()=>{l()},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:[o.jsx("option",{value:"",children:"Default"}),e.map(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function eB(){const n=kt(_=>_.isRecording),e=kt(_=>_.levelMeterEnabled),[i,r]=R.useState(0),[s,a]=R.useState(0),d=R.useRef(0);d.current=s;const[l,c]=R.useState(0),[p,m]=R.useState(!1),f=R.useRef(null);if(R.useEffect(()=>{if(!n||!e){r(0),a(0);return}let _=0,y=!1,k=null,x=null;const w=()=>{if(y)return;const E=x??JT();if(!E){_=requestAnimationFrame(w);return}x!==E&&(x=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=k;E.getByteTimeDomainData(j);let N=0;for(let O=0;O<j.length;O++){const U=j[O]-128;N+=U*U}const A=Math.sqrt(N/j.length)/128,P=A>0?20*Math.log10(A):-60,I=Math.max(0,Math.min(1,(P+60)/60));a(A),r(I),A>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),_=requestAnimationFrame(w)};_=requestAnimationFrame(w);const S=setInterval(()=>{y||c(Math.round(d.current*100))},250);return()=>{y=!0,cancelAnimationFrame(_),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const b=p?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function BN(){const n=kt(p=>p.submitCountdownStartAt),e=kt(p=>p.submitDelayMs),[i,r]=R.useState(()=>performance.now());if(R.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${d}%`}})})})}function tB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(q4,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(sB,{}),o.jsx(BN,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(LN,{}),o.jsx(zN,{}),o.jsx(Z4,{})]}),o.jsx(nB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(rB,{})]}),o.jsx(eB,{})]})})}function nB(){const n=kt(a=>a.isRecording),[e,i]=R.useState(null);if(R.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=iB(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function iB(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.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 rB(){const[n,e]=R.useState(null);if(R.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.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:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="toggle",onChange:()=>i("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function sB(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Ow=null;function oB(){return Ow||(Ow=nv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(m1.config({monaco:n}),n))),Ow}function FN({value:n,onChange:e,path:i,readOnly:r}){const s=R.useRef(null),a=d=>{s.current=d};return o.jsx(g1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),onMount:a,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let f2=!1;async function aB(n){if(f2)return;const e=await oB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),f2=!0}function $1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=R.useState(""),[l,c]=R.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:br[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:_=>d(_.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(GN,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function GN(n){return n.node.kind==="object"?o.jsx(lB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(cB,{...n,node:n.node}):o.jsx(dB,{...n,node:n.node})}function m2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Wp(n,e,i){return!!(!i.trim()||n.some(r=>m2(r,i))||e!=null&&e.description&&m2(e.description,i))}function lB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:p}){const[m,f]=R.useState(p??d<2),b=(l==null?void 0:l.at(e))??null,_=new Set(Object.keys(n.children)),y=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([..._,...y])).sort(),x=R.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Wp([...e,S],E,a)?!0:_.has(S)?UN(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Wp(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",_.size,y.length>_.size?`/${new Set([..._,...y]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(S=>w(S))]});function w(S){if(_.has(S))return o.jsx(GN,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(uB,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function UN(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Wp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(UN(n.children[a],[...e,a],i,r))return!0;return!1}function cB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=R.useState(!0),c=(a==null?void 0:a.at(e))??null;return Wp(e,c,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(qg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.items.map((p,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:Xb(p.value)}),o.jsx(Q_,{scope:p.fromScope})]},m))]}):null}function dB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,p]=R.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Wp(e,m,a))return null;const f=n.winner!==r,b=n.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Xb(n.value)}),o.jsx(Q_,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(qg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&hB(n.value,m.default)&&o.jsx(qg,{tone:"dim",children:"= default"}),n.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(HN,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((_,y)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Xb(_.value)}),o.jsx(Q_,{scope:_.scope,dim:!0})]},y))]})}function uB({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Wp(n,i,d))return null;const l=i.default!==void 0?i.default:pB(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(qg,{tone:"dim",children:c}),i.required&&o.jsx(qg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Xb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(HN,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,l),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${br[r].label} draft`,children:"set"})]})}function hB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function pB(n){switch(Array.isArray(n)?n[0]:n){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function Xb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function Q_({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function qg({children:n,tone:e="default"}){const i={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i}`,children:n})}function HN({values:n}){const e=n.map(i=>String(i)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const fB=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],mB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function WN(n){return n.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((r,s)=>{const a=mB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function VN(n){const e=new Set,i=[];for(const s of fB){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function gB(n,e){return VN(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const vB={};function qN(n,e){if(e)return{text:e,authored:!1};const i=vB[n];return i?{text:i,authored:!0}:null}const xB={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},bB=["user","project","local","default"],yB={user:"user",project:"project",local:"local",default:"default"};function wB({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=R.useState(""),[d,l]=R.useState(!1),[c,p]=R.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),_=new Set([...f,...b]),y=R.useMemo(()=>VN(_),[Array.from(_).sort().join(",")]),k=R.useMemo(()=>gB(_,new Set(f)),[Array.from(_).sort().join(","),f.join(",")]),[x,w]=R.useState(null),S=R.useRef(null),E=N=>{const A=y.find(P=>P.id===N);A!=null&&A.advanced&&!d&&l(!0),w(N)};R.useEffect(()=>{if(!x)return;w(null);const N=S.current,A=document.getElementById(`settings-group-${x}`);if(!N||!A)return;const P=A.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:P,behavior:"smooth"})},[x]);const j=R.useMemo(()=>y.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter(A=>{const P=(m==null?void 0:m.children[A])!==void 0;if(!c&&!P)return!1;if(!s.trim())return!0;const I=r.at([A]);return[A,WN(A),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[y,s,d,c,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:N=>p(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>l(N.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:N=>a(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx(_B,{groups:k,onJump:E}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[j.map(N=>o.jsx(SB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map(A=>{const P=m==null?void 0:m.children[A],I=r.at([A]);return o.jsx(kB,{keyName:A,node:P,info:I,targetScope:e,onOverride:(O,U)=>i([A],O,U)},A)})},N.id)),j.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function _B({groups:n,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(an,{name:xB[i.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function SB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=R.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function kB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=R.useState(!1),[l,c]=R.useState(!1),p=WN(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,_=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",y=i==null?void 0:i.default,k=b&&y!==void 0&&YN(b.value,y),x=$B({isSet:m,leafNode:b,defaultVal:y,isDefault:!!k,node:e}),w=CB(b,y),S=w.length>=2,E=!!b&&!k,j=qN(n,i==null?void 0:i.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>d(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:p}),o.jsx(PB,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||d(!0),c(A=>!A)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",w.map(N=>yB[N]).join(" · ")]}),E&&b&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,b.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.deprecated)&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(i==null?void 0:i.required)&&!m&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),j&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${j.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:j.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:RB(j.text)}),a&&l&&b&&o.jsx(EB,{leaf:b,defaultVal:y,onReset:N=>s(void 0,N)}),a&&o.jsx(TB,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(AB,{node:e,info:i,onSet:N=>{s(N)},disabled:_&&m})})]})})}function CB(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),bB.filter(r=>i.has(r))}function EB({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],d=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?Lp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(s),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${br[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?Lp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function TB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=qN(n,i==null?void 0:i.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Lp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:Lp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Lp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.scope].label})]},p))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(jB,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function jB({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=KN(e==null?void 0:e.type);if(d==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:c,label:p})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const c=YN(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(NB,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(DB,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function NB({value:n,integer:e,onCommit:i,target:r}){const[s,a]=R.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:d,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function DB({value:n,onCommit:e,target:i}){const[r,s]=R.useState(n);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function AB({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=KN(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function $B({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Lp(i)}`}:{kind:"unset",label:"not configured"}}function PB({kind:n,label:e}){const i={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function KN(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function YN(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function RB(n){const e=n.trim().split(`
|
|
3073
|
+
(Give a different rewrite than the last one.)`,!1)},[y,i.instruction]),S=R.useCallback(E=>{const j=i.diff;if(!j)return{ok:!1,reason:"not-found"};const N=v4(E,j.before,j.after);return N.ok?(s.current+=1,r({type:"ACCEPT"})):Re.error(N.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),N},[i.diff]);return{state:i,select:p,cancel:m,listen:f,sendHeard:x,run:k,retry:w,accept:S}}const E4=[{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."}],YC=320,ng=8;function T4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function j4(n){const e=typeof window<"u"?window.innerWidth:1024,i=Math.min(Math.max(n.left,ng),Math.max(ng,e-YC-ng)),r=Math.max(n.top-ng,ng);return{position:"fixed",left:i,top:r,width:YC,transform:"translateY(-100%)",zIndex:50}}function N4({phase:n,rect:e,diff:i,transcript:r,modelStatus:s,onQuickAction:a,onRunCustom:d,onListen:l,onSendHeard:c,onCancel:p,onAccept:m,onReject:f,onRetry:b}){const[_,y]=R.useState(""),k=()=>{const x=_.trim();x&&(d(x),y(""))};return o.jsxs("div",{"data-doc-edit-popover":!0,style:j4(e),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[n==="popover"&&o.jsxs("div",{className:"p-2",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsxs("div",{className:"flex flex-wrap gap-1",children:[o.jsx("button",{onClick:l,"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"}),E4.map(x=>o.jsx("button",{onClick:()=>a(x.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:x.label},x.label))]}),o.jsx("button",{onClick:p,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),o.jsx("input",{autoFocus:!0,value:_,onChange:x=>y(x.target.value),onKeyDown:x=>{x.key==="Enter"?k():x.key==="Escape"&&p()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),n==="listening"&&o.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[o.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(T4,{}),"Listening…"]}),s&&o.jsx("span",{className:"text-[10px] text-fg-faint",children:s})]}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[o.jsxs("p",{className:"italic text-fg mb-2",children:["«",r,"»"]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsxs("div",{className:"p-3 flex items-center justify-between",children:[o.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),o.jsx("button",{onClick:p,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="diff"&&i&&o.jsxs("div",{className:"p-3",children:[o.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]}),o.jsxs("div",{className:"flex justify-end gap-1.5",children:[o.jsx("button",{onClick:f,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:b,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function D4(){return o.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),o.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function XC({phase:n,transcript:e,diff:i,editCount:r,modelStatus:s,onListen:a,onSendHeard:d,onCancel:l,onAccept:c,onReject:p,onRetry:m}){return o.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[o.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[o.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),o.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:rv(k4)})]}),o.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[n==="idle"&&o.jsxs("div",{className:"text-fg-faint",children:[o.jsx("p",{children:"Select text in the doc…"}),o.jsxs("p",{className:"mt-2 text-[10px]",children:[r," edit",r===1?"":"s"," this session"]})]}),n==="popover"&&o.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),n==="listening"&&o.jsxs("div",{children:[o.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[o.jsx(D4,{}),"Listening…"]}),s&&o.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:s}),o.jsx("button",{onClick:l,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),n==="review"&&o.jsxs("div",{children:[o.jsxs("p",{className:"italic text-fg mb-3",children:["«",e,"»"]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:a,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),o.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),n==="thinking"&&o.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),n==="diff"&&i&&o.jsxs("div",{children:[o.jsxs("div",{className:"mb-3 space-y-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),o.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:i.before})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),o.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:i.after})]})]}),o.jsxs("div",{className:"flex gap-1.5",children:[o.jsx("button",{onClick:p,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),o.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),o.jsx("button",{onClick:c,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function JC(n){return n.split("/").filter(Boolean).pop()||n}function A4({path:n,onRenamed:e,onDeleted:i}){const[r,s]=R.useState(!1),[a,d]=R.useState(!1),[l,c]=R.useState(""),[p,m]=R.useState(!1),f=Pn(U=>U.buffers[n]),b=Pn(U=>U.openFile),_=Pn(U=>U.renameOpenFile),y=Pn(U=>U.closeFile),k=cd(),x=JC(n),w=()=>s(!1),S=()=>{c(x),d(!0),w()},E=async()=>{const U=l.trim();if(!U||U===x){d(!1);return}try{const B=await window.api.files.rename(n,U);if(B.ok){const J=n.slice(0,n.lastIndexOf("/")),Z=B.newPath??`${J}/${U}`;_(n,Z),e==null||e(n,Z),Re.info(`Renamed to ${U}`)}else Re.error(B.error??`Couldn't rename ${x}`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't rename ${x}`)}d(!1)},j=async()=>{w();try{const U=await window.api.files.duplicate(n);U.ok&&U.path?(b(U.path),Re.info(`Duplicated as ${JC(U.path)}`)):Re.error(U.error??`Couldn't duplicate ${x}`)}catch(U){Re.error(U instanceof Error?U.message:`Couldn't duplicate ${x}`)}},N=async()=>{try{const U=await window.api.files.delete(n);U.ok?(y(n),i==null||i(n),Re.info(`Deleted ${x}`)):Re.error(U.error??`Couldn't delete ${x}`)}catch(U){Re.error(U instanceof Error?U.message:`Couldn't delete ${x}`)}m(!1)},A=async()=>{w();const U=f??"";try{await navigator.clipboard.writeText(U),Re.info(`Copied ${U.length} chars`)}catch(B){Re.error(B instanceof Error?B.message:`Couldn't copy ${x}`)}},P=()=>{if(w(),!k){Re.error("No terminal tab is active");return}window.api.pty.write({tabId:k.id,data:`@${n} `}),Re.info(`Added ${x} to Claude context`)},I=()=>{w(),window.api.shell.open({as:"openPath",path:n}).then(U=>{U.ok||Re.error(U.error??`Couldn't open ${x}`)}).catch(U=>Re.error(U instanceof Error?U.message:`Couldn't open ${x}`))},O=()=>{w(),window.api.shell.open({as:"revealPath",path:n}).then(U=>{U.ok||Re.error(U.error??`Couldn't reveal ${x}`)}).catch(U=>Re.error(U instanceof Error?U.message:`Couldn't reveal ${x}`))};return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>s(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${r?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),r&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:w}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[o.jsx(Pw,{children:"Edit"}),o.jsx(cu,{label:"Rename",onClick:S}),o.jsx(cu,{label:"Duplicate",onClick:j}),o.jsx(cu,{label:"Delete document",danger:!0,onClick:()=>{w(),m(!0)}}),o.jsx(ZC,{}),o.jsx(Pw,{children:"Open"}),o.jsx(cu,{label:"Open in default app",onClick:I}),o.jsx(cu,{label:"Reveal in OS",onClick:O}),o.jsx(ZC,{}),o.jsx(Pw,{children:"Export"}),o.jsx(cu,{label:"Copy as Markdown",onClick:A}),o.jsx(cu,{label:"Add to Claude context",onClick:P,disabled:!k,title:k?void 0:"No terminal tab is active"})]})]}),a&&o.jsx($4,{value:l,onChange:c,onCancel:()=>d(!1),onConfirm:()=>void E()}),p&&o.jsx(P4,{name:x,onCancel:()=>m(!1),onConfirm:()=>void N()})]})}function Pw({children:n}){return o.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:n})}function cu({label:n,onClick:e,danger:i,disabled:r,title:s}){return o.jsx("button",{onClick:e,disabled:r,title:s,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${i?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:n})}function ZC(){return o.jsx("div",{className:"my-1 border-t border-line"})}function $4({value:n,onChange:e,onCancel:i,onConfirm:r}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:s=>{s.target===s.currentTarget&&i()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),o.jsx("input",{autoFocus:!0,value:n,onChange:s=>e(s.target.value),onKeyDown:s=>{s.key==="Enter"?r():s.key==="Escape"&&i()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function P4({name:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",n,"? This cannot be undone."]}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function R4(){const[n,e]=R.useState(!1),i=Ap();return o.jsxs("div",{className:"relative inline-block mr-1",children:[o.jsx("button",{onClick:()=>e(r=>!r),className:`px-2 py-0.5 text-[10px] border border-line rounded ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),n&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>e(!1)}),o.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[o.jsx(Sp,{label:"Text size",children:o.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[o.jsx("button",{onClick:()=>i.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),o.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:i.fontSize}),o.jsx("button",{onClick:()=>i.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),o.jsx(Sp,{label:"Word wrap",children:o.jsx(Fx,{on:i.wordWrap,onClick:i.toggleWordWrap})}),o.jsx(Sp,{label:"Minimap",children:o.jsx(Fx,{on:i.minimap,onClick:i.toggleMinimap})}),o.jsx(Sp,{label:"Theme",children:o.jsx("button",{onClick:()=>i.setTheme(i.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:i.theme==="dark"?"Dark":"Paper"})}),o.jsx(Sp,{label:"Autosave",children:o.jsx(Fx,{on:i.autosave,onClick:i.toggleAutosave})}),o.jsx(Sp,{label:"Wide measure",children:o.jsx(Fx,{on:i.wideMeasure,onClick:i.toggleWideMeasure})})]})]})]})}function Sp({label:n,children:e}){return o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:n}),e]})}function Fx({on:n,onClick:e}){return o.jsx("button",{onClick:e,className:`px-2 py-0.5 text-[10px] rounded border border-line ${n?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:n?"On":"Off"})}const I4=R.lazy(()=>nv(()=>import("./TiptapBody-g5zDcgLc.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(n=>({default:n.TiptapBody})));function Gx(n){return n.split("/").filter(Boolean).pop()||n}function Ux(n,e){if(!e.length)return n;const i=new Set(e),r={};for(const[s,a]of Object.entries(n))i.has(s)||(r[s]=a);return r}function Hx(n){return pN(n)||fN(n)}function Yb(){const n=cv(),e=Pn(Je=>Je.openFiles),i=Pn(Je=>Je.activeFilePath),r=Pn(Je=>Je.dirty),s=Pn(Je=>Je.viewMode),a=Pn(Je=>Je.buffers),d=Pn(Je=>Je.setActive),l=Pn(Je=>Je.closeFile),c=Pn(Je=>Je.closeOthers),p=Pn(Je=>Je.closeToTheRight),m=Pn(Je=>Je.closeAll),f=Pn(Je=>Je.loadBuffer),b=Pn(Je=>Je.setBuffer),_=Pn(Je=>Je.markSaved),y=Pn(Je=>Je.setViewMode),k=Ap(),[x,w]=R.useState({}),[S,E]=R.useState({}),[j,N]=R.useState(null),[A,P]=R.useState(null),[I,O]=R.useState(!1),[U,B]=R.useState(!1),[J,Z]=R.useState(!0),W=R.useRef(null),q=R.useRef(null),Q=R.useRef(void 0),oe=R.useRef(null),le=R.useRef(null),H=C4(i??"",a[i??""]??""),ee=R.useCallback(Je=>{W.current=Je},[]),Y=R.useCallback(()=>W.current,[]);R.useEffect(()=>{const Je=i;if(!Je||Hx(Je))return;if(Pn.getState().hasBuffer(Je)){w(xt=>xt[Je]==="ready"?xt:{...xt,[Je]:"ready"});return}let Ct=!1;return w(xt=>({...xt,[Je]:"loading"})),window.api.files.read(Je).then(xt=>{Ct||(xt.binary?w(pn=>({...pn,[Je]:{binary:!0,size:xt.size??0,mime:xt.mime??"application/octet-stream",reason:xt.error??"Binary file"}})):xt.ok?(f(Je,xt.text),w(pn=>({...pn,[Je]:"ready"}))):w(pn=>({...pn,[Je]:{error:xt.error??"failed to read"}})))}),()=>{Ct=!0}},[i,f]),R.useEffect(()=>{P(null)},[i]);const ce=R.useCallback(async(Je,Ct=!1)=>{const xt=Pn.getState().buffers[Je];if(xt==null)return;Ct&&O(!0);const pn=await window.api.files.write(Je,xt);pn.ok?(_(Je),E($n=>({...$n,[Je]:($n[Je]??0)+1})),Ct||Re.info(`Saved ${Gx(Je)}`)):Re.error(pn.error??`Couldn't save ${Gx(Je)}`),Ct&&O(!1)},[_]);R.useEffect(()=>{if(!k.autosave)return;const Je=i;if(!(!Je||Hx(Je)||!r[Je]))return window.clearTimeout(Q.current),Q.current=window.setTimeout(()=>{ce(Je,!0)},1200),()=>window.clearTimeout(Q.current)},[k.autosave,i,r,a,ce]);const ae=R.useCallback(Je=>{Je.length&&(w(Ct=>Ux(Ct,Je)),E(Ct=>Ux(Ct,Je)))},[]),xe=R.useCallback((Je,Ct)=>{w(xt=>Je in xt?{...Ux(xt,[Je]),[Ct]:xt[Je]}:xt),E(xt=>Je in xt?{...Ux(xt,[Je]),[Ct]:xt[Je]}:xt)},[]),Ne=R.useCallback(Je=>{r[Je]?N({kind:"one",path:Je}):(l(Je),ae([Je]))},[r,l,ae]),me=R.useCallback(Je=>{e.some(xt=>xt.path!==Je&&r[xt.path])?N({kind:"others",path:Je}):(c(Je),ae(e.filter(xt=>xt.path!==Je).map(xt=>xt.path)))},[e,r,c,ae]),re=R.useCallback(Je=>{const Ct=e.findIndex(pn=>pn.path===Je);Ct!==-1&&e.slice(Ct+1).some(pn=>r[pn.path])?N({kind:"right",path:Je}):(p(Je),ae(Ct!==-1?e.slice(Ct+1).map(pn=>pn.path):[]))},[e,r,p,ae]);R.useEffect(()=>{const Je=Ct=>{if(n.current)if((Ct.metaKey||Ct.ctrlKey)&&(Ct.key==="s"||Ct.key==="S")){const xt=Pn.getState().activeFilePath;xt&&!Hx(xt)&&(Ct.preventDefault(),ce(xt))}else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="f"||Ct.key==="F"))Ct.preventDefault(),B(xt=>!xt);else if((Ct.metaKey||Ct.ctrlKey)&&Ct.shiftKey&&(Ct.key==="w"||Ct.key==="W")){const xt=Pn.getState().activeFilePath;xt&&Pn.getState().openFiles.length>1&&(Ct.preventDefault(),me(xt))}else Ct.key==="Escape"&&H.state.phase!=="idle"?H.cancel():Ct.key==="Escape"&&U&&B(!1)};return window.addEventListener("keydown",Je),()=>window.removeEventListener("keydown",Je)},[ce,U,me,H.state.phase,H.cancel]),R.useEffect(()=>{if(H.state.phase==="idle")return;const Je=Ct=>{var pn,$n;const xt=Ct.target;(pn=le.current)!=null&&pn.contains(xt)||($n=oe.current)!=null&&$n.contains(xt)||H.cancel()};return window.addEventListener("mousedown",Je),()=>window.removeEventListener("mousedown",Je)},[H.state.phase,H.cancel]),R.useEffect(()=>{H.cancel()},[i,H.cancel]);const te=R.useCallback(()=>{e.some(Ct=>r[Ct.path])?N({kind:"all",path:""}):(m(),w({}),E({}))},[e,r,m]),we=()=>{if(j){if(j.kind==="one")l(j.path),ae([j.path]);else if(j.kind==="others"){const Je=e.filter(Ct=>Ct.path!==j.path).map(Ct=>Ct.path);c(j.path),ae(Je)}else if(j.kind==="right"){const Je=e.findIndex(xt=>xt.path===j.path),Ct=Je!==-1?e.slice(Je+1).map(xt=>xt.path):[];p(j.path),ae(Ct)}else m(),w({}),E({});N(null)}};if(e.length===0)return o.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"mb-2",children:"no file open"}),o.jsxs("div",{children:["open the ",o.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const be=i,Ue=be?Gx(be):"",et=be?x[be]:void 0,ut=be?vN(be):!1,zt=be?D5(be):!1,pt=be&&ut?s[be]??A5(be):"edit",it=!!be&&!Hx(be)&&et==="ready",ot=it,Dt=zt?["edit","wysiwyg","preview","split"]:ut?["edit","preview"]:[],sn=be&&o.jsx(z5,{path:be,name:Ue,value:a[be]??"",onChange:Je=>b(be,Je),onSave:()=>void ce(be),onReady:ee,onCursor:P}),gn=I?"Saving…":be&&r[be]?k.autosave?"Editing…":"Unsaved":"All changes saved";return o.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!U&&o.jsx(I5,{openFiles:e,activeFilePath:i,dirty:r,onSelectFile:d,onCloseFile:Ne,onCloseOthers:me,onCloseToTheRight:re,onCloseAll:te}),be&&!U&&o.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[o.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ue}),o.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:be}),it&&o.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",gn]}),Ml(be)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:()=>Z(Je=>!Je),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${J?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),Ml(be)&&(pt==="preview"||pt==="split")&&o.jsx("button",{onClick:k.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${k.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),Dt.length>0&&o.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:Dt.map(Je=>o.jsx("button",{onClick:()=>y(be,Je),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${pt===Je?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Je},Je))}),o.jsx("div",{className:"flex-1"}),o.jsx(A4,{path:be,onRenamed:xe,onDeleted:Je=>ae([Je])}),it&&o.jsx(R4,{}),o.jsx("button",{onClick:()=>B(!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&&o.jsx("button",{onClick:()=>B(!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"}),o.jsx("div",{className:"flex-1 min-h-0",children:be?pN(be)?o.jsx(l4,{path:be,name:Ue}):fN(be)?o.jsx(c4,{path:be}):et&&typeof et=="object"&&"binary"in et?o.jsx(g4,{path:be,name:Ue,size:et.size,mime:et.mime,reason:et.reason}):et&&typeof et=="object"&&"error"in et?o.jsx("div",{className:"p-6 text-xs text-red-400",children:et.error}):et!=="ready"?o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):pt==="wysiwyg"&&Ml(be)?o.jsx(R.Suspense,{fallback:o.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:o.jsx(I4,{value:a[be]??"",onChange:Je=>b(be,Je)},be)}):pt==="split"&&Ml(be)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(VC,{text:a[be]??"",scrollRef:q}),o.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[o.jsx(WC,{getEditor:Y}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}),o.jsx("div",{ref:oe,className:"flex-1 min-w-0",children:o.jsx(X_,{ref:q,text:a[be]??"",flush:!0,wideMeasure:k.wideMeasure,onSelect:H.select,onDismissSelection:H.cancel})}),!U&&k.assistantRail&&o.jsx(XC,{phase:H.state.phase,transcript:H.state.transcript,diff:H.state.diff,editCount:H.state.editCount,modelStatus:H.state.modelStatus,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)},onReject:H.cancel,onRetry:H.retry})]}):pt==="preview"&&Ml(be)?o.jsxs("div",{className:"flex h-full",children:[J&&o.jsx(VC,{text:a[be]??"",scrollRef:q}),o.jsx("div",{ref:oe,className:"flex-1 min-w-0",children:o.jsx(X_,{ref:q,text:a[be]??"",wideMeasure:k.wideMeasure,onSelect:H.select,onDismissSelection:H.cancel})}),!U&&k.assistantRail&&o.jsx(XC,{phase:H.state.phase,transcript:H.state.transcript,diff:H.state.diff,editCount:H.state.editCount,modelStatus:H.state.modelStatus,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)},onReject:H.cancel,onRetry:H.retry})]}):pt==="preview"&&hN(be)?o.jsx(o4,{path:be,dirty:!!r[be],reloadToken:S[be]??0}):pt==="preview"&&mN(be)?o.jsx(u4,{path:be,text:a[be]??""}):pt==="preview"&&gN(be)?o.jsx(f4,{path:be,text:a[be]??""}):Ml(be)?o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsx(WC,{getEditor:Y}),o.jsx("div",{className:"flex-1 min-h-0",children:sn})]}):sn:null}),ot&&o.jsx(s4,{text:a[be]??"",cursor:A,language:no(be)||void 0}),be&&Ml(be)&&(pt==="preview"||pt==="split")&&H.state.phase!=="idle"&&H.state.selection&&o.jsx("div",{ref:le,children:o.jsx(N4,{phase:H.state.phase,rect:H.state.selection.rect,diff:H.state.diff,transcript:H.state.transcript,modelStatus:H.state.modelStatus,onQuickAction:H.run,onRunCustom:H.run,onListen:H.listen,onSendHeard:H.sendHeard,onCancel:H.cancel,onReject:H.cancel,onRetry:H.retry,onAccept:()=>{const Je=H.accept(a[be]??"");Je.ok&&b(be,Je.next)}})}),j&&o.jsx(M4,{message:j.kind==="one"?`Discard unsaved changes to ${Gx(j.path)}?`:j.kind==="others"?"Discard unsaved changes in the other open files?":j.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:we})]})}function M4({message:n,onCancel:e,onConfirm:i}){return o.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:r=>{r.target===r.currentTarget&&e()},children:o.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[o.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:n}),o.jsxs("div",{className:"flex justify-end gap-2",children:[o.jsx("button",{onClick:e,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),o.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const QC={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},O4={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function Rw(n){return n>=1e6?(n/1e6).toFixed(1)+"M":n>=1e3?(n/1e3).toFixed(1)+"K":String(n)}function L4({open:n,onClose:e,variant:i="overlay"}){const r=vt(N=>N.tabs.find(A=>A.id===N.activeTabId)??null),s=(r==null?void 0:r.cwd)??null,[a,d]=R.useState(null),[l,c]=R.useState(!1),[p,m]=R.useState(null),f=R.useRef(null),b=R.useCallback(async N=>{c(!0),m(null);try{const A=await window.api.repo.analyze(N);A.ok?d(A):(m(A.error||"Analysis failed"),d(null))}catch(A){m(A instanceof Error?A.message:String(A)),d(null)}finally{c(!1)}},[]);R.useEffect(()=>{if(n){if(!s){m("No active session — open a tab in a folder first.");return}b(s)}},[n,s,b]),R.useEffect(()=>{var A;if(!n)return;const N=P=>{P.key==="Escape"&&(P.stopPropagation(),e())};return window.addEventListener("keydown",N),(A=f.current)==null||A.focus(),()=>window.removeEventListener("keydown",N)},[n,e]);const _=R.useCallback(()=>{s&&b(s)},[s,b]),y=R.useMemo(()=>a?Object.entries(a.languageBreakdown).map(([A,P])=>[A,P.files,P.lines]).sort((A,P)=>P[1]-A[1]).slice(0,12):[],[a]),k=R.useMemo(()=>y.length===0?1:y[0][1],[y]),x=R.useMemo(()=>{if(!a)return[];const N=a.topDirectories;if(N.length===0)return[];const A=N.map(I=>Math.sqrt(Math.max(1,I.fileCount))),P=A.reduce((I,O)=>I+O,0)||1;return N.map((I,O)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:A[O]/P*100}))},[a]);if(!n)return null;const w=N=>{N.target===N.currentTarget&&e()},S=s?s.split("/").filter(Boolean).pop()||s:"no folder",E=i==="page",j=o.jsx("div",{className:E?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:E?void 0:w,"data-testid":"repoviz-backdrop",children:o.jsxs("div",{ref:f,role:E?void 0:"dialog","aria-modal":E?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:E?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[o.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[o.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),o.jsxs("div",{className:"text-xs text-fg-dim truncate",title:s??"",children:[S,(a==null?void 0:a.gitStatus.branch)&&o.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",a.gitStatus.branch,")"]}),(a==null?void 0:a.truncated)&&o.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),o.jsxs("div",{className:"flex items-center gap-1",children:[a&&a.gitStatus.uncommitted>0&&o.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${a.gitStatus.uncommitted} uncommitted files`,children:[a.gitStatus.uncommitted," uncommitted"]}),o.jsxs("button",{type:"button",onClick:_,disabled:l||!s,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[l?"…":"↻"," Refresh"]}),o.jsx("button",{type:"button",onClick:e,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:l&&!a?o.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[o.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),o.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),o.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):p?o.jsxs("div",{className:"py-16 text-center",children:[o.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),o.jsx("div",{className:"text-sm text-red-400",children:p})]}):a?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[o.jsx(Iw,{label:"Files",value:Rw(a.totalFiles)}),o.jsx(Iw,{label:"Lines of code",value:Rw(a.totalLines)}),o.jsx(Iw,{label:"Uncommitted",value:String(a.gitStatus.uncommitted),tone:a.gitStatus.uncommitted>0?"warn":"neutral"})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),y.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):o.jsx("div",{className:"space-y-1.5",children:y.map(([N,A,P])=>{const I=QC[N]??QC.other,O=O4[N]??N,U=A/k*100;return o.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-24 text-fg-dim truncate",title:O,children:O}),o.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:o.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),o.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[A," files"]}),o.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[Rw(P)," L"]})]},N)})})]}),o.jsxs("section",{children:[o.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),x.length===0?o.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):o.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:x.map(N=>o.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max(N.basis,6)}%`,flexGrow:N.basis>15?1:0},title:`${N.path} — ${N.fileCount} files, ${N.totalLines.toLocaleString()} lines`,children:[o.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:N.path}),o.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[N.fileCount," files"]})]},N.path))})]}),o.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",a.durationMs,"ms",a.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):o.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!E&&typeof document<"u"&&document.body?Iu.createPortal(j,document.body):j}function Iw({label:n,value:e,tone:i="neutral"}){const r=i==="warn"?"text-amber-400":"text-fg";return o.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[o.jsx("div",{className:`text-xl font-medium ${r}`,children:e}),o.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:n})]})}const e2=n=>/[/\\\-_.\s]/.test(n),t2=n=>n>="A"&&n<="Z";function z4(n,e,i){if(!n)return{match:!0,score:0,matched:[]};const r=n.toLowerCase(),s=e.toLowerCase(),a=(i||e).toLowerCase(),d=e.split("/").pop()||e,l=d.toLowerCase();if(l===r)return{match:!0,score:1e3,matched:Array.from({length:d.length},(w,S)=>S)};if(l.startsWith(r))return{match:!0,score:900,matched:Array.from({length:n.length},(w,S)=>S)};let c=0;for(const w of a.split("/")){if(w===r)return{match:!0,score:800,matched:[]};w.startsWith(r)&&(c=Math.max(c,700))}const p=l.indexOf(r);if(p!==-1)return{match:!0,score:p===0||e2(l[p-1])||t2(d[p])?650:600,matched:Array.from({length:n.length},(S,E)=>p+E)};if(a.includes(r))return{match:!0,score:Math.max(500,c),matched:[]};let m=0,f=0,b=0,_=-1,y=0;const k=[];for(let w=0;w<s.length&&m<r.length;w++)s[w]===r[m]&&(k.push(w),f+=10,_===w-1?(b++,f+=b*8):b=0,(w===0||e2(s[w-1])||t2(e[w]))&&(y++,f+=15,w===0&&(f+=10)),_=w,m++);if(m!==r.length)return{match:!1,score:0,matched:[]};const x=Math.max(0,50-(s.length-r.length));if(f+=x,y>=r.length*.5&&(f+=30),k.length>1){const w=k[k.length-1]-k[0];w>r.length*3&&(f-=Math.min(50,(w-r.length*3)*2))}return{match:!0,score:Math.max(1,f),matched:k}}function Mw(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function n2(n){const e=n.lastIndexOf("/");return e<0?"":n.slice(0,e)}const i2="session-manager.quickopen.recent",B4=8;function F4({open:n,onClose:e,variant:i="overlay"}){const r=vt(O=>O.tabs.find(U=>U.id===O.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState([]),[p,m]=R.useState(!1),[f,b]=R.useState(0),[_,y]=R.useState([]),k=R.useRef(null),x=R.useRef(null);R.useEffect(()=>{if(n)try{const O=localStorage.getItem(i2);O&&y(JSON.parse(O))}catch{}},[n]),R.useEffect(()=>{if(!n){d(""),b(0);return}const O=setTimeout(()=>{var U;return(U=k.current)==null?void 0:U.focus()},0);return()=>clearTimeout(O)},[n]),R.useEffect(()=>{if(!n||!s)return;let O=!1;return m(!0),window.api.search.files(s,"",{limit:5e3}).then(U=>{if(!O){if(!U.ok){Re.error(`File search failed: ${U.error??"unknown error"}`),c([]);return}c(U.files)}}).catch(U=>{const B=U instanceof Error?U.message:String(U);ht.error("quick-open","search.files threw",{error:B},{cwd:s,tabId:r==null?void 0:r.id}),Re.error(`File search failed: ${B}`),c([])}).finally(()=>{O||m(!1)}),()=>{O=!0}},[n,s]);const w=R.useMemo(()=>{if(!a.trim())return[...l].sort((J,Z)=>J.name.localeCompare(Z.name)).slice(0,100).map(J=>({file:J,score:0,matched:[]}));const O=a.trim(),U=[];for(const B of l){const J=z4(O,B.name,B.path);J.match&&U.push({file:B,score:J.score,matched:J.matched})}return U.sort((B,J)=>J.score-B.score),U.slice(0,100)},[l,a]),S=R.useMemo(()=>a.trim()?[]:_.map(O=>l.find(U=>U.path===O)||null).filter(O=>O!==null).slice(0,5),[_,l,a]);R.useEffect(()=>{const O=S.length+w.length;f>=O&&b(Math.max(0,O-1))},[S.length,w.length,f]),R.useEffect(()=>{if(!x.current)return;const O=x.current.querySelector(`[data-row="${f}"]`);O&&O.scrollIntoView({block:"nearest"})},[f]);const E=R.useCallback(O=>{try{const Z=[O,..._.filter(W=>W!==O)].slice(0,B4);y(Z),localStorage.setItem(i2,JSON.stringify(Z))}catch{}const U=r==null?void 0:r.id;if(!U){Re.error("No active tab to receive file path");return}const J=(s?Mw(O,s):O)||O;try{window.api.pty.write({tabId:U,data:J})}catch(Z){const W=Z instanceof Error?Z.message:String(Z);ht.error("quick-open","pty.write failed",{error:W},{cwd:s,tabId:U}),Re.error(`Failed to write to terminal: ${W}`);return}e()},[r==null?void 0:r.id,s,_,e]),j=R.useCallback(O=>{const U=S.length+w.length;if(O.key==="Escape"){O.preventDefault(),e();return}if(O.key==="ArrowDown"){if(O.preventDefault(),U===0)return;b(B=>Math.min(U-1,B+1));return}if(O.key==="ArrowUp"){if(O.preventDefault(),U===0)return;b(B=>Math.max(0,B-1));return}if(O.key==="Enter"){if(O.preventDefault(),f<S.length){const Z=S[f];Z&&E(Z.path);return}const B=f-S.length,J=w[B];J&&E(J.file.path)}},[f,w,S,E,e]);if(!n)return null;const N=(O,U)=>{if(U.length===0)return O;const B=new Set(U);return O.split("").map((J,Z)=>o.jsx("span",{className:B.has(Z)?"text-accent font-semibold":"",children:J},Z))};let A=-1;const P=i==="page",I=o.jsx("div",{className:P?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:P?void 0:O=>{O.target===O.currentTarget&&e()},"data-testid":"quick-open-backdrop",children:o.jsxs("div",{role:P?void 0:"dialog","aria-modal":P?void 0:"true","aria-label":"Quick Open",className:P?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:j,children:[o.jsx("div",{className:"border-b border-line p-2",children:o.jsx("input",{ref:k,type:"text",value:a,onChange:O=>{d(O.target.value),b(0)},placeholder:s?"Search files in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),o.jsx("div",{ref:x,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:p?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):s?S.length===0&&w.length===0?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:a?"No files match.":"No files found in this project."}):o.jsxs(o.Fragment,{children:[S.length>0&&o.jsxs("div",{children:[o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),S.map(O=>{A++;const U=A,B=U===f;return o.jsxs("button",{"data-row":U,role:"option","aria-selected":B,onClick:()=>E(O.path),onMouseEnter:()=>b(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${B?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:O.name}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Mw(n2(O.path),s)})]},`r:${O.path}`)})]}),w.length>0&&o.jsxs("div",{children:[S.length>0&&o.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),w.map(({file:O,matched:U})=>{A++;const B=A,J=B===f;return o.jsxs("button",{"data-row":B,role:"option","aria-selected":J,onClick:()=>E(O.path),onMouseEnter:()=>b(B),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${J?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"truncate",children:N(O.name,U)}),o.jsx("span",{className:"text-xs text-fg-dim truncate",children:Mw(n2(O.path),s)})]},O.path)})]})]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[w.length+S.length," ",w.length+S.length===1?"file":"files"]})]})]})});return!P&&typeof document<"u"&&document.body?Iu.createPortal(I,document.body):I}function r2(n,e){return n.startsWith(e+"/")?n.slice(e.length+1):n===e?"":n}function G4(n,e,i){if(!e)return n;const r=i?n:n.toLowerCase(),s=i?e:e.toLowerCase(),a=r.indexOf(s);return a<0?n:o.jsxs(o.Fragment,{children:[n.slice(0,a),o.jsx("span",{className:"text-accent font-semibold",children:n.slice(a,a+e.length)}),n.slice(a+e.length)]})}function U4({open:n,onClose:e,variant:i="overlay"}){const r=vt(Z=>Z.tabs.find(W=>W.id===Z.activeTabId)??null),s=(r==null?void 0:r.cwd)??"",[a,d]=R.useState(""),[l,c]=R.useState(!1),[p,m]=R.useState([]),[f,b]=R.useState(!1),[_,y]=R.useState(null),[k,x]=R.useState(0),[w,S]=R.useState(null),E=R.useRef(null),j=R.useRef(null),N=R.useRef(0);R.useEffect(()=>{if(!n){d(""),m([]),y(null),x(0);return}const Z=setTimeout(()=>{var W;return(W=E.current)==null?void 0:W.focus()},0);return()=>clearTimeout(Z)},[n]),R.useEffect(()=>{if(!n||!s)return;const Z=a.trim();if(!Z){m([]),y(null),b(!1);return}const W=++N.current;b(!0);const q=setTimeout(()=>{window.api.search.text(s,Z,{caseSensitive:l,limit:500}).then(Q=>{W===N.current&&(Q.ok?(m(Q.matches),y(null)):(y(Q.error??"unknown error"),m([])),S(Q.usedRipgrep))}).catch(Q=>{if(W!==N.current)return;const oe=Q instanceof Error?Q.message:String(Q);ht.error("global-search","search.text threw",{error:oe},{cwd:s,tabId:r==null?void 0:r.id}),y(oe),m([])}).finally(()=>{W===N.current&&b(!1)})},250);return()=>clearTimeout(q)},[n,s,a,l]);const A=R.useMemo(()=>{const Z=new Map;for(const q of p){const Q=Z.get(q.path);Q?Q.push(q):Z.set(q.path,[q])}const W=[];for(const[q,Q]of Z)W.push({path:q,matches:Q});return W.sort((q,Q)=>Q.matches.length-q.matches.length||q.path.localeCompare(Q.path)),W},[p]),P=R.useMemo(()=>p,[p]);R.useEffect(()=>{k>=P.length&&x(Math.max(0,P.length-1))},[P.length,k]),R.useEffect(()=>{if(!j.current)return;const Z=j.current.querySelector(`[data-match="${k}"]`);Z&&Z.scrollIntoView({block:"nearest"})},[k]);const I=R.useCallback(Z=>{const W=r==null?void 0:r.id;if(!W){Re.error("No active tab to receive path");return}const Q=`${(s?r2(Z.path,s):Z.path)||Z.path}:${Z.line}`;try{window.api.pty.write({tabId:W,data:Q})}catch(oe){const le=oe instanceof Error?oe.message:String(oe);ht.error("global-search","pty.write failed",{error:le},{cwd:s,tabId:W}),Re.error(`Failed to write to terminal: ${le}`);return}e()},[r==null?void 0:r.id,s,e]),O=R.useCallback(Z=>{if(Z.key==="Escape"){Z.preventDefault(),e();return}if(Z.key==="ArrowDown"){if(Z.preventDefault(),P.length===0)return;x(W=>Math.min(P.length-1,W+1));return}if(Z.key==="ArrowUp"){if(Z.preventDefault(),P.length===0)return;x(W=>Math.max(0,W-1));return}if(Z.key==="Enter"){Z.preventDefault();const W=P[k];W&&I(W)}},[P,k,I,e]);if(!n)return null;const U=i==="page";let B=-1;const J=o.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:Z=>{Z.target===Z.currentTarget&&e()},"data-testid":"global-search-backdrop",children:o.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:O,children:[o.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[o.jsx("input",{ref:E,type:"text",value:a,onChange:Z=>{d(Z.target.value),x(0)},placeholder:s?"Search in this project…":"No active tab — open a terminal first",disabled:!s,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),o.jsx("button",{type:"button",onClick:()=>c(Z=>!Z),className:`px-2 py-1 text-xs rounded border ${l?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":l,children:"Aa"})]}),o.jsx("div",{ref:j,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:s?a.trim()?f?o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):_?o.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:_}):P.length===0?o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(a),"."]}):o.jsx("div",{children:A.map(Z=>o.jsxs("div",{children:[o.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[r2(Z.path,s)," ",o.jsxs("span",{className:"text-fg-faint",children:["(",Z.matches.length,")"]})]}),Z.matches.map(W=>{B++;const q=B,Q=q===k;return o.jsxs("button",{"data-match":q,role:"option","aria-selected":Q,onClick:()=>I(W),onMouseEnter:()=>x(q),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${Q?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[o.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:W.line}),o.jsx("span",{className:"truncate",children:G4(W.text,a,l)})]},`${W.path}:${W.line}:${W.column}:${q}`)})]},Z.path))}):o.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",o.jsx("span",{className:"font-mono",children:s}),"."]}):o.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),o.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[o.jsxs("span",{children:[o.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",o.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),o.jsxs("span",{children:[P.length," ",P.length===1?"match":"matches",w===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Iu.createPortal(J,document.body):J}const H4=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function W4({open:n,onClose:e,variant:i="page",initialMode:r="files"}){const[s,a]=R.useState(r);return R.useEffect(()=>{a(r)},[r]),n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[o.jsx(Ql,{options:H4,active:s,onChange:a}),o.jsx("span",{className:"text-[11px] text-fg-faint",children:s==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),o.jsx("div",{className:"flex-1 min-h-0",children:s==="files"?o.jsx(F4,{open:!0,onClose:e,variant:"page"}):o.jsx(U4,{open:!0,onClose:e,variant:"page"})})]}):null}const V4={sm:"max-w-md",md:"max-w-xl",lg:"max-w-3xl",xl:"max-w-5xl",full:"max-w-[min(96vw,1400px)]"},s2='button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';function ef({open:n,onClose:e,children:i,title:r,size:s="sm",fillHeight:a=!1,noPadding:d=!1,variant:l="overlay"}){if(l==="page")return n?o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[r&&o.jsx("h2",{className:`text-base font-medium text-fg ${d?"px-6 pt-6 pb-3":"px-6 pt-4 pb-2"}`,children:r}),o.jsx("div",{className:`flex-1 min-h-0 min-w-0 flex flex-col ${d?"":"p-6 pt-0"}`,children:i})]}):null;const c=R.useRef(null),p=R.useRef(null),m=R.useRef(e);if(m.current=e,R.useEffect(()=>{if(!n)return;p.current=typeof document<"u"?document.activeElement:null;const y=setTimeout(()=>{const x=c.current;if(!x)return;const w=x.querySelector(s2);w?w.focus():x.focus()},0),k=x=>{if(x.key==="Escape"){x.stopPropagation(),m.current();return}if(x.key==="Tab"){const w=c.current;if(!w)return;const S=Array.from(w.querySelectorAll(s2)).filter(A=>!A.hasAttribute("disabled")&&A.tabIndex!==-1);if(S.length===0){x.preventDefault(),w.focus();return}const E=S[0],j=S[S.length-1],N=document.activeElement;x.shiftKey?(N===E||!w.contains(N))&&(x.preventDefault(),j.focus()):(N===j||!w.contains(N))&&(x.preventDefault(),E.focus())}};return document.addEventListener("keydown",k),()=>{clearTimeout(y),document.removeEventListener("keydown",k);const x=p.current;if(x&&x instanceof HTMLElement)try{x.focus()}catch{}p.current=null}},[n]),!n)return null;const f=_=>{_.target===_.currentTarget&&e()},b=o.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:f,"data-testid":"modal-backdrop",children:o.jsxs("div",{ref:c,role:"dialog","aria-modal":"true","aria-label":r??"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 ${V4[s]} ${a?"max-h-[90vh] h-[90vh]":""} ${d?"":"p-6"}`,"data-testid":"modal-dialog",children:[r?o.jsx("h2",{className:`text-base font-medium text-fg break-words ${d?"px-6 pt-6 pb-3":"mb-3"}`,children:r}):null,a?o.jsx("div",{className:"flex-1 min-h-0 min-w-0 flex flex-col",children:i}):i]})});return typeof document<"u"&&document.body?Iu.createPortal(b,document.body):b}class MN extends R.Component{constructor(){super(...arguments);qn(this,"state",{error:null});qn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(i){return{error:i}}componentDidCatch(i,r){console.error("[ErrorBoundary]",i,r)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):o.jsxs("div",{className:"p-6 text-xs",children:[o.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),o.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),o.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 q4({open:n,onClose:e,title:i,children:r,variant:s="overlay"}){return o.jsxs(ef,{open:n,onClose:e,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:s,children:[s==="overlay"&&o.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[o.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:i}),o.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:"✕"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o.jsx(MN,{children:r})})]})}function ON(n,e={}){switch(n){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 o2=n=>Symbol.iterator in n,a2=n=>"entries"in n,l2=(n,e)=>{const i=n instanceof Map?n:new Map(n.entries()),r=e instanceof Map?e:new Map(e.entries());if(i.size!==r.size)return!1;for(const[s,a]of i)if(!r.has(s)||!Object.is(a,r.get(s)))return!1;return!0},K4=(n,e)=>{const i=n[Symbol.iterator](),r=e[Symbol.iterator]();let s=i.next(),a=r.next();for(;!s.done&&!a.done;){if(!Object.is(s.value,a.value))return!1;s=i.next(),a=r.next()}return!!s.done&&!!a.done};function Y4(n,e){return Object.is(n,e)?!0:typeof n!="object"||n===null||typeof e!="object"||e===null||Object.getPrototypeOf(n)!==Object.getPrototypeOf(e)?!1:o2(n)&&o2(e)?a2(n)&&a2(e)?l2(n,e):K4(n,e):l2({entries:()=>Object.entries(n)},{entries:()=>Object.entries(e)})}function A1(n){const e=Rt.useRef(void 0);return i=>{const r=n(i);return Y4(e.current,r)?e.current:e.current=r}}let c2=0;const X4=1e3;function J4(n){const e=performance.now();e-c2<X4||(c2=e,ht.debug("voice","mic.gate.click_rejected",{reason:n}))}function LN(){const n=kt(p=>p.isRecording),e=kt(p=>p.error),i=kt(p=>p.loadingProgress),r=kt(A1(Mb)),s=()=>{const p=kt.getState(),{canRecord:m,reason:f}=Mb(p);if(p.isRecording)return p.stopRecording();if(p.wizardArmed&&!p.wizardOpen){p.openWizard();return}if(f==="error"||f==="load-timeout"){p.resetAndRetryModel();return}if(!m)return J4(f);const b=vt.getState().activeTabId;b&&p.startRecording(b)},a=ON(r.reason,{loadingPct:i,errorMessage:e,isRecording:n}),d=r.reason==="unsupported",l=!r.canRecord,c=r.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":r.reason==="error"||r.reason==="load-timeout"?"text-red-400 cursor-pointer":r.reason==="permission-denied"?"text-amber-400 cursor-pointer":r.reason==="idle"?"text-fg-faint cursor-pointer":r.reason==="unsupported"?"text-fg-faint cursor-not-allowed":n?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return o.jsx("button",{onClick:s,disabled:d,"aria-disabled":l,"aria-label":a,title:a,"data-testid":"mic-button","data-state":r.reason,className:`p-1.5 rounded transition-colors ${c}`,children:o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function Z4(){const n=kt(i=>i.ttsEnabled),e=kt(i=>i.toggleTTS);return o.jsxs("button",{onClick:e,title:n?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${n?"text-accent":"text-fg-dim hover:text-fg"}`,children:[o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),n?o.jsxs(o.Fragment,{children:[o.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),o.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):o.jsxs(o.Fragment,{children:[o.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),o.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),o.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Q4(n){return/^monitor of /i.test(n.trim())}function d2(n){return n.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function u2(n,e,i){if(n){const d=i.find(l=>l.deviceId===n);if(d)return d}if(!e)return null;const r=i.filter(d=>d.label===e);if(r.length===1)return r[0];if(r.length>1)return null;const s=d2(e),a=i.filter(d=>d.label&&d2(d.label)===s);return a.length===1?a[0]:null}async function h2(n){var i;return(i=navigator.mediaDevices)!=null&&i.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(r=>!(r.kind!=="audioinput"||r.label&&Q4(r.label))):[]}const p2=!1;function zN(){const n=kt(p=>p.isRecording);kt(p=>p.startRecording),kt(p=>p.stopRecording);const[e,i]=R.useState([]),[r,s]=R.useState(null),[a,d]=R.useState(null);R.useEffect(()=>{let p=!1;return(async()=>{try{const m=await window.api.voice.getDevicePref();if(p)return;const f=await h2(p2);if(p)return;i(f),d(m.selectedLabel);const b=u2(m.selectedDeviceId,m.selectedLabel,f);b?(s(b.deviceId),m.selectedDeviceId&&b.deviceId!==m.selectedDeviceId&&(ht.info("voice","device-picker rebind-by-label",{fromIdPrefix:m.selectedDeviceId.slice(0,8),toIdPrefix:b.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:b.deviceId,selectedLabel:b.label||m.selectedLabel}).catch(()=>{}))):((m.selectedDeviceId||m.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:m.selectedLabel,hadId:!!m.selectedDeviceId}),ht.warn("voice","device-picker selected-unavailable",{hadId:!!m.selectedDeviceId})),s(null))}catch(m){ht.warn("voice","device-picker init failed",{error:m instanceof Error?m.message:String(m)})}})(),()=>{p=!0}},[]);const l=R.useCallback(async()=>{try{const p=await h2(p2);if(i(p),r&&!p.some(m=>m.deviceId===r)){const m=u2(null,a,p);m?(s(m.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:m.deviceId,selectedLabel:m.label||a}).catch(()=>{})):s(null)}}catch(p){ht.warn("voice","device-picker refresh failed",{error:p instanceof Error?p.message:String(p)})}},[r,a]);R.useEffect(()=>{const p=()=>{l()};return window.addEventListener("mic-device-change",p),()=>window.removeEventListener("mic-device-change",p)},[l]);const c=async p=>{var _;const m=p.target.value,f=m===""?null:m,b=f?((_=e.find(y=>y.deviceId===f))==null?void 0:_.label)??null:null;s(f),d(b);try{await window.api.voice.setDevicePref({selectedDeviceId:f,selectedLabel:b}),ht.info("voice","device-picker selected",{deviceIdPrefix:f?f.slice(0,8):null})}catch(y){ht.warn("voice","setDevicePref failed",{error:y instanceof Error?y.message:String(y)})}if(n)try{await kt.getState().restartWithDevice()}catch(y){ht.warn("voice","device-picker restart failed",{error:y instanceof Error?y.message:String(y)})}};return o.jsxs("select",{value:r??"",onChange:c,onFocus:()=>{l()},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:[o.jsx("option",{value:"",children:"Default"}),e.map(p=>o.jsx("option",{value:p.deviceId,children:p.label||`Mic ${p.deviceId.slice(0,6)}`},p.deviceId))]})}function eB(){const n=kt(_=>_.isRecording),e=kt(_=>_.levelMeterEnabled),[i,r]=R.useState(0),[s,a]=R.useState(0),d=R.useRef(0);d.current=s;const[l,c]=R.useState(0),[p,m]=R.useState(!1),f=R.useRef(null);if(R.useEffect(()=>{if(!n||!e){r(0),a(0);return}let _=0,y=!1,k=null,x=null;const w=()=>{if(y)return;const E=x??JT();if(!E){_=requestAnimationFrame(w);return}x!==E&&(x=E,k=new Uint8Array(new ArrayBuffer(E.fftSize)));const j=k;E.getByteTimeDomainData(j);let N=0;for(let O=0;O<j.length;O++){const U=j[O]-128;N+=U*U}const A=Math.sqrt(N/j.length)/128,P=A>0?20*Math.log10(A):-60,I=Math.max(0,Math.min(1,(P+60)/60));a(A),r(I),A>=.95&&(m(!0),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>m(!1),150)),_=requestAnimationFrame(w)};_=requestAnimationFrame(w);const S=setInterval(()=>{y||c(Math.round(d.current*100))},250);return()=>{y=!0,cancelAnimationFrame(_),clearInterval(S),f.current&&(clearTimeout(f.current),f.current=null)}},[n,e]),!n||!e)return null;const b=p?"bg-red-500":s>=.7?"bg-amber-400":"bg-green-500";return o.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${p?"ring-1 ring-red-500":""}`,children:o.jsx("div",{className:`h-full ${b} transition-[width] duration-75 ease-out`,style:{width:`${i*100}%`}})})}function BN(){const n=kt(p=>p.submitCountdownStartAt),e=kt(p=>p.submitDelayMs),[i,r]=R.useState(()=>performance.now());if(R.useEffect(()=>{if(n===null)return;let p;const m=()=>{r(performance.now()),p=requestAnimationFrame(m)};return p=requestAnimationFrame(m),()=>cancelAnimationFrame(p)},[n]),n===null)return null;const s=i-n,a=Math.max(0,e-s),d=Math.max(0,Math.min(100,a/e*100)),l=a<500,c=kt.getState().cancelSubmit;return o.jsx("div",{className:"px-3 pb-1",onClick:c,title:`Submitting in ${(a/1e3).toFixed(1)}s — click to cancel`,children:o.jsx("div",{className:"h-0.5 w-full bg-bg rounded overflow-hidden cursor-pointer",children:o.jsx("div",{className:`h-full transition-colors ${l?"bg-amber-400":"bg-accent"}`,style:{width:`${d}%`}})})})}function tB({open:n,onClose:e,variant:i="overlay"}){return o.jsx(q4,{open:n,onClose:e,title:"Voice / Microphone",variant:i,children:o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(sB,{}),o.jsx(BN,{}),o.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[o.jsx(LN,{}),o.jsx(zN,{}),o.jsx(Z4,{})]}),o.jsx(nB,{}),o.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[o.jsx("button",{type:"button",onClick:()=>kt.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),o.jsx(rB,{})]}),o.jsx(eB,{})]})})}function nB(){const n=kt(a=>a.isRecording),[e,i]=R.useState(null);if(R.useEffect(()=>{let a=!1;window.api.voice.getHotkeyConfig().then(l=>{a||i(l)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(l=>i(l));return()=>{a=!0,d()}},[]),n||!e)return null;const r=e.mode==="hold"?"Hold":"Press",s=iB(e.accelerator);return o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("span",{children:[r," "]}),o.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:s}),o.jsx("span",{children:" to record"})]})}function iB(n){const e=typeof navigator<"u"&&/Mac/.test(navigator.platform);return n.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 rB(){const[n,e]=R.useState(null);if(R.useEffect(()=>{let r=!1;window.api.voice.getHotkeyConfig().then(a=>{r||e(a)}).catch(a=>ht.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(a)}));const s=window.api.voice.onHotkeyConfigChanged(a=>{e(a)});return()=>{r=!0,s()}},[]),!n)return null;const i=async r=>{if(n.mode===r)return;const s={...n,mode:r};e(s);try{await window.api.voice.setHotkeyConfig(s)}catch(a){ht.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:a instanceof Error?a.message:String(a)})}};return o.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:[o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="toggle",onChange:()=>i("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),o.jsx("span",{children:"Tap on/off"})]}),o.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[o.jsx("input",{type:"radio",name:"hotkey-mode",checked:n.mode==="hold",onChange:()=>i("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),o.jsx("span",{children:"Hold to talk"})]})]})}function sB(){const n=kt(a=>a.isRecording),e=kt(a=>a.lastTranscript),i=kt(a=>a.error),r=kt(a=>a.modelStatus),s=kt(a=>a.loadingProgress);return i?o.jsxs("div",{className:"text-[11px] text-red-400",title:i,children:["⚠ ",i]}):n?o.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),o.jsx("span",{className:"truncate",title:e,children:e||"Listening…"})]}):r==="loading"?o.jsxs("div",{className:"text-[11px] text-fg-faint",children:[o.jsxs("div",{className:"flex items-center justify-between mb-1",children:[o.jsx("span",{children:"Loading speech model"}),o.jsxs("span",{className:"font-mono",children:[s,"%"]})]}),o.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:o.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${s}%`}})})]}):null}let Ow=null;function oB(){return Ow||(Ow=nv(()=>import("./monaco-editor-BW5C4Iv1.js").then(n=>n.b),__vite__mapDeps([1,2]),import.meta.url).then(n=>(m1.config({monaco:n}),n))),Ow}function FN({value:n,onChange:e,path:i,readOnly:r}){const s=R.useRef(null),a=d=>{s.current=d};return o.jsx(g1,{path:`file://${i}`,defaultLanguage:"json",value:n,onChange:d=>e(d??""),onMount:a,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:r,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let f2=!1;async function aB(n){if(f2)return;const e=await oB(),i=await Promise.all(n.map(async s=>{let a=s.schema;if(!a){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const l=new URL(s.uri).origin;if(!d.includes(l))throw new Error("untrusted origin");const c=await fetch(s.uri);c.ok&&(a=await c.json())}catch{}}return{uri:s.uri,fileMatch:s.fileMatch,schema:a}}));e.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:i.filter(s=>s.schema),enableSchemaRequest:!0}),f2=!0}function $1({node:n,targetScope:e,onOverride:i,schema:r,rootLabel:s}){const[a,d]=R.useState(""),[l,c]=R.useState(!0),p=[],m=n.kind==="object"&&Object.keys(n.children).length===0,b=((r==null?void 0:r.rootKeys())??[]).length>0;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",o.jsx("span",{className:"text-fg-dim",children:br[e].label})]}),b&&o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:l,onChange:_=>c(_.target.checked),className:"accent-accent"}),"show unset keys"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:a,onChange:_=>d(_.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),o.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:m&&!l?o.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):o.jsx(GN,{node:n,path:p,label:s??"(root)",targetScope:e,onOverride:i,filter:a,depth:0,schema:r,showGhosts:l,defaultOpen:!0})})]})}function GN(n){return n.node.kind==="object"?o.jsx(lB,{...n,node:n.node}):n.node.kind==="array"?o.jsx(cB,{...n,node:n.node}):o.jsx(dB,{...n,node:n.node})}function m2(n,e){return e.trim()?n.toLowerCase().includes(e.toLowerCase()):!0}function Wp(n,e,i){return!!(!i.trim()||n.some(r=>m2(r,i))||e!=null&&e.description&&m2(e.description,i))}function lB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l,showGhosts:c,defaultOpen:p}){const[m,f]=R.useState(p??d<2),b=(l==null?void 0:l.at(e))??null,_=new Set(Object.keys(n.children)),y=c?(b==null?void 0:b.knownChildren)??[]:[],k=Array.from(new Set([..._,...y])).sort(),x=R.useMemo(()=>a.trim()?k.filter(S=>{const E=(l==null?void 0:l.at([...e,S]))??null;return Wp([...e,S],E,a)?!0:_.has(S)?UN(n.children[S],[...e,S],a,l):!1}):k,[k.join(","),a,n,e.join("."),l]);if(a.trim()&&x.length===0&&!Wp(e,b,a))return null;if(e.length===0)return o.jsx("div",{children:x.map(S=>w(S))});return o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>f(!m),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:m?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" {",_.size,y.length>_.size?`/${new Set([..._,...y]).size}`:"","}"]}),(b==null?void 0:b.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:b.description,children:["— ",b.description]})]}),m&&x.map(S=>w(S))]});function w(S){if(_.has(S))return o.jsx(GN,{node:n.children[S],path:[...e,S],label:S,targetScope:r,onOverride:s,filter:a,depth:d+1,schema:l,showGhosts:c},S);const E=(l==null?void 0:l.at([...e,S]))??null;return E?o.jsx(uB,{path:[...e,S],label:S,info:E,targetScope:r,onSet:s,depth:d+1,filter:a},S):null}}function UN(n,e,i,r){const s=(r==null?void 0:r.at(e))??null;if(Wp(e,s,i))return!0;if(n.kind!=="object")return!1;for(const a of Object.keys(n.children))if(UN(n.children[a],[...e,a],i,r))return!0;return!1}function cB({node:n,path:e,label:i,filter:r,depth:s,schema:a}){const[d,l]=R.useState(!0),c=(a==null?void 0:a.at(e))??null;return Wp(e,c,r)?o.jsxs("div",{children:[o.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:s*14},onClick:()=>l(!d),children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),o.jsx("span",{className:"text-fg",children:i}),o.jsxs("span",{className:"text-fg-faint",children:[" [",n.items.length,"]"]}),o.jsx(qg,{tone:"warn",children:"accumulated"}),(c==null?void 0:c.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:c.description,children:["— ",c.description]})]}),d&&n.items.map((p,m)=>o.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(s+1)*14},children:[o.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),o.jsxs("span",{className:"text-fg-faint",children:[m,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:Xb(p.value)}),o.jsx(Q_,{scope:p.fromScope})]},m))]}):null}function dB({node:n,path:e,label:i,targetScope:r,onOverride:s,filter:a,depth:d,schema:l}){const[c,p]=R.useState(!1),m=(l==null?void 0:l.at(e))??null;if(!Wp(e,m,a))return null;const f=n.winner!==r,b=n.shadowed.length>0;return o.jsxs("div",{children:[o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[o.jsx("span",{className:`w-3 shrink-0 ${b?"text-fg-faint cursor-pointer":""}`,onClick:()=>b&&p(!c),children:b?c?"▾":"▸":""}),o.jsxs("span",{className:"text-fg",children:[i,":"]}),o.jsx("span",{className:"text-fg-dim truncate max-w-md",children:Xb(n.value)}),o.jsx(Q_,{scope:n.winner}),(m==null?void 0:m.deprecated)&&o.jsx(qg,{tone:"warn",children:"deprecated"}),(m==null?void 0:m.default)!==void 0&&hB(n.value,m.default)&&o.jsx(qg,{tone:"dim",children:"= default"}),n.typeMismatch&&o.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(m==null?void 0:m.description)&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:m.description,children:["— ",m.description]}),o.jsx("div",{className:"flex-1"}),(m==null?void 0:m.enum)&&o.jsx(HN,{values:m.enum}),o.jsx("button",{disabled:!f,onClick:()=>s(e,n.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${f?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:f?`copy into ${br[r].label} draft`:`already winning in ${br[r].label}`,children:"override"})]}),c&&n.shadowed.map((_,y)=>o.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[o.jsx("span",{children:"shadowed:"}),o.jsx("span",{className:"truncate max-w-xl",children:Xb(_.value)}),o.jsx(Q_,{scope:_.scope,dim:!0})]},y))]})}function uB({path:n,label:e,info:i,targetScope:r,onSet:s,depth:a,filter:d}){if(!Wp(n,i,d))return null;const l=i.default!==void 0?i.default:pB(i.type),c=Array.isArray(i.type)?i.type.join("|"):i.type??"?";return o.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:a*14},children:[o.jsx("span",{className:"w-3 shrink-0"}),o.jsx("span",{className:"text-fg-dim",children:e}),o.jsx(qg,{tone:"dim",children:c}),i.required&&o.jsx(qg,{tone:"warn",children:"required"}),i.default!==void 0&&o.jsxs("span",{className:"text-fg-faint",children:["default: ",Xb(i.default)]}),i.description&&o.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:i.description,children:["— ",i.description]}),o.jsx("div",{className:"flex-1"}),i.enum&&o.jsx(HN,{values:i.enum}),o.jsx("button",{onClick:()=>s(n,l),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${br[r].label} draft`,children:"set"})]})}function hB(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function pB(n){switch(Array.isArray(n)?n[0]:n){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function Xb(n){if(typeof n=="string")return JSON.stringify(n);if(n===null)return"null";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>100?e.slice(0,100)+"…":e}return String(n)}function Q_({scope:n,dim:e}){const i=n==="user"?"bg-bg-hi text-fg-dim border-line":n==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i} ${e?"opacity-60":""}`,children:br[n].label})}function qg({children:n,tone:e="default"}){const i={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[e];return o.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${i}`,children:n})}function HN({values:n}){const e=n.map(i=>String(i)).join(" | ");return o.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${e}`,children:["∈ ",e.length>30?e.slice(0,30)+"…":e]})}const fB=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],mB={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function WN(n){return n.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((r,s)=>{const a=mB[r];return a||(s===0?r.charAt(0).toUpperCase()+r.slice(1):r)}).join(" ")}function VN(n){const e=new Set,i=[];for(const s of fB){const a=s.keys.filter(d=>n.has(d));a.forEach(d=>e.add(d)),a.length!==0&&i.push({id:s.id,title:s.title,summary:s.summary,advanced:!!s.advanced,keys:a})}const r=Array.from(n).filter(s=>!e.has(s)&&s!=="$schema").sort();return r.length>0&&i.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:r}),i}function gB(n,e){return VN(n).map(i=>({id:i.id,title:i.title,advanced:i.advanced,total:i.keys.length,setCount:i.keys.filter(r=>e.has(r)).length}))}const vB={};function qN(n,e){if(e)return{text:e,authored:!1};const i=vB[n];return i?{text:i,authored:!0}:null}const xB={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},bB=["user","project","local","default"],yB={user:"user",project:"project",local:"local",default:"default"};function wB({node:n,targetScope:e,onOverride:i,schema:r}){const[s,a]=R.useState(""),[d,l]=R.useState(!1),[c,p]=R.useState(!0),m=n.kind==="object"?n:null,f=m?Object.keys(m.children):[],b=r.rootKeys(),_=new Set([...f,...b]),y=R.useMemo(()=>VN(_),[Array.from(_).sort().join(",")]),k=R.useMemo(()=>gB(_,new Set(f)),[Array.from(_).sort().join(","),f.join(",")]),[x,w]=R.useState(null),S=R.useRef(null),E=N=>{const A=y.find(P=>P.id===N);A!=null&&A.advanced&&!d&&l(!0),w(N)};R.useEffect(()=>{if(!x)return;w(null);const N=S.current,A=document.getElementById(`settings-group-${x}`);if(!N||!A)return;const P=A.getBoundingClientRect().top-N.getBoundingClientRect().top;N.scrollBy({top:P,behavior:"smooth"})},[x]);const j=R.useMemo(()=>y.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter(A=>{const P=(m==null?void 0:m.children[A])!==void 0;if(!c&&!P)return!1;if(!s.trim())return!0;const I=r.at([A]);return[A,WN(A),(I==null?void 0:I.description)??""].join(" ").toLowerCase().includes(s.toLowerCase())})})).filter(N=>N.keys.length>0),[y,s,d,c,m,r]);return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[o.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",o.jsx("span",{className:"text-fg-dim font-medium",children:br[e].label})]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:c,onChange:N=>p(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),o.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[o.jsx("input",{type:"checkbox",checked:d,onChange:N=>l(N.target.checked),className:"accent-accent"}),"show advanced"]}),o.jsx("div",{className:"flex-1"}),o.jsx("input",{value:s,onChange:N=>a(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),o.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[o.jsx(_B,{groups:k,onJump:E}),o.jsxs("div",{ref:S,className:"flex-1 overflow-auto py-3",children:[j.map(N=>o.jsx(SB,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map(A=>{const P=m==null?void 0:m.children[A],I=r.at([A]);return o.jsx(kB,{keyName:A,node:P,info:I,targetScope:e,onOverride:(O,U)=>i([A],O,U)},A)})},N.id)),j.length===0&&o.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',s,'"']})]})]})]})}function _B({groups:n,onJump:e}){return o.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:n.map(i=>o.jsxs("button",{onClick:()=>e(i.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${i.title}`,children:[o.jsx(an,{name:xB[i.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),o.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:i.title}),o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[i.setCount,"/",i.total]})]},i.id))})}function SB({id:n,title:e,summary:i,advanced:r,children:s}){const[a,d]=R.useState(!0);return o.jsxs("section",{id:`settings-group-${n}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[o.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!a),children:[o.jsx("span",{className:"text-fg-faint w-3",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("h2",{className:"text-fg text-base font-semibold",children:e}),r&&o.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),o.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:i})]})]}),a&&o.jsx("div",{className:"divide-y divide-line/60",children:s})]})}function kB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const[a,d]=R.useState(!1),[l,c]=R.useState(!1),p=WN(n),m=e!==void 0,b=(e==null?void 0:e.kind)==="leaf"?e:null,_=(e==null?void 0:e.kind)==="object"||(e==null?void 0:e.kind)==="array",y=i==null?void 0:i.default,k=b&&y!==void 0&&YN(b.value,y),x=$B({isSet:m,leafNode:b,defaultVal:y,isDefault:!!k,node:e}),w=CB(b,y),S=w.length>=2,E=!!b&&!k,j=qN(n,i==null?void 0:i.description);return o.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:o.jsxs("div",{className:"flex items-start gap-3",children:[o.jsx("button",{onClick:()=>d(!a),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:a?"collapse":"expand",children:a?"▾":"▸"}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[o.jsx("h3",{className:"text-fg text-sm",children:p}),o.jsx(PB,{kind:x.kind,label:x.label}),S&&o.jsxs("button",{onClick:N=>{N.stopPropagation(),a||d(!0),c(A=>!A)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",w.map(N=>yB[N]).join(" · ")]}),E&&b&&o.jsx("button",{onClick:N=>{N.stopPropagation(),s(void 0,b.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${br[b.winner].label}`,children:"↺ reset"}),(i==null?void 0:i.deprecated)&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(i==null?void 0:i.required)&&!m&&o.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),j&&o.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${j.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:j.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:RB(j.text)}),a&&l&&b&&o.jsx(EB,{leaf:b,defaultVal:y,onReset:N=>s(void 0,N)}),a&&o.jsx(TB,{keyName:n,node:e,info:i,targetScope:r,onOverride:N=>s(N)})]}),o.jsx("div",{className:"shrink-0",children:!a&&o.jsx(AB,{node:e,info:i,onSet:N=>{s(N)},disabled:_&&m})})]})})}function CB(n,e){if(!n)return[];const i=new Set;i.add(n.winner);for(const r of n.shadowed)i.add(r.scope);return e!==void 0&&i.add("default"),bB.filter(r=>i.has(r))}function EB({leaf:n,defaultVal:e,onReset:i}){const r={};r[n.winner]={value:n.value,winner:!0};for(const s of n.shadowed)r[s.scope]={value:s.value,winner:!1};return o.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[o.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),o.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(s=>{const a=r[s],d=a!==void 0;return o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:br[s].label}),o.jsx("span",{className:`font-mono truncate ${a!=null&&a.winner?"text-accent":"text-fg-dim"}`,children:d?Lp(a.value):o.jsx("span",{className:"text-fg-faint",children:"—"})}),d?o.jsx("button",{onClick:()=>i(s),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${br[s].label}`,children:"↺"}):o.jsx("span",{})]},s)}),o.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[o.jsx("span",{className:"text-fg-faint",children:"Default"}),o.jsx("span",{className:"font-mono text-fg-dim truncate",children:e!==void 0?Lp(e):o.jsx("span",{className:"text-fg-faint",children:"—"})}),o.jsx("span",{})]})]})]})}function TB({keyName:n,node:e,info:i,targetScope:r,onOverride:s}){const d=(e==null?void 0:e.kind)==="leaf"?e:null,l=qN(n,i==null?void 0:i.description);return o.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[l&&o.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${l.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:l.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:l.text}),o.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(i==null?void 0:i.type)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Type"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(i.type)?i.type.join(" | "):i.type})]}),(i==null?void 0:i.default)!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Default"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:Lp(i.default)})]}),(i==null?void 0:i.enum)&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Options"}),o.jsx("dd",{className:"text-fg-dim font-mono",children:i.enum.map(c=>String(c)).join(" | ")})]}),d&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Current"}),o.jsxs("dd",{className:"font-mono",children:[o.jsx("span",{className:"text-fg-dim",children:Lp(d.value)}),o.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",br[d.winner].label]})]})]}),d&&d.shadowed.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Shadowed"}),o.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((c,p)=>o.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Lp(c.value)," —"," ",o.jsx("span",{className:"no-underline",children:br[c.scope].label})]},p))})]}),(e==null?void 0:e.kind)==="array"&&o.jsxs(o.Fragment,{children:[o.jsx("dt",{children:"Accumulated"}),o.jsxs("dd",{className:"text-fg-dim",children:[e.items.length," items across all scopes"]})]})]}),o.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:o.jsx(jB,{keyName:n,node:e,info:i,onChange:s,targetScope:r})})]})}function jB({node:n,info:e,onChange:i,targetScope:r}){const a=(n==null?void 0:n.kind)==="leaf"?n.value:e==null?void 0:e.default,d=KN(e==null?void 0:e.type);if(d==="boolean"){const l=a===!0;return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:c,label:p})=>o.jsx("button",{onClick:()=>i(c),className:`px-3 py-0.5 text-xs transition-colors ${l===c?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:p},p))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]})}return e!=null&&e.enum?o.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-fg-faint",children:"Choose:"}),e.enum.map(l=>{const c=YN(a,l);return o.jsx("button",{onClick:()=>i(l),className:`px-2 py-0.5 text-xs rounded border ${c?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(l)},String(l))}),o.jsxs("span",{className:"text-fg-faint",children:["→ ",br[r].label]})]}):d==="integer"||d==="number"?o.jsx(NB,{value:typeof a=="number"?a:void 0,integer:d==="integer",onCommit:i,target:br[r].label}):d==="string"?o.jsx(DB,{value:typeof a=="string"?a:"",onCommit:i,target:br[r].label}):o.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",o.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function NB({value:n,integer:e,onCommit:i,target:r}){const[s,a]=R.useState(n!==void 0?String(n):""),d=()=>{const l=e?parseInt(s,10):parseFloat(s);Number.isNaN(l)||i(l)};return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-fg-faint",children:"Set to:"}),o.jsx("input",{type:"number",value:s,onChange:l=>a(l.target.value),onBlur:d,onKeyDown:l=>{l.key==="Enter"&&l.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function DB({value:n,onCommit:e,target:i}){const[r,s]=R.useState(n);return o.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[o.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),o.jsx("input",{type:"text",value:r,onChange:a=>s(a.target.value),onKeyDown:a=>{a.key==="Enter"&&e(r)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),o.jsxs("button",{onClick:()=>e(r),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function AB({node:n,info:e,onSet:i,disabled:r}){const s=(n==null?void 0:n.kind)==="leaf",a=KN(e==null?void 0:e.type);if(r)return null;if(a==="boolean"){const d=s&&n.value===!0;return o.jsx("button",{onClick:()=>i(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function $B({isSet:n,leafNode:e,defaultVal:i,isDefault:r,node:s}){return n?(s==null?void 0:s.kind)==="array"?{kind:"accumulated",label:`${s.items.length} items`}:(s==null?void 0:s.kind)==="object"?{kind:"set",label:"configured"}:e?r?{kind:"default",label:`= default · ${br[e.winner].label}`}:e.shadowed.length>0?{kind:"override",label:`overriding ${e.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${br[e.winner].label}`}:{kind:"set",label:"configured"}:i!==void 0?{kind:"default",label:`using default: ${Lp(i)}`}:{kind:"unset",label:"not configured"}}function PB({kind:n,label:e}){const i={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[n];return o.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${i}`,children:e})}function KN(n){if(n)return Array.isArray(n)?n.find(i=>i!=="null")??n[0]:n}function YN(n,e){return n===e?!0:typeof n!=typeof e?!1:n&&e&&typeof n=="object"?JSON.stringify(n)===JSON.stringify(e):!1}function RB(n){const e=n.trim().split(`
|
|
3074
3074
|
`)[0],i=e.match(/^([^.!?]+[.!?])/);return i?i[1]:e.length>120?e.slice(0,120)+"…":e}function Lp(n){if(typeof n=="string")return n===""?'""':JSON.stringify(n);if(n===null)return"null";if(n===void 0)return"—";if(typeof n=="object"){const e=JSON.stringify(n);return e.length>60?e.slice(0,60)+"…":e}return String(n)}function P1(n,e,i){const r=cn(c=>c.files),s=cn(c=>c.loadJson),a=cn(c=>c.watchFile),d=cn(c=>c.unwatchFile),l=R.useMemo(()=>{const c={};for(const p of n.scopes){const m=n.resolve(p,e??"",i);m&&(c[p]=m)}return c},[n,e,i]);return R.useEffect(()=>{const c=Object.values(l).filter(Boolean);return c.forEach(p=>{r[p]||s(p),a(p)}),()=>{c.forEach(p=>d(p))}},[JSON.stringify(l)]),l}const IB=[];function Wx(n){return Array.isArray(n)?"array":n!==null&&typeof n=="object"?"object":"scalar"}function R1(n){const e=n.filter(i=>i.data!==void 0);return e.length===0?{kind:"object",children:{}}:XN(e,[])}function XN(n,e){const i=IB.includes(e.join(".")),r=n.every(m=>Wx(m.data)==="object"),s=n.every(m=>Wx(m.data)==="array");if(r){const m=new Set;for(const b of n)for(const _ of Object.keys(b.data))m.add(_);const f={};for(const b of m){const _=n.filter(y=>b in y.data).map(y=>({scope:y.scope,data:y.data[b]}));f[b]=XN(_,[...e,b])}return{kind:"object",children:f}}if(s&&!i){const m=[];for(const f of[...n].reverse())for(const b of f.data)m.push({value:b,fromScope:f.scope,index:m.length});return{kind:"array",items:m}}const a=[...n].reverse(),d=a[0],l=a.slice(1).map(m=>({scope:m.scope,value:m.data})),c=Wx(d.data),p=l.some(m=>Wx(m.value)!==c);return{kind:"leaf",value:d.data,winner:d.scope,shadowed:l,...p?{typeMismatch:!0}:{}}}function I1(n,e){if(e.length===0)return n;if(n.kind!=="object")return null;const[i,...r]=e,s=n.children[i];return s?I1(s,r):null}function $y(n,e,i){if(e.length===0)return i;const[r,...s]=e,a=n&&typeof n=="object"&&!Array.isArray(n)?{...n}:{};return a[r]=$y(a[r],s,i),a}const MB=["user","project","local"];function M1(n,e){const i=[];for(const r of MB){const s=e[r];if(!s)continue;const a=n[s];if(!a||!a.exists)continue;const d=a.draftRaw??"";if(d.trim())try{i.push({scope:r,data:JSON.parse(d)})}catch{}}return i}const OB="http://json-schema.org/draft-07/schema#",LB="https://json.schemastore.org/claude-code-settings.json",zB={permissionRule:{type:"string",description:`Tool permission rule.
|
|
3075
3075
|
See https://code.claude.com/docs/en/settings#permission-rule-syntax
|
|
3076
3076
|
See https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.`,pattern:"^((Agent|Bash|Edit|ExitPlanMode|Glob|Grep|KillShell|LSP|NotebookEdit|Read|Skill|TaskCreate|TaskGet|TaskList|TaskOutput|TaskStop|TaskUpdate|TodoWrite|ToolSearch|WebFetch|WebSearch|Write)(\\((?=.*[^)*?])[^)]+\\))?|mcp__.*)$",examples:["Bash","Bash(npm run build)","Bash(git commit *)","Bash(npm run *)","Bash(ls*)","Bash(git * main)","Edit","Edit(/src/**/*.ts)","Read(./.env)","Read(./secrets/**)","Read(//Users/alice/secrets/**)","Read(~/Documents/*.pdf)","Agent(Explore)","WebFetch","WebFetch(domain:example.com)","mcp__puppeteer","mcp__github__search_repositories"]},hookCommand:{anyOf:[{type:"object",description:"Bash command hook",additionalProperties:!1,required:["type","command"],properties:{type:{type:"string",description:"Hook type",const:"command"},command:{type:"string",description:"Shell command to execute",minLength:1},timeout:{type:"number",description:"Optional timeout in seconds",exclusiveMinimum:0},async:{type:"boolean",description:"Run this hook asynchronously without blocking Claude Code"},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"LLM prompt hook. See https://code.claude.com/docs/en/hooks#prompt-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"prompt"},prompt:{type:"string",description:"Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"Agent hook with multi-turn tool access for verification. See https://code.claude.com/docs/en/hooks#agent-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"agent"},prompt:{type:"string",description:"Prompt describing what to verify. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 60)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"HTTP webhook hook. POST JSON to a URL and receive JSON response. See https://code.claude.com/docs/en/hooks#http-hooks",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",description:"Hook type",const:"http"},url:{type:"string",description:"URL to POST hook input JSON to. Endpoint must accept POST requests and return JSON.",minLength:1},headers:{type:"object",additionalProperties:{type:"string"},description:"Custom HTTP headers (e.g., Authorization: Bearer token). Values support $VAR_NAME or ${VAR_NAME} interpolation."},allowedEnvVars:{type:"array",items:{type:"string",minLength:1},description:"List of environment variable names permitted for interpolation in headers. If not set, no env var interpolation is allowed."},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}}]},hookMatcher:{type:"object",description:"Hook matcher configuration with multiple hooks",additionalProperties:!1,required:["hooks"],properties:{matcher:{type:"string",description:"Optional pattern to match event contexts, case-sensitive. Behavior depends on event type. See https://code.claude.com/docs/en/hooks#matcher-patterns for event-specific details and examples"},hooks:{type:"array",description:"Array of hooks to execute",items:{$ref:"#/$defs/hookCommand"}}}}},BB="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",FB=!0,GB=!0,UB="object",HB=JSON.parse(`{"$schema":{"type":"string","description":"JSON Schema reference for Claude Code settings"},"apiKeyHelper":{"type":"string","description":"Path to a script that outputs authentication values","examples":["/bin/generate_temp_api_key.sh"],"minLength":1},"autoMemoryEnabled":{"type":"boolean","description":"Enable automatic memory saves that capture useful context to .claude/memory/. Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#auto-memory","default":true},"autoUpdatesChannel":{"type":"string","enum":["stable","latest"],"description":"Release channel to follow for updates. Use \\"stable\\" for a version that is typically about one week old and skips versions with major regressions, or \\"latest\\" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable updates entirely.","default":"latest"},"awsCredentialExport":{"type":"string","description":"Path to a script that exports AWS credentials","examples":["/bin/generate_aws_grant.sh"],"minLength":1},"awsAuthRefresh":{"type":"string","description":"Path to a script that refreshes AWS authentication","examples":["aws sso login --profile myprofile"],"minLength":1},"claudeMdExcludes":{"type":"array","items":{"type":"string","minLength":1},"description":"Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claudemd-files","examples":[["**/monorepo/CLAUDE.md","/home/user/monorepo/other-team/.claude/rules/**"]]},"cleanupPeriodDays":{"type":"integer","minimum":0,"description":"Number of days to retain chat transcripts (0 to disable cleanup)","examples":[20,30,60],"default":30},"env":{"type":"object","additionalProperties":false,"description":"Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.\\nUNDOCUMENTED: CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS (plugin marketplace git timeout in ms, default 120000, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2151).\\nUNDOCUMENTED: ENABLE_CLAUDEAI_MCP_SERVERS (set to false to opt out of claude.ai MCP servers, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2163).","examples":[{"ANTHROPIC_MODEL":"claude-opus-4-1","ANTHROPIC_SMALL_FAST_MODEL":"claude-3-5-haiku-latest"}],"default":{},"patternProperties":{"^[A-Z_][A-Z0-9_]*$":{"type":"string","description":"Environment variable value"}}},"attribution":{"type":"object","description":"Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings","additionalProperties":false,"properties":{"commit":{"type":"string","description":"Attribution for git commits, including any trailers. Empty string hides commit attribution"},"pr":{"type":"string","description":"Attribution for pull request descriptions. Empty string hides pull request attribution"}}},"includeGitInstructions":{"type":"boolean","description":"Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings","default":true},"includeCoAuthoredBy":{"type":"boolean","description":"DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)","default":true},"plansDirectory":{"type":"string","description":"Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)","default":"~/.claude/plans","examples":["./plans"]},"respectGitignore":{"type":"boolean","description":"Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions","default":true},"permissions":{"type":"object","properties":{"allow":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for allowed operations","uniqueItems":true},"deny":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for denied operations","uniqueItems":true},"ask":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules that should always prompt for confirmation","uniqueItems":true},"defaultMode":{"type":"string","enum":["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"],"description":"Default permission mode.\\n\\"default\\": prompts on first use.\\n\\"acceptEdits\\": auto-accepts file edits.\\n\\"plan\\": read-only, no modifications.\\nUNDOCUMENTED. \\"delegate\\": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).\\n\\"dontAsk\\": auto-denies unless pre-approved via permissions.\\n\\"bypassPermissions\\": skips all prompts (use only in isolated environments).\\nSee https://code.claude.com/docs/en/permissions"},"disableBypassPermissionsMode":{"type":"string","enum":["disable"],"description":"Disable the ability to bypass permission prompts"},"additionalDirectories":{"type":"array","items":{"type":"string","minLength":1},"description":"Additional directories to include in the permission scope","examples":[["//Users/alice/Documents","~/projects"]],"uniqueItems":true}},"additionalProperties":false,"description":"Tool usage permissions configuration.\\nSee https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings\\nSee https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.","examples":[{"allow":["Bash(git add:*)"],"ask":["Bash(gh pr create:*)","Bash(git commit:*)"],"deny":["Read(*.env)","Bash(rm:*)","Bash(curl:*)"],"defaultMode":"default"}]},"language":{"type":"string","description":"Preferred language for Claude's responses","examples":["japanese","spanish","french"]},"model":{"type":"string","enum":["opus","sonnet","haiku","default"],"description":"Override the default model used by Claude Code. Accepts a short alias (opus|sonnet|haiku) or a full model ID. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config"},"availableModels":{"type":"array","items":{"type":"string"},"description":"Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection","examples":[["sonnet","haiku"]]},"modelOverrides":{"type":"object","additionalProperties":{"type":"string"},"description":"Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version","examples":[{"claude-opus-4-6":"arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"}]},"effortLevel":{"type":"string","enum":["low","medium","high"],"description":"Control Opus 4.6 adaptive reasoning effort. Lower effort is faster and cheaper for straightforward tasks, higher effort provides deeper reasoning. Defaults vary by model and plan (Opus 4.6 defaults to medium for Max and Team subscribers). Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level"},"fastMode":{"type":"boolean","description":"Enable fast mode for Opus 4.6 (research preview). Fast mode uses the same model with 2.5x faster output at higher per-token cost. Requires extra usage enabled. Alternatively, toggle with /fast command. See https://code.claude.com/docs/en/fast-mode","default":false},"fastModePerSessionOptIn":{"type":"boolean","description":"Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode","default":false},"feedbackSurveyRate":{"type":"number","minimum":0,"maximum":1,"description":"Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings","examples":[0.05]},"editorMode":{"type":"string","enum":["normal","vim"],"default":"normal","description":"Editor input mode for the Claude Code terminal prompt. 'vim' enables modal editing (Esc for normal mode, i for insert). See https://code.claude.com/docs/en/settings"},"skillOverrides":{"type":"object","additionalProperties":{"type":"string","enum":["on","name-only","user-invocable-only","off"]},"description":"Per-skill availability override map. Keys are skill names; values are one of 'on' (default), 'name-only' (skill name listed but not auto-loaded), 'user-invocable-only' (load only when user explicitly invokes), or 'off' (hidden). Requires Claude Code v2.1.129+. See https://code.claude.com/docs/en/settings","examples":[{"playwright-debug":"user-invocable-only","init":"off"}]},"disableAgentView":{"type":"boolean","default":false,"description":"Disable the Agent View feature (read-only inspection of sub-agent activity). Useful when administering managed deployments. Requires Claude Code v2.1.139+. See https://code.claude.com/docs/en/settings"},"disableRemoteControl":{"type":"boolean","default":false,"description":"Block the \`claude remote-control\` channel that allows external clients to drive this Claude Code instance. Recommended default for shared/CI environments. Requires Claude Code v2.1.128+. See https://code.claude.com/docs/en/settings"},"enableAllProjectMcpServers":{"type":"boolean","description":"Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp","examples":[true]},"enabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["memory","github"]]},"disabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["filesystem"]]},"allowedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that users are allowed to configure"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"deniedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that is explicitly blocked"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"httpHookAllowedEnvVars":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["MY_TOKEN","HOOK_SECRET"]]},"hooks":{"type":"object","additionalProperties":false,"description":"Custom commands to run before/after tool executions. See https://code.claude.com/docs/en/hooks","examples":[{"PostToolUse":[{"matcher":"Edit|Write","hooks":[{"type":"command","command":"prettier --write","timeout":5}]}]}],"properties":{"PreToolUse":{"type":"array","description":"Hooks that run before tool calls","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUse":{"type":"array","description":"Hooks that run after tool completion","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUseFailure":{"type":"array","description":"Hooks that run after a tool fails","items":{"$ref":"#/$defs/hookMatcher"}},"PermissionRequest":{"type":"array","description":"Hooks that run when a permission dialog appears","items":{"$ref":"#/$defs/hookMatcher"}},"Notification":{"type":"array","description":"Hooks that trigger on notifications","items":{"$ref":"#/$defs/hookMatcher"}},"UserPromptSubmit":{"type":"array","description":"Hooks that run when a user submits a prompt","items":{"$ref":"#/$defs/hookMatcher"}},"Stop":{"type":"array","description":"Hooks that run when agents finish responding. Does not run on user interrupt","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStart":{"type":"array","description":"Hooks that run when a subagent is spawned","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStop":{"type":"array","description":"Hooks that run when subagents finish responding","items":{"$ref":"#/$defs/hookMatcher"}},"PreCompact":{"type":"array","description":"Hooks that run before the context is compacted","items":{"$ref":"#/$defs/hookMatcher"}},"PostCompact":{"type":"array","description":"Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"Elicitation":{"type":"array","description":"Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"ElicitationResult":{"type":"array","description":"Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"TeammateIdle":{"type":"array","description":"Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle","items":{"$ref":"#/$defs/hookMatcher"}},"TaskCompleted":{"type":"array","description":"Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted","items":{"$ref":"#/$defs/hookMatcher"}},"Setup":{"type":"array","description":"UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)","items":{"$ref":"#/$defs/hookMatcher"}},"InstructionsLoaded":{"type":"array","description":"Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded","items":{"$ref":"#/$defs/hookMatcher"}},"ConfigChange":{"type":"array","description":"Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeCreate":{"type":"array","description":"Hooks that run when a worktree is created via --worktree or isolation: \\"worktree\\" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeRemove":{"type":"array","description":"Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove","items":{"$ref":"#/$defs/hookMatcher"}},"SessionStart":{"type":"array","description":"Hooks that run when a new session starts","items":{"$ref":"#/$defs/hookMatcher"}},"SessionEnd":{"type":"array","description":"Hooks that run when a session ends","items":{"$ref":"#/$defs/hookMatcher"}}}},"disableAllHooks":{"type":"boolean","description":"Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks"},"allowedHttpHookUrls":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["https://hooks.example.com/*","http://localhost:*"]]},"allowManagedHooksOnly":{"type":"boolean","description":"(Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration"},"allowManagedPermissionRulesOnly":{"type":"boolean","description":"(Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings"},"statusLine":{"type":"object","properties":{"type":{"type":"string","description":"The type of status line handler; must be set to \\"command\\" to run a custom shell script that receives JSON session data via stdin.","const":"command"},"command":{"type":"string","description":"A shell command or path to a script that displays session information (context usage, costs, git status, etc.) by reading JSON data from stdin and writing output to stdout. See https://code.claude.com/docs/en/statusline"},"padding":{"type":"number","description":"Optional number of extra horizontal spacing characters added to the status line content; defaults to 0."}},"required":["type","command"],"additionalProperties":false,"description":"Custom status line display configuration. See https://code.claude.com/docs/en/statusline","examples":[{"type":"command","command":"~/.claude/statusline.sh"}]},"fileSuggestion":{"type":"object","properties":{"type":{"type":"string","description":"The type of file suggestion handler; must be set to \\"command\\" to execute a custom shell script that generates file suggestions for the @ file picker.","const":"command"},"command":{"type":"string","description":"Shell command to execute for file suggestions"}},"required":["type","command"],"additionalProperties":false,"description":"Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings","examples":[{"type":"command","command":"~/.claude/file-suggestion.sh"}]},"enabledPlugins":{"type":"object","additionalProperties":{"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"boolean"},{"not":{}}]},"description":"Enabled plugins using plugin-id@marketplace-id format. Example: { \\"formatter@anthropic-tools\\": true }. See https://code.claude.com/docs/en/plugins"},"extraKnownMarketplaces":{"type":"object","additionalProperties":{"type":"object","properties":{"source":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","pattern":"\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false}],"description":"Where to fetch the marketplace from"},"installLocation":{"type":"string","description":"Local cache path where marketplace manifest is stored (auto-generated if not provided)"}},"required":["source"],"additionalProperties":false},"description":"Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces"},"strictKnownMarketplaces":{"type":"array","description":"(Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/settings#strictknownmarketplaces","items":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"HTTP headers for authenticated access"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package name (supports scoped packages)"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Absolute path to marketplace.json file"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Absolute path to directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"pathPattern"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"],"additionalProperties":false}]},"examples":[[{"source":"github","repo":"acme-corp/approved-plugins"},{"source":"npm","package":"@acme-corp/compliance-plugins"}]]},"skippedMarketplaces":{"type":"array","items":{"type":"string","minLength":1},"description":"List of marketplace names the user has chosen not to install when prompted"},"skippedPlugins":{"type":"array","items":{"type":"string","minLength":1},"description":"List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted"},"forceLoginMethod":{"type":"string","enum":["claudeai","console"],"description":"Force a specific login method: \\"claudeai\\" for Claude Pro/Max, \\"console\\" for Console billing","examples":["claudeai"]},"forceLoginOrgUUID":{"type":"string","description":"Organization UUID to use for OAuth login","examples":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"],"minLength":1},"otelHeadersHelper":{"type":"string","description":"Path to a script that outputs OpenTelemetry headers","minLength":1},"outputStyle":{"type":"string","description":"Controls the output style for assistant responses. Built-in styles: default, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles","examples":["default","Explanatory","Learning"],"minLength":1},"skipWebFetchPreflight":{"type":"boolean","description":"Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"},"sandbox":{"type":"object","description":"Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing","properties":{"network":{"type":"object","description":"Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.","properties":{"allowUnixSockets":{"type":"array","items":{"type":"string"},"description":"Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified"},"allowLocalBinding":{"type":"boolean","description":"Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified"},"httpProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"socksProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"allowAllUnixSockets":{"type":"boolean","description":"Allow all Unix domain socket connections. If true, this overrides allowUnixSockets"},"allowedDomains":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com"},"allowManagedDomainsOnly":{"type":"boolean","description":"(Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts."}},"additionalProperties":false},"ignoreViolations":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"},"description":"List of filesystem paths to ignore sandbox violations for when this command pattern matches"},"description":"Map of command patterns to filesystem paths to ignore violations for. Use \\"*\\" to match all commands"},"excludedCommands":{"type":"array","items":{"type":"string"},"description":"Commands that should never run in the sandbox (e.g., [\\"git\\", \\"docker\\"])"},"autoAllowBashIfSandboxed":{"type":"boolean","description":"Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed.","default":true},"enableWeakerNetworkIsolation":{"type":"boolean","description":"macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/settings#sandbox-settings","default":false},"enableWeakerNestedSandbox":{"type":"boolean","description":"Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable.Default: false (secure)."},"allowUnsandboxedCommands":{"type":"boolean","description":"Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."},"enabled":{"type":"boolean","description":"Enable sandboxed bash"},"filesystem":{"type":"object","description":"Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation","properties":{"allowWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path)"},"denyWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite"},"denyRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied read access"},"allowRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths"},"allowManagedReadPathsOnly":{"type":"boolean","description":"When true (managed settings only), only allowRead paths from managed settings are used"}},"additionalProperties":false}},"additionalProperties":false},"spinnerVerbs":{"type":"object","description":"Customize the verbs shown in spinner progress messages","properties":{"mode":{"type":"string","enum":["append","replace"],"description":"How to combine custom verbs with default spinner verbs: 'append' adds custom verbs to the default list, 'replace' uses only custom verbs"},"verbs":{"type":"array","items":{"type":"string","minLength":1},"minItems":1,"description":"Custom verbs used in spinner progress text"}},"required":["verbs"],"additionalProperties":false},"spinnerTipsEnabled":{"type":"boolean","description":"Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)","default":true},"spinnerTipsOverride":{"type":"object","description":"Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings","properties":{"excludeDefault":{"type":"boolean","description":"If true, only show custom tips. If false or absent, custom tips merge with built-in tips","default":false},"tips":{"type":"array","items":{"type":"string","minLength":1},"description":"Custom tip strings to display in the spinner","minItems":1}},"required":["tips"],"additionalProperties":false},"terminalProgressBarEnabled":{"type":"boolean","description":"Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)","default":true},"showTurnDuration":{"type":"boolean","description":"Show turn duration messages after responses (e.g., \\"Cooked for 1m 6s\\"). Set to false to hide these messages (default: true)","default":true},"prefersReducedMotion":{"type":"boolean","description":"Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility","default":false},"alwaysThinkingEnabled":{"type":"boolean","description":"Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode"},"companyAnnouncements":{"type":"array","items":{"type":"string","minLength":1},"description":"Company announcements to display at startup (one will be randomly selected if multiple are provided)"},"teammateMode":{"type":"string","enum":["auto","in-process","tmux"],"description":"How agent team teammates display: \\"auto\\" picks split panes in tmux or iTerm2, in-process otherwise. Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams","default":"auto"},"worktree":{"type":"object","additionalProperties":false,"description":"Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings","properties":{"sparsePaths":{"type":"array","items":{"type":"string","minLength":1},"description":"Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos.","examples":[["packages/my-app","shared/utils"]]}}},"pluginTrustMessage":{"type":"string","description":"(Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings","minLength":1},"pluginConfigs":{"type":"object","additionalProperties":{"type":"object","properties":{"mcpServers":{"type":"object","additionalProperties":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"array","items":{"type":"string"}}]}},"description":"User configuration values for MCP servers keyed by server name"}},"additionalProperties":false},"description":"Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins"},"allowManagedMcpServersOnly":{"type":"boolean","description":"(Managed settings only) Only allowedMcpServers from managed settings are respected. deniedMcpServers still merges from all sources. Users can still add their own MCP servers, but only the admin-defined allowlist applies."},"blockedMarketplaces":{"type":"array","description":"(Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"url","description":"Block marketplace fetched from direct URL"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Custom HTTP headers (e.g., for authentication)"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"github","description":"Block marketplace from GitHub repository"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","repo"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"git","description":"Block marketplace from git repository URL"},"url":{"type":"string","pattern":".*\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"npm","description":"Block marketplace from NPM package"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"file","description":"Block marketplace from local file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"directory","description":"Block marketplace from local directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"hostPattern","description":"Block marketplace by host pattern matching"},"hostPattern":{"type":"string","description":"Regex pattern to match the host/domain extracted from any marketplace source type"}},"required":["source","hostPattern"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"pathPattern","description":"Block marketplace by file/directory path pattern matching"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"]}]}}}`),WB="Claude Code Settings",VB={$schema:OB,$id:LB,$defs:zB,description:BB,allowTrailingCommas:FB,additionalProperties:GB,type:UB,properties:HB,title:WB};function qB(n){const e=n??{},i={...e.$defs??{},...e.definitions??{}},r=_=>{if(!_)return{};if(!_.$ref)return d(_);const y=/^#\/(\$defs|definitions)\/(.+)$/.exec(_.$ref);if(!y)return d(_);const k=i[y[2]];return k?r({...k,...l(_)}):d(_)},s=new Set(["__proto__","constructor","prototype"]),a=_=>{if(!_)return{};const y={};for(const[k,x]of Object.entries(_))s.has(k)||(y[k]=x);return y},d=_=>{if(!_.allOf||_.allOf.length===0)return _;const y={..._};delete y.allOf;for(const k of _.allOf){const x=r(k);Object.assign(y,{properties:{...a(y.properties),...a(x.properties)},required:KB([...y.required??[],...x.required??[]])}),!y.description&&x.description&&(y.description=x.description),y.default===void 0&&x.default!==void 0&&(y.default=x.default),!y.type&&x.type&&(y.type=x.type)}return y},l=_=>{const{$ref:y,...k}=_;return k},c=(_,y)=>{let k=r(_);for(const x of y){if(!k)return null;if(/^\d+$/.test(x)){const E=Array.isArray(k.items)?k.items[Number(x)]:k.items;k=E?r(E):null;continue}const w=k.properties;if(w&&!s.has(x)&&x in w){k=r(w[x]);continue}const S=k.additionalProperties;if(S&&typeof S=="object"){k=r(S);continue}return null}return k},p=(_,y,k)=>{if(!_)return null;const x={};if(_.description&&(x.description=_.description),_.type&&(x.type=_.type),_.default!==void 0&&(x.default=_.default),_.enum&&(x.enum=_.enum),_.const!==void 0&&(x.const=_.const),_.deprecated&&(x.deprecated=!0),_.examples&&(x.examples=_.examples),_.properties&&(x.knownChildren=Object.keys(_.properties)),k&&(y!=null&&y.includes(k))&&(x.required=!0),_.items&&!Array.isArray(_.items)){const w=r(_.items),S=p(w,void 0,null);S&&(x.itemsInfo=S)}return(_.additionalProperties===!0||typeof _.additionalProperties=="object")&&(x.open=!0),x},m=_=>y=>{if(y.length===0)return p(r(_),void 0,null);const k=c(_,y.slice(0,-1));if(!k)return null;const x=y[y.length-1],w=c(k,[x]);return p(w,k.required,x)},f=_=>{const y=r(_);return Object.keys(y.properties??{})},b=_=>({at:m(_),rootKeys:()=>f(_),rootedAt:y=>{const k=c(_,y);return b(k??{})}});return b(e)}function KB(n){return Array.from(new Set(n))}let Lw=null;function Jb(){return Lw||(Lw=qB(VB)),Lw}function YB(){const[n,e]=R.useState(null),[i,r]=R.useState(null),[s,a]=R.useState(null),[d,l]=R.useState(null),[c,p]=R.useState(!1),[m,f]=R.useState(null),[b,_]=R.useState(null);if(R.useEffect(()=>{let S=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([E,j,N])=>{S||(e(E),a(E),r(j),l(N))}).catch(E=>{console.warn("[telemetry] load failed:",E==null?void 0:E.message)}),()=>{S=!0}},[]),!s||!n)return o.jsx(Lt,{title:"loading…"});const y=JSON.stringify(s)!==JSON.stringify(n),k=(S,E)=>{f(null),a({...s,[S]:E})},x=async()=>{p(!0),f(null);try{const S=await window.api.otel.setConfig(s);!S.ok&&S.error&&f(S.error),e(S.config),a(S.config),r(S.status),_(Date.now())}catch(S){f(S instanceof Error?S.message:String(S))}finally{p(!1)}},w=()=>{f(null),a(n)};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Telemetry — OpenTelemetry export"}),o.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"When enabled, every classified transcript event (tool_use, todo_write, plan, usage, agent_spawn) is mirrored as a 0-duration OTLP/HTTP span. Point this at a local collector (Jaeger, Grafana Tempo, SigNoz, Honeycomb) for cross-session analysis."}),d&&o.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",o.jsx("span",{className:"font-mono",children:d})]})]}),o.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),o.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),o.jsx(Wg,{checked:s.enabled,onChange:S=>k("enabled",S),label:s.enabled?"on":"off"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),o.jsx("input",{type:"text",value:s.endpoint,onChange:S=>k("endpoint",S.target.value),placeholder:"http://localhost:4318/v1/traces",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",o.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),o.jsx("textarea",{value:s.headers,onChange:S=>k("headers",S.target.value),placeholder:"x-honeycomb-team: YOUR_API_KEY",rows:3,className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),o.jsx("input",{type:"text",value:s.serviceName,onChange:S=>k("serviceName",S.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),o.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[o.jsxs("div",{children:[o.jsx("div",{className:"text-fg",children:"Include content (PII)"}),o.jsxs("div",{className:"text-fg-faint text-xs leading-relaxed",children:["Adds tool inputs, plan text, and agent prompts to span attributes. Off by default — matches upstream Claude Code's ",o.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),o.jsx(Wg,{checked:s.includeContent,onChange:S=>k("includeContent",S),label:s.includeContent?"on":"off"})]})]}),i&&o.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[o.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),o.jsxs("div",{children:[o.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",o.jsx("span",{className:i.enabled?"text-accent":"text-fg-dim",children:String(i.enabled)})]}),i.error&&o.jsxs("div",{className:"text-red-400 break-words",children:[o.jsx("span",{className:"text-fg-faint",children:"error:"})," ",i.error]}),!i.error&&i.enabled&&o.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),o.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[o.jsx("button",{onClick:x,disabled:!y||c,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:c?"saving…":"Save"}),o.jsx("button",{onClick:w,disabled:!y||c,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert"}),m&&o.jsx("span",{className:"text-red-400 text-xs",children:m}),!m&&b&&!y&&o.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function XB(){const{model:n,setModel:e}=N$();return o.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[o.jsxs("header",{className:"space-y-1",children:[o.jsx("h2",{className:"text-fg text-base font-medium",children:"Session Manager preferences"}),o.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"Native app preferences, stored locally — not part of Claude Code's own settings."})]}),o.jsx("section",{className:"border border-line rounded p-3 space-y-3",children:o.jsxs("label",{className:"block space-y-1",children:[o.jsx("span",{className:"text-fg-dim text-xs",children:"Default model for raw sessions"}),o.jsx("select",{value:n,onChange:i=>e(i.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:jT.map(i=>o.jsx("option",{value:i,children:i.charAt(0).toUpperCase()+i.slice(1)},i))}),o.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function JB(){const n=Oi(),e=vt(O=>O.tabs),i=vt(O=>O.activeTabId),r=e.find(O=>O.id===i)??null,s=(r==null?void 0:r.cwd)??null,a=mn(O=>O.navFace),d=R.useRef(!1),l=R.useRef(a),[c,p]=R.useState(()=>a==="project"&&s?"project":"user"),[m,f]=R.useState("effective");R.useEffect(()=>{if(l.current!==a){if(l.current=a,d.current){d.current=!1;return}p(a==="project"&&s?"project":"user")}},[a,s]),R.useEffect(()=>{a==="project"&&(m==="telemetry"||m==="app")&&f("effective")},[a,m]);const b=O=>{d.current=!0,p(O)},_=P1(Du,n,s),y=_[c]??null,k=cn(O=>O.files),x=cn(O=>O.setDraft),w=cn(O=>O.saveJson),S=cn(O=>O.revert),[E,j]=R.useState(null),N=R.useMemo(()=>R1(M1(k,_)),[k,_]),A=(O,U,B)=>{var oe;const Z=_[B??c];if(!Z)return;j(null);const W=((oe=k[Z])==null?void 0:oe.draftRaw)??"";let q={};if(W.trim())try{q=JSON.parse(W)}catch{q={}}const Q=$y(q,O,U);x(Z,JSON.stringify(Q,null,2)+`
|
|
@@ -3178,7 +3178,7 @@ ${e}`}let C0=null;function Vq(n){C0=n,window.dispatchEvent(new CustomEvent("sm:s
|
|
|
3178
3178
|
|
|
3179
3179
|
Describe the task here.
|
|
3180
3180
|
`);try{const Ne=await window.api.schedule.writePrd(ae,xe);if(!Ne.ok){Re.error(`Failed to create PRD: ${Ne.error}`);return}const me=await window.api.schedule.listPrds();i(i_(me)),Z(ae)}catch(Ne){Re.error(`Failed to create PRD: ${Ne instanceof Error?Ne.message:String(Ne)}`)}}async function Y(){var ae;j(!0),A(null);try{const xe=[..._],Ne=await window.api.schedule.archivePrds(xe);if(!Ne.ok)A(Ne.error??"archive failed");else{const me=((ae=Ne.results)==null?void 0:ae.filter(re=>!re.ok))??[];me.length>0&&Re.warn(`Archive: ${me.length} of ${Ne.results.length} PRD${me.length===1?"":"s"} failed to move`),le(),x(!1),await H()}}catch(xe){A(xe instanceof Error?xe.message:String(xe))}finally{j(!1)}}async function ce(ae,xe){j(!0),A(null);try{const Ne=[];for(const re of _){const te={slug:re};ae!==null&&(te.parallelGroup=ae),xe!==null&&(te.estimateMinutes=xe),Ne.push(te)}const me=await window.api.schedule.retagPrds(Ne);if(!me.ok)A(me.error??"retag failed");else{le(),S(!1),await H();for(const re of me.results)if(re.newSlug&&re.newSlug!==re.slug){const te=J(re.slug),we=J(re.newSlug);te&&we&&Pn.getState().renameOpenFile(te,we)}a&&me.results.some(re=>re.slug===a&&re.newSlug&&re.newSlug!==re.slug)&&d(null)}}catch(Ne){A(Ne instanceof Error?Ne.message:String(Ne))}finally{j(!1)}}return o.jsxs(o.Fragment,{children:[a?o.jsxs("div",{className:"h-full flex flex-col min-h-0",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-line flex-wrap shrink-0",children:[o.jsx("button",{type:"button",onClick:W,className:"text-[11px] text-fg-faint hover:text-fg",children:"← PRDs"}),o.jsx("span",{className:"font-mono text-xs text-fg-dim truncate",children:a}),o.jsx(Wb,{status:B}),o.jsx("div",{className:"flex-1"}),o.jsx(r_,{label:"Reset",tip:"Reset failed job to pending",onClick:()=>{window.api.schedule.resetJob(a)},disabled:B!=="failed"}),o.jsx(r_,{label:"Run now",tip:"Run all pending jobs immediately",onClick:()=>{window.api.schedule.runNow()}}),o.jsx(r_,{label:p?"Hide log":"Last run log",tip:"Toggle most recent run log",onClick:q})]}),o.jsx("div",{className:"flex-1 min-h-0",children:o.jsx(Yb,{})}),p&&l!==null&&o.jsxs("div",{className:"border-t border-line max-h-64 overflow-auto bg-bg-elev",children:[o.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 border-b border-line sticky top-0 bg-bg-elev",children:[o.jsxs("span",{className:"text-[10px] text-fg-faint font-mono",children:["run log",U!=null&&U.runId?` — ${U.runId}`:""]}),o.jsx("button",{onClick:()=>m(!1),className:"ml-auto text-[10px] text-fg-faint hover:text-fg",children:"close"})]}),o.jsx("pre",{className:"p-3 text-[11px] font-mono text-fg-dim whitespace-pre-wrap",children:l})]})]}):o.jsxs("div",{className:"px-6 py-5 overflow-auto",children:[o.jsxs("div",{className:"flex items-start justify-between mb-5 gap-4",children:[o.jsxs("p",{className:"text-[14px] text-fg-dim leading-relaxed max-w-[560px]",children:["PRDs are the source the scheduler runs from. Each one becomes a"," ",o.jsx("code",{className:"font-mono text-[13px]",children:"claude -p"})," job when you queue it. This is where you write and edit the source — to watch a run in progress, use the Queue tab."]}),o.jsx("button",{type:"button",onClick:ee,className:"shrink-0 bg-accent text-white rounded-lg px-4 py-[9px] text-[13.5px] font-semibold leading-none",children:"+ New PRD"})]}),_.size>0&&o.jsxs("div",{className:"mb-4 px-4 py-2 bg-bg border border-line rounded-lg flex items-center gap-2",children:[o.jsxs("span",{className:"text-xs text-fg-dim",children:[_.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsx("button",{type:"button",onClick:()=>x(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Archive…"}),o.jsx("button",{type:"button",onClick:()=>S(!0),className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Retag…"}),o.jsx("button",{type:"button",onClick:le,className:"text-xs px-3 py-1.5 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Clear"})]}),O.length===0?o.jsx(Lt,{title:"no PRDs found"}):o.jsx("div",{className:"grid gap-3",children:O.map(ae=>{const xe=r==null?void 0:r.jobs.find(we=>we.slug===ae.slug),Ne=bC(xe),me=F0({epicId:ae.epicId??(xe==null?void 0:xe.epicId)??null,sourcePromptId:ae.sourcePromptId??(xe==null?void 0:xe.sourcePromptId)??null,sourceTabId:(xe==null?void 0:xe.sourceTabId)??null},I),re=(xe==null?void 0:xe.status)==="running",te=(xe==null?void 0:xe.status)==="needs_review";return o.jsxs("div",{className:"flex items-stretch bg-bg-elev border border-line rounded-2xl overflow-hidden",children:[o.jsx("label",{className:"flex items-center px-3 cursor-pointer hover:bg-bg-hi",children:o.jsx("input",{type:"checkbox",checked:_.has(ae.slug),onChange:()=>Q(ae.slug),className:"accent-accent w-3.5 h-3.5"})}),o.jsxs("div",{className:"flex-1 min-w-0 py-4 pr-2",children:[o.jsxs("div",{className:"flex items-center gap-2.5 mb-[5px] flex-wrap",children:[Dp(ae.slug)&&o.jsx(lN,{n:Dp(ae.slug)}),o.jsx("button",{type:"button",onClick:()=>Z(ae.slug),className:"font-serif text-[18px] font-semibold text-fg leading-tight hover:underline text-left",children:ae.title||ae.slug}),o.jsx(Wb,{status:Ne}),(xe==null?void 0:xe.status)&&o.jsx("span",{className:"sr-only",children:xe.status})]}),o.jsxs("div",{className:"flex items-center gap-4 font-mono text-xs text-fg-faint flex-wrap",children:[o.jsx(Ny,{cwd:ae.cwd}),o.jsx(_1,{epicId:me.epicId,label:me.label,onOpen:Kq}),ae.estimateMinutes!=null&&o.jsxs("span",{children:[ae.estimateMinutes,"m"]}),o.jsxs("span",{children:["g",ae.parallelGroup]}),o.jsxs("span",{children:["edited ",ds(ae.mtimeMs,Date.now())]})]}),o.jsx("button",{type:"button",onClick:()=>Z(ae.slug),className:"mt-1.5 font-mono text-[11px] text-fg-faint hover:text-fg-dim leading-none",children:ae.slug}),te&&o.jsxs("div",{className:"mt-3 space-y-2",children:[(xe==null?void 0:xe.verifierVerdict)&&o.jsxs("div",{className:"text-xs text-fg-faint",children:["verdict: ",o.jsx("span",{className:"font-mono",children:Vg(xe.verifierVerdict)})]}),o.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(ae.slug),className:"text-xs px-2.5 py-1 rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Re-fire"})]})]}),o.jsx("div",{className:"flex flex-col gap-2 items-stretch px-[18px] py-4",children:o.jsx("button",{type:"button",onClick:()=>window.api.schedule.runNow(),disabled:re,className:"bg-fg text-bg rounded-lg px-[18px] py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-50",children:re?"Running…":"Queue job"})})]},ae.slug)})})]}),o.jsx(Xq,{open:k,count:_.size,busy:E,onClose:()=>x(!1),onConfirm:Y}),o.jsx(Jq,{open:w,count:_.size,busy:E,onClose:()=>S(!1),onConfirm:ce})]})}function Xq({open:n,count:e,busy:i,onClose:r,onConfirm:s}){return o.jsxs(ef,{open:n,onClose:r,title:"Archive PRDs",children:[o.jsxs("p",{className:"text-xs text-fg-dim",children:["Move ",o.jsx("span",{className:"font-mono",children:e})," PRD",e===1?"":"s"," to"," ",o.jsx("span",{className:"font-mono",children:"prds-archived/<timestamp>/"}),"?"]}),o.jsx("p",{className:"text-[10px] text-fg-faint mt-2",children:"Files are renamed, never deleted. Restore manually from disk if needed."}),o.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[o.jsx("button",{type:"button",onClick:r,disabled:i,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),o.jsx("button",{type:"button",onClick:s,disabled:i||e===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:i?"Archiving…":`Archive ${e}`})]})]})}function Jq({open:n,count:e,busy:i,onClose:r,onConfirm:s}){const[a,d]=R.useState(""),[l,c]=R.useState(""),[p,m]=R.useState(null);R.useEffect(()=>{n&&(d(""),c(""),m(null))},[n]);function f(){m(null);let b=null,_=null;if(a.trim()){const y=Number(a);if(!Number.isInteger(y)||y<0||y>999){m("parallelGroup must be 0–999");return}b=y}if(l.trim()){const y=Number(l);if(!Number.isInteger(y)||y<=0){m("estimateMinutes must be a positive integer");return}_=y}if(b===null&&_===null){m("set at least one field");return}s(b,_)}return o.jsxs(ef,{open:n,onClose:r,title:"Retag PRDs",children:[o.jsxs("p",{className:"text-xs text-fg-dim",children:["Update ",o.jsx("span",{className:"font-mono",children:e})," PRD",e===1?"":"s",". Leave a field blank to keep its current value."]}),o.jsxs("p",{className:"text-[10px] text-fg-faint mt-2",children:["Changing parallelGroup on an ",o.jsx("span",{className:"font-mono",children:"NN-kebab"})," slug renames the file. Every change is logged to ",o.jsx("span",{className:"font-mono",children:"retag-log.jsonl"})," so it's reversible."]}),o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-32 text-fg-faint",children:"parallelGroup:"}),o.jsx("input",{type:"number",min:0,max:999,value:a,onChange:b=>d(b.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]}),o.jsxs("label",{className:"flex items-center gap-2 text-xs",children:[o.jsx("span",{className:"w-32 text-fg-faint",children:"estimateMinutes:"}),o.jsx("input",{type:"number",min:1,value:l,onChange:b=>c(b.target.value),placeholder:"(unchanged)",className:"flex-1 bg-bg border border-line rounded px-2 py-1 font-mono text-xs"})]})]}),p&&o.jsx("div",{className:"mt-2 text-[10px] text-red-300",children:p}),o.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[o.jsx("button",{type:"button",onClick:r,disabled:i,className:"px-2 py-1 text-xs border border-line rounded text-fg-dim hover:text-fg disabled:opacity-40",children:"Cancel"}),o.jsx("button",{type:"button",onClick:f,disabled:i||e===0,className:"px-2 py-1 text-xs border border-accent/60 text-accent rounded hover:bg-bg-hi disabled:opacity-40",children:i?"Retagging…":`Retag ${e}`})]})]})}function Zq(n){Xp(n),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))}function FE(n){return n?n.slice(0,10):""}const Qq=[{value:"all",label:"All"},{value:"completed",label:"Completed"},{value:"failed",label:"Failed"}];function eK({scopeCwd:n=null}){const[e,i]=R.useState(null),[r,s]=R.useState(!0),[a,d]=R.useState(""),[l,c]=R.useState(""),[p,m]=R.useState(""),[f,b]=R.useState("all");R.useEffect(()=>{s(!0),window.api.schedule.getHistory().then(x=>i(x)).catch(x=>i({ok:!1,jobs:[],error:x instanceof Error?x.message:String(x)})).finally(()=>s(!1))},[]);const _=R.useMemo(()=>{if(!(e!=null&&e.jobs))return[];const x=new Set;for(const w of e.jobs){const S=ha(w.cwd);S&&x.add(S)}return[...x].sort()},[e]),y=R.useMemo(()=>e!=null&&e.jobs?e.jobs.filter(x=>!(n&&x.cwd!==n||f!=="all"&&x.status!==f||a&&ha(x.cwd)!==a||l&&FE(x.finishedAt)<l||p&&FE(x.finishedAt)>p)):[],[e,f,a,l,p,n]);if(r)return o.jsx(Lt,{title:"Loading history…"});if(!(e!=null&&e.ok)||e.error)return o.jsxs("div",{className:"p-4 text-xs text-red-300",children:["Failed to load history: ",(e==null?void 0:e.error)??"unknown error"]});if(e.jobs.length===0)return o.jsx(Lt,{title:"No history yet",hint:"Completed and failed jobs appear here."});const k=f!=="all"||!!a||!!l||!!p;return o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2.5 border-b border-line flex-wrap",children:[o.jsx(rS,{options:Qq,value:f,onChange:b,pillPadding:"px-3 py-1"}),o.jsx("span",{className:"w-px h-4 bg-line mx-1","aria-hidden":"true"}),_.length>0&&o.jsxs("select",{value:a,onChange:x=>d(x.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-[12.5px] text-fg-dim max-w-[12rem] font-medium",children:[o.jsx("option",{value:"",children:"All projects"}),_.map(x=>o.jsx("option",{value:x,children:x},x))]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[o.jsx("span",{children:"from"}),o.jsx("input",{type:"date",value:l,onChange:x=>c(x.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),o.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-fg-faint",children:[o.jsx("span",{children:"to"}),o.jsx("input",{type:"date",value:p,onChange:x=>m(x.target.value),className:"bg-bg-hi border border-line rounded-lg px-2 py-1 text-fg-dim font-mono text-[12px]"})]}),o.jsxs("span",{className:"text-[12px] text-fg-faint ml-auto font-mono",children:[y.length," / ",e.jobs.length]}),k&&o.jsx("button",{type:"button",onClick:()=>{b("all"),d(""),c(""),m("")},className:"text-[12px] text-fg-faint hover:text-fg-dim underline",children:"clear"})]}),o.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:y.length===0?o.jsx(Lt,{title:"No matches",hint:"Try adjusting the filters."}):o.jsxs("div",{className:"mx-4 my-3 bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[o.jsx("div",{className:"flex items-center px-[18px] py-3 bg-bg-elev",children:o.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[y.length," job",y.length!==1?"s":""]})}),y.map(x=>o.jsx(tK,{job:x},`${x.slug}-${x.finishedAt??""}`))]})})]})}function tK({job:n}){const[e,i]=R.useState(!1),[r,s]=R.useState(!1),a=rn(b=>b.sessions),d=R.useMemo(()=>F0(n,a),[n,a]),l=n.startedAt&&n.finishedAt?Date.parse(n.finishedAt)-Date.parse(n.startedAt):null,c=n.startedAt?new Date(n.startedAt).toLocaleString():"—",p=n.finishedAt?new Date(n.finishedAt).toLocaleString():"—",m=l!==null?Gp(l):"—",f=n.exitCode!==null?String(n.exitCode):"—";return o.jsxs("div",{className:"border-t border-line/60",children:[o.jsxs("button",{type:"button",className:`w-full text-left grid items-center gap-4 px-[18px] py-3.5 cursor-pointer transition-colors hover:bg-bg-elev ${e?"bg-bg-elev":"bg-transparent"}`,style:{gridTemplateColumns:"116px 1fr auto auto"},onClick:()=>i(b=>!b),"aria-expanded":e,children:[o.jsx(w1,{status:n.status}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-[14.5px] font-medium text-fg leading-snug text-pretty",children:n.title}),n.error&&!e&&(n.status==="failed"||n.status==="needs_review")&&o.jsx("div",{className:"text-[12.5px] mt-0.5 text-accent/80 truncate",children:n.error}),d.epicId&&o.jsx("span",{className:"flex mt-0.5",children:o.jsx(_1,{epicId:d.epicId,label:d.label,onOpen:Zq})})]}),o.jsx(Ny,{cwd:n.cwd}),o.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint whitespace-nowrap",children:[m,o.jsx("span",{className:"inline-flex transition-transform duration-150",style:{transform:e?"rotate(90deg)":"none"},"aria-hidden":"true",children:"›"})]})]}),e&&o.jsxs("div",{className:"grid gap-5 px-[18px] pt-1 pb-5 bg-bg-elev",style:{gridTemplateColumns:"repeat(auto-fit, minmax(160px, 1fr))"},children:[o.jsxs(nd,{label:"Status",children:[o.jsx(yi,{k:"result",v:f}),o.jsx(yi,{k:"state",v:n.status.replace("_"," ")}),n.verifierVerdict&&o.jsx(yi,{k:"verifier",v:Vg(n.verifierVerdict)})]}),o.jsxs(nd,{label:"Timing",children:[o.jsx(yi,{k:"started",v:c}),o.jsx(yi,{k:"finished",v:p}),o.jsx(yi,{k:"duration",v:m})]}),o.jsxs(nd,{label:"Location",children:[o.jsx(yi,{k:"group",v:n.parallelGroup!=null?String(n.parallelGroup):"—"}),o.jsx(yi,{k:"slug",v:n.slug}),o.jsx(yi,{k:"epic",v:d.label??d.epicId??"—",wrap:!0}),n.cwd&&o.jsx(yi,{k:"cwd",v:n.cwd,wrap:!0})]}),o.jsx(nd,{label:"Actions",children:o.jsxs("div",{className:"flex flex-col gap-2 items-start",children:[n.runId&&o.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),s(!0)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"view log →"}),n.status!=="pending"&&o.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),window.api.schedule.resetJob(n.slug)},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 p-0 cursor-pointer",children:"reset to pending →"}),n.error&&o.jsx("p",{className:"text-[12px] text-accent/90 mt-1 break-words whitespace-pre-wrap max-w-sm m-0",children:n.error})]})})]}),r&&n.runId&&o.jsx(iS,{runId:n.runId,slug:n.slug,title:n.title||n.slug,onClose:()=>s(!1)})]})}function nK(n){return n?Object.values(n).reduce((e,i)=>e+(i??[]).reduce((r,s)=>{var a;return r+(((a=s.hooks)==null?void 0:a.length)??0)},0),0):0}function iK(n){var e,i,r;return n?(((e=n.allow)==null?void 0:e.length)??0)+(((i=n.deny)==null?void 0:i.length)??0)+(((r=n.ask)==null?void 0:r.length)??0):0}function rK({navigate:n}){const e=Oi(),i=cn(j=>j.files),r=cn(j=>j.loadJson),s=cn(j=>j.loadText),a=cn(j=>j.watchFile),d=cn(j=>j.unwatchFile),l=e?Du.resolve("user",e,null):null,c=e?ku.resolve("user",e,null):null,p=e?`${e}/.claude.json`:null;R.useEffect(()=>{const j=[l,p].filter(Boolean);j.forEach(A=>{i[A]||r(A),a(A)});const N=[c].filter(Boolean);return N.forEach(A=>{i[A]||s(A),a(A)}),()=>{[...j,...N].forEach(A=>d(A))}},[l,c,p]);const[m,f]=R.useState(null);R.useEffect(()=>{if(!e)return;let j=!1;return(async()=>{const N=await eN(`${e}/.claude/skills`);j||f(N.length)})(),()=>{j=!0}},[e]);const b=l?i[l]:null,_=p?i[p]:null,y=c?i[c]:null,k=R.useMemo(()=>{if(!(b!=null&&b.exists)||b.parseError)return null;const j=b.diskData;return j===null||typeof j!="object"||Array.isArray(j)?{}:j},[b]),x=R.useMemo(()=>{if(!(_!=null&&_.exists)||_.parseError)return null;const j=_.diskData;return j===null||typeof j!="object"||Array.isArray(j)?{}:j},[_]),w=b?b.parseError?"invalid JSON":null:"loading…",S=_?_.parseError?"invalid JSON":null:"loading…",E=[{key:"settings",title:"Settings",summary:w??(k?`${Object.keys(k).length} top-level key${Object.keys(k).length===1?"":"s"} configured`:"not configured")},{key:"permissions",title:"Permissions",summary:w??(k?`${iK(k.permissions)} rule(s) configured`:"not configured")},{key:"hooks",title:"Hooks",summary:w??(k?`${nK(k.hooks)} hook(s) configured`:"not configured")},{key:"mcp",title:"MCP Servers",summary:S??(x?`${Object.keys(x.mcpServers??{}).length} MCP server(s)`:"not configured")},{key:"system-prompt",title:"System Prompt",summary:y!=null&&y.exists&&y.diskRaw.trim().length>0?`configured (${y.diskRaw.length.toLocaleString()} chars)`:"not set"},{key:"skills",title:"Skills",summary:m===null?"loading…":`${m} skill(s) installed`}];return o.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[o.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Global Controls"}),o.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Machine-wide (user-scope) config state for the tabs that default to global here on Home. Read-only summary — open a card to edit."}),o.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:E.map(j=>o.jsxs("button",{type:"button",onClick:()=>n==null?void 0:n(j.key),className:"text-left border border-line rounded-lg bg-bg px-3 py-2.5 hover:border-accent transition-colors",children:[o.jsx("div",{className:"text-[13px] font-medium text-fg",children:j.title}),o.jsx("div",{className:"mt-0.5 text-[12px] text-fg-dim",children:j.summary})]},j.key))})]})}function sK({navigate:n}){const[e,i]=R.useState(null),[r,s]=R.useState(!1),[a,d]=R.useState(!1);R.useEffect(()=>{let c=!0;return q0().then(p=>{c&&s(p.openToHomeOnLaunch===!0)}),()=>{c=!1}},[]);const l=async c=>{s(c),d(!0);try{await uP({openToHomeOnLaunch:c})}catch{s(!c),Re.error('Failed to save "Open to Home on launch" — try again.')}finally{d(!1)}};return R.useEffect(()=>{let c=!0;const p=()=>{window.api.schedule.sessionSlots().then(f=>{c&&i(f)}).catch(()=>{})};p();const m=setInterval(p,5e3);return()=>{c=!1,clearInterval(m)}},[]),o.jsxs("div",{className:"max-w-[760px] space-y-6",children:[o.jsx(rK,{navigate:n}),o.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[o.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Session pool"}),o.jsxs("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:["One machine-wide pool of concurrent Claude sessions. Scheduler jobs and Epic chat runs each request a slot before launching; work waits when the pool is full. Adjustable from 0 (pauses new launches) to 10 on the Home tab, default 5 — or pin it with"," ",o.jsx("code",{className:"font-mono text-[12px]",children:"SM_SESSION_SLOTS"})," (clamped 0–10)."]}),o.jsxs("div",{className:"flex items-center gap-2",children:[Array.from({length:(e==null?void 0:e.total)??5},(c,p)=>o.jsx("span",{className:`w-3.5 h-3.5 rounded-full border ${p<((e==null?void 0:e.inUse)??0)?"bg-accent border-accent":"bg-bg border-line"}`},p)),o.jsx("span",{className:"ml-2 font-mono text-[12.5px] text-fg-faint",children:e?`${e.inUse} / ${e.total} in use`:"loading…"})]}),e&&e.holders.length>0&&o.jsx("ul",{className:"mt-2 mb-0 pl-0 list-none space-y-0.5",children:e.holders.map((c,p)=>o.jsxs("li",{className:"font-mono text-[12px] text-fg-dim",children:[c.owner," ",o.jsxs("span",{className:"text-fg-faint",children:["since ",new Date(c.at).toLocaleTimeString()]})]},p))})]}),o.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[o.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"Behavior"}),o.jsx("p",{className:"mt-0 mb-3 text-[13px] text-fg-dim leading-relaxed",children:"Cross-project app behavior, independent of any single project's config."}),o.jsx(Wg,{checked:r,onChange:l,disabled:a,label:"Open to Home on launch"})]}),o.jsxs("section",{className:"border border-line rounded-xl bg-bg-hi px-5 py-4",children:[o.jsx("h2",{className:"m-0 mb-1 font-serif text-[18px] font-semibold text-fg",children:"On disk"}),o.jsxs("p",{className:"mt-0 mb-2 text-[13px] text-fg-dim leading-relaxed",children:["Global runtime state is deliberately small — everything project-scoped lives inside that project's ",o.jsx("code",{className:"font-mono text-[12px]",children:"session-manager-operations/"})," folder."]}),o.jsxs("ul",{className:"m-0 pl-0 list-none space-y-1 font-mono text-[12px] text-fg-dim",children:[o.jsxs("li",{children:["~/.claude/session-manager/scheduler-machine.json ",o.jsx("span",{className:"text-fg-faint",children:"— policy + pause state"})]}),o.jsxs("li",{children:["<project>/session-manager-operations/scheduler/state/ ",o.jsx("span",{className:"text-fg-faint",children:"— per-project queue + history"})]}),o.jsxs("li",{children:["<project>/session-manager-operations/scheduler/epics/<epic>/prds/ ",o.jsx("span",{className:"text-fg-faint",children:"— PRD sources, per Epic"})]})]})]})]})}const oK={"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."]},browser:{headline:"An embedded dev browser for capturing DOM state and recording click-sequences",intro:"Browser is a foundation stub today — the tab shell exists so later work can add sub-tabs, an address bar, an embedded webview, and capture/record/observe tooling without a routing change.",sections:[{title:"What you see",items:[{body:"A placeholder page. The embedded browser, DOM capture, and click-recording features arrive in follow-up work."}]}]},"system-prompt":{headline:"Edit the CLAUDE.md files that shape Claude's house rules",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, project context, and “always do X / never do Y” rules. Up to three files combine at runtime: User (global, applies everywhere), Project (this repo), and Local (your personal overrides for this repo, gitignored by convention). This tab is a markdown editor over whichever scope you pick.",sections:[{title:"Editor / Presets toggle",items:[{term:"Editor",body:"Edit the actual CLAUDE.md file at the selected scope. 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:"Scope (User / Project / Local)",items:[{term:"User",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",body:"Lives at <repo>/CLAUDE.md. Applies only when working in this repo. Best for shared team context: stack, architecture, do/don't lists, conventions. Commit it to git."},{term:"Local",body:"Lives at <repo>/CLAUDE.local.md. Applies only in this repo, only on your machine. Best for personal overrides that shouldn't reach teammates. Gitignore it."},{body:"Project and Local scopes need an open project — if no tab has a working directory, those scopes are unavailable and the editor prompts you to open one. At runtime all present files combine; more-specific wins: Local > Project > User."}]},{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:"dirty marker (•) on a scope",body:"You have unsaved edits at that scope. Switching scope does NOT auto-save; use Save in the bottom bar (or Revert to discard)."},{body:"If a file doesn't exist yet, the bottom bar notes it will be created on save."}]}],tips:["New users: start with 3–5 bullets at User scope (“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."]},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."]},keybindings:{headline:"Rebind the Claude Code CLI like a game controls screen",intro:'The CLI ships with sensible defaults, but every shortcut can be rebound via ~/.claude/keybindings.json. The Controls view works like a game settings menu: pick a context, click "+ bind" next to an action, press the keys. Presets (Claude defaults / Vim motion / Emacs flow) apply a whole layout in one click. The JSON view edits the same draft directly for chords and command: bindings.',sections:[{title:"How it maps to the file",items:[{term:"Contexts",body:"Bindings are scoped to where you are in the CLI — Global, Chat, Select pickers, Scroll mode, Confirmation dialogs, etc. Global applies everywhere. The left sidebar shows how many keys you've customized in each."},{term:"Keycaps",body:'Each chip is one keystroke pattern ("ctrl+shift+k"). Removing a chip (the ✕) reverts that key to the Claude Code default.'},{term:"Disable a key",body:'The "+ disable a key" capture binds a key to null, turning its Claude Code default off in that context.'},{term:"command: bindings",body:'A key can fire a slash command as if typed ("command:commit"). These and any unrecognized bindings show under "Command & other bindings" but are edited in the JSON view.'},{term:"Reserved keys",body:"ctrl+c, ctrl+d and ctrl+m cannot be rebound; the capture rejects them. Cmd/meta combos are also rejected — Claude Code runs in a terminal."}]}],tips:['Presets replace the whole file — Save commits, Revert restores what was on disk. Editing any binding turns a preset into a "custom layout".',`Defaults stay in effect for any key you don't override; after saving, restart Claude Code so the CLI picks up changes. The "reference ↗" link opens the official docs.`]},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."]},repoviz:{headline:"Repo visualization",intro:"A quick visual map of the project open in your active terminal. It walks the files, counts lines, and reads git status — all locally — then shows you the language mix, the biggest directories, and how many files are uncommitted. Nothing leaves your machine.",sections:[{title:"What it shows",items:[{term:"Summary stats",body:"Three cards at the top: total files, total lines of code, and uncommitted files (highlighted amber when above zero). The current git branch is shown next to the folder name."},{term:"Languages",body:"A colour-coded bar per language (top 12 by file count), each labelled with its file count and line count. Bar length is relative to the largest language."},{term:"Top directories",body:"Treemap-style boxes for the biggest directories, sized by file count so one huge folder doesn't crowd out the rest. Hover a box for its exact file and line counts."}]}],tips:["Open a terminal tab in a folder first — the visualization analyses whichever project your active tab is in, and re-runs automatically when you switch tabs.",'Hit Refresh to re-scan after big changes. Very large repos stop early (5,000-file cap or a 30-second timeout) and are flagged "truncated".']},search:{headline:"Search",intro:"One search surface with two modes, both scoped to the project in your active terminal. Files (⌘P) fuzzy-finds a file by name. Content (⌘⇧F) searches inside files for text. Picking a result inserts its path into the active terminal so you can @-mention it to Claude — it does not open the file.",sections:[{title:"Files mode (⌘P)",items:[{term:"Fuzzy file find",body:"Type part of a filename to fuzzy-match files in the current project; filename and path-prefix matches rank highest. With the box empty, recently-opened files show first, then the rest alphabetically."},{term:"Insert",body:"↑/↓ to move, Enter (or click) inserts the file's path into the active terminal. The path is relative to the project folder when the file lives inside it."}]},{title:"Content mode (⌘⇧F)",items:[{term:"Search inside files",body:'Type to search file contents across the whole project. Uses ripgrep when it is installed and falls back to a built-in file walk otherwise (a "fs walk (rg missing)" note appears in that case). Searching is debounced as you type.'},{term:"Results",body:"Matches are grouped by file with line numbers; the matched text is highlighted. Enter (or click) inserts that file's path and line as path:line into the active terminal."}]}],tips:["Toggle Files / Content at the top, or jump straight in with ⌘P (Files) / ⌘⇧F (Content).","In Content mode, the Aa button turns on case-sensitive matching."]},remote:{headline:"Remote Access — disabled by default",intro:'Lets a paired phone or web browser see your sessions and, optionally, send commands to this machine over an encrypted relay. It is off until you turn it on, and even then only a fixed list of command types is accepted — there is no "run any shell command" verb exposed to the relay. Two separate switches keep watching and controlling apart.',sections:[{title:"Two switches",items:[{term:"Allow remote control from the web",body:"The master switch. While off, the relay refuses every connection and no remote traffic is accepted. Turning it on lets a paired device connect and watch session output."},{term:"Allow command writes (pty + scheduler)",body:"A second switch, off by default, that must also be on before a paired device can run terminal commands or queue scheduler jobs. With it off, devices can watch but cannot change anything."}]},{title:"Security model",items:[{term:"Command allowlist",body:"Only an enumerated set of command types is accepted (17 today: 2 plain reads, 6 sensitive reads, and 9 write/control commands). Anything unrecognised is rejected with an opaque error so the relay learns nothing."},{term:"Encrypted session + code check",body:"Sessions establish an end-to-end key, then show a short verification code you compare with the one in the browser. Until you confirm the codes match, sensitive reads and all command writes stay blocked."},{term:"Path safety",body:"Any folder or file path in a remote command passes through the same home-directory boundary check (validatePath) used by the local app — nothing outside your home directory can be reached."},{term:"Audit log",body:"Every command is recorded to ~/.claude/session-manager/logs/remote-audit-YYYY-MM-DD.log (file mode 0600, stays on this machine). Token and payload values are never written. You can view the last 100 lines in-app from the Audit log section."}]}],tips:['Pair a device by clicking "Pair Device…" and entering the 8-character code shown under "Add Device" in the web app.','Revoke a single device from the Paired Devices list, or hit Panic / "Revoke all" to tear down every session and invalidate all device tokens at once if you suspect compromise.']},"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."]}},sS="sm.learningPanel.collapsed";function GE(){try{const n=localStorage.getItem(sS);if(n===null)return!1;if(n.startsWith("{")){const e=JSON.parse(n);return!!(e&&typeof e=="object"&&Object.values(e).some(Boolean))}return n==="1"||n==="true"}catch{return!1}}function UE(n){try{localStorage.setItem(sS,n?"1":"0")}catch{}}function EA({active:n}){const[e,i]=R.useState(()=>!GE()),r=R.useRef(null),s=R.useCallback(()=>{i(l=>{const c=!l;return UE(!c),c})},[]);R.useEffect(()=>{const l=c=>{c.key===sS&&i(!GE())};return window.addEventListener("storage",l),()=>window.removeEventListener("storage",l)},[]),R.useEffect(()=>{if(!e)return;const l=c=>{var p;(p=r.current)!=null&&p.contains(c.target)||(i(!1),UE(!0))};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[e]);const a=R.useRef(!1);R.useEffect(()=>{if(!a.current){a.current=!0;return}i(!1)},[n]);const d=oK[n];return d?o.jsxs("span",{ref:r,className:"relative inline-block",children:[o.jsx("button",{type:"button",onClick:s,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&&o.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:[o.jsx("p",{className:"text-xs text-fg-dim leading-relaxed mb-3",children:d.intro}),d.sections.map(l=>o.jsxs("div",{className:"mb-3 last:mb-0",children:[o.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg font-medium mb-1",children:l.title}),o.jsx("ul",{className:"space-y-1",children:l.items.map((c,p)=>o.jsxs("li",{className:"text-xs text-fg-dim leading-relaxed",children:[c.term&&o.jsx("span",{className:"text-fg font-medium",children:c.term}),c.term&&" — ",o.jsx("span",{children:c.body})]},p))})]},l.title)),d.tips&&d.tips.length>0&&o.jsxs("div",{className:"mt-3 pt-3 border-t border-line",children:[o.jsx("h3",{className:"text-[11px] uppercase tracking-wider text-fg-dim font-medium mb-1",children:"Tips"}),o.jsx("ul",{className:"space-y-1",children:d.tips.map((l,c)=>o.jsxs("li",{className:"text-xs text-fg-faint leading-relaxed",children:["• ",l]},c))})]})]})]}):null}const HE="sm.schedulerTab.subView",aK=[{key:"queue",label:"Queue"},{key:"prds",label:"PRDs"},{key:"history",label:"History"}];function lK(n,e){const i=new Date(n),r=new Date(e);return i.getFullYear()===r.getFullYear()&&i.getMonth()===r.getMonth()&&i.getDate()===r.getDate()}function cK(n,e,i){if(n==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(n==="rate_limit"){if(e){const s=new Date(e).getTime()-i;return s>0?`Paused for rate limit — resumes in ${la(s)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return n==="network"?"Paused: billing endpoint unreachable for 30+ min.":n==="manual"?"Scheduler paused manually. Click Resume to restart.":`Scheduler paused (${n})`}function dK({scopeCwd:n}){const{snapshot:e}=to(),[i,r]=R.useState(()=>Date.now());if(R.useEffect(()=>{const x=setInterval(()=>r(Date.now()),3e4);return()=>clearInterval(x)},[]),!e)return null;const s=(e.jobs??[]).filter(x=>!n||x.cwd===n),a=s.filter(x=>x.status==="pending").length,d=s.filter(x=>x.status==="running").length,l=s.filter(x=>x.status==="completed"&&(x.finishedAt?lK(x.finishedAt,i):!1)).length,c=e.nextReset?new Date(e.nextReset).getTime():null,p=c?c>i?la(c-i):"soon":"—",m=ds(e.lastRunAt?new Date(e.lastRunAt).getTime():null,i),f=e.paused,b=e.pollHealth,_=b!=null&&!b.lastPollOk,k=(f==null?void 0:f.reason)==="auth"||(f==null?void 0:f.reason)==="network"?"bg-red-950/60 border-red-700/50 text-red-200":"bg-amber-950/60 border-amber-700/50 text-amber-200";return o.jsxs("div",{className:"flex flex-col gap-2",children:[f&&o.jsxs("div",{className:`flex items-center gap-3 border rounded-xl px-4 py-2.5 text-[13px] ${k}`,children:[o.jsx("span",{className:"flex-1 leading-snug",children:cK(f.reason,f.resumeAt,i)}),o.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:"shrink-0 px-2.5 py-1 rounded border border-current/40 hover:bg-white/10 transition-colors text-[12px] font-medium",children:"Resume"})]}),o.jsxs("div",{className:"flex items-center gap-5 flex-wrap bg-bg-hi border border-line rounded-xl px-4 py-3",children:[o.jsxs("span",{className:"inline-flex items-center gap-2 text-[13.5px] text-fg font-semibold whitespace-nowrap",children:[o.jsx("span",{className:"text-sage","aria-hidden":"true",children:o.jsx(an,{name:"clock",size:15})}),"Window resets in ",p]}),o.jsx("span",{className:"w-px h-[18px] bg-rule shrink-0","aria-hidden":"true"}),o.jsx(kw,{dotClass:"bg-fg-faint",n:a,label:"pending"}),o.jsx(kw,{dotClass:"bg-accent",n:d,label:"running"}),o.jsx(kw,{dotClass:"bg-sage",n:l,label:"completed today"}),e.utilization!==null&&e.utilization!==void 0&&o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"w-px h-[18px] bg-rule shrink-0","aria-hidden":"true"}),_?o.jsxs("span",{className:"font-mono text-[12.5px] text-amber-400/70",title:"Billing poll failing — this reading may be outdated",children:[Math.round(e.utilization),"% of window used · last good reading"," ",ds(b.lastPollAt,i)]}):o.jsxs("span",{className:"font-mono text-[12.5px] text-fg-faint",children:[Math.round(e.utilization),"% of window used"]})]}),o.jsxs("span",{className:"ml-auto font-mono text-[12.5px] text-fg-faint whitespace-nowrap",children:["last batch ",m]})]})]})}function uK({navigate:n}={}){var l;const[e,i]=R.useState(()=>{const c=localStorage.getItem(HE);return c==="prds"||c==="history"||c==="machine"?c:"queue"}),r=vt(c=>c.tabs),s=vt(c=>c.activeTabId),a=((l=r.find(c=>c.id===s))==null?void 0:l.cwd)??null,d=a;return R.useEffect(()=>{a&&(rn.getState().hydrate(a),rn.getState().hydrateArchived(a))},[a]),R.useEffect(()=>{localStorage.setItem(HE,e)},[e]),o.jsxs("div",{className:"h-full flex flex-col",children:[o.jsxs("div",{className:"shrink-0 px-9 pt-7 pb-0",children:[o.jsxs("div",{className:"flex items-start justify-between gap-4",children:[o.jsx("div",{className:"text-xs font-bold text-fg-faint tracking-[0.8px] uppercase mb-1",children:"Workspace"}),o.jsx(EA,{active:"scheduler"})]}),o.jsx("h1",{className:"m-0 font-serif text-[40px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),o.jsxs("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:["Global scheduler policy and the machine-wide session pool, plus — when a project tab is active — that project's PRDs, run as"," ",o.jsx("code",{className:"font-mono text-[13.5px]",children:"claude -p"})," ","jobs against your 5-hour window. Jobs auto-pause on rate-limit and resume on the next reset."]}),o.jsx("div",{className:"mt-[18px] mb-[22px]",children:o.jsx(dK,{scopeCwd:d})}),o.jsxs("div",{className:"flex items-center gap-3 pb-0",children:[o.jsx(aq,{options:aK,active:e,onChange:i}),o.jsxs("button",{type:"button",onClick:()=>i("machine"),"aria-pressed":e==="machine",className:`inline-flex items-center gap-1.5 px-[15px] py-2 rounded-lg text-[13.5px] transition-colors ${e==="machine"?"bg-bg-elev border border-line font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,title:"Machine-wide config that applies to every project — not this project's live queue.",children:[o.jsx("span",{"aria-hidden":"true",children:"⚙"})," Machine"]})]}),e==="queue"&&o.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"What's running right now, and what fires next."}),e==="prds"&&o.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"Authored PRD source files on disk — edit, lint, archive, or queue them."}),e==="history"&&o.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"The last 50 completed and failed jobs, for this project."}),e==="machine"&&o.jsx("p",{className:"mt-2 text-[14.5px] text-fg-dim leading-relaxed max-w-[600px]",children:"Machine-wide setup that applies to every project."})]}),o.jsxs("div",{className:"flex-1 min-h-0",children:[e==="queue"&&o.jsx(Cq,{scopeCwd:d,navigate:n}),e==="prds"&&o.jsx(Yq,{scopeCwd:d}),e==="history"&&o.jsx(eK,{scopeCwd:d}),e==="machine"&&o.jsx("div",{className:"h-full overflow-y-auto px-9 py-6",children:o.jsx(sK,{navigate:n})})]})]})}function ib({children:n,right:e}){return o.jsxs("div",{className:"flex items-baseline justify-between mb-2.5",children:[o.jsx("span",{className:"text-[11.5px] font-bold uppercase tracking-[0.8px] text-fg-faint",children:n}),e]})}function WE({label:n,hint:e,on:i,onChange:r,warn:s,disabled:a,first:d}){return o.jsxs("div",{className:`flex items-center justify-between gap-4 px-[18px] py-[15px] ${d?"":"border-t border-rule"} ${a?"opacity-50":""}`,children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"text-sm font-semibold text-fg mb-0.5",children:n}),o.jsxs("div",{className:`text-[12.5px] leading-snug flex items-center gap-1.5 ${s?"text-honey-dark":"text-fg-faint"}`,children:[s&&o.jsx("span",{"aria-hidden":!0,children:"⚠"}),e]})]}),o.jsx(Wg,{checked:i,onChange:a?()=>{}:r,disabled:a})]})}function s_({kind:n="soft",icon:e,children:i,onClick:r,disabled:s}){return o.jsxs("button",{type:"button",onClick:r,disabled:s,className:`shrink-0 inline-flex items-center gap-2 rounded-lg px-3.5 py-2 text-[13px] font-semibold transition-colors disabled:opacity-50 ${n==="soft"?"bg-bg-hi border border-line text-fg hover:bg-bg":"text-fg-dim hover:text-fg"}`,children:[e&&o.jsx(an,{name:e,size:15}),i]})}function hK({children:n}){return o.jsx("span",{className:"text-[11.5px] text-fg-faint",children:n})}function pK({device:n,online:e,onRevoke:i,revoking:r}){const s=n.lastConnectedAt?new Date(n.lastConnectedAt).toLocaleString():`paired ${new Date(n.issuedAt).toLocaleDateString()}`;return o.jsxs("div",{className:"flex items-center gap-3.5 bg-bg-hi border border-line rounded-xl px-[18px] py-3.5",children:[o.jsx("span",{className:"w-[34px] h-[34px] rounded-lg bg-bg border border-line grid place-items-center text-fg-dim shrink-0",children:o.jsx(an,{name:"remote",size:17})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2.5 mb-0.5",children:[o.jsx("span",{className:"text-sm font-semibold text-fg truncate",children:n.deviceName}),e&&o.jsx(Kn,{tone:"default",className:"!text-sage !border-sage/40",children:"online"})]}),o.jsxs("div",{className:"font-mono text-[11.5px] text-fg-faint truncate",children:[n.deviceId," · last seen ",s]})]}),o.jsx("button",{onClick:()=>i(n.deviceId),disabled:r,className:"shrink-0 rounded-lg border border-line bg-bg text-accent px-3.5 py-1.5 text-[12.5px] font-semibold hover:bg-bg-hi disabled:opacity-50 transition-colors",children:"Revoke"})]})}function fK(){var ce;const[n,e]=R.useState(null),[i,r]=R.useState(!0),[s,a]=R.useState(!1),[d,l]=R.useState(!1),[c,p]=R.useState("idle"),[m,f]=R.useState(""),[b,_]=R.useState(null),[y,k]=R.useState(!1),[x,w]=R.useState([]),[S,E]=R.useState(!1),j=R.useRef(null);R.useEffect(()=>{let ae=null;window.api.webRemote.getStatus().then(me=>{e(me),r(!1)}).catch(me=>{Re.error(`Remote status: ${(me==null?void 0:me.message)||String(me)}`),r(!1)}),ae=window.api.webRemote.onStatus(me=>e(me));const xe=window.api.webRemote.onTokenRevoked(()=>{Re.warn("Remote device token was revoked. Re-pair to reconnect."),window.api.webRemote.getStatus().then(e).catch(()=>{})}),Ne=window.api.webRemote.onRevokedAll(({revokedCount:me})=>{Re.info(`Panic: all ${me} device(s) revoked and sessions torn down.`),window.api.webRemote.getStatus().then(e).catch(()=>{})});return()=>{ae==null||ae(),xe(),Ne()}},[]),R.useEffect(()=>{c==="enter-otp"&&setTimeout(()=>{var ae;return(ae=j.current)==null?void 0:ae.focus()},50)},[c]);const N=async()=>{if(n){a(!0);try{n.enabled?await window.api.webRemote.disable():await window.api.webRemote.enable();const ae=await window.api.webRemote.getStatus();e(ae)}catch(ae){Re.error(`Failed: ${(ae==null?void 0:ae.message)||String(ae)}`)}finally{a(!1)}}},A=async()=>{if(n){l(!0);try{n.remoteControlEnabled?await window.api.webRemote.disableControl():await window.api.webRemote.enableControl();const ae=await window.api.webRemote.getStatus();e(ae)}catch(ae){Re.error(`Failed: ${(ae==null?void 0:ae.message)||String(ae)}`)}finally{l(!1)}}},P=async()=>{const ae=m.trim().toUpperCase();if(!/^[A-Z0-9]{8}$/.test(ae)){Re.warn("OTP must be 8 alphanumeric characters.");return}p("pairing");try{const xe=await window.api.webRemote.pair(ae);if(!xe.ok){Re.error(xe.error||"Pairing failed."),p("enter-otp");return}Re.info("Device paired successfully."),f(""),p("idle");const Ne=await window.api.webRemote.getStatus();e(Ne)}catch(xe){Re.error(`Pairing error: ${(xe==null?void 0:xe.message)||String(xe)}`),p("enter-otp")}},I=async ae=>{_(ae);try{const xe=await window.api.webRemote.revokeDevice(ae);if(!xe.ok){Re.error(xe.error||"Revoke failed.");return}const Ne=await window.api.webRemote.getStatus();e(Ne)}catch(xe){Re.error(`Revoke error: ${(xe==null?void 0:xe.message)||String(xe)}`)}finally{_(null)}},O=async()=>{k(!0);try{const ae=await window.api.webRemote.revokeAll();ae.ok||Re.error(ae.error||"Panic revoke failed.")}catch(ae){Re.error(`Panic revoke error: ${(ae==null?void 0:ae.message)||String(ae)}`)}finally{k(!1)}},U=async()=>{if(S){E(!1);return}try{const ae=await window.api.webRemote.auditTail(100);w(ae.lines??[]),E(!0)}catch(ae){Re.error(`Audit log: ${(ae==null?void 0:ae.message)||String(ae)}`)}};if(i)return o.jsx("div",{className:"p-6 text-fg-faint text-sm",children:"Loading…"});const B=(n==null?void 0:n.enabled)??!1,J=(n==null?void 0:n.remoteControlEnabled)??!1,Z=(n==null?void 0:n.connected)??!1,W=(n==null?void 0:n.e2eActive)??!1,q=(n==null?void 0:n.e2eAuthenticated)??!1,Q=(n==null?void 0:n.e2eState)??"idle",oe=(n==null?void 0:n.pendingSas)??null,le=(n==null?void 0:n.devices)??[],H=B&&Z,ee=Z?((ce=le.reduce((ae,xe)=>xe.lastConnectedAt&&(!ae||(ae.lastConnectedAt??"")<xe.lastConnectedAt)?xe:ae,null))==null?void 0:ce.deviceId)??null:null,Y=async()=>{try{const ae=await window.api.webRemote.confirmSas();ae!=null&&ae.ok||Re.error(`SAS confirm failed: ${(ae==null?void 0:ae.error)??"unexpected state — reconnect the mobile app"}`)}catch(ae){Re.error(`SAS confirm failed: ${(ae==null?void 0:ae.message)||String(ae)}`)}};return o.jsxs("div",{className:"max-w-[760px] mx-auto space-y-[22px]",children:[oe&&o.jsxs("div",{className:"flex items-start gap-3.5 px-5 py-4 rounded-2xl border border-accent/40 bg-accent/[0.06]",children:[o.jsx("span",{className:"w-[38px] h-[38px] rounded-[11px] shrink-0 grid place-items-center bg-bg-hi text-accent",children:o.jsx(an,{name:"shield",size:20})}),o.jsxs("div",{className:"flex-1 min-w-0 text-sm text-fg",children:[o.jsx("strong",{className:"font-semibold",children:"Verify E2E session."})," Compare this code with the browser — they must match.",o.jsx("div",{className:"my-2 text-3xl font-mono tracking-[0.3em] text-center text-accent select-all",children:oe}),o.jsx("p",{className:"text-[12.5px] text-fg-faint mb-3",children:"If the codes match, confirm below. Mutating commands are blocked until confirmed."}),o.jsx("button",{onClick:Y,className:"rounded-lg bg-accent text-white px-4 py-2 text-[13px] font-semibold hover:opacity-90 transition-opacity",children:"Codes match — confirm"})]})]}),Q==="failed"&&o.jsxs("div",{className:"flex items-center gap-3.5 px-5 py-4 rounded-2xl border border-[#eccdbe] bg-[#f8e8e0]",children:[o.jsx("span",{className:"w-4 h-4 rounded-full bg-accent text-white grid place-items-center text-[11px] font-bold shrink-0",children:"!"}),o.jsxs("div",{className:"text-[13px] text-[#9a3f1f]",children:[o.jsx("strong",{className:"font-semibold",children:"E2E key exchange failed."})," ",o.jsx("span",{className:"text-fg-dim",children:"The session key could not be established. Reconnect the mobile app to retry."})]})]}),o.jsxs("div",{className:`flex items-center gap-3.5 px-5 py-4 rounded-2xl border ${H?"border-[#e8cdb9] bg-[#f5e9df]":"border-line bg-bg-hi"}`,children:[o.jsx("span",{className:`w-[38px] h-[38px] rounded-[11px] shrink-0 grid place-items-center ${H?"bg-[#f0d9c8] text-accent":"bg-[#e4ebd6] text-sage"}`,children:o.jsx(an,{name:H?"wifi":"shield",size:20})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"text-[14.5px] font-semibold text-fg mb-0.5",children:H?"Remote control is active":B?"Remote control is idle":"Remote control is off"}),o.jsx("div",{className:"text-[13px] text-fg-dim leading-snug",children:H?"A web session can send commands to this machine. Revoke below if unexpected.":B?"The relay is on but no device is connected. Pair a device to begin.":"The relay connection is closed — no remote commands are accepted. Enable it below only when you need it."})]}),W&&q?o.jsx(Kn,{tone:"default",className:"!text-sage !border-sage/40",children:"E2E authenticated"}):W?o.jsx(Kn,{tone:"warn",children:"E2E · awaiting SAS"}):o.jsx(Kn,{tone:"dim",children:"relay only · not E2E yet"})]}),o.jsxs("div",{children:[o.jsx(ib,{children:"Remote control"}),o.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[o.jsx(WE,{first:!0,label:"Allow remote control from the web",hint:"Master switch. When off, the relay refuses every connection.",on:B,onChange:()=>{s||N()}}),o.jsx(WE,{label:"Allow command writes (pty + scheduler)",hint:J?"A paired device can run shell commands and queue jobs on this machine.":"Paired devices can watch session output but cannot send commands.",warn:J,disabled:!B||d,on:J&&B,onChange:()=>{B&&!d&&A()}})]})]}),o.jsxs("div",{children:[o.jsx(ib,{children:"Pair a device"}),c==="idle"?o.jsxs("div",{className:"flex items-center justify-between gap-4 bg-bg-hi border border-line rounded-2xl px-5 py-[18px]",children:[o.jsxs("div",{className:"text-[13.5px] text-fg-dim leading-relaxed max-w-[420px]",children:["Open the ",o.jsx("strong",{className:"text-fg font-semibold",children:"web app"})," on your phone and tap"," ",o.jsx("strong",{className:"text-fg font-semibold",children:"Add Device"})," to get an 8-character code, then enter it here."]}),o.jsx(s_,{kind:"soft",icon:"link",onClick:()=>p("enter-otp"),children:"Pair Device…"})]}):o.jsxs("div",{className:"flex items-center gap-5 bg-bg-hi border border-accent/40 rounded-2xl px-6 py-[22px] shadow-[0_0_0_1px_rgba(184,92,52,0.25)]",children:[o.jsx("span",{className:"w-[52px] h-[52px] rounded-xl bg-bg border border-line grid place-items-center text-accent shrink-0",children:o.jsx(an,{name:"link",size:24})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx("div",{className:"text-[11.5px] font-bold uppercase tracking-[0.8px] text-fg-faint mb-2",children:"Enter the code from your phone"}),o.jsx("input",{ref:j,value:m,onChange:ae=>f(ae.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")),onKeyDown:ae=>{ae.key==="Enter"&&P()},maxLength:8,placeholder:"XXXXXXXX",disabled:c==="pairing",className:"w-full bg-transparent border-0 outline-none font-mono text-[30px] font-semibold tracking-[6px] text-fg placeholder:text-fg-faint/40 disabled:opacity-50"})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.jsx(s_,{kind:"soft",onClick:P,disabled:c==="pairing"||m.length<8,children:c==="pairing"?"Pairing…":"Confirm"}),o.jsx(s_,{kind:"ghost",onClick:()=>{p("idle"),f("")},disabled:c==="pairing",children:"cancel"})]})]})]}),o.jsxs("div",{children:[o.jsx(ib,{right:le.length>0?o.jsxs(hK,{children:[le.length," paired"]}):void 0,children:"Paired devices"}),le.length===0?o.jsx("div",{className:"bg-bg-hi border border-line rounded-xl p-5 text-center text-[13.5px] text-fg-faint italic font-serif",children:"No devices paired yet."}):o.jsx("div",{className:"space-y-2",children:le.map(ae=>o.jsx(pK,{device:ae,online:ae.deviceId===ee,onRevoke:I,revoking:b===ae.deviceId},ae.deviceId))})]}),o.jsxs("div",{children:[o.jsx(ib,{right:o.jsx("button",{onClick:U,className:"text-[12px] text-fg-faint hover:text-fg-dim transition-colors",children:S?"Hide":"Show last 100 · 0600, stays on this machine"}),children:"Audit log"}),S&&o.jsx("div",{className:"bg-bg-hi border border-line rounded-xl overflow-auto max-h-64 mb-2",children:x.length===0?o.jsx("p",{className:"p-4 text-[12.5px] text-fg-faint",children:"No entries today."}):o.jsx("pre",{className:"p-4 text-[12px] text-fg-dim font-mono whitespace-pre-wrap leading-relaxed",children:x.join(`
|
|
3181
|
-
`)})}),o.jsxs("p",{className:"text-[12px] text-fg-faint",children:["Full log at"," ",o.jsx("code",{className:"font-mono text-fg-faint",children:"~/.claude/session-manager/logs/remote-audit-YYYY-MM-DD.log"})," ","(0600, never leaves this machine)"]})]}),o.jsxs("div",{className:"flex items-center justify-between gap-4 bg-[#f8e8e0] border border-[#eccdbe] rounded-2xl px-5 py-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"w-4 h-4 rounded-full bg-accent text-white grid place-items-center text-[11px] font-bold shrink-0",children:"!"}),o.jsx("span",{className:"text-sm font-semibold text-[#9a3f1f]",children:"Panic — disconnect & revoke everything"})]}),o.jsx("div",{className:"text-[12.5px] text-fg-dim leading-snug max-w-[440px]",children:"Tears down every active session and invalidates all paired-device tokens. Devices must re-pair. Use if you suspect compromise."})]}),o.jsx("button",{onClick:O,disabled:y,className:"shrink-0 rounded-lg bg-accent text-white px-[18px] py-2 text-[13px] font-semibold hover:opacity-90 disabled:opacity-50 transition-opacity",children:y?"Revoking…":"Revoke all"})]})]})}function mu({children:n,onClick:e,disabled:i,variant:r="default",tooltip:s,type:a="button",className:d}){const c=`px-2 py-0.5 text-xs rounded border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r==="primary"?"text-accent border-accent/50 hover:bg-bg-hi":r==="danger"?"text-red-400 hover:text-red-300 border-line hover:border-red-400/50":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"} ${d??""}`,p=o.jsx("button",{type:a,title:s,onClick:e,disabled:i,className:c,children:n});return s?o.jsx(By,{content:s,align:"bottom-center",children:p}):p}const gu=[{tag:"feature",label:"Feature",description:`The tag also sets how eagerly /develop should fire inside that Epic's session — see the session-manager-dev:develop skill's "Tag-aware default": feature/bug treat PRD decomposition as the expected next step.`,developEagerness:"expected-default"},{tag:"bug",label:"Bug",description:`The tag also sets how eagerly /develop should fire inside that Epic's session — see the session-manager-dev:develop skill's "Tag-aware default": feature/bug treat PRD decomposition as the expected next step.`,developEagerness:"expected-default"},{tag:"discussion",label:"Discussion",description:"discussion keeps /develop available but never assumed until whether-to-build is actually settled.",developEagerness:"available-not-assumed"},{tag:"build",label:"Build",description:"A build Epic's whole point is to run the Builder skill — decomposition into PRDs (or a direct build run) is the expected next step, the same as feature/bug.",developEagerness:"expected-default"},{tag:"project-home-builder",label:"Project Home Builder",description:"Generates a project's 3 static Project Page HTML files via the project-home-builder local agent — see session-manager-operations/architecture/project-pages-pipeline.md. Decomposition into PRDs is the expected next step, same as feature/bug/build.",developEagerness:"expected-default"}],mK=gu.map(n=>n.tag),gK=["inherit","haiku","sonnet","opus"],VE=["Read","Grep","Glob","Bash","Write","Edit","WebFetch","WebSearch","Task"],vK=["","red","orange","yellow","green","cyan","blue","purple","pink"],TA={red:"#c0392b",orange:"#b85c34",yellow:"#c9a227",green:"#6f7d52",cyan:"#3f8f8a",blue:"#4a6fa5",purple:"#7a6a8a",pink:"#b45a80"};function o_(n){return{name:n.name,description:n.description??"",tools:n.tools,model:n.model??"inherit",color:n.color??"",tags:n.tags,body:n.body}}const qE={name:"new-agent",description:"",tools:["Read","Grep"],model:"inherit",color:"",tags:[],body:""};function xK(){const[n,e]=R.useState(null),[i,r]=R.useState(null),[s,a]=R.useState(""),[d,l]=R.useState(null),[c,p]=R.useState(!1),[m,f]=R.useState(!1),[b,_]=R.useState(!1),y=R.useRef(!0);R.useEffect(()=>()=>{y.current=!1},[]);const k=async W=>{try{const q=await window.api.agents.listPersonas();if(!y.current)return;e(q),r(Q=>{var oe;return W??Q??((oe=q[0])==null?void 0:oe.name)??null})}catch(q){if(!y.current)return;e([]),Re.error(q.message||"failed to load agent personas")}};if(R.useEffect(()=>{k()},[]),n===null)return o.jsx(Lt,{title:"loading…"});const x=s.toLowerCase(),w=n.filter(W=>!x||W.name.toLowerCase().includes(x)||(W.description??"").toLowerCase().includes(x)),S=n.find(W=>W.name===i)??n[0]??null,E=d??(S?o_(S):null),j=!!d&&!!S&&JSON.stringify(d)!==JSON.stringify(o_(S)),N=c,A=W=>{l(null),p(!1),f(!1),r(W)},P=W=>l(q=>({...q??(S?o_(S):qE),...W})),I=()=>{l({...qE}),p(!0),f(!1)},O=()=>{E&&(l({...E,name:E.name+"-copy"}),p(!0))},U=()=>{l(null),p(!1)},B=async()=>{if(E){if(!/^[a-z][a-z0-9-]*$/.test(E.name)){Re.error('agent name must be lowercase, hyphenated (e.g. "my-agent")');return}_(!0);try{const W={name:E.name,originalName:N||S==null?void 0:S.name,description:E.description,tools:E.tools,model:E.model,color:E.color,tags:E.tags,body:E.body};await window.api.agents.savePersona(W),Re.info(N?`created ${E.name}`:`saved ${E.name}`),l(null),p(!1),await k(E.name)}catch(W){Re.error(W.message||"failed to save agent persona")}finally{_(!1)}}},J=async()=>{if(S){_(!0);try{await window.api.agents.deletePersona({name:S.name}),Re.info(`deleted ${S.name}`),f(!1),l(null),p(!1),await k()}catch(W){Re.error(W.message||"failed to delete agent persona")}finally{_(!1)}}},Z=async W=>{if(S)try{await window.api.agents.removeOverride({name:S.name,projectName:W}),Re.info(`removed ${W}'s override of ${S.name}`),await k(S.name)}catch(q){Re.error(q.message||"failed to remove override")}};return o.jsx(Ti,{toolbar:o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-fg-faint",children:[n.length," persona",n.length===1?"":"s"]}),o.jsx("input",{value:s,onChange:W=>a(W.target.value),placeholder:"filter…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-40"}),o.jsx("div",{className:"flex-1"}),o.jsx(mu,{variant:"primary",onClick:I,children:"+ New agent"})]}),children:o.jsx(ec,{sidebar:o.jsxs("div",{className:"py-1",children:[N&&o.jsx("div",{className:"w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 bg-bg-hi text-fg border-l-2 border-accent",children:o.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[o.jsx("span",{className:"truncate font-mono",children:E==null?void 0:E.name}),o.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"new"})]})}),w.length===0&&!N?o.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no agent personas found"}):w.map(W=>{const q=!N&&W.name===i,Q=q&&j;return o.jsxs("button",{onClick:()=>A(W.name),className:`w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 border-l-2 ${q?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[o.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[o.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{background:W.color?TA[W.color]??W.color:"var(--fg-faint, #999)",opacity:W.color?1:.35}}),o.jsx("span",{className:"truncate font-mono",children:W.name})]}),Q&&o.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"unsaved"}),!Q&&W.overridingProjects.length>0&&o.jsx("span",{className:"shrink-0",children:o.jsxs(Kn,{tone:"dim",children:[W.overridingProjects.length," override",W.overridingProjects.length>1?"s":""]})})]}),W.description&&o.jsx("span",{className:"truncate text-fg-faint",children:W.description})]},W.name)})]}),detail:E?o.jsx(bK,{obj:E,set:P,saved:S,dirty:j,isNew:N,busy:b,confirmDelete:m,setConfirmDelete:f,onDuplicate:O,onRevert:U,onSave:B,onDelete:J,onDropOverride:Z}):o.jsx(Lt,{title:"select an agent"})})})}function bK({obj:n,set:e,saved:i,dirty:r,isNew:s,busy:a,confirmDelete:d,setConfirmDelete:l,onDuplicate:c,onRevert:p,onSave:m,onDelete:f,onDropOverride:b}){const _=`~/.claude/agents/${n.name}.md`,y=r||s;return o.jsxs("div",{className:"max-w-3xl",children:[o.jsxs("div",{className:"px-4 py-3 border-b border-line flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-sm font-semibold text-fg font-mono",children:n.name}),s?o.jsx(Kn,{tone:"accent",children:"unsaved draft"}):r?o.jsx(Kn,{tone:"warn",children:"edited"}):o.jsx(Kn,{tone:"good",children:"saved"}),o.jsx("span",{className:"ml-auto text-[11px] text-fg-faint font-mono",children:_})]}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(Uc,{label:"name",hint:"Filename on disk — lowercase, hyphenated.",children:o.jsx("input",{value:n.name,onChange:k=>e({name:k.target.value.toLowerCase()}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg font-mono"})}),o.jsx(Uc,{label:"description",hint:"Shown in the list and in agent pickers.",children:o.jsx("input",{value:n.description,onChange:k=>e({description:k.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg"})}),o.jsx(Uc,{label:"model",hint:"Cheap models for read-only personas; opus for judgement calls.",children:o.jsx(yK,{options:gK,value:n.model,onChange:k=>e({model:k}),mono:!0})}),o.jsx(Uc,{label:"tools",hint:`${n.tools.length} of ${VE.length} granted. Anything not ticked is refused at call time.`,children:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:VE.map(k=>{const x=n.tools.includes(k);return o.jsx("button",{onClick:()=>e({tools:x?n.tools.filter(w=>w!==k):[...n.tools,k]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${x?"bg-sage/15 text-sage-dark border-sage/30":"bg-bg-hi text-fg-faint border-line"}`,children:k},k)})})}),o.jsx(Uc,{label:"color",children:o.jsx("div",{className:"flex gap-1.5",children:vK.map(k=>o.jsx("button",{title:k||"none",onClick:()=>e({color:k}),className:"w-5 h-5 rounded",style:{background:k?TA[k]:"transparent",border:n.color===k?"2px solid var(--accent, #b85c34)":"1px solid var(--line, #555)"}},k||"none"))})}),o.jsx(Uc,{label:"tags",hint:"Epic intent tags this persona is associated with — shown as the default agent on that tag's own page.",children:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:gu.map(k=>{const x=n.tags.includes(k.tag),w=yy(k.tag);return o.jsxs("button",{onClick:()=>e({tags:x?n.tags.filter(S=>S!==k.tag):[...n.tags,k.tag]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${x?`${w.bg} ${w.text} ${w.border?"border-current/30":"border-transparent"}`:"bg-bg-hi text-fg-faint border-line"}`,children:["#",k.tag]},k.tag)})})}),o.jsx(Uc,{label:"definition",hint:"The system prompt this persona runs under.",children:o.jsx("textarea",{rows:9,value:n.body,onChange:k=>e({body:k.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono leading-relaxed resize-y"})}),o.jsx(Uc,{label:"project overrides",hint:"Open projects that shadow this definition with a local copy.",children:i&&i.overridingProjects.length>0?o.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.overridingProjects.map(k=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[k,o.jsx("button",{onClick:()=>b(k),title:"Drop the local copy",className:"text-fg-faint hover:text-fg",children:"×"})]},k))}):o.jsx("div",{className:"text-xs text-fg-faint italic",children:s?"save first to see project overrides.":"no open project overlays this agent — the global definition applies everywhere."})})]}),o.jsx("div",{className:"px-4 py-2.5 border-t border-line flex items-center gap-2 flex-wrap",children:d?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-xs text-fg-dim",children:["Delete ",o.jsx("strong",{className:"font-mono",children:n.name})," and its file?"]}),o.jsx(mu,{variant:"danger",onClick:f,disabled:a,children:"Delete"}),o.jsx(mu,{onClick:()=>l(!1),children:"Keep"})]}):o.jsxs(o.Fragment,{children:[o.jsx(mu,{onClick:c,disabled:a,children:"Duplicate"}),!s&&o.jsx(mu,{variant:"danger",onClick:()=>l(!0),disabled:a,children:"Delete"}),o.jsx("div",{className:"flex-1"}),y&&o.jsx("span",{className:"text-[11px] text-fg-faint",children:"unsaved changes"}),o.jsx(mu,{onClick:p,disabled:!y||a,children:"Revert"}),o.jsx(mu,{variant:"primary",onClick:m,disabled:!y||a,children:a?"Saving…":s?"Create":"Save"})]})})]})}function Uc({label:n,hint:e,children:i}){return o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:n}),i,e&&o.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:e})]})}function yK({options:n,value:e,onChange:i,mono:r}){return o.jsx("div",{className:"flex flex-wrap gap-1",children:n.map(s=>{const a=s===e;return o.jsx("button",{onClick:()=>i(s),className:`px-2.5 py-1 rounded text-xs border ${r?"font-mono":""} ${a?"bg-accent/15 text-accent border-accent/40 font-semibold":"bg-bg-hi text-fg-dim border-line"}`,children:s},s)})})}function wK(){const[n,e]=R.useState(gu[0].tag),[i,r]=R.useState(null),[s,a]=R.useState(!1),d=R.useRef(!0);R.useEffect(()=>()=>{d.current=!1},[]);const l=async()=>{try{const f=await window.api.agents.listPersonas();d.current&&r(f)}catch(f){if(!d.current)return;r([]),Re.error(f.message||"failed to load agent personas")}};R.useEffect(()=>{l()},[]);const c=gu.find(f=>f.tag===n)??null,p=async(f,b)=>{try{await window.api.agents.savePersona({name:f.name,originalName:f.name,description:f.description??"",tools:f.tools,model:f.model??"inherit",color:f.color??"",tags:[...f.tags,b],body:f.body}),a(!1),await l()}catch(_){Re.error(_.message||"failed to assign tag")}},m=async(f,b)=>{try{await window.api.agents.savePersona({name:f.name,originalName:f.name,description:f.description??"",tools:f.tools,model:f.model??"inherit",color:f.color??"",tags:f.tags.filter(_=>_!==b),body:f.body}),await l()}catch(_){Re.error(_.message||"failed to remove tag")}};return o.jsx(Ti,{toolbar:o.jsxs("span",{className:"text-fg-faint",children:[gu.length," tag",gu.length===1?"":"s"]}),children:o.jsx(ec,{sidebar:o.jsx("div",{className:"py-1",children:gu.map(f=>{const b=yy(f.tag),_=n===f.tag,y=(i==null?void 0:i.filter(k=>k.tags.includes(f.tag)).length)??0;return o.jsxs("button",{onClick:()=>{e(f.tag),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 ${_?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-semibold ${b.bg} ${b.text} ${b.border?"border border-current/30":""}`,children:["#",f.tag]}),o.jsx("span",{className:"truncate",children:f.label}),y>0&&o.jsx("span",{className:"ml-auto text-[10.5px] text-fg-faint font-mono shrink-0",children:y})]},f.tag)})}),detail:c?o.jsx(_K,{entry:c,personas:i,adding:s,setAdding:a,onAssign:p,onUnassign:m}):o.jsx(Lt,{title:"select a tag"})})})}function _K({entry:n,personas:e,adding:i,setAdding:r,onAssign:s,onUnassign:a}){const d=yy(n.tag),l=l1(n.tag),c=(e==null?void 0:e.filter(m=>m.tags.includes(n.tag)))??[],p=(e==null?void 0:e.filter(m=>!m.tags.includes(n.tag)))??[];return o.jsxs("div",{className:"p-4 space-y-4 max-w-3xl",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("span",{className:`px-2 py-1 rounded text-xs font-mono font-semibold ${d.bg} ${d.text} ${d.border?"border border-current/30":""}`,children:["#",n.tag]}),o.jsx("span",{className:"text-sm font-semibold text-fg",children:n.label})]}),o.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:n.description}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"/develop eagerness"}),o.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:n.developEagerness})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"agents carrying this tag"}),e===null?o.jsx("div",{className:"text-xs text-fg-faint italic",children:"loading…"}):o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c.map(m=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[m.name,o.jsx("button",{onClick:()=>a(m,n.tag),title:"Remove this tag from the agent",className:"text-fg-faint hover:text-fg",children:"×"})]},m.name)),c.length===0&&!i&&o.jsx("span",{className:"text-xs text-fg-faint italic mr-1",children:"no agent carries this tag yet."}),i?p.length>0?o.jsxs("select",{autoFocus:!0,defaultValue:"",onChange:m=>{const f=e.find(b=>b.name===m.target.value);f&&s(f,n.tag)},onBlur:()=>r(!1),className:"bg-bg border border-line rounded px-2 py-0.5 text-[11px] text-fg font-mono",children:[o.jsx("option",{value:"",disabled:!0,children:"pick an agent…"}),p.map(m=>o.jsx("option",{value:m.name,children:m.name},m.name))]}):o.jsx("span",{className:"text-xs text-fg-faint italic",children:"every agent already carries this tag."}):o.jsx("button",{onClick:()=>r(!0),className:"px-2 py-0.5 rounded-full text-[11px] font-mono border border-line text-fg-faint hover:text-fg hover:bg-bg-hi",children:"+ assign agent"})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"opening framing — sent before the human's goal"}),o.jsx("pre",{className:"text-xs text-fg-dim whitespace-pre-wrap bg-bg-elev border border-line rounded p-3 leading-relaxed font-sans",children:l.initialPromptTemplate})]})]})}function SK({eyebrow:n,title:e,intro:i,frame:r=!0,learnKey:s,children:a}){const d=r&&(n||e||i);return o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[d&&o.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"max-w-[820px]",children:[n&&o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:n}),e&&o.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),i&&o.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:i})]}),s&&o.jsx(EA,{active:s})]}),o.jsx("div",{className:`flex-1 min-h-0 ${d?"px-8 pb-7":"p-8"}`,children:a})]})}const kK={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."},keybindings:{title:"Keybindings",intro:"Shortcuts you can override. Bindings here apply to Claude Code itself, not the Session Manager chrome."},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:"Every agent persona available on this machine — global definitions in ~/.claude/agents, and which currently-open projects override them locally. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk."},"tag-library":{title:"Tag Library",intro:"Every Epic intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},remote:{title:"Remote Access",intro:"Web remote control — disabled by default. Pair your browser, then issue scheduler + terminal commands from any device over a secure relay you self-host."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},repoviz:{title:"Repo visualization",intro:"Language + directory map of the current project, computed locally."},search:{title:"Search",intro:"Find by filename (⌘P) or by content (⌘⇧F) across the active cwd. The chosen path is inserted into the active terminal."}},a_=()=>{};function CK(n,e){switch(n){case"overview":return o.jsx(n3,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return o.jsx(U3,{});case"editor":return o.jsx(Yb,{});case"projects":return o.jsx(M7,{});case"browser":return o.jsx(SA,{})}const i=kK[n],r=(()=>{switch(n){case"skills":return o.jsx(zL,{});case"history":return o.jsx(k5,{});case"scheduler":return o.jsx(uK,{navigate:e.onNavigate});case"plugins":return o.jsx(O9,{});case"mcp":return o.jsx(Z9,{});case"hooks":return o.jsx(a7,{});case"keybindings":return o.jsx(b6,{});case"memory":return o.jsx(R6,{});case"system-prompt":return o.jsx(l6,{});case"permissions":return o.jsx(t6,{});case"settings":return o.jsx(JB,{});case"remote":return o.jsx(fK,{});case"agent-library":return o.jsx(xK,{});case"tag-library":return o.jsx(wK,{});case"voice":return o.jsx(tB,{open:!0,onClose:a_,variant:"page"});case"repoviz":return o.jsx(L4,{open:!0,onClose:a_,variant:"page"});case"search":return o.jsx(W4,{open:!0,onClose:a_,variant:"page",initialMode:e.searchMode??"files"});default:return null}})();if(!r)return null;const s=aP[n];return i&&s?o.jsx(SK,{eyebrow:s,title:i.title,intro:i.intro,learnKey:n,children:r}):r}var l_={exports:{}},KE;function EK(){return KE||(KE=1,(function(n,e){(function(i,r){n.exports=r()})(globalThis,(()=>(()=>{var i={4567:function(d,l,c){var p=this&&this.__decorate||function(S,E,j,N){var A,P=arguments.length,I=P<3?E:N===null?N=Object.getOwnPropertyDescriptor(E,j):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(S,E,j,N);else for(var O=S.length-1;O>=0;O--)(A=S[O])&&(I=(P<3?A(I):P>3?A(E,j,I):A(E,j))||I);return P>3&&I&&Object.defineProperty(E,j,I),I},m=this&&this.__param||function(S,E){return function(j,N){E(j,N,S)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const f=c(9042),b=c(9924),_=c(844),y=c(4725),k=c(2585),x=c(3656);let w=l.AccessibilityManager=class extends _.Disposable{constructor(S,E,j,N){super(),this._terminal=S,this._coreBrowserService=j,this._renderService=N,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let A=0;A<this._terminal.rows;A++)this._rowElements[A]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[A]);if(this._topBoundaryFocusListener=A=>this._handleBoundaryFocus(A,0),this._bottomBoundaryFocusListener=A=>this._handleBoundaryFocus(A,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((A=>this._handleResize(A.rows)))),this.register(this._terminal.onRender((A=>this._refreshRows(A.start,A.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((A=>this._handleChar(A)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3181
|
+
`)})}),o.jsxs("p",{className:"text-[12px] text-fg-faint",children:["Full log at"," ",o.jsx("code",{className:"font-mono text-fg-faint",children:"~/.claude/session-manager/logs/remote-audit-YYYY-MM-DD.log"})," ","(0600, never leaves this machine)"]})]}),o.jsxs("div",{className:"flex items-center justify-between gap-4 bg-[#f8e8e0] border border-[#eccdbe] rounded-2xl px-5 py-4",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"w-4 h-4 rounded-full bg-accent text-white grid place-items-center text-[11px] font-bold shrink-0",children:"!"}),o.jsx("span",{className:"text-sm font-semibold text-[#9a3f1f]",children:"Panic — disconnect & revoke everything"})]}),o.jsx("div",{className:"text-[12.5px] text-fg-dim leading-snug max-w-[440px]",children:"Tears down every active session and invalidates all paired-device tokens. Devices must re-pair. Use if you suspect compromise."})]}),o.jsx("button",{onClick:O,disabled:y,className:"shrink-0 rounded-lg bg-accent text-white px-[18px] py-2 text-[13px] font-semibold hover:opacity-90 disabled:opacity-50 transition-opacity",children:y?"Revoking…":"Revoke all"})]})]})}function mu({children:n,onClick:e,disabled:i,variant:r="default",tooltip:s,type:a="button",className:d}){const c=`px-2 py-0.5 text-xs rounded border transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r==="primary"?"text-accent border-accent/50 hover:bg-bg-hi":r==="danger"?"text-red-400 hover:text-red-300 border-line hover:border-red-400/50":"text-fg-dim border-line hover:text-fg hover:bg-bg-hi"} ${d??""}`,p=o.jsx("button",{type:a,title:s,onClick:e,disabled:i,className:c,children:n});return s?o.jsx(By,{content:s,align:"bottom-center",children:p}):p}const gu=[{tag:"feature",label:"Feature",description:`The tag also sets how eagerly /develop should fire inside that Epic's session — see the session-manager-dev:develop skill's "Tag-aware default": feature/bug treat PRD decomposition as the expected next step.`,developEagerness:"expected-default"},{tag:"bug",label:"Bug",description:`The tag also sets how eagerly /develop should fire inside that Epic's session — see the session-manager-dev:develop skill's "Tag-aware default": feature/bug treat PRD decomposition as the expected next step.`,developEagerness:"expected-default"},{tag:"discussion",label:"Discussion",description:"discussion keeps /develop available but never assumed until whether-to-build is actually settled.",developEagerness:"available-not-assumed"},{tag:"build",label:"Build",description:"A build Epic's whole point is to run the Builder skill — decomposition into PRDs (or a direct build run) is the expected next step, the same as feature/bug.",developEagerness:"expected-default"},{tag:"project-home-builder",label:"Project Home Builder",description:"Generates a project's 3 static Project Page HTML files via the project-home-builder local agent — see session-manager-operations/architecture/project-pages-pipeline.md. Decomposition into PRDs is the expected next step, same as feature/bug/build.",developEagerness:"expected-default"}],mK=gu.map(n=>n.tag),gK=["inherit","haiku","sonnet","opus"],VE=["Read","Grep","Glob","Bash","Write","Edit","WebFetch","WebSearch","Task"],vK=["","red","orange","yellow","green","cyan","blue","purple","pink"],TA={red:"#c0392b",orange:"#b85c34",yellow:"#c9a227",green:"#6f7d52",cyan:"#3f8f8a",blue:"#4a6fa5",purple:"#7a6a8a",pink:"#b45a80"};function o_(n){return{name:n.name,description:n.description??"",tools:n.tools,model:n.model??"inherit",color:n.color??"",tags:n.tags,body:n.body}}const qE={name:"new-agent",description:"",tools:["Read","Grep"],model:"inherit",color:"",tags:[],body:""};function xK(){const[n,e]=R.useState(null),[i,r]=R.useState(null),[s,a]=R.useState(""),[d,l]=R.useState(null),[c,p]=R.useState(!1),[m,f]=R.useState(!1),[b,_]=R.useState(!1),y=R.useRef(!0);R.useEffect(()=>()=>{y.current=!1},[]);const k=async W=>{try{const q=await window.api.agents.listPersonas();if(!y.current)return;e(q),r(Q=>{var oe;return W??Q??((oe=q[0])==null?void 0:oe.name)??null})}catch(q){if(!y.current)return;e([]),Re.error(q.message||"failed to load agent personas")}};if(R.useEffect(()=>{k()},[]),R.useEffect(()=>window.api.agents.onChanged(()=>k()),[]),n===null)return o.jsx(Lt,{title:"loading…"});const x=s.toLowerCase(),w=n.filter(W=>!x||W.name.toLowerCase().includes(x)||(W.description??"").toLowerCase().includes(x)),S=n.find(W=>W.name===i)??n[0]??null,E=d??(S?o_(S):null),j=!!d&&!!S&&JSON.stringify(d)!==JSON.stringify(o_(S)),N=c,A=W=>{l(null),p(!1),f(!1),r(W)},P=W=>l(q=>({...q??(S?o_(S):qE),...W})),I=()=>{l({...qE}),p(!0),f(!1)},O=()=>{E&&(l({...E,name:E.name+"-copy"}),p(!0))},U=()=>{l(null),p(!1)},B=async()=>{if(E){if(!/^[a-z][a-z0-9-]*$/.test(E.name)){Re.error('agent name must be lowercase, hyphenated (e.g. "my-agent")');return}_(!0);try{const W={name:E.name,originalName:N||S==null?void 0:S.name,description:E.description,tools:E.tools,model:E.model,color:E.color,tags:E.tags,body:E.body};await window.api.agents.savePersona(W),Re.info(N?`created ${E.name}`:`saved ${E.name}`),l(null),p(!1),await k(E.name)}catch(W){Re.error(W.message||"failed to save agent persona")}finally{_(!1)}}},J=async()=>{if(S){_(!0);try{await window.api.agents.deletePersona({name:S.name}),Re.info(`deleted ${S.name}`),f(!1),l(null),p(!1),await k()}catch(W){Re.error(W.message||"failed to delete agent persona")}finally{_(!1)}}},Z=async W=>{if(S)try{await window.api.agents.removeOverride({name:S.name,projectName:W}),Re.info(`removed ${W}'s override of ${S.name}`),await k(S.name)}catch(q){Re.error(q.message||"failed to remove override")}};return o.jsx(Ti,{toolbar:o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-fg-faint",children:[n.length," persona",n.length===1?"":"s"]}),o.jsx("input",{value:s,onChange:W=>a(W.target.value),placeholder:"filter…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-40"}),o.jsx("div",{className:"flex-1"}),o.jsx(mu,{variant:"primary",onClick:I,children:"+ New agent"})]}),children:o.jsx(ec,{sidebar:o.jsxs("div",{className:"py-1",children:[N&&o.jsx("div",{className:"w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 bg-bg-hi text-fg border-l-2 border-accent",children:o.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[o.jsx("span",{className:"truncate font-mono",children:E==null?void 0:E.name}),o.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"new"})]})}),w.length===0&&!N?o.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no agent personas found"}):w.map(W=>{const q=!N&&W.name===i,Q=q&&j;return o.jsxs("button",{onClick:()=>A(W.name),className:`w-full text-left px-3 py-1 text-xs flex flex-col gap-0.5 border-l-2 ${q?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[o.jsxs("span",{className:"flex items-center gap-2 justify-between w-full",children:[o.jsxs("span",{className:"flex items-center gap-1.5 min-w-0",children:[o.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{background:W.color?TA[W.color]??W.color:"var(--fg-faint, #999)",opacity:W.color?1:.35}}),o.jsx("span",{className:"truncate font-mono",children:W.name})]}),Q&&o.jsx("span",{className:"shrink-0 text-[10px] font-semibold text-accent",children:"unsaved"}),!Q&&W.overridingProjects.length>0&&o.jsx("span",{className:"shrink-0",children:o.jsxs(Kn,{tone:"dim",children:[W.overridingProjects.length," override",W.overridingProjects.length>1?"s":""]})})]}),W.description&&o.jsx("span",{className:"truncate text-fg-faint",children:W.description})]},W.name)})]}),detail:E?o.jsx(bK,{obj:E,set:P,saved:S,dirty:j,isNew:N,busy:b,confirmDelete:m,setConfirmDelete:f,onDuplicate:O,onRevert:U,onSave:B,onDelete:J,onDropOverride:Z}):o.jsx(Lt,{title:"select an agent"})})})}function bK({obj:n,set:e,saved:i,dirty:r,isNew:s,busy:a,confirmDelete:d,setConfirmDelete:l,onDuplicate:c,onRevert:p,onSave:m,onDelete:f,onDropOverride:b}){const _=`~/.claude/agents/${n.name}.md`,y=r||s;return o.jsxs("div",{className:"max-w-3xl",children:[o.jsxs("div",{className:"px-4 py-3 border-b border-line flex items-center gap-2 flex-wrap",children:[o.jsx("span",{className:"text-sm font-semibold text-fg font-mono",children:n.name}),s?o.jsx(Kn,{tone:"accent",children:"unsaved draft"}):r?o.jsx(Kn,{tone:"warn",children:"edited"}):o.jsx(Kn,{tone:"good",children:"saved"}),o.jsx("span",{className:"ml-auto text-[11px] text-fg-faint font-mono",children:_})]}),o.jsxs("div",{className:"p-4 space-y-4",children:[o.jsx(Uc,{label:"name",hint:"Filename on disk — lowercase, hyphenated.",children:o.jsx("input",{value:n.name,onChange:k=>e({name:k.target.value.toLowerCase()}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg font-mono"})}),o.jsx(Uc,{label:"description",hint:"Shown in the list and in agent pickers.",children:o.jsx("input",{value:n.description,onChange:k=>e({description:k.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1 text-xs text-fg"})}),o.jsx(Uc,{label:"model",hint:"Cheap models for read-only personas; opus for judgement calls.",children:o.jsx(yK,{options:gK,value:n.model,onChange:k=>e({model:k}),mono:!0})}),o.jsx(Uc,{label:"tools",hint:`${n.tools.length} of ${VE.length} granted. Anything not ticked is refused at call time.`,children:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:VE.map(k=>{const x=n.tools.includes(k);return o.jsx("button",{onClick:()=>e({tools:x?n.tools.filter(w=>w!==k):[...n.tools,k]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${x?"bg-sage/15 text-sage-dark border-sage/30":"bg-bg-hi text-fg-faint border-line"}`,children:k},k)})})}),o.jsx(Uc,{label:"color",children:o.jsx("div",{className:"flex gap-1.5",children:vK.map(k=>o.jsx("button",{title:k||"none",onClick:()=>e({color:k}),className:"w-5 h-5 rounded",style:{background:k?TA[k]:"transparent",border:n.color===k?"2px solid var(--accent, #b85c34)":"1px solid var(--line, #555)"}},k||"none"))})}),o.jsx(Uc,{label:"tags",hint:"Epic intent tags this persona is associated with — shown as the default agent on that tag's own page.",children:o.jsx("div",{className:"flex flex-wrap gap-1.5",children:gu.map(k=>{const x=n.tags.includes(k.tag),w=yy(k.tag);return o.jsxs("button",{onClick:()=>e({tags:x?n.tags.filter(S=>S!==k.tag):[...n.tags,k.tag]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${x?`${w.bg} ${w.text} ${w.border?"border-current/30":"border-transparent"}`:"bg-bg-hi text-fg-faint border-line"}`,children:["#",k.tag]},k.tag)})})}),o.jsx(Uc,{label:"definition",hint:"The system prompt this persona runs under.",children:o.jsx("textarea",{rows:9,value:n.body,onChange:k=>e({body:k.target.value}),className:"w-full bg-bg border border-line rounded px-2 py-1.5 text-xs text-fg font-mono leading-relaxed resize-y"})}),o.jsx(Uc,{label:"project overrides",hint:"Open projects that shadow this definition with a local copy.",children:i&&i.overridingProjects.length>0?o.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.overridingProjects.map(k=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[k,o.jsx("button",{onClick:()=>b(k),title:"Drop the local copy",className:"text-fg-faint hover:text-fg",children:"×"})]},k))}):o.jsx("div",{className:"text-xs text-fg-faint italic",children:s?"save first to see project overrides.":"no open project overlays this agent — the global definition applies everywhere."})})]}),o.jsx("div",{className:"px-4 py-2.5 border-t border-line flex items-center gap-2 flex-wrap",children:d?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"text-xs text-fg-dim",children:["Delete ",o.jsx("strong",{className:"font-mono",children:n.name})," and its file?"]}),o.jsx(mu,{variant:"danger",onClick:f,disabled:a,children:"Delete"}),o.jsx(mu,{onClick:()=>l(!1),children:"Keep"})]}):o.jsxs(o.Fragment,{children:[o.jsx(mu,{onClick:c,disabled:a,children:"Duplicate"}),!s&&o.jsx(mu,{variant:"danger",onClick:()=>l(!0),disabled:a,children:"Delete"}),o.jsx("div",{className:"flex-1"}),y&&o.jsx("span",{className:"text-[11px] text-fg-faint",children:"unsaved changes"}),o.jsx(mu,{onClick:p,disabled:!y||a,children:"Revert"}),o.jsx(mu,{variant:"primary",onClick:m,disabled:!y||a,children:a?"Saving…":s?"Create":"Save"})]})})]})}function Uc({label:n,hint:e,children:i}){return o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:n}),i,e&&o.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:e})]})}function yK({options:n,value:e,onChange:i,mono:r}){return o.jsx("div",{className:"flex flex-wrap gap-1",children:n.map(s=>{const a=s===e;return o.jsx("button",{onClick:()=>i(s),className:`px-2.5 py-1 rounded text-xs border ${r?"font-mono":""} ${a?"bg-accent/15 text-accent border-accent/40 font-semibold":"bg-bg-hi text-fg-dim border-line"}`,children:s},s)})})}function wK(){const[n,e]=R.useState(gu[0].tag),[i,r]=R.useState(null),[s,a]=R.useState(!1),d=R.useRef(!0);R.useEffect(()=>()=>{d.current=!1},[]);const l=async()=>{try{const f=await window.api.agents.listPersonas();d.current&&r(f)}catch(f){if(!d.current)return;r([]),Re.error(f.message||"failed to load agent personas")}};R.useEffect(()=>{l()},[]),R.useEffect(()=>window.api.agents.onChanged(()=>l()),[]);const c=gu.find(f=>f.tag===n)??null,p=async(f,b)=>{try{await window.api.agents.savePersona({name:f.name,originalName:f.name,description:f.description??"",tools:f.tools,model:f.model??"inherit",color:f.color??"",tags:[...f.tags,b],body:f.body}),a(!1),await l()}catch(_){Re.error(_.message||"failed to assign tag")}},m=async(f,b)=>{try{await window.api.agents.savePersona({name:f.name,originalName:f.name,description:f.description??"",tools:f.tools,model:f.model??"inherit",color:f.color??"",tags:f.tags.filter(_=>_!==b),body:f.body}),await l()}catch(_){Re.error(_.message||"failed to remove tag")}};return o.jsx(Ti,{toolbar:o.jsxs("span",{className:"text-fg-faint",children:[gu.length," tag",gu.length===1?"":"s"]}),children:o.jsx(ec,{sidebar:o.jsx("div",{className:"py-1",children:gu.map(f=>{const b=yy(f.tag),_=n===f.tag,y=(i==null?void 0:i.filter(k=>k.tags.includes(f.tag)).length)??0;return o.jsxs("button",{onClick:()=>{e(f.tag),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 ${_?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[o.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-semibold ${b.bg} ${b.text} ${b.border?"border border-current/30":""}`,children:["#",f.tag]}),o.jsx("span",{className:"truncate",children:f.label}),y>0&&o.jsx("span",{className:"ml-auto text-[10.5px] text-fg-faint font-mono shrink-0",children:y})]},f.tag)})}),detail:c?o.jsx(_K,{entry:c,personas:i,adding:s,setAdding:a,onAssign:p,onUnassign:m}):o.jsx(Lt,{title:"select a tag"})})})}function _K({entry:n,personas:e,adding:i,setAdding:r,onAssign:s,onUnassign:a}){const d=yy(n.tag),l=l1(n.tag),c=(e==null?void 0:e.filter(m=>m.tags.includes(n.tag)))??[],p=(e==null?void 0:e.filter(m=>!m.tags.includes(n.tag)))??[];return o.jsxs("div",{className:"p-4 space-y-4 max-w-3xl",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsxs("span",{className:`px-2 py-1 rounded text-xs font-mono font-semibold ${d.bg} ${d.text} ${d.border?"border border-current/30":""}`,children:["#",n.tag]}),o.jsx("span",{className:"text-sm font-semibold text-fg",children:n.label})]}),o.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:n.description}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"/develop eagerness"}),o.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:n.developEagerness})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"agents carrying this tag"}),e===null?o.jsx("div",{className:"text-xs text-fg-faint italic",children:"loading…"}):o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c.map(m=>o.jsxs("span",{className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim",children:[m.name,o.jsx("button",{onClick:()=>a(m,n.tag),title:"Remove this tag from the agent",className:"text-fg-faint hover:text-fg",children:"×"})]},m.name)),c.length===0&&!i&&o.jsx("span",{className:"text-xs text-fg-faint italic mr-1",children:"no agent carries this tag yet."}),i?p.length>0?o.jsxs("select",{autoFocus:!0,defaultValue:"",onChange:m=>{const f=e.find(b=>b.name===m.target.value);f&&s(f,n.tag)},onBlur:()=>r(!1),className:"bg-bg border border-line rounded px-2 py-0.5 text-[11px] text-fg font-mono",children:[o.jsx("option",{value:"",disabled:!0,children:"pick an agent…"}),p.map(m=>o.jsx("option",{value:m.name,children:m.name},m.name))]}):o.jsx("span",{className:"text-xs text-fg-faint italic",children:"every agent already carries this tag."}):o.jsx("button",{onClick:()=>r(!0),className:"px-2 py-0.5 rounded-full text-[11px] font-mono border border-line text-fg-faint hover:text-fg hover:bg-bg-hi",children:"+ assign agent"})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"opening framing — sent before the human's goal"}),o.jsx("pre",{className:"text-xs text-fg-dim whitespace-pre-wrap bg-bg-elev border border-line rounded p-3 leading-relaxed font-sans",children:l.initialPromptTemplate})]})]})}function SK({eyebrow:n,title:e,intro:i,frame:r=!0,learnKey:s,children:a}){const d=r&&(n||e||i);return o.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg",children:[d&&o.jsxs("header",{className:"shrink-0 px-8 pt-7 pb-5 flex items-start justify-between gap-4",children:[o.jsxs("div",{className:"max-w-[820px]",children:[n&&o.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.08em] text-fg-faint mb-2",children:n}),e&&o.jsx("h1",{className:"font-serif text-[34px] font-medium leading-[1.1] text-fg m-0",children:e}),i&&o.jsx("p",{className:"mt-3 text-[14px] text-fg-dim leading-[1.55]",children:i})]}),s&&o.jsx(EA,{active:s})]}),o.jsx("div",{className:`flex-1 min-h-0 ${d?"px-8 pb-7":"p-8"}`,children:a})]})}const kK={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."},keybindings:{title:"Keybindings",intro:"Shortcuts you can override. Bindings here apply to Claude Code itself, not the Session Manager chrome."},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:"Every agent persona available on this machine — global definitions in ~/.claude/agents, and which currently-open projects override them locally. Create, edit, duplicate, or delete a persona; each change writes the matching file on disk."},"tag-library":{title:"Tag Library",intro:"Every Epic intent tag, its meaning, and its /develop-eagerness default. Assign or remove which agent personas carry each tag."},remote:{title:"Remote Access",intro:"Web remote control — disabled by default. Pair your browser, then issue scheduler + terminal commands from any device over a secure relay you self-host."},voice:{title:"Voice & microphone",intro:"Whisper transcription, push-to-talk hotkey, device selection, and TTS toggle."},repoviz:{title:"Repo visualization",intro:"Language + directory map of the current project, computed locally."},search:{title:"Search",intro:"Find by filename (⌘P) or by content (⌘⇧F) across the active cwd. The chosen path is inserted into the active terminal."}},a_=()=>{};function CK(n,e){switch(n){case"overview":return o.jsx(n3,{onNavigate:e.onNavigate,onNewSession:e.onNewSession,onOpenVoice:e.onOpenVoice,onOpenScheduler:e.onOpenScheduler});case"project-home":return o.jsx(U3,{});case"editor":return o.jsx(Yb,{});case"projects":return o.jsx(M7,{});case"browser":return o.jsx(SA,{})}const i=kK[n],r=(()=>{switch(n){case"skills":return o.jsx(zL,{});case"history":return o.jsx(k5,{});case"scheduler":return o.jsx(uK,{navigate:e.onNavigate});case"plugins":return o.jsx(O9,{});case"mcp":return o.jsx(Z9,{});case"hooks":return o.jsx(a7,{});case"keybindings":return o.jsx(b6,{});case"memory":return o.jsx(R6,{});case"system-prompt":return o.jsx(l6,{});case"permissions":return o.jsx(t6,{});case"settings":return o.jsx(JB,{});case"remote":return o.jsx(fK,{});case"agent-library":return o.jsx(xK,{});case"tag-library":return o.jsx(wK,{});case"voice":return o.jsx(tB,{open:!0,onClose:a_,variant:"page"});case"repoviz":return o.jsx(L4,{open:!0,onClose:a_,variant:"page"});case"search":return o.jsx(W4,{open:!0,onClose:a_,variant:"page",initialMode:e.searchMode??"files"});default:return null}})();if(!r)return null;const s=aP[n];return i&&s?o.jsx(SK,{eyebrow:s,title:i.title,intro:i.intro,learnKey:n,children:r}):r}var l_={exports:{}},KE;function EK(){return KE||(KE=1,(function(n,e){(function(i,r){n.exports=r()})(globalThis,(()=>(()=>{var i={4567:function(d,l,c){var p=this&&this.__decorate||function(S,E,j,N){var A,P=arguments.length,I=P<3?E:N===null?N=Object.getOwnPropertyDescriptor(E,j):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(S,E,j,N);else for(var O=S.length-1;O>=0;O--)(A=S[O])&&(I=(P<3?A(I):P>3?A(E,j,I):A(E,j))||I);return P>3&&I&&Object.defineProperty(E,j,I),I},m=this&&this.__param||function(S,E){return function(j,N){E(j,N,S)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const f=c(9042),b=c(9924),_=c(844),y=c(4725),k=c(2585),x=c(3656);let w=l.AccessibilityManager=class extends _.Disposable{constructor(S,E,j,N){super(),this._terminal=S,this._coreBrowserService=j,this._renderService=N,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let A=0;A<this._terminal.rows;A++)this._rowElements[A]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[A]);if(this._topBoundaryFocusListener=A=>this._handleBoundaryFocus(A,0),this._bottomBoundaryFocusListener=A=>this._handleBoundaryFocus(A,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new b.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((A=>this._handleResize(A.rows)))),this.register(this._terminal.onRender((A=>this._refreshRows(A.start,A.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((A=>this._handleChar(A)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3182
3182
|
`)))),this.register(this._terminal.onA11yTab((A=>this._handleTab(A)))),this.register(this._terminal.onKey((A=>this._handleKey(A.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,x.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,_.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(S){for(let E=0;E<S;E++)this._handleChar(" ")}_handleChar(S){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==S&&(this._charsToAnnounce+=S):this._charsToAnnounce+=S,S===`
|
|
3183
3183
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=f.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(S){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(S)||this._charsToConsume.push(S)}_refreshRows(S,E){this._liveRegionDebouncer.refresh(S,E,this._terminal.rows)}_renderRows(S,E){const j=this._terminal.buffer,N=j.lines.length.toString();for(let A=S;A<=E;A++){const P=j.lines.get(j.ydisp+A),I=[],O=(P==null?void 0:P.translateToString(!0,void 0,void 0,I))||"",U=(j.ydisp+A+1).toString(),B=this._rowElements[A];B&&(O.length===0?(B.innerText=" ",this._rowColumns.set(B,[0,1])):(B.textContent=O,this._rowColumns.set(B,I)),B.setAttribute("aria-posinset",U),B.setAttribute("aria-setsize",N))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(S,E){const j=S.target,N=this._rowElements[E===0?1:this._rowElements.length-2];if(j.getAttribute("aria-posinset")===(E===0?"1":`${this._terminal.buffer.lines.length}`)||S.relatedTarget!==N)return;let A,P;if(E===0?(A=j,P=this._rowElements.pop(),this._rowContainer.removeChild(P)):(A=this._rowElements.shift(),P=j,this._rowContainer.removeChild(A)),A.removeEventListener("focus",this._topBoundaryFocusListener),P.removeEventListener("focus",this._bottomBoundaryFocusListener),E===0){const I=this._createAccessibilityTreeNode();this._rowElements.unshift(I),this._rowContainer.insertAdjacentElement("afterbegin",I)}else{const I=this._createAccessibilityTreeNode();this._rowElements.push(I),this._rowContainer.appendChild(I)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(E===0?-1:1),this._rowElements[E===0?1:this._rowElements.length-2].focus(),S.preventDefault(),S.stopImmediatePropagation()}_handleSelectionChange(){var O;if(this._rowElements.length===0)return;const S=document.getSelection();if(!S)return;if(S.isCollapsed)return void(this._rowContainer.contains(S.anchorNode)&&this._terminal.clearSelection());if(!S.anchorNode||!S.focusNode)return void console.error("anchorNode and/or focusNode are null");let E={node:S.anchorNode,offset:S.anchorOffset},j={node:S.focusNode,offset:S.focusOffset};if((E.node.compareDocumentPosition(j.node)&Node.DOCUMENT_POSITION_PRECEDING||E.node===j.node&&E.offset>j.offset)&&([E,j]=[j,E]),E.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(E={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(E.node))return;const N=this._rowElements.slice(-1)[0];if(j.node.compareDocumentPosition(N)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(j={node:N,offset:((O=N.textContent)==null?void 0:O.length)??0}),!this._rowContainer.contains(j.node))return;const A=({node:U,offset:B})=>{const J=U instanceof Text?U.parentNode:U;let Z=parseInt(J==null?void 0:J.getAttribute("aria-posinset"),10)-1;if(isNaN(Z))return console.warn("row is invalid. Race condition?"),null;const W=this._rowColumns.get(J);if(!W)return console.warn("columns is null. Race condition?"),null;let q=B<W.length?W[B]:W.slice(-1)[0]+1;return q>=this._terminal.cols&&(++Z,q=0),{row:Z,column:q}},P=A(E),I=A(j);if(P&&I){if(P.row>I.row||P.row===I.row&&P.column>=I.column)throw new Error("invalid range");this._terminal.select(P.column,P.row,(I.row-P.row)*this._terminal.cols-P.column+I.column)}}_handleResize(S){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let E=this._rowContainer.children.length;E<this._terminal.rows;E++)this._rowElements[E]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[E]);for(;this._rowElements.length>S;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const S=this._coreBrowserService.mainDocument.createElement("div");return S.setAttribute("role","listitem"),S.tabIndex=-1,this._refreshRowDimensions(S),S}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let S=0;S<this._terminal.rows;S++)this._refreshRowDimensions(this._rowElements[S])}}_refreshRowDimensions(S){S.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=w=p([m(1,k.IInstantiationService),m(2,y.ICoreBrowserService),m(3,y.IRenderService)],w)},3614:(d,l)=>{function c(b){return b.replace(/\r?\n/g,"\r")}function p(b,_){return _?"\x1B[200~"+b+"\x1B[201~":b}function m(b,_,y,k){b=p(b=c(b),y.decPrivateModes.bracketedPasteMode&&k.rawOptions.ignoreBracketedPasteMode!==!0),y.triggerDataEvent(b,!0),_.value=""}function f(b,_,y){const k=y.getBoundingClientRect(),x=b.clientX-k.left-10,w=b.clientY-k.top-10;_.style.width="20px",_.style.height="20px",_.style.left=`${x}px`,_.style.top=`${w}px`,_.style.zIndex="1000",_.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=c,l.bracketTextForPaste=p,l.copyHandler=function(b,_){b.clipboardData&&b.clipboardData.setData("text/plain",_.selectionText),b.preventDefault()},l.handlePasteEvent=function(b,_,y,k){b.stopPropagation(),b.clipboardData&&m(b.clipboardData.getData("text/plain"),_,y,k)},l.paste=m,l.moveTextAreaUnderMouseCursor=f,l.rightClickHandler=function(b,_,y,k,x){f(b,_,y),x&&k.rightClickSelect(b),_.value=k.selectionText,_.select()}},7239:(d,l,c)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const p=c(1505);l.ColorContrastCache=class{constructor(){this._color=new p.TwoKeyMap,this._css=new p.TwoKeyMap}setCss(m,f,b){this._css.set(m,f,b)}getCss(m,f){return this._css.get(m,f)}setColor(m,f,b){this._color.set(m,f,b)}getColor(m,f){return this._color.get(m,f)}clear(){this._color.clear(),this._css.clear()}}},3656:(d,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(c,p,m,f){c.addEventListener(p,m,f);let b=!1;return{dispose:()=>{b||(b=!0,c.removeEventListener(p,m,f))}}}},3551:function(d,l,c){var p=this&&this.__decorate||function(w,S,E,j){var N,A=arguments.length,P=A<3?S:j===null?j=Object.getOwnPropertyDescriptor(S,E):j;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(w,S,E,j);else for(var I=w.length-1;I>=0;I--)(N=w[I])&&(P=(A<3?N(P):A>3?N(S,E,P):N(S,E))||P);return A>3&&P&&Object.defineProperty(S,E,P),P},m=this&&this.__param||function(w,S){return function(E,j){S(E,j,w)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const f=c(3656),b=c(8460),_=c(844),y=c(2585),k=c(4725);let x=l.Linkifier=class extends _.Disposable{get currentLink(){return this._currentLink}constructor(w,S,E,j,N){super(),this._element=w,this._mouseService=S,this._renderService=E,this._bufferService=j,this._linkProviderService=N,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new b.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new b.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,_.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,_.toDisposable)((()=>{var A;this._lastMouseEvent=void 0,(A=this._activeProviderReplies)==null||A.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,f.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,f.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,f.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(w){this._lastMouseEvent=w;const S=this._positionFromMouseEvent(w,this._element,this._mouseService);if(!S)return;this._isMouseOut=!1;const E=w.composedPath();for(let j=0;j<E.length;j++){const N=E[j];if(N.classList.contains("xterm"))break;if(N.classList.contains("xterm-hover"))return}this._lastBufferCell&&S.x===this._lastBufferCell.x&&S.y===this._lastBufferCell.y||(this._handleHover(S),this._lastBufferCell=S)}_handleHover(w){if(this._activeLine!==w.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(w,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,w)||(this._clearCurrentLink(),this._askForLink(w,!0))}_askForLink(w,S){var j,N;this._activeProviderReplies&&S||((j=this._activeProviderReplies)==null||j.forEach((A=>{A==null||A.forEach((P=>{P.link.dispose&&P.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=w.y);let E=!1;for(const[A,P]of this._linkProviderService.linkProviders.entries())S?(N=this._activeProviderReplies)!=null&&N.get(A)&&(E=this._checkLinkProviderResult(A,w,E)):P.provideLinks(w.y,(I=>{var U,B;if(this._isMouseOut)return;const O=I==null?void 0:I.map((J=>({link:J})));(U=this._activeProviderReplies)==null||U.set(A,O),E=this._checkLinkProviderResult(A,w,E),((B=this._activeProviderReplies)==null?void 0:B.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(w.y,this._activeProviderReplies)}))}_removeIntersectingLinks(w,S){const E=new Set;for(let j=0;j<S.size;j++){const N=S.get(j);if(N)for(let A=0;A<N.length;A++){const P=N[A],I=P.link.range.start.y<w?0:P.link.range.start.x,O=P.link.range.end.y>w?this._bufferService.cols:P.link.range.end.x;for(let U=I;U<=O;U++){if(E.has(U)){N.splice(A--,1);break}E.add(U)}}}}_checkLinkProviderResult(w,S,E){var A;if(!this._activeProviderReplies)return E;const j=this._activeProviderReplies.get(w);let N=!1;for(let P=0;P<w;P++)this._activeProviderReplies.has(P)&&!this._activeProviderReplies.get(P)||(N=!0);if(!N&&j){const P=j.find((I=>this._linkAtPosition(I.link,S)));P&&(E=!0,this._handleNewLink(P))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!E)for(let P=0;P<this._activeProviderReplies.size;P++){const I=(A=this._activeProviderReplies.get(P))==null?void 0:A.find((O=>this._linkAtPosition(O.link,S)));if(I){E=!0,this._handleNewLink(I);break}}return E}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(w){if(!this._currentLink)return;const S=this._positionFromMouseEvent(w,this._element,this._mouseService);S&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,S)&&this._currentLink.link.activate(w,this._currentLink.link.text)}_clearCurrentLink(w,S){this._currentLink&&this._lastMouseEvent&&(!w||!S||this._currentLink.link.range.start.y>=w&&this._currentLink.link.range.end.y<=S)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,_.disposeArray)(this._linkCacheDisposables))}_handleNewLink(w){if(!this._lastMouseEvent)return;const S=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);S&&this._linkAtPosition(w.link,S)&&(this._currentLink=w,this._currentLink.state={decorations:{underline:w.link.decorations===void 0||w.link.decorations.underline,pointerCursor:w.link.decorations===void 0||w.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,w.link,this._lastMouseEvent),w.link.decorations={},Object.defineProperties(w.link.decorations,{pointerCursor:{get:()=>{var E,j;return(j=(E=this._currentLink)==null?void 0:E.state)==null?void 0:j.decorations.pointerCursor},set:E=>{var j;(j=this._currentLink)!=null&&j.state&&this._currentLink.state.decorations.pointerCursor!==E&&(this._currentLink.state.decorations.pointerCursor=E,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",E))}},underline:{get:()=>{var E,j;return(j=(E=this._currentLink)==null?void 0:E.state)==null?void 0:j.decorations.underline},set:E=>{var j,N,A;(j=this._currentLink)!=null&&j.state&&((A=(N=this._currentLink)==null?void 0:N.state)==null?void 0:A.decorations.underline)!==E&&(this._currentLink.state.decorations.underline=E,this._currentLink.state.isHovered&&this._fireUnderlineEvent(w.link,E))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((E=>{if(!this._currentLink)return;const j=E.start===0?0:E.start+1+this._bufferService.buffer.ydisp,N=this._bufferService.buffer.ydisp+1+E.end;if(this._currentLink.link.range.start.y>=j&&this._currentLink.link.range.end.y<=N&&(this._clearCurrentLink(j,N),this._lastMouseEvent)){const A=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);A&&this._askForLink(A,!1)}}))))}_linkHover(w,S,E){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!0),this._currentLink.state.decorations.pointerCursor&&w.classList.add("xterm-cursor-pointer")),S.hover&&S.hover(E,S.text)}_fireUnderlineEvent(w,S){const E=w.range,j=this._bufferService.buffer.ydisp,N=this._createLinkUnderlineEvent(E.start.x-1,E.start.y-j-1,E.end.x,E.end.y-j-1,void 0);(S?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(N)}_linkLeave(w,S,E){var j;(j=this._currentLink)!=null&&j.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(S,!1),this._currentLink.state.decorations.pointerCursor&&w.classList.remove("xterm-cursor-pointer")),S.leave&&S.leave(E,S.text)}_linkAtPosition(w,S){const E=w.range.start.y*this._bufferService.cols+w.range.start.x,j=w.range.end.y*this._bufferService.cols+w.range.end.x,N=S.y*this._bufferService.cols+S.x;return E<=N&&N<=j}_positionFromMouseEvent(w,S,E){const j=E.getCoords(w,S,this._bufferService.cols,this._bufferService.rows);if(j)return{x:j[0],y:j[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(w,S,E,j,N){return{x1:w,y1:S,x2:E,y2:j,cols:this._bufferService.cols,fg:N}}};l.Linkifier=x=p([m(1,k.IMouseService),m(2,k.IRenderService),m(3,y.IBufferService),m(4,k.ILinkProviderService)],x)},9042:(d,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(d,l,c){var p=this&&this.__decorate||function(k,x,w,S){var E,j=arguments.length,N=j<3?x:S===null?S=Object.getOwnPropertyDescriptor(x,w):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(k,x,w,S);else for(var A=k.length-1;A>=0;A--)(E=k[A])&&(N=(j<3?E(N):j>3?E(x,w,N):E(x,w))||N);return j>3&&N&&Object.defineProperty(x,w,N),N},m=this&&this.__param||function(k,x){return function(w,S){x(w,S,k)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const f=c(511),b=c(2585);let _=l.OscLinkProvider=class{constructor(k,x,w){this._bufferService=k,this._optionsService=x,this._oscLinkService=w}provideLinks(k,x){var O;const w=this._bufferService.buffer.lines.get(k-1);if(!w)return void x(void 0);const S=[],E=this._optionsService.rawOptions.linkHandler,j=new f.CellData,N=w.getTrimmedLength();let A=-1,P=-1,I=!1;for(let U=0;U<N;U++)if(P!==-1||w.hasContent(U)){if(w.loadCell(U,j),j.hasExtendedAttrs()&&j.extended.urlId){if(P===-1){P=U,A=j.extended.urlId;continue}I=j.extended.urlId!==A}else P!==-1&&(I=!0);if(I||P!==-1&&U===N-1){const B=(O=this._oscLinkService.getLinkData(A))==null?void 0:O.uri;if(B){const J={start:{x:P+1,y:k},end:{x:U+(I||U!==N-1?0:1),y:k}};let Z=!1;if(!(E!=null&&E.allowNonHttpProtocols))try{const W=new URL(B);["http:","https:"].includes(W.protocol)||(Z=!0)}catch{Z=!0}Z||S.push({text:B,range:J,activate:(W,q)=>E?E.activate(W,q,J):y(0,q),hover:(W,q)=>{var Q;return(Q=E==null?void 0:E.hover)==null?void 0:Q.call(E,W,q,J)},leave:(W,q)=>{var Q;return(Q=E==null?void 0:E.leave)==null?void 0:Q.call(E,W,q,J)}})}I=!1,j.hasExtendedAttrs()&&j.extended.urlId?(P=U,A=j.extended.urlId):(P=-1,A=-1)}}x(S)}};function y(k,x){if(confirm(`Do you want to navigate to ${x}?
|
|
3184
3184
|
|
|
@@ -3205,7 +3205,7 @@ Check git vs the published package for this project, decide the right version bu
|
|
|
3205
3205
|
|
|
3206
3206
|
${W.join(`
|
|
3207
3207
|
`)}`:B;y({tabId:n.id,sessionId:n.claudeSessionId,cwd:n.cwd,prompt:q}),s==null||s(),i==null||i()}finally{m(!1)}},I=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),P())},O=B=>{B.preventDefault(),b(!1),B.dataTransfer.files.length&&_.add(B.dataTransfer.files)},U=R.useRef(null);return o.jsxs("div",{"data-testid":"epic-composer",onDragOver:B=>{B.preventDefault(),b(!0)},onDragLeave:()=>b(!1),onDrop:O,className:`border-t px-[22px] pb-3 pt-2 ${f?"border-accent bg-accent/5":"border-rule bg-bg"}`,children:[o.jsx(qA,{att:_,testId:"epic-composer-attach-tray",hideZoneWhenEmpty:!0}),r&&o.jsxs("div",{className:"mt-2 flex items-start gap-2 rounded-md border-l-2 border-accent bg-bg-hi py-1.5 pl-2.5 pr-2","data-testid":"epic-composer-quote-strip",children:[o.jsx("p",{className:"min-w-0 flex-1 line-clamp-2 text-[12.5px] leading-relaxed text-fg-dim",children:r}),o.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(),"data-testid":"epic-composer-quote-clear","aria-label":"Clear quoted text",className:"shrink-0 text-fg-faint hover:text-fg",children:"✕"})]}),o.jsxs("div",{className:"mt-2 flex items-end gap-2",children:[o.jsxs("div",{className:"flex h-[58px] shrink-0 items-center overflow-hidden rounded-[10px] border border-line bg-bg-hi","data-testid":"epic-composer-input-tools",children:[o.jsx("button",{type:"button","data-testid":"epic-composer-mic",onClick:j,disabled:E.reason==="unsupported","aria-pressed":x,"aria-label":N,title:N,className:`grid h-full w-11 place-items-center ${x?"text-red-400":S?"text-fg-faint":"text-accent hover:text-accent/80"}`,children:o.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),o.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),o.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),o.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})}),o.jsx("span",{className:"h-full w-px bg-line","aria-hidden":"true"}),o.jsx("button",{type:"button","data-testid":"epic-composer-attach",onClick:()=>{var B;return(B=U.current)==null?void 0:B.click()},"aria-label":"Attach files or paste a screenshot",title:"Attach files or paste a screenshot",className:"grid h-full w-11 place-items-center text-fg-dim hover:text-fg",children:o.jsx(an,{name:"folder",size:17})}),o.jsx("input",{ref:U,"data-testid":"epic-composer-attach-input",type:"file",multiple:!0,className:"hidden",onChange:B=>{B.target.files&&_.add(B.target.files),B.target.value=""}})]}),o.jsx("textarea",{ref:k,"data-testid":"epic-composer-textarea",value:l,onChange:B=>c(B.target.value),onKeyDown:I,onPaste:B=>my(B,_),rows:2,placeholder:d?"Queue a follow-up…":`Add to "${n.goalText}" — Enter to send, ⌘V to attach a screenshot`,className:"min-h-[58px] max-h-[180px] flex-1 resize-none overflow-y-auto rounded-[10px] border border-line bg-bg-hi px-3 py-2.5 text-[13px] leading-relaxed text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none"}),d&&o.jsx("button",{type:"button","data-testid":"epic-composer-cancel",onClick:()=>window.api.chat.cancel(n.id),className:"h-[58px] shrink-0 px-1 text-[12.5px] font-semibold text-delta-bad hover:text-delta-bad/80",children:"Cancel"}),o.jsxs("button",{type:"button","data-testid":"epic-composer-send",onClick:()=>void P(),disabled:!A||p,className:`inline-flex h-[58px] shrink-0 items-center gap-1.5 rounded-[10px] px-5 text-[13px] font-semibold ${A&&!p?"bg-accent text-white hover:bg-accent/90":"bg-bg-hi text-fg-faint"}`,children:[o.jsx(an,{name:"send",size:13}),d?"Queue":"Send"]})]})]})}function dX({epic:n}){const[e,i]=R.useState(!1),r=()=>{if(!e){i(!0);try{const a=rn.getState().approveProposed(n.id,"EpicApprovalBar");if(!a){Re.error("This Epic is no longer awaiting approval.");return}An.getState().send({tabId:a.id,sessionId:a.claudeSessionId,cwd:a.cwd,prompt:a.openingPrompt||a.goalText})}finally{i(!1)}}},s=()=>{e||(i(!0),rn.getState().markCompleted(n.id,"EpicApprovalBar discard").catch(a=>Re.error(`Could not discard: ${a instanceof Error?a.message:String(a)}`)).finally(()=>i(!1)))};return o.jsxs("div",{"data-testid":"epic-approval-bar",className:"border-t border-butter/40 bg-butter/10 px-[22px] py-3",children:[o.jsxs("div",{className:"mb-1.5 flex items-center gap-2",children:[o.jsx("span",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-wide text-fg-dim",children:"proposed — not started"}),o.jsx(p1,{kind:n.tag,small:!0})]}),o.jsx("p",{className:"mb-2.5 max-w-[760px] text-[12.5px] leading-relaxed text-fg-dim",children:"Filed for you to decide on. Nothing has run and nothing has been spent. Approving sends the objective above as this Epic's first prompt."}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("button",{type:"button","data-testid":"epic-approve",onClick:r,disabled:e,className:"rounded-md bg-accent px-4 py-2 text-[12.5px] font-semibold text-bg-hi hover:bg-accent-dark disabled:opacity-50",children:"Approve & start"}),o.jsx("button",{type:"button","data-testid":"epic-discard",onClick:s,disabled:e,className:"rounded-md border border-line bg-bg-hi px-3.5 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev disabled:opacity-50",children:"Discard"})]})]})}function gy(n){return Math.round(n.length/4/1e3*10)/10}async function f_(n,e,i){const r=await window.api.config.readText(n);if(!r.exists)return{name:e,detail:"not present",tokK:0,present:!1};const s=r.text?r.text.split(`
|
|
3208
|
-
`).length:0;return{name:e,detail:i(s),tokK:gy(r.text),present:!0}}async function cT(n,e,i){const r=await window.api.config.listDir(n,{dirsOnly:!0}),s=r.ok?r.entries.length:0;return!r.ok||s===0?{name:e,detail:`no ${i} installed`,tokK:0,present:!1}:{name:e,detail:`${s} installed`,tokK:gy(r.entries.map(a=>a.name).join(" "))+.1*s,present:!0}}function uX(n){try{const i=JSON.parse(n).hooks??{};return Object.values(i).reduce((r,s)=>r+(Array.isArray(s)?s.length:0),0)}catch{return 0}}async function hX(n){var Z;const{home:e,cwd:i,agentPersonaPath:r,agentPersonaName:s,openTerminalTabsInProject:a,otherEpicsInProject:d}=n,l=ku.resolve("user",e,null),c=Du.resolve("user",e,null),p=ku.resolve("project",e,i),m=ku.resolve("local",e,i),f=Du.resolve("project",e,i),[b,_,y,k,x,w,S,E,j,N,A]=await Promise.all([f_(l,"CLAUDE.md",W=>`global preferences · ${W} lines`),window.api.config.readText(c),cT(`${e}/.claude/skills`,"skills/","skills"),r?window.api.config.readText(r):Promise.resolve(null),f_(p,"CLAUDE.md",W=>`${W} lines`),cT(`${i}/.claude/skills`,".claude/skills/","skills"),window.api.config.readJson(`${e}/.claude.json`),window.api.config.readText(f),window.api.config.exists(`${i}/session-manager-operations/project-brief/brief.json`),f_(m,"CLAUDE.local.md",W=>`personal notes · ${W} lines`),window.api.app.gitBranch(i)]),P=((Z=S.data)==null?void 0:Z.mcpServers)??{},I=Object.keys(P).length,O=uX(E.text),U={key:"system",label:"System",path:"~/.claude/",items:[b,{name:"settings.json",detail:_.exists?"model, permissions, output style":"not present",tokK:_.exists?gy(_.text):0,present:_.exists},y,k?{name:`agents/${s}.md`,detail:"system prompt for the selected role · required",tokK:gy(k.text),present:k.exists,locked:!0}:{name:"agents/*.md",detail:"no agent selected — default persona",tokK:0,present:!1}]},B={key:"project",label:"Project",path:`${i}/`,items:[x,w,I>0?{name:`mcp servers · ${I}`,detail:Object.keys(P).slice(0,3).join(", "),tokK:.2*I,present:!0}:{name:"mcp servers",detail:"none configured",tokK:0,present:!1},O>0?{name:`hooks · ${O}`,detail:"from .claude/settings.json",tokK:.1*O,present:!0}:{name:"hooks",detail:"none configured",tokK:0,present:!1},{name:"Project brief",detail:j?"LLM-maintained scope + conventions":"not generated yet",tokK:j?2:0,present:j}]},J={key:"local",label:"Local",path:`${i}/ · this machine only`,items:[N,{name:"working tree",detail:A?`⎇ ${A}`:"not a git repo",tokK:0,present:!!A},a>0?{name:`open Terminal tabs · ${a}`,detail:"other tabs on this project",tokK:0,present:!0}:{name:"open Terminal tabs",detail:"none open right now",tokK:0,present:!1},d>0?{name:`other Epics · ${d}`,detail:"proposed/active in this project",tokK:0,present:!0}:{name:"other Epics",detail:"none yet in this project",tokK:0,present:!1}]};return[U,B,J]}const pX=[{tag:"feature",label:"Feature"},{tag:"bug",label:"Bug"},{tag:"discussion",label:"Discussion"}],dT=["#b85c34","#a3441f","#6f7d52","#8a7a60","#7a6a8a","#5f7a7d","#c96442","#4f7d72"];function uT(n){let e=0;for(let i=0;i<n.length;i+=1)e=e*31+n.charCodeAt(i)>>>0;return dT[e%dT.length]}function fX({onCreated:n,onCancel:e}){const i=rn(me=>me.createPromptSession),r=rn(me=>me.approveProposed),s=rn(me=>me.sessions),{rows:a,enriched:d}=ov(),l=vt(me=>me.tabs),c=vt(me=>{var re;return((re=me.tabs.find(te=>te.id===me.activeTabId))==null?void 0:re.cwd)??null}),p=R.useMemo(()=>{var te;const me=new Set,re=[];for(const we of a){const be=((te=d[we.encoded])==null?void 0:te.cwd)??Yp(we.encoded);!be||me.has(be)||(me.add(be),re.push(be))}return re},[a,d]),[m,f]=R.useState(""),[b,_]=R.useState(""),[y,k]=R.useState(""),[x,w]=R.useState("feature"),[S,E]=R.useState(""),[j,N]=R.useState(null),A=WA(),[P,I]=R.useState(!1),[O,U]=R.useState(!1),[B,J]=R.useState(null),[Z,W]=R.useState(null);R.useEffect(()=>{let me=!1;return(async()=>{try{const re=await window.api.agents.listPersonas();me||N(re)}catch(re){me||(N([]),Re.error(re.message||"failed to load Agent Library"))}})(),()=>{me=!0}},[]),R.useEffect(()=>{let me=!1;return(async()=>{try{const re=await window.api.app.homeDir();me||J(re)}catch{}})(),()=>{me=!0}},[]);const q=(j==null?void 0:j.find(me=>me.name===S))??null,Q=m||(c&&p.includes(c)?c:"")||p[0]||"",oe=y.trim(),le=!!(Q&&oe),H=!(c&&p.includes(c));R.useEffect(()=>{if(!O||!B||!Q)return;let me=!1;return hX({home:B,cwd:Q,agentPersonaPath:(q==null?void 0:q.path)??null,agentPersonaName:(q==null?void 0:q.name)??null,openTerminalTabsInProject:l.filter(re=>re.cwd===Q).length,otherEpicsInProject:Object.values(s).filter(re=>re.cwd===Q).length}).then(re=>{me||W(re)}).catch(re=>{me||Re.error(re.message||"failed to read grounding sources")}),()=>{me=!0}},[O,B,Q,q,l,s]);const ee=()=>{f(""),_(""),k(""),w("feature"),E(""),U(!1),W(null),A.clear()},Y=async()=>{if(!(!le||P)){I(!0);try{const me=await VA(A.items,Q),{goalText:re,openingPrompt:te}=f1({title:b,goal:y,referencePaths:me,tag:x,agentName:q==null?void 0:q.name,agentDescription:(q==null?void 0:q.description)??void 0}),we=q?i(Q,re,x,"NewEpicCard",q.name):i(Q,re,x,"NewEpicCard");r(we.id,"NewEpicCard"),An.getState().send({tabId:we.id,sessionId:we.claudeSessionId,cwd:Q,prompt:te}),ee(),n(we.id)}finally{I(!1)}}},ce=()=>{ee(),e()},ae=l1(x).description,xe=Z?Z.reduce((me,re)=>me+re.items.filter(te=>te.present).length,0):0,Ne=Z?Z.reduce((me,re)=>me+re.items.reduce((te,we)=>te+we.tokK,0),0):0;return o.jsx("section",{className:"flex-1 min-w-0 grid place-items-center overflow-y-auto bg-bg p-6","data-testid":"new-epic-card",children:o.jsx("div",{className:"w-full transition-[max-width] duration-500",style:{maxWidth:O?"min(1320px, 94vw)":"min(920px, 92vw)",perspective:2400},children:o.jsxs("div",{className:"relative w-full transition-transform duration-500",style:{height:"min(760px, 84vh)",transformStyle:"preserve-3d",transform:O?"rotateY(180deg)":"none"},children:[o.jsxs("div",{className:"absolute inset-0 flex flex-col rounded-2xl border border-line bg-bg-hi px-[26px] pt-6 pb-[18px]",style:{backfaceVisibility:"hidden"},children:[o.jsx(hT,{eyebrow:"New Epic",advanced:O,setAdvanced:U}),o.jsx("h2",{className:"m-0 font-serif text-2xl font-semibold tracking-[-0.3px] text-fg",children:"What are we trying to achieve?"}),o.jsx("p",{className:"my-2 mb-[18px] text-[13.5px] leading-[1.55] text-fg-dim",children:"One goal per Epic — fixed for the life of its session. The title and objective are sent as the first message the moment you start it, so the agent is already working when it opens."}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:[H?o.jsxs("label",{className:"mb-2.5 flex flex-col gap-1",children:[o.jsx("span",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",children:"Project"}),o.jsxs("select",{"data-testid":"new-prompt-cwd",value:Q,onChange:me=>f(me.target.value),className:"rounded-md border border-line bg-bg px-2 py-1.5 font-mono text-[12.5px] text-fg",children:[p.length===0&&o.jsx("option",{value:"",children:"No known projects"}),p.map(me=>o.jsx("option",{value:me,children:zg(me)},me))]})]}):o.jsxs("div",{"data-testid":"new-prompt-cwd-static",className:"mb-2.5 flex items-center gap-1.5 font-mono text-[11px] text-fg-faint",children:[o.jsx("span",{className:"uppercase tracking-[0.09em]",children:"Project"}),o.jsx("span",{className:"text-fg-dim",children:zg(Q)})]}),o.jsxs("div",{className:"mb-3.5 grid grid-cols-2 gap-3.5",children:[o.jsxs("div",{children:[o.jsx("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",title:"Who runs this Epic — from the Agent Library (~/.claude/agents).",children:"1 · agent — who is working"}),o.jsxs("div",{className:"grid gap-1",children:[o.jsxs("button",{type:"button","data-testid":"new-epic-agent-default",onClick:()=>E(""),className:`flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-left ${S===""?"border-accent bg-bg-elev":"border-line bg-bg"}`,children:[o.jsx("span",{className:"h-1.5 w-1.5 rotate-45 rounded-sm bg-fg-faint"}),o.jsx("span",{className:"font-mono text-xs font-medium text-fg",children:"Default"})]}),(j??[]).map(me=>{const re=S===me.name;return o.jsxs("button",{type:"button","data-testid":`new-epic-agent-${me.name}`,onClick:()=>E(me.name),className:`flex items-center gap-2 rounded-lg border px-2.5 py-1.5 text-left ${re?"border-accent bg-bg-elev":"border-line bg-bg"}`,children:[o.jsx("span",{className:"h-1.5 w-1.5 rotate-45 rounded-sm",style:{background:uT(me.name)}}),o.jsx("span",{className:`font-mono text-xs ${re?"font-semibold":"font-medium"} text-fg`,children:me.name}),me.description&&o.jsx("span",{className:"ml-auto truncate whitespace-nowrap text-[11px] text-fg-faint",children:me.description})]},me.name)})]})]}),o.jsxs("div",{children:[o.jsx("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",title:"The Epic's mission — from the Tag Library. Sets how eagerly /develop fires.",children:"2 · mission — how they work"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:pX.map(me=>{const re=x===me.tag;return o.jsx("button",{type:"button","data-testid":`new-epic-kind-${me.tag}`,onClick:()=>w(me.tag),className:`rounded-md px-2.5 py-1 text-xs font-medium ${re?"bg-bg text-fg ring-1 ring-inset ring-line font-semibold":"text-fg-faint"}`,children:me.label},me.tag)})}),o.jsxs("div",{className:"mt-2 border-l-2 border-accent-muted pl-2.5 text-[12.5px] leading-[1.5] text-fg-dim",children:[ae,o.jsxs("div",{className:"mt-1 font-mono text-[11px] text-fg-faint",children:["sonnet",q?` · ${q.tools.join(" ")||"no tool restriction"}`:""]})]})]})]}),o.jsx("input",{"data-testid":"new-epic-title",type:"text",value:b,onChange:me=>_(me.target.value),onPaste:me=>my(me,A),placeholder:"Epic title",className:"mb-2 w-full appearance-none rounded-[10px] border border-line bg-bg px-[13px] py-[11px] text-sm font-semibold text-fg outline-none"}),o.jsx("textarea",{"data-testid":"new-epic-goal",rows:3,value:y,onChange:me=>k(me.target.value),onPaste:me=>my(me,A),placeholder:"The objective, in a sentence or two — this is sent as the first instruction.",className:"mb-3 w-full resize-y appearance-none rounded-[10px] border border-line bg-bg px-[13px] py-[11px] text-[13px] leading-[1.55] text-fg outline-none"}),o.jsxs("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",children:["references",A.items.length?` · ${A.items.length}`:""]}),o.jsx(qA,{att:A,tall:!0,testId:"new-epic-attach-tray"})]}),o.jsxs("div",{className:"mt-3 flex flex-shrink-0 items-center gap-2.5 border-t border-rule pt-3",children:[o.jsxs("button",{type:"button","data-testid":"new-epic-flip-to-grounding",onClick:()=>U(!0),title:"See what this Epic's session will actually load",className:"rounded-md border border-accent-muted bg-bg px-2.5 py-1.5 text-xs font-semibold text-accent hover:bg-bg-elev",children:["⤺ Grounding",Z?` · ${xe} sources`:""]}),o.jsxs("span",{className:"ml-auto flex gap-1.5",children:[o.jsx("button",{type:"button","data-testid":"new-epic-cancel",onClick:ce,className:"rounded-md border border-line bg-bg px-3.5 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:"Cancel"}),o.jsx("button",{type:"button","data-testid":"new-epic-create",onClick:()=>void Y(),disabled:!le||P,className:"rounded-md bg-accent px-4 py-2 text-[12.5px] font-semibold text-bg-hi disabled:cursor-not-allowed disabled:opacity-40",children:P?"Starting…":"Start Epic"})]})]})]}),o.jsxs("div",{className:"absolute inset-0 flex flex-col rounded-2xl border border-line bg-bg-hi px-[26px] pt-6 pb-[18px]",style:{backfaceVisibility:"hidden",transform:"rotateY(180deg)"},children:[o.jsx(hT,{eyebrow:"New Epic · grounding",advanced:O,setAdvanced:U}),o.jsx("h2",{className:"m-0 font-serif text-2xl font-semibold tracking-[-0.3px] text-fg",children:"What this Epic will know"}),o.jsx("p",{className:"my-2 mb-[18px] text-[13.5px] leading-[1.55] text-fg-dim",children:"Every layer of context this Epic's session actually loads before your goal is sent — real files this app can read, never a guess. Read-only: session-manager has no way to tell the claude CLI to skip one of these once it's on disk."}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto pr-1",children:[o.jsxs("div",{className:"mb-3 rounded-[10px] border border-line bg-bg px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs font-semibold text-fg",children:[o.jsx("span",{className:"h-1.5 w-1.5 rotate-45 rounded-sm",style:{background:q?uT(q.name):"#8a7a60"}}),(q==null?void 0:q.name)??"default"]}),o.jsx("span",{className:"text-fg-faint",children:"·"}),o.jsxs("span",{className:"rounded-full bg-fg-faint px-2 py-0.5 font-mono text-[11px] font-semibold text-bg-hi",children:["#",x]}),o.jsxs("span",{className:"ml-auto font-mono text-[11px] text-fg-faint",children:[Ne.toFixed(1),"k of 200k window (estimate)"]})]}),o.jsx("div",{className:"mt-1 text-sm font-semibold text-fg",children:b||"Untitled Epic"}),o.jsx("div",{className:"mt-0.5 text-[12.5px] leading-[1.5] text-fg-dim",children:y||ae})]}),Z?o.jsx("div",{className:"grid grid-cols-3 gap-2.5",children:Z.map(me=>o.jsxs("div",{"data-testid":`grounding-group-${me.key}`,className:"overflow-hidden rounded-[10px] border border-line bg-bg",children:[o.jsxs("div",{className:"border-b border-rule bg-bg-hi px-2.5 py-2",children:[o.jsxs("div",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-[12.5px] font-semibold text-fg",children:me.label}),o.jsxs("span",{className:"ml-auto font-mono text-[10.5px] text-fg-faint",children:[me.items.filter(re=>re.present).length,"/",me.items.length]})]}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[10.5px] text-fg-faint",children:me.path})]}),o.jsx("div",{children:me.items.map((re,te)=>o.jsxs("div",{className:`px-2.5 py-1.5 ${te?"border-t border-rule":""} ${re.present?"":"opacity-60"}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:`grid h-3 w-3 flex-shrink-0 place-items-center rounded ${re.present?"bg-accent text-bg-hi":"ring-1 ring-inset ring-line"}`,children:re.present?"✓":""}),o.jsx("span",{className:"truncate font-mono text-[11px] text-fg",children:re.name}),re.tokK>0&&o.jsxs("span",{className:"ml-auto flex-shrink-0 font-mono text-[10.5px] text-fg-faint",children:[re.tokK.toFixed(1),"k"]})]}),o.jsxs("div",{className:"pl-[18px] text-[11px] leading-[1.4] text-fg-faint",children:[re.detail,(re.locked,"")]})]},re.name))})]},me.key))}):o.jsx("div",{className:"rounded-[10px] border border-dashed border-rule px-4 py-6 text-center text-[12.5px] text-fg-faint",children:"Reading grounding sources…"})]}),o.jsxs("div",{className:"mt-3 flex flex-shrink-0 items-center gap-2.5 border-t border-rule pt-3",children:[o.jsx("button",{type:"button","data-testid":"new-epic-flip-to-goal",onClick:()=>U(!1),className:"rounded-md border border-accent-muted bg-bg px-2.5 py-1.5 text-xs font-semibold text-accent hover:bg-bg-elev",children:"⤺ Back to the goal"}),o.jsxs("span",{className:"ml-auto flex items-center gap-2.5",children:[o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:[xe," sources · ",Ne.toFixed(1),"k"]}),o.jsx("button",{type:"button",onClick:ce,className:"rounded-md border border-line bg-bg px-3.5 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:"Cancel"}),o.jsx("button",{type:"button",onClick:()=>void Y(),disabled:!le||P,className:"rounded-md bg-accent px-4 py-2 text-[12.5px] font-semibold text-bg-hi disabled:cursor-not-allowed disabled:opacity-40",children:P?"Starting…":"Start Epic"})]})]})]})]})})})}function hT({eyebrow:n,advanced:e,setAdvanced:i}){return o.jsxs("div",{className:"mb-1.5 flex items-center gap-2.5",children:[o.jsx("span",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.11em] text-accent",children:n}),o.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[o.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:"advanced"}),o.jsx("button",{type:"button",role:"switch","aria-checked":e,"data-testid":"new-epic-advanced-toggle",onClick:()=>i(!e),className:`flex h-[19px] w-[34px] items-center rounded-full p-0.5 ${e?"justify-end bg-accent":"justify-start bg-rule"}`,children:o.jsx("span",{className:"h-[15px] w-[15px] rounded-full bg-bg-hi shadow"})})]})]})}const mX=[];function KA({cwd:n}={}){const e=rn(Q=>Q.sessions),i=rn(Q=>Q.events),r=Ey(),s=to(Q=>{var oe;return(oe=Q.snapshot)==null?void 0:oe.jobs})??mX,{rows:a,enriched:d}=ov(),[l,c]=R.useState(null);R.useEffect(()=>(rn.getState().setFocusedEpicId(l),()=>rn.getState().setFocusedEpicId(null)),[l]);const[p,m]=R.useState(!1),f=d1(),[b,_]=R.useState(void 0),y=R.useMemo(()=>{var le;const Q=new Set,oe=[];for(const H of a){const ee=((le=d[H.encoded])==null?void 0:le.cwd)??Yp(H.encoded);!ee||Q.has(ee)||(Q.add(ee),oe.push(ee))}return oe},[a,d]),k=vt(Q=>Q.tabs),x=vt(Q=>Q.activeTabId),w=k.find(Q=>Q.id===x)??null,S=n??(w==null?void 0:w.cwd)??void 0,E=y.join(`
|
|
3208
|
+
`).length:0;return{name:e,detail:i(s),tokK:gy(r.text),present:!0}}async function cT(n,e,i){const r=await window.api.config.listDir(n,{dirsOnly:!0}),s=r.ok?r.entries.length:0;return!r.ok||s===0?{name:e,detail:`no ${i} installed`,tokK:0,present:!1}:{name:e,detail:`${s} installed`,tokK:gy(r.entries.map(a=>a.name).join(" "))+.1*s,present:!0}}function uX(n){try{const i=JSON.parse(n).hooks??{};return Object.values(i).reduce((r,s)=>r+(Array.isArray(s)?s.length:0),0)}catch{return 0}}async function hX(n){var Z;const{home:e,cwd:i,agentPersonaPath:r,agentPersonaName:s,openTerminalTabsInProject:a,otherEpicsInProject:d}=n,l=ku.resolve("user",e,null),c=Du.resolve("user",e,null),p=ku.resolve("project",e,i),m=ku.resolve("local",e,i),f=Du.resolve("project",e,i),[b,_,y,k,x,w,S,E,j,N,A]=await Promise.all([f_(l,"CLAUDE.md",W=>`global preferences · ${W} lines`),window.api.config.readText(c),cT(`${e}/.claude/skills`,"skills/","skills"),r?window.api.config.readText(r):Promise.resolve(null),f_(p,"CLAUDE.md",W=>`${W} lines`),cT(`${i}/.claude/skills`,".claude/skills/","skills"),window.api.config.readJson(`${e}/.claude.json`),window.api.config.readText(f),window.api.config.exists(`${i}/session-manager-operations/project-brief/brief.json`),f_(m,"CLAUDE.local.md",W=>`personal notes · ${W} lines`),window.api.app.gitBranch(i)]),P=((Z=S.data)==null?void 0:Z.mcpServers)??{},I=Object.keys(P).length,O=uX(E.text),U={key:"system",label:"System",path:"~/.claude/",items:[b,{name:"settings.json",detail:_.exists?"model, permissions, output style":"not present",tokK:_.exists?gy(_.text):0,present:_.exists},y,k?{name:`agents/${s}.md`,detail:"system prompt for the selected role · required",tokK:gy(k.text),present:k.exists,locked:!0}:{name:"agents/*.md",detail:"no agent selected — default persona",tokK:0,present:!1}]},B={key:"project",label:"Project",path:`${i}/`,items:[x,w,I>0?{name:`mcp servers · ${I}`,detail:Object.keys(P).slice(0,3).join(", "),tokK:.2*I,present:!0}:{name:"mcp servers",detail:"none configured",tokK:0,present:!1},O>0?{name:`hooks · ${O}`,detail:"from .claude/settings.json",tokK:.1*O,present:!0}:{name:"hooks",detail:"none configured",tokK:0,present:!1},{name:"Project brief",detail:j?"LLM-maintained scope + conventions":"not generated yet",tokK:j?2:0,present:j}]},J={key:"local",label:"Local",path:`${i}/ · this machine only`,items:[N,{name:"working tree",detail:A?`⎇ ${A}`:"not a git repo",tokK:0,present:!!A},a>0?{name:`open Terminal tabs · ${a}`,detail:"other tabs on this project",tokK:0,present:!0}:{name:"open Terminal tabs",detail:"none open right now",tokK:0,present:!1},d>0?{name:`other Epics · ${d}`,detail:"proposed/active in this project",tokK:0,present:!0}:{name:"other Epics",detail:"none yet in this project",tokK:0,present:!1}]};return[U,B,J]}const pX=[{tag:"feature",label:"Feature"},{tag:"bug",label:"Bug"},{tag:"discussion",label:"Discussion"}],dT=["#b85c34","#a3441f","#6f7d52","#8a7a60","#7a6a8a","#5f7a7d","#c96442","#4f7d72"];function uT(n){let e=0;for(let i=0;i<n.length;i+=1)e=e*31+n.charCodeAt(i)>>>0;return dT[e%dT.length]}function fX({onCreated:n,onCancel:e}){const i=rn(me=>me.createPromptSession),r=rn(me=>me.approveProposed),s=rn(me=>me.sessions),{rows:a,enriched:d}=ov(),l=vt(me=>me.tabs),c=vt(me=>{var re;return((re=me.tabs.find(te=>te.id===me.activeTabId))==null?void 0:re.cwd)??null}),p=R.useMemo(()=>{var te;const me=new Set,re=[];for(const we of a){const be=((te=d[we.encoded])==null?void 0:te.cwd)??Yp(we.encoded);!be||me.has(be)||(me.add(be),re.push(be))}return re},[a,d]),[m,f]=R.useState(""),[b,_]=R.useState(""),[y,k]=R.useState(""),[x,w]=R.useState("feature"),[S,E]=R.useState(""),[j,N]=R.useState(null),A=WA(),[P,I]=R.useState(!1),[O,U]=R.useState(!1),[B,J]=R.useState(null),[Z,W]=R.useState(null);R.useEffect(()=>{let me=!1;return(async()=>{try{const re=await window.api.agents.listPersonas();me||N(re)}catch(re){me||(N([]),Re.error(re.message||"failed to load Agent Library"))}})(),()=>{me=!0}},[]),R.useEffect(()=>{let me=!1;return(async()=>{try{const re=await window.api.app.homeDir();me||J(re)}catch{}})(),()=>{me=!0}},[]);const q=(j==null?void 0:j.find(me=>me.name===S))??null,Q=m||(c&&p.includes(c)?c:"")||p[0]||"",oe=y.trim(),le=!!(Q&&oe),H=!(c&&p.includes(c));R.useEffect(()=>{if(!O||!B||!Q)return;let me=!1;return hX({home:B,cwd:Q,agentPersonaPath:(q==null?void 0:q.path)??null,agentPersonaName:(q==null?void 0:q.name)??null,openTerminalTabsInProject:l.filter(re=>re.cwd===Q).length,otherEpicsInProject:Object.values(s).filter(re=>re.cwd===Q).length}).then(re=>{me||W(re)}).catch(re=>{me||Re.error(re.message||"failed to read grounding sources")}),()=>{me=!0}},[O,B,Q,q,l,s]);const ee=()=>{f(""),_(""),k(""),w("feature"),E(""),U(!1),W(null),A.clear()},Y=async()=>{if(!(!le||P)){I(!0);try{const me=await VA(A.items,Q),{goalText:re,openingPrompt:te}=f1({title:b,goal:y,referencePaths:me,tag:x,agentName:q==null?void 0:q.name,agentDescription:(q==null?void 0:q.description)??void 0}),we=q?i(Q,re,x,"NewEpicCard",q.name):i(Q,re,x,"NewEpicCard");r(we.id,"NewEpicCard"),An.getState().send({tabId:we.id,sessionId:we.claudeSessionId,cwd:Q,prompt:te}),ee(),n(we.id)}finally{I(!1)}}},ce=()=>{ee(),e()},ae=l1(x).description,xe=Z?Z.reduce((me,re)=>me+re.items.filter(te=>te.present).length,0):0,Ne=Z?Z.reduce((me,re)=>me+re.items.reduce((te,we)=>te+we.tokK,0),0):0;return o.jsx("section",{className:"flex-1 min-w-0 grid place-items-center overflow-y-auto bg-bg p-6","data-testid":"new-epic-card",children:o.jsx("div",{className:"w-full transition-[max-width] duration-500",style:{maxWidth:O?"min(1320px, 94vw)":"min(920px, 92vw)",perspective:2400},children:o.jsxs("div",{className:"relative w-full transition-transform duration-500",style:{height:"min(760px, 84vh)",transformStyle:"preserve-3d",transform:O?"rotateY(180deg)":"none"},children:[o.jsxs("div",{className:"absolute inset-0 flex flex-col rounded-2xl border border-line bg-bg-hi px-[26px] pt-6 pb-[18px]",style:{backfaceVisibility:"hidden"},children:[o.jsx(hT,{eyebrow:"New Epic",advanced:O,setAdvanced:U}),o.jsx("h2",{className:"m-0 font-serif text-2xl font-semibold tracking-[-0.3px] text-fg",children:"What are we trying to achieve?"}),o.jsx("p",{className:"my-2 mb-[18px] text-[13.5px] leading-[1.55] text-fg-dim",children:"One goal per Epic — fixed for the life of its session. The title and objective are sent as the first message the moment you start it, so the agent is already working when it opens."}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-1",children:[H?o.jsxs("label",{className:"mb-2.5 flex flex-col gap-1",children:[o.jsx("span",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",children:"Project"}),o.jsxs("select",{"data-testid":"new-prompt-cwd",value:Q,onChange:me=>f(me.target.value),className:"rounded-md border border-line bg-bg px-2 py-1.5 font-mono text-[12.5px] text-fg",children:[p.length===0&&o.jsx("option",{value:"",children:"No known projects"}),p.map(me=>o.jsx("option",{value:me,children:zg(me)},me))]})]}):o.jsxs("div",{"data-testid":"new-prompt-cwd-static",className:"mb-2.5 flex items-center gap-1.5 font-mono text-[11px] text-fg-faint",children:[o.jsx("span",{className:"uppercase tracking-[0.09em]",children:"Project"}),o.jsx("span",{className:"text-fg-dim",children:zg(Q)})]}),o.jsxs("div",{className:"mb-3.5 grid grid-cols-2 gap-3.5",children:[o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",title:"Who runs this Epic — from the Agent Library (~/.claude/agents).",children:"1 · agent — who is working"}),o.jsxs("div",{className:"grid min-w-0 gap-1",children:[o.jsxs("button",{type:"button","data-testid":"new-epic-agent-default",onClick:()=>E(""),className:`flex min-w-0 items-center gap-2 rounded-lg border px-2.5 py-1.5 text-left ${S===""?"border-accent bg-bg-elev":"border-line bg-bg"}`,children:[o.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rotate-45 rounded-sm bg-fg-faint"}),o.jsx("span",{className:"flex-shrink-0 font-mono text-xs font-medium text-fg",children:"Default"})]}),(j??[]).map(me=>{const re=S===me.name;return o.jsxs("button",{type:"button","data-testid":`new-epic-agent-${me.name}`,onClick:()=>E(me.name),className:`flex min-w-0 items-center gap-2 rounded-lg border px-2.5 py-1.5 text-left ${re?"border-accent bg-bg-elev":"border-line bg-bg"}`,children:[o.jsx("span",{className:"h-1.5 w-1.5 flex-shrink-0 rotate-45 rounded-sm",style:{background:uT(me.name)}}),o.jsx("span",{className:`flex-shrink-0 font-mono text-xs ${re?"font-semibold":"font-medium"} text-fg`,children:me.name}),me.description&&o.jsx("span",{className:"min-w-0 flex-1 truncate text-right text-[11px] text-fg-faint",children:me.description})]},me.name)})]})]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",title:"The Epic's mission — from the Tag Library. Sets how eagerly /develop fires.",children:"2 · mission — how they work"}),o.jsx("div",{className:"flex flex-wrap gap-1",children:pX.map(me=>{const re=x===me.tag;return o.jsx("button",{type:"button","data-testid":`new-epic-kind-${me.tag}`,onClick:()=>w(me.tag),className:`rounded-md px-2.5 py-1 text-xs font-medium ${re?"bg-bg text-fg ring-1 ring-inset ring-line font-semibold":"text-fg-faint"}`,children:me.label},me.tag)})}),o.jsxs("div",{className:"mt-2 border-l-2 border-accent-muted pl-2.5 text-[12.5px] leading-[1.5] text-fg-dim",children:[ae,o.jsxs("div",{className:"mt-1 font-mono text-[11px] text-fg-faint",children:["sonnet",q?` · ${q.tools.join(" ")||"no tool restriction"}`:""]})]})]})]}),o.jsx("input",{"data-testid":"new-epic-title",type:"text",value:b,onChange:me=>_(me.target.value),onPaste:me=>my(me,A),placeholder:"Epic title",className:"mb-2 w-full appearance-none rounded-[10px] border border-line bg-bg px-[13px] py-[11px] text-sm font-semibold text-fg outline-none"}),o.jsx("textarea",{"data-testid":"new-epic-goal",rows:3,value:y,onChange:me=>k(me.target.value),onPaste:me=>my(me,A),placeholder:"The objective, in a sentence or two — this is sent as the first instruction.",className:"mb-3 w-full resize-y appearance-none rounded-[10px] border border-line bg-bg px-[13px] py-[11px] text-[13px] leading-[1.55] text-fg outline-none"}),o.jsxs("div",{className:"mb-1.5 font-mono text-[10.5px] font-semibold uppercase tracking-[0.09em] text-fg-faint",children:["references",A.items.length?` · ${A.items.length}`:""]}),o.jsx(qA,{att:A,tall:!0,testId:"new-epic-attach-tray"})]}),o.jsxs("div",{className:"mt-3 flex flex-shrink-0 items-center gap-2.5 border-t border-rule pt-3",children:[o.jsxs("button",{type:"button","data-testid":"new-epic-flip-to-grounding",onClick:()=>U(!0),title:"See what this Epic's session will actually load",className:"rounded-md border border-accent-muted bg-bg px-2.5 py-1.5 text-xs font-semibold text-accent hover:bg-bg-elev",children:["⤺ Grounding",Z?` · ${xe} sources`:""]}),o.jsxs("span",{className:"ml-auto flex gap-1.5",children:[o.jsx("button",{type:"button","data-testid":"new-epic-cancel",onClick:ce,className:"rounded-md border border-line bg-bg px-3.5 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:"Cancel"}),o.jsx("button",{type:"button","data-testid":"new-epic-create",onClick:()=>void Y(),disabled:!le||P,className:"rounded-md bg-accent px-4 py-2 text-[12.5px] font-semibold text-bg-hi disabled:cursor-not-allowed disabled:opacity-40",children:P?"Starting…":"Start Epic"})]})]})]}),o.jsxs("div",{className:"absolute inset-0 flex flex-col rounded-2xl border border-line bg-bg-hi px-[26px] pt-6 pb-[18px]",style:{backfaceVisibility:"hidden",transform:"rotateY(180deg)"},children:[o.jsx(hT,{eyebrow:"New Epic · grounding",advanced:O,setAdvanced:U}),o.jsx("h2",{className:"m-0 font-serif text-2xl font-semibold tracking-[-0.3px] text-fg",children:"What this Epic will know"}),o.jsx("p",{className:"my-2 mb-[18px] text-[13.5px] leading-[1.55] text-fg-dim",children:"Every layer of context this Epic's session actually loads before your goal is sent — real files this app can read, never a guess. Read-only: session-manager has no way to tell the claude CLI to skip one of these once it's on disk."}),o.jsxs("div",{className:"min-h-0 flex-1 overflow-y-auto overflow-x-hidden pr-1",children:[o.jsxs("div",{className:"mb-3 rounded-[10px] border border-line bg-bg px-3 py-2.5",children:[o.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[o.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs font-semibold text-fg",children:[o.jsx("span",{className:"h-1.5 w-1.5 rotate-45 rounded-sm",style:{background:q?uT(q.name):"#8a7a60"}}),(q==null?void 0:q.name)??"default"]}),o.jsx("span",{className:"text-fg-faint",children:"·"}),o.jsxs("span",{className:"rounded-full bg-fg-faint px-2 py-0.5 font-mono text-[11px] font-semibold text-bg-hi",children:["#",x]}),o.jsxs("span",{className:"ml-auto font-mono text-[11px] text-fg-faint",children:[Ne.toFixed(1),"k of 200k window (estimate)"]})]}),o.jsx("div",{className:"mt-1 text-sm font-semibold text-fg",children:b||"Untitled Epic"}),o.jsx("div",{className:"mt-0.5 text-[12.5px] leading-[1.5] text-fg-dim",children:y||ae})]}),Z?o.jsx("div",{className:"grid grid-cols-3 gap-2.5",children:Z.map(me=>o.jsxs("div",{"data-testid":`grounding-group-${me.key}`,className:"overflow-hidden rounded-[10px] border border-line bg-bg",children:[o.jsxs("div",{className:"border-b border-rule bg-bg-hi px-2.5 py-2",children:[o.jsxs("div",{className:"flex items-baseline gap-1.5",children:[o.jsx("span",{className:"text-[12.5px] font-semibold text-fg",children:me.label}),o.jsxs("span",{className:"ml-auto font-mono text-[10.5px] text-fg-faint",children:[me.items.filter(re=>re.present).length,"/",me.items.length]})]}),o.jsx("div",{className:"mt-0.5 truncate font-mono text-[10.5px] text-fg-faint",children:me.path})]}),o.jsx("div",{children:me.items.map((re,te)=>o.jsxs("div",{className:`px-2.5 py-1.5 ${te?"border-t border-rule":""} ${re.present?"":"opacity-60"}`,children:[o.jsxs("div",{className:"flex items-center gap-1.5",children:[o.jsx("span",{className:`grid h-3 w-3 flex-shrink-0 place-items-center rounded ${re.present?"bg-accent text-bg-hi":"ring-1 ring-inset ring-line"}`,children:re.present?"✓":""}),o.jsx("span",{className:"truncate font-mono text-[11px] text-fg",children:re.name}),re.tokK>0&&o.jsxs("span",{className:"ml-auto flex-shrink-0 font-mono text-[10.5px] text-fg-faint",children:[re.tokK.toFixed(1),"k"]})]}),o.jsxs("div",{className:"pl-[18px] text-[11px] leading-[1.4] text-fg-faint",children:[re.detail,(re.locked,"")]})]},re.name))})]},me.key))}):o.jsx("div",{className:"rounded-[10px] border border-dashed border-rule px-4 py-6 text-center text-[12.5px] text-fg-faint",children:"Reading grounding sources…"})]}),o.jsxs("div",{className:"mt-3 flex flex-shrink-0 items-center gap-2.5 border-t border-rule pt-3",children:[o.jsx("button",{type:"button","data-testid":"new-epic-flip-to-goal",onClick:()=>U(!1),className:"rounded-md border border-accent-muted bg-bg px-2.5 py-1.5 text-xs font-semibold text-accent hover:bg-bg-elev",children:"⤺ Back to the goal"}),o.jsxs("span",{className:"ml-auto flex items-center gap-2.5",children:[o.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:[xe," sources · ",Ne.toFixed(1),"k"]}),o.jsx("button",{type:"button",onClick:ce,className:"rounded-md border border-line bg-bg px-3.5 py-2 text-[12.5px] font-semibold text-fg-dim hover:bg-bg-elev",children:"Cancel"}),o.jsx("button",{type:"button",onClick:()=>void Y(),disabled:!le||P,className:"rounded-md bg-accent px-4 py-2 text-[12.5px] font-semibold text-bg-hi disabled:cursor-not-allowed disabled:opacity-40",children:P?"Starting…":"Start Epic"})]})]})]})]})})})}function hT({eyebrow:n,advanced:e,setAdvanced:i}){return o.jsxs("div",{className:"mb-1.5 flex items-center gap-2.5",children:[o.jsx("span",{className:"font-mono text-[10.5px] font-semibold uppercase tracking-[0.11em] text-accent",children:n}),o.jsxs("span",{className:"ml-auto flex items-center gap-1.5",children:[o.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:"advanced"}),o.jsx("button",{type:"button",role:"switch","aria-checked":e,"data-testid":"new-epic-advanced-toggle",onClick:()=>i(!e),className:`flex h-[19px] w-[34px] items-center rounded-full p-0.5 ${e?"justify-end bg-accent":"justify-start bg-rule"}`,children:o.jsx("span",{className:"h-[15px] w-[15px] rounded-full bg-bg-hi shadow"})})]})]})}const mX=[];function KA({cwd:n}={}){const e=rn(Q=>Q.sessions),i=rn(Q=>Q.events),r=Ey(),s=to(Q=>{var oe;return(oe=Q.snapshot)==null?void 0:oe.jobs})??mX,{rows:a,enriched:d}=ov(),[l,c]=R.useState(null);R.useEffect(()=>(rn.getState().setFocusedEpicId(l),()=>rn.getState().setFocusedEpicId(null)),[l]);const[p,m]=R.useState(!1),f=d1(),[b,_]=R.useState(void 0),y=R.useMemo(()=>{var le;const Q=new Set,oe=[];for(const H of a){const ee=((le=d[H.encoded])==null?void 0:le.cwd)??Yp(H.encoded);!ee||Q.has(ee)||(Q.add(ee),oe.push(ee))}return oe},[a,d]),k=vt(Q=>Q.tabs),x=vt(Q=>Q.activeTabId),w=k.find(Q=>Q.id===x)??null,S=n??(w==null?void 0:w.cwd)??void 0,E=y.join(`
|
|
3209
3209
|
`);R.useEffect(()=>{for(const Q of E?E.split(`
|
|
3210
3210
|
`):[])rn.getState().hydrate(Q),rn.getState().hydrateArchived(Q)},[E]),R.useEffect(()=>{var ee,Y,ce,ae;const Q=E?E.split(`
|
|
3211
3211
|
`):[];if(!Q.length||typeof((Y=(ee=window.api)==null?void 0:ee.config)==null?void 0:Y.watch)!="function"||typeof((ae=(ce=window.api)==null?void 0:ce.config)==null?void 0:ae.onChanged)!="function")return;const oe=Q.map(xe=>W0(xe)),le=new Map(oe.map((xe,Ne)=>[xe,Q[Ne]]));window.api.config.watch(oe);const H=window.api.config.onChanged(({path:xe})=>{const Ne=le.get(xe);Ne&&rn.getState().hydrate(Ne)});return()=>{var xe,Ne;H(),typeof((Ne=(xe=window.api)==null?void 0:xe.config)==null?void 0:Ne.unwatch)=="function"&&window.api.config.unwatch(oe)}},[E]);const[j,N]=R.useState(null);R.useEffect(()=>{const Q=H=>{m(!1),rn.getState().sessions[H]?(c(H),N(null)):N(H)},oe=FM();oe&&Q(oe);const le=H=>Q(H.detail);return window.addEventListener("sm:select-prompt-session",le),()=>window.removeEventListener("sm:select-prompt-session",le)},[]),R.useEffect(()=>{j&&e[j]&&(c(j),m(!1),N(null))},[j,e]),R.useEffect(()=>{var H;const Q={};for(const ee of Object.values(e))ee.status==="active"&&(Q[ee.claudeSessionId]=ee.id);const oe=Object.keys(Q);if(!oe.length)return;const le=(H=window.api.pty)==null?void 0:H.alive;typeof le=="function"&&le(oe).then(ee=>{const Y=Hl.getState();for(const ce of ee){const ae=Q[ce];Y.isAttached(ae)||(Y.setMode(ae,"terminal"),Y.setAttached(ae,!0))}}).catch(()=>{})},[e]);const A=R.useMemo(()=>S?Object.values(e).filter(Q=>Q.cwd===S):Object.values(e),[e,S]),P=JE(Q=>Q.usage),I=JE(Q=>Q.fetch),O=A.map(Q=>Q.id).join(`
|