@openchamber/web 1.4.3 → 1.4.5

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.
@@ -0,0 +1,128 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-B2HtLj-d.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-DYNTzpsQ.js","assets/index-g64tpi5J.js","assets/index-hru9kOov.css"])))=>i.map(i=>d[i]);
2
+ import{t as jf,c as Sf,F as kf,j as e,R as Nf,T as Cf,P as Mf,C as Df,A as Af,a as Ef,b as Bt,d as Xt,p as Ts,e as Fs,f as If,_ as is,g as c,r as Pf,i as Ht,I as Tf,k as Ff,l as Rf,m as _f,n as Of,o as $f,q as Lf,s as Bf,u as At,v as zf,S as Wf,L as Hf,w as Jd,x as Uf,y as Vf,z as Gf,B as Ce,D as Pl,E as fi,G as Kf,H as Mt,K as Bi,J as qf,U as cs,M as Zd,N as Yf,O as Dr,Z as Xf,Y as nr,Q as Er,W as Ot,V as na,X as Qf,$ as Kr,a0 as Qr,a1 as yn,a2 as pi,a3 as Es,a4 as eu,a5 as Jf,a6 as Zf,a7 as ep,a8 as tp,a9 as sp,aa as rp,ab as np,ac as Co,ad as op,ae as ap,af as zo,ag as bn,ah as se,ai as ls,aj as yr,ak as Jr,al as to,am as Kt,an as or,ao as ip,ap as lp,aq as tu,ar as zi,as as qr,at as su,au as ar,av as ru,aw as wn,ax as cp,ay as oa,az as Us,aA as Na,aB as dp,aC as Ir,aD as mr,aE as Gs,aF as up,aG as Ks,aH as mp,aI as Tl,aJ as fp,aK as pp,aL as hp,aM as gp,aN as xp,aO as yp,aP as bp,aQ as wp,aR as vp,aS as jp,aT as ur,aU as Ca,aV as Sp,aW as ir,aX as Wi,aY as Hi,aZ as kp,a_ as Np,a$ as Cp,b0 as Mp,b1 as Dp,b2 as Ap,b3 as Ep,b4 as Ip,b5 as Pp,b6 as Tp,b7 as Fp,b8 as Rp,b9 as _p,ba as Op,bb as $p,bc as Lp,bd as Bp,be as zp,bf as Wp,bg as fr,bh as Wo,bi as br,bj as tr,bk as Hp,bl as Up,bm as aa,bn as Vp,bo as Ui,bp as Gp,bq as Kp,br as qp,bs as Kn,bt as Yp,bu as Xp,bv as Qp,bw as Jp,bx as Zp,by as hi,bz as Mo,bA as ia,bB as eh,bC as th,bD as Bn,bE as un,bF as nu,bG as ou,bH as sh,bI as rh,bJ as Ps,bK as au,bL as nh,bM as iu,bN as oh,bO as ah,bP as gi,bQ as ih,bR as lu,bS as hr,bT as qn,bU as lh,bV as Mn,bW as ch,bX as la,bY as cu,bZ as Vi,b_ as Gi,b$ as Ki,c0 as dh,c1 as uh,c2 as mh,c3 as Fl,c4 as du,c5 as fh,c6 as Rl,c7 as Yn,c8 as uu,c9 as mu,ca as Ma,cb as ca,cc as fu,cd as ph,ce as xi,cf as pu,cg as yi,ch as hh,ci as gh,cj as xh,ck as yh,cl as bh,cm as wh,cn as vh,co as jh,cp as Sh}from"./vendor-.bun-B2HtLj-d.js";import{c as kh,l as Nh,g as Ch,r as Mh,d as Dh,a as Ah,b as Eh,e as Ih,u as Ph,f as Th,h as Fh,i as Rh,j as _h,k as Oh}from"./index-g64tpi5J.js";const os=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,qi=()=>typeof window>"u"?!1:!os()&&!Wt(),Pr=()=>os()?window.opencodeDesktop??null:null,hu=()=>{if(typeof window>"u")return null;if(window.opencodeDesktopSettings)return window.opencodeDesktopSettings;const s=window.opencodeDesktop;return s?.getSettings&&s?.updateSettings?{getSettings:s.getSettings.bind(s),updateSettings:s.updateSettings.bind(s)}:null},gu=async()=>{const s=Pr();if(typeof window<"u"){const r=window.__OPENCHAMBER_HOME__;if(r&&r.length>0)return r}if(!s)return null;if(typeof s.homeDirectory=="string"&&s.homeDirectory.length>0)return s.homeDirectory;try{if(!s.getHomeDirectory)return null;const r=await s.getHomeDirectory();if(r?.success&&typeof r.path=="string"&&r.path.length>0)return r.path}catch(r){console.warn("Failed to obtain desktop home directory:",r)}return null},$h=async()=>{const s=Pr();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Lh=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Dn=async()=>{const s=hu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Bh=async s=>{const r=hu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},zh=async s=>{const r=Pr();if(!r||!r.requestDirectoryAccess)return{success:!0,path:s};try{return await r.requestDirectoryAccess(s)}catch(t){return console.warn("Failed to request directory access",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},Wh=async s=>{const r=Pr();if(!r||!r.startAccessingDirectory)return{success:!0};try{return await r.startAccessingDirectory(s)}catch(t){return console.warn("Failed to start accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},Hh=async s=>{const r=Pr();if(!r||!r.stopAccessingDirectory)return{success:!0};try{return await r.stopAccessingDirectory(s)}catch(t){return console.warn("Failed to stop accessing directory",t),{success:!1,error:t instanceof Error?t.message:String(t)}}},Uh=async()=>{const s=Pr();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},Vh=async s=>{const r=Pr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},Gh=async()=>{const s=Pr();if(!s||!s.restartToUpdate)return!1;try{return await s.restartToUpdate(),!0}catch(r){return console.warn("Failed to restart for update",r),!1}};function P(...s){return jf(Sf(s))}const xu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Cs=s=>xu()&&os()?s.metaKey:s.ctrlKey,Zt=()=>xu()&&os()?"⌘":"Ctrl",yu=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>i)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Ho=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Hr(s,r){if(!s)return"";const t=Ho(s);if(t==="/")return"/";const n=r?Ho(r):void 0;if(n&&n!=="/"){if(t===n)return"~";if(t.startsWith(`${n}/`)){const o=t.slice(n.length+1);return o?`~/${o}`:"~"}}return t}function _l(s,r){if(!s)return"/";const t=Ho(s);if(!t||t==="/")return"/";const n=r?Ho(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function As(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new kf([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function Kh({delayDuration:s=0,...r}){return e.jsx(Ef,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function rt({delayDuration:s=0,...r}){return e.jsx(Kh,{delayDuration:s,children:e.jsx(Nf,{"data-slot":"tooltip",...r})})}function nt({...s}){return e.jsx(Cf,{"data-slot":"tooltip-trigger",...s})}function tt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Mf,{children:e.jsxs(Df,{"data-slot":"tooltip-content",sideOffset:r,className:P("bg-muted text-muted-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-xl px-3 py-1.5 typography-meta text-balance overflow-hidden transform-gpu will-change-transform",s),...n,children:[t,e.jsx(Af,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Da=null;const Ol=()=>{const s=new Map;return{getItem:r=>s.get(r)??null,setItem:(r,t)=>{s.set(r,t)},removeItem:r=>{s.delete(r)},clear:()=>{s.clear()},key:r=>Array.from(s.keys())[r]??null,get length(){return s.size}}},qh=()=>{if(typeof window>"u"||!window.localStorage)return Ol();const s=window.localStorage,r=Ol();let t=!0;const n=()=>{t=!1};return{getItem:u=>{if(t)try{const m=s.getItem(u);if(m!==null)return m}catch{n()}return r.getItem(u)},setItem:(u,m)=>{if(t)try{s.setItem(u,m),r.removeItem(u);return}catch{n()}r.setItem(u,m)},removeItem:u=>{if(t)try{s.removeItem(u)}catch{n()}r.removeItem(u)},clear:()=>{if(t)try{s.clear()}catch{n()}r.clear()},key:u=>{if(t)try{return s.key(u)}catch{n()}return r.key(u)},get length(){if(t)try{return s.length+r.length}catch{n()}return r.length}}},us=()=>(Da||(Da=qh()),Da),Yi={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},Yh={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function $l(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const pr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},Do={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...pr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:Do.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Do.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:Do.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...pr.tool.inline})},_e=Bt()(Xt(Ts((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,isTimelineDialogOpen:!1,setTheme:t=>{s({theme:t}),r().applyTheme()},toggleSidebar:()=>{s(t=>{const n=!t.isSidebarOpen;if(n&&typeof window<"u"){const o=Math.floor(window.innerWidth*.2);return{isSidebarOpen:n,sidebarWidth:o,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:n}})},setSidebarOpen:t=>{s(()=>{if(t&&typeof window<"u"){const n=Math.floor(window.innerWidth*.2);return{isSidebarOpen:t,sidebarWidth:n,hasManuallyResizedLeftSidebar:!1}}return{isSidebarOpen:t}})},setSidebarWidth:t=>{s({sidebarWidth:t,hasManuallyResizedLeftSidebar:!0})},setSessionSwitcherOpen:t=>{s({isSessionSwitcherOpen:t})},setActiveMainTab:t=>{s({activeMainTab:t})},setPendingDiffFile:t=>{s({pendingDiffFile:t})},navigateToDiff:t=>{s({pendingDiffFile:t,activeMainTab:"diff"})},consumePendingDiffFile:()=>{const{pendingDiffFile:t}=r();return t&&s({pendingDiffFile:null}),t},setIsMobile:t=>{s({isMobile:t})},toggleCommandPalette:()=>{s(t=>({isCommandPaletteOpen:!t.isCommandPaletteOpen}))},setCommandPaletteOpen:t=>{s({isCommandPaletteOpen:t})},toggleHelpDialog:()=>{s(t=>({isHelpDialogOpen:!t.isHelpDialogOpen}))},setHelpDialogOpen:t=>{s({isHelpDialogOpen:t})},setAboutDialogOpen:t=>{s({isAboutDialogOpen:t})},setSessionCreateDialogOpen:t=>{s({isSessionCreateDialogOpen:t})},setSettingsDialogOpen:t=>{s({isSettingsDialogOpen:t})},setModelSelectorOpen:t=>{s({isModelSelectorOpen:t})},setSidebarSection:t=>{s({sidebarSection:t})},setEventStreamStatus:(t,n)=>{s({eventStreamStatus:t,eventStreamHint:n??null})},setShowReasoningTraces:t=>{s({showReasoningTraces:t})},setAutoDeleteEnabled:t=>{s({autoDeleteEnabled:t})},setAutoDeleteAfterDays:t=>{const n=Math.max(1,Math.min(365,t));s({autoDeleteAfterDays:n})},setAutoDeleteLastRunAt:t=>{s({autoDeleteLastRunAt:t})},setToolCallExpansion:t=>{s({toolCallExpansion:t})},setFontSize:t=>{const n=Math.max(50,Math.min(200,t));s({fontSize:n}),r().applyTypography()},setPadding:t=>{const n=Math.max(50,Math.min(200,t));s({padding:n}),r().applyPadding()},applyTypography:()=>{const{fontSize:t}=r(),n=document.documentElement,o=t/100,a=Object.entries(Yi);if(o===1){for(const[i]of a)n.style.removeProperty($l(i));return}for(const[i,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty($l(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})}}),{name:"ui-store",storage:Fs(()=>us()),partialize:s=>({theme:s.theme,isSidebarOpen:s.isSidebarOpen,sidebarWidth:s.sidebarWidth,isSessionSwitcherOpen:s.isSessionSwitcherOpen,activeMainTab:s.activeMainTab,sidebarSection:s.sidebarSection,isSessionCreateDialogOpen:s.isSessionCreateDialogOpen,isSettingsDialogOpen:s.isSettingsDialogOpen,showReasoningTraces:s.showReasoningTraces,autoDeleteEnabled:s.autoDeleteEnabled,autoDeleteAfterDays:s.autoDeleteAfterDays,autoDeleteLastRunAt:s.autoDeleteLastRunAt,toolCallExpansion:s.toolCallExpansion,fontSize:s.fontSize,padding:s.padding,favoriteModels:s.favoriteModels,recentModels:s.recentModels,diffLayoutPreference:s.diffLayoutPreference,diffWrapLines:s.diffWrapLines})}),{name:"ui-store"}));async function Xh(){try{const s=await fetch("/api/openchamber/update-check",{method:"GET",headers:{Accept:"application/json"}});if(!s.ok)throw new Error(`Server responded with ${s.status}`);const r=await s.json();return{available:r.available??!1,version:r.version,currentVersion:r.currentVersion??"unknown",body:r.body,packageManager:r.packageManager,updateCommand:r.updateCommand}}catch(s){return console.warn("Failed to check for web updates:",s),null}}function Qh(){return os()?"desktop":qi()?"web":null}const Ll={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},da=Bt()((s,r)=>({...Ll,checkForUpdates:async()=>{const t=Qh();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await Uh():t==="web"&&(n=await Xh()),s({checking:!1,available:n?.available??!1,info:n,lastChecked:Date.now()})}catch(n){s({checking:!1,error:n instanceof Error?n.message:"Failed to check for updates"})}}},downloadUpdate:async()=>{const{available:t,runtimeType:n}=r();if(!(n!=="desktop"||!t)){s({downloading:!0,error:null,progress:null});try{await Vh(o=>{s({progress:o})}),s({downloading:!1,downloaded:!0})}catch(o){s({downloading:!1,error:o instanceof Error?o.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:t,runtimeType:n}=r();if(!(n!=="desktop"||!t))try{await Gh()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(Ll)}})),Jh="/api",Zh=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,eg=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(Zh.test(r)||typeof window>"u")return r;const t=window.location?.href||window.location?.origin;if(!t)return r;try{return new URL(r,t).toString()}catch(n){return console.warn("Failed to normalize OpenCode base URL:",n),r}},tg=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_DESKTOP_SERVER__,r=!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop;if(!s||!r)return null;const t=typeof s.origin=="string"&&s.origin.length>0?s.origin:null;return t?`${t}/api`:null},oo=s=>s.replace(/\\/g,"/"),Aa=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class sg{client;baseUrl;sseAbortControllers=new Map;currentDirectory=void 0;globalSseAbortController=null;globalSseTask=null;globalSseLastEventId;globalSseIsConnected=!1;globalSseListeners=new Set;globalSseOpenListeners=new Set;globalSseErrorListeners=new Set;constructor(r=Jh){const n=tg()||r;this.baseUrl=eg(n),this.client=If({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async convertHeicToJpeg(r){try{const t=(await is(async()=>{const{default:f}=await import("./vendor-.bun-B2HtLj-d.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.charCodeAt(f);const l=new Blob([i],{type:r.mime}),d=await t({blob:l,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const g=new FileReader;g.onload=()=>f(g.result),g.onerror=p,g.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(t){return console.warn("Failed to convert HEIC to JPEG:",t),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(!this.shouldNormalizeToTextPlain(r.mime))return r;let t=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const i=await this.normalizeFilePart(a),l={type:"file",mime:i.mime,filename:i.filename,url:i.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const i of a.files){const l=await this.normalizeFilePart(i),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async listToolIds(r){try{const t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const t=await this.getConfig(),n=r(t);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const t=r.split(`
3
+ `),n=[];let o;for(const i of t)if(i.startsWith("data:"))n.push(i.slice(5).replace(/^\s/,""));else if(i.startsWith("id:")){const l=i.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
4
+ `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const t=r,n=typeof t.directory=="string"?t.directory:typeof t.properties=="object"&&t.properties!==null?t.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof t.type=="string")return{directory:o&&o.length>0?o:"global",payload:t};const a=t.payload;if(a&&typeof a=="object"){const i=a;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}return null}emitGlobalSseEvent(r){for(const t of this.globalSseListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(t){console.warn("[OpencodeClient] Global SSE open handler error:",t)}}notifyGlobalSseError(r){for(const t of this.globalSseErrorListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(t=>{t?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",t)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const t=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const i=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!i.ok||!i.body)throw new Error(`Global SSE connect failed with status ${i.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=i.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
+ `);const g=u.split(`
6
+
7
+ `);u=g.pop()??"";for(const w of g){const h=this.parseSseBlock(w);if(!h)continue;h.id&&(this.globalSseLastEventId=h.id);const j=this.normalizeRoutedSsePayload(h.data);j&&this.emitGlobalSseEvent(j)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,t,n,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(i),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const i=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(i);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(i,u);let m;if(l==="global"){let p=null;const g=h=>{if(h.directory==="global")return h.payload;const j=h.payload,b=typeof j.properties=="object"&&j.properties!==null?j.properties:{};return b.directory===h.directory?h.payload:{...j,properties:{...b,directory:h.directory}}},w=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)};return u.signal.addEventListener("abort",w,{once:!0}),p=this.subscribeToGlobalEvents(h=>{u.signal.aborted||r(g(h))},t?h=>{u.signal.aborted||t(h)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{w(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const g=p;if(typeof g.type=="string")return g;const w=g.payload;if(w&&typeof w=="object"){const h=w;if(typeof h.type=="string"){if(typeof g.directory=="string"&&g.directory.length>0){const b={...(typeof h.properties=="object"&&h.properties!==null?h.properties:null)??{},directory:g.directory};return{...h,properties:b}}return h}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const g=async w=>{try{const h=p?{directory:p}:void 0,j={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:x=>{x instanceof Error&&x.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",x),t&&!u.signal.aborted&&t(x))},onSseEvent:x=>{if(u.signal.aborted)return;x.id&&typeof x.id=="string"&&(m=x.id);const v=x.data,N=f(v);N&&r(N)}};m&&(j.headers={...j.headers||{},"Last-Event-ID":m});const b=await this.client.event.subscribe(h,j);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const x of b.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(h){if(h?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",h),t&&t(h);const j=Math.min(3e3*Math.pow(2,w),3e4);await new Promise(b=>setTimeout(b,j)),u.signal.aborted||await g(w+1);return}if(!u.signal.aborted){const h=Math.min(3e3*Math.pow(2,w),3e4);await new Promise(j=>setTimeout(j,h)),await g(w+1)}};try{await g(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i),u.abort()}}async readFile(r){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${r}
8
+ // This would be loaded from the server`}}async listFiles(r){try{const t=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(r){try{const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){const n=t.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?r="/health":t.endsWith("/api")?r=`${t.slice(0,-4)}/health`:r=`${t}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const t=Aa();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(i||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r){const t=Aa();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:oo(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;r&&r.trim().length>0&&n.set("path",r);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const l=await a.json().catch(()=>({})),d=typeof l.error=="string"?l.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(r,t){const n=Aa(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?oo(o):null;if(n)try{const m=await n.search({directory:o||"",query:r,maxResults:t?.limit});return Array.isArray(m)?m.map(f=>{const p=oo(f.path),g=p.split("/").filter(Boolean).pop()||p,w=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?oo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||g;return{name:g,path:p,relativePath:w,extension:g.includes(".")?g.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof r=="string"&&i.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const l=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await gu();if(r)return r;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",r);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const ke=new sg,rg=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:ke},Symbol.toStringTag,{value:"Module"})),bi=new Set;function ua(s){return bi.add(s),()=>{bi.delete(s)}}function sr(s,r){const t=Array.isArray(s)?s:[s],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of bi)try{const i=a(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function Xn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const Xi="Updating OpenCode configuration...";let rr=0,Ar=Xi;const wi=new Set;function Uo(){const s={isUpdating:rr>0,message:Ar};wi.forEach(r=>r(s))}function Vs(s){rr+=1,rr===1?(Ar=s||Xi,Uo()):s&&(Ar=s,Uo())}function Ds(){rr!==0&&(rr-=1,rr===0&&(Ar=Xi,Uo()))}function gr(s){Ar===s&&rr>0||(Ar=s,rr>0&&Uo())}function ng(s){return wi.add(s),s({isUpdating:rr>0,message:Ar}),()=>{wi.delete(s)}}function og(){return{isUpdating:rr>0,message:Ar}}const Zs=Bt()(Xt(Ts((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(i=>{const l=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...l,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(l=>l.id!==n);if(i.length===0){const{[t]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(l=>l.id===n);return i?(s(l=>{const u=(l.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[t]:u}}}),i):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),ns({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Fs(()=>us()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Bl=s=>{if(!s||typeof s!="object")return null;const r={};return typeof s.showReasoningTraces=="boolean"&&(r.showReasoningTraces=s.showReasoningTraces),Object.keys(r).length>0?r:null},ag=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},ig=s=>{const r=_e.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},lg=async()=>{if(typeof window>"u")return null;if(os()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Bl(typeof t=="object"&&t!==null?t:null)}catch(t){return console.warn("Failed to load appearance preferences from desktop storage:",t),null}}const s=localStorage.getItem("appearance-preferences");if(!s)return null;try{const r=JSON.parse(s),t=ag(r);return Bl(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let bu=null;const zl=s=>{bu=s},Zr=()=>bu,Ao=s=>{typeof window>"u"||(s.themeId&&localStorage.setItem("selectedThemeId",s.themeId),s.themeVariant&&localStorage.setItem("selectedThemeVariant",s.themeVariant),s.lightThemeId&&localStorage.setItem("lightThemeId",s.lightThemeId),s.darkThemeId&&localStorage.setItem("darkThemeId",s.darkThemeId),typeof s.useSystemTheme=="boolean"&&localStorage.setItem("useSystemTheme",String(s.useSystemTheme)),s.lastDirectory&&localStorage.setItem("lastDirectory",s.lastDirectory),s.homeDirectory&&(localStorage.setItem("homeDirectory",s.homeDirectory),window.__OPENCHAMBER_HOME__=s.homeDirectory),Array.isArray(s.projects)&&s.projects.length>0?localStorage.setItem("projects",JSON.stringify(s.projects)):localStorage.removeItem("projects"),s.activeProjectId?localStorage.setItem("activeProjectId",s.activeProjectId):localStorage.removeItem("activeProjectId"),Array.isArray(s.pinnedDirectories)&&s.pinnedDirectories.length>0?localStorage.setItem("pinnedDirectories",JSON.stringify(s.pinnedDirectories)):localStorage.removeItem("pinnedDirectories"))},cg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!l||t.has(a)||(t.add(a),r.push({id:a,label:i,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},dg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},wu=()=>{const s=_e.persist;if(s&&typeof s=="object")return s},vu=()=>Zr()?.settings??null,Eo=s=>{const r=_e.getState(),t=Zs.getState();if(typeof s.showReasoningTraces=="boolean"&&s.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&s.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,s.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof s.queueModeEnabled=="boolean"&&s.queueModeEnabled!==t.queueModeEnabled&&t.setQueueMode(s.queueModeEnabled)},Wl=s=>{if(!s||typeof s!="object")return null;const r=s,t={};typeof r.themeId=="string"&&r.themeId.length>0&&(t.themeId=r.themeId),(r.useSystemTheme===!0||r.useSystemTheme===!1)&&(t.useSystemTheme=r.useSystemTheme),typeof r.themeVariant=="string"&&(r.themeVariant==="light"||r.themeVariant==="dark")&&(t.themeVariant=r.themeVariant),typeof r.lightThemeId=="string"&&r.lightThemeId.length>0&&(t.lightThemeId=r.lightThemeId),typeof r.darkThemeId=="string"&&r.darkThemeId.length>0&&(t.darkThemeId=r.darkThemeId),typeof r.lastDirectory=="string"&&r.lastDirectory.length>0&&(t.lastDirectory=r.lastDirectory),typeof r.homeDirectory=="string"&&r.homeDirectory.length>0&&(t.homeDirectory=r.homeDirectory);const n=dg(r.projects);n&&(t.projects=n),typeof r.activeProjectId=="string"&&r.activeProjectId.length>0&&(t.activeProjectId=r.activeProjectId),Array.isArray(r.approvedDirectories)&&(t.approvedDirectories=r.approvedDirectories.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.securityScopedBookmarks)&&(t.securityScopedBookmarks=r.securityScopedBookmarks.filter(a=>typeof a=="string"&&a.length>0)),Array.isArray(r.pinnedDirectories)&&(t.pinnedDirectories=Array.from(new Set(r.pinnedDirectories.filter(a=>typeof a=="string"&&a.length>0)))),typeof r.showReasoningTraces=="boolean"&&(t.showReasoningTraces=r.showReasoningTraces),typeof r.autoDeleteEnabled=="boolean"&&(t.autoDeleteEnabled=r.autoDeleteEnabled),typeof r.autoDeleteAfterDays=="number"&&Number.isFinite(r.autoDeleteAfterDays)&&(t.autoDeleteAfterDays=r.autoDeleteAfterDays),typeof r.defaultModel=="string"&&r.defaultModel.length>0&&(t.defaultModel=r.defaultModel),typeof r.defaultVariant=="string"&&r.defaultVariant.length>0&&(t.defaultVariant=r.defaultVariant),typeof r.defaultAgent=="string"&&r.defaultAgent.length>0&&(t.defaultAgent=r.defaultAgent),typeof r.autoCreateWorktree=="boolean"&&(t.autoCreateWorktree=r.autoCreateWorktree),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const o=cg(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},ug=async()=>{const s=vu();if(s)try{const r=await s.load();return Wl(r.settings)}catch(r){console.warn("Failed to load shared settings from runtime settings API:",r)}try{const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return null;const t=await r.json().catch(()=>null);return Wl(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},ju=async()=>{if(typeof window>"u")return;const s=wu(),r=t=>{Ao(t);const n=()=>Eo(t);if(s?.hasHydrated?.())n();else if(n(),s?.onFinishHydration){const o=s.onFinishHydration(()=>{o?.(),n()})}typeof window<"u"&&window.dispatchEvent(new CustomEvent("openchamber:settings-synced",{detail:t}))};try{const t=os()?await Dn():await ug();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ns=async s=>{if(typeof window>"u")return;if(os()){try{const t=await Bh(s);t&&(Ao(t),Eo(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=vu();if(r)try{const t=await r.save(s);t&&(Ao(t),Eo(t));return}catch(t){console.warn("Failed to update settings via runtime settings API:",t)}try{const t=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(s)});if(!t.ok){console.warn("Failed to update shared settings via API:",t.status,t.statusText);return}const n=await t.json().catch(()=>null);n&&(Ao(n),Eo(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Su=async()=>{if(typeof window>"u")return;const s=wu();try{const r=await lg();if(!r)return;const t=()=>ig(r);if(s?.hasHydrated?.()){t();return}if(t(),s?.onFinishHydration){const n=s.onFinishHydration(()=>{n?.(),t()})}}catch(r){console.warn("Failed to load appearance preferences:",r)}},mg=3e4,fg=40,pg=60,hg=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},Qi=Bt()(Xt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=pg){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",l=hg(a,i,o),d=Date.now(),u=r().cache[l];if(u&&d-u.timestamp<mg)return u.files;const m=r().inFlight[l];if(m)return m;const f=ke.searchFiles(i,{directory:a,limit:o}).then(p=>(s(g=>{const w={...g.cache,[l]:{files:p,timestamp:Date.now()}},h=g.cacheKeys.filter(j=>j!==l);for(h.push(l);h.length>fg;){const j=h.shift();j&&delete w[j]}return{cache:w,cacheKeys:h}}),p)).finally(()=>{s(p=>{const g={...p.inFlight};return delete g[l],{inFlight:g}})});return s(p=>({inFlight:{...p.inFlight,[l]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const i={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete i[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),qt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var gg={};let Ws=null;const zs=us(),Hl=zs.getItem("lastDirectory"),xg=typeof Hl=="string"&&Hl.length>0,ao=s=>{try{Qi.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},yg=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},bg=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},Io=(s,r)=>{const t=bg(s,r);return yg(t)},Vo=()=>{if(typeof window<"u"){const r=zs.getItem("homeDirectory")||Ws||null,t=zs.getItem("lastDirectory");if(t)return Io(t,r);if(Ws)return Ws;const n=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:window.opencodeDesktop&&typeof window.opencodeDesktop.homeDirectory=="string"?window.opencodeDesktop.homeDirectory:null;if(n&&n.length>0)return Ws=n,zs.setItem("homeDirectory",n),n;if(r)return Ws=r,r}const s=typeof process<"u"&&gg?.HOME;return s||process?.cwd?.()||"/"},wg=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");if(t.length>1){const n=t.replace(/\/+$/,"");if(n&&n.length>0)return n==="/"?null:n}return t==="/"||t.length===0?null:t},vg=s=>(Ws=s,typeof window<"u"&&zs.setItem("homeDirectory",s),ns({homeDirectory:s}),s),ku=async()=>{const s=n=>{const o=wg(n);return o?vg(o):null};try{const n=await ke.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await ke.getSystemInfo(),o=s(n?.homeDirectory);if(o)return o}catch(n){console.warn("Failed to get home directory from system info:",n)}try{const n=await gu(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Vo(),t=s(r);return t||r},Ur=Vo();Ur&&ke.setDirectory(Ur);const jg=!!(Ur&&Ur!=="/"),ct=Bt()(Xt((s,r)=>({currentDirectory:Ur,directoryHistory:[Ur],historyIndex:0,homeDirectory:Ur,hasPersistedDirectory:xg,isHomeReady:jg,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Ws||r().homeDirectory||zs.getItem("homeDirectory"),a=Io(t,o);qt()&&console.log("[DirectoryStore] setDirectory called with path:",a),ke.setDirectory(a),ao(),s(i=>{const l=[...i.directoryHistory.slice(0,i.historyIndex+1),a];return zs.setItem("lastDirectory",a),ns({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];ke.setDirectory(o),ao(),zs.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goForward:()=>{const t=r();if(t.historyIndex<t.directoryHistory.length-1){const n=t.historyIndex+1,o=t.directoryHistory[n];ke.setDirectory(o),ao(),zs.setItem("lastDirectory",o),ns({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Ws||r().homeDirectory||Vo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const l=Ws||Vo();n(l)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ws||r().homeDirectory||await ku();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Ws=o;const a=n.homeDirectory!==o,i=zs.getItem("lastDirectory"),l=typeof i=="string"&&i.length>0,d=!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||s({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?Io(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(h=>Io(h,o)),p=f.some((h,j)=>h!==n.directoryHistory[j]),g=!!(m&&m!==n.currentDirectory),w={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:u};if(d?(w.currentDirectory=o,w.directoryHistory=[o],w.historyIndex=0,w.isSwitchingDirectory=!1):(g||p)&&(w.currentDirectory=m,w.directoryHistory=f,w.historyIndex=Math.min(n.historyIndex,f.length-1),w.isSwitchingDirectory=!1),s(()=>w),(d||g)&&u){const h=d?o:m;ke.setDirectory(h),ao(),zs.setItem("lastDirectory",h),ns({lastDirectory:h})}ns({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&ku().then(s=>{ct.getState().synchronizeHomeDirectory(s)});const pn=us(),Nu="projects",vi="activeProjectId",Sg=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},ma=s=>{const r=s.trim();if(!r)return"";const t=pn.getItem("homeDirectory")||ct.getState().homeDirectory||"",o=Sg(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Cu=s=>{const r=ma(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},kg=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Mu=s=>{if(!Array.isArray(s))return[];const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=ma(l);if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},Ng=()=>{try{const s=pn.getItem(Nu);return s?Mu(JSON.parse(s)):[]}catch{return[]}},Cg=()=>{try{const s=pn.getItem(vi);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},Ji=(s,r)=>{try{pn.setItem(Nu,JSON.stringify(s))}catch{}try{r?pn.setItem(vi,r):pn.removeItem(vi)}catch{}},nn=(s,r)=>{Ji(s,r),ns({projects:s,activeProjectId:r??void 0})},Mg=Ng(),Dg=()=>{if(typeof window>"u"||!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode)return null;const r=window.__VSCODE_CONFIG__?.workspaceFolder;if(typeof r!="string"||r.trim().length===0)return null;const t=ma(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:Cu(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return qt()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Ls=Dg(),Zi=Ls?.projects??Mg,Du=Ls?.activeProjectId??Cg()??Zi[0]?.id??null;Ls&&Ji(Zi,Du);const Pt=Bt()(Xt((s,r)=>({projects:Zi,activeProjectId:Du,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=ma(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Ls)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const i=a.normalizedPath,l=r().projects.find(w=>w.path===i);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||Cu(i),m=n?.id?.trim(),p={id:m&&!r().projects.some(w=>w.id===m)?m:kg(),path:i,label:u,addedAt:d,lastOpenedAt:d},g=[...r().projects,p];return s({projects:g}),qt()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Ls)return;const n=r(),o=n.projects.filter(i=>i.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),nn(o,a),a){const i=o.find(l=>l.id===a);i&&(ke.setDirectory(i.path),ct.getState().setDirectory(i.path,{showOverlay:!1}))}else ct.getState().goHome()},setActiveProject:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),nn(l,t),ke.setDirectory(a.path),ct.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),nn(l,t)},renameProject:(t,n)=>{if(Ls)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:i}=r(),l=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:l}),nn(l,i)},reorderProjects:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const i=[...o],[l]=i.splice(t,1);i.splice(n,0,l),s({projects:i}),nn(i,a)},synchronizeFromSettings:t=>{if(Ls)return;const n=Mu(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),i=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!i&&!l)&&(s({projects:n,activeProjectId:o}),Ji(n,o),o)){const d=n.find(u=>u.id===o);d&&(ke.setDirectory(d.path),ct.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:t,activeProjectId:n}=r();return n?t.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r(),i=o.find(u=>u.id===t);if(!i)return;const l={...i.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?l.branchPrefix=n.branchPrefix.trim():delete l.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);s({projects:d}),nn(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&Pt.getState().synchronizeFromSettings(r)});const Ag=new Set(["init","review"]),mn=s=>Ag.has(s.name),zn="useCommandsStore",ji=s=>new Promise(r=>setTimeout(r,s)),io=()=>{try{const r=Pt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=ke.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},Eg=2e4,Ul=300,Vl=4,Ig=800,Pg=200,Tg=2e3,Tr=Bt()(Xt(Ts((s,r)=>({selectedCommandName:null,commands:[],isLoading:!1,commandDraft:null,setSelectedCommand:t=>{s({selectedCommandName:t})},setCommandDraft:t=>{s({commandDraft:t})},loadCommands:async()=>{s({isLoading:!0});const t=r().commands;let n=null;for(let o=0;o<3;o++)try{const a=io(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await ke.withDirectory(a,()=>ke.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${i}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const g=f.sources;p=(g.md?.exists?g.md.scope:void 0)??(g.json?.exists?g.json.scope:void 0)??g.md?.scope??g.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(t)!==JSON.stringify(d)?s({commands:d,isLoading:!1}):s({isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{Vs("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=io(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await Ea({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&sr("commands",{source:zn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Ds()}},updateCommand:async(t,n)=>{Vs("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=io(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await Ea({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&sr("commands",{source:zn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Ds()}},deleteCommand:async t=>{Vs("Deleting command configuration…");let n=!1;try{const o=io(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await Ea({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&sr("commands",{source:zn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Ds()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Fs(()=>us()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Tr);async function Fg(s){const r=typeof s=="number"&&s>0?Math.min(s,Ul):0;r>0&&await ji(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Eg;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=Vl&&a<1200?Ul:Math.min(Ig+Math.max(0,n-Vl)*Pg,Tg);await ji(i)}throw o||new Error("OpenCode did not become ready in time")}async function Ea(s={}){const{message:r,delayMs:t}=s;try{gr(r||"Refreshing commands…")}catch{}try{await Fg(t),gr("Refreshing commands…"),await Tr.getState().loadCommands(),sr("commands",{source:zn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),gr("OpenCode refresh failed. Please retry refreshing configuration manually."),await ji(1500)}finally{Ds()}}let Gl=null;Gl||(Gl=ua(s=>{if(s.source!==zn&&Xn(s,"commands")){const{loadCommands:r}=Tr.getState();r()}}));const jr=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},Po="useSkillsStore",Hs=Bt()(Xt(Ts((s,r)=>({selectedSkillName:null,skills:[],isLoading:!1,skillDraft:null,setSelectedSkill:t=>{s({selectedSkillName:t})},setSkillDraft:t=>{s({skillDraft:t})},loadSkills:async()=>{s({isLoading:!0});const t=r().skills;let n=null;for(let o=0;o<3;o++)try{const a=jr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${i}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const m=((await l.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return s({skills:m,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=jr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{Vs("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=jr(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&sr("skills",{source:Po}),d}catch{return!1}finally{Ds()}},updateSkill:async(t,n)=>{Vs("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=jr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&sr("skills",{source:Po}),u}catch{return!1}finally{Ds()}},deleteSkill:async t=>{Vs("Deleting skill...");try{const n=jr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),i=await a.json().catch(()=>null);if(!a.ok){const d=i?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&sr("skills",{source:Po}),r().selectedSkillName===t&&s({selectedSkillName:null}),l}catch{return!1}finally{Ds()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=jr(),a=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=jr(),i=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=jr(),a=o?`?directory=${encodeURIComponent(o)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${a}`,{method:"DELETE"})).ok}catch{return!1}}}),{name:"skills-store",storage:Fs(()=>us()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Hs);let Kl=null;Kl||(Kl=ua(s=>{if(s.source!==Po&&Xn(s,"skills")){const{loadSkills:r}=Hs.getState();r()}}));const Ia=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},so=Bt()(Xt((s,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:t=>s({selectedSourceId:t}),loadCatalog:async t=>{s({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const i=Ia(),l=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${l}`:l?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const h=200*(a+1);await new Promise(j=>setTimeout(j,h));continue}const f=m.sources||[],p=m.itemsBySource||{},g=r().selectedSourceId,w=g&&f.some(h=>h.id===g)?g:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:w}),!0}catch(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};const l=200*(a+1);await new Promise(d=>setTimeout(d,l))}return s({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{s({isLoadingCatalog:!1})}},scanRepo:async t=>{s({isScanning:!0,lastScanError:null,scanResults:null});try{const n=Ia(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!a.ok||!i){const l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:l}),{ok:!1,error:l}}return i.ok?(s({scanResults:i.items||[]}),i):(s({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=Ia(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!i){const l={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!i.ok){const l=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}return Hs.getState().loadSkills(),i}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),Rg=()=>{const s=ke.getDirectory();if(typeof s=="string"&&s.trim().length>0)return s;try{const r=window.__zustand_directory_store__;if(r)return r.getState().currentDirectory}catch{}return null},lo=()=>{try{const r=Pt.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=ke.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},zr=s=>{const r=s;return r.native===!0||r.builtIn===!0},Au=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},Eu=s=>s.filter(r=>!Au(r)),To="useAgentsStore",Go=s=>new Promise(r=>setTimeout(r,s)),_g=2e4,ql=300,Yl=4,Og=800,$g=200,Lg=2e3,Fr=Bt()(Xt(Ts((s,r)=>({selectedAgentName:null,agents:[],isLoading:!1,agentDraft:null,setSelectedAgent:t=>{s({selectedAgentName:t})},setAgentDraft:t=>{s({agentDraft:t})},loadAgents:async()=>{s({isLoading:!0});const t=r().agents;for(let n=0;n<3;n++)try{const o=lo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await ke.withDirectory(o,()=>ke.listAgents()),l=await Promise.all(i.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(t)!==JSON.stringify(l)?s({agents:l,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{Vs("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope),console.log("[AgentsStore] Agent config to save:",o);const a=lo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Wn({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&sr("agents",{source:To}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Ds()}},updateAgent:async(t,n)=>{Vs("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=lo(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Wn({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&sr("agents",{source:To}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Ds()}},deleteAgent:async t=>{Vs("Deleting agent configuration…");let n=!1;try{const o=lo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await Wn({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&sr("agents",{source:To}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||Ds()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return Eu(t)}}),{name:"agents-store",storage:Fs(()=>us()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=Fr);async function Bg(s){const r=typeof s=="number"&&s>0?Math.min(s,ql):0;r>0&&await Go(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<_g;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await ke.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=Yl&&a<1200?ql:Math.min(Og+Math.max(0,n-Yl)*$g,Lg);await Go(i)}throw o||new Error("OpenCode did not become ready in time")}const zg=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function Wg(s={}){const{message:r,delayMs:t}=s,n=zg(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{gr(r||"Refreshing configuration…")}catch{}try{await Bg(t);const a=et.getState(),i=Fr.getState(),l=Tr.getState(),d=Hs.getState(),u=so.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),g=n.includes("all")||n.includes("commands"),w=n.includes("all")||n.includes("skills"),h=Rg(),j=o==="projects"?Pt.getState().projects:[],b=Array.from(new Set([...h?[h]:[],...j.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&et.setState({directoryScoped:{}});const x=[];for(const N of b)m&&x.push(a.loadProviders({directory:N}).then(()=>{})),f&&x.push(a.loadAgents({directory:N}).then(()=>{}));const v=[];p&&v.push(i.loadAgents().then(()=>{})),g&&v.push(l.loadCommands().then(()=>{})),w&&(v.push(d.loadSkills().then(()=>{})),v.push(u.loadCatalog().then(()=>{}))),gr("Refreshing configuration…"),await Promise.all([...x,...v])}catch{gr("OpenCode refresh failed. Please retry."),await Go(1500)}finally{Ds()}}async function Wn(s){await Wg(s)}async function Hn(s){Vs(s?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await r.json().catch(()=>null);if(!r.ok){const o=t?.error||"Failed to reload configuration";throw new Error(o)}const n={...s,scopes:s?.scopes??["all"],mode:s?.mode??"projects"};t?.requiresReload?await Wn({...n,message:t.message,delayMs:t.reloadDelayMs}):await Wn(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),gr("Failed to reload configuration. Please try again."),await Go(2e3),Ds(),r}}let Xl=null;Xl||(Xl=ua(s=>{if(s.source!==To&&Xn(s,"agents")){const{loadAgents:r}=Fr.getState();r()}}));const Hg="https://models.dev/api.json",Ug="/api/openchamber/models-metadata",Ql="opencode",Jl="big-pickle",Vg=async()=>{try{if(os()){const i=await Dn();return{defaultModel:i?.defaultModel,defaultVariant:i?.defaultVariant,defaultAgent:i?.defaultAgent,autoCreateWorktree:i?.autoCreateWorktree}}const s=Zr()?.settings;if(s)try{const l=(await s.load())?.settings;if(l){const d=typeof l?.defaultModel=="string"?l.defaultModel.trim():"",u=typeof l?.defaultVariant=="string"?l.defaultVariant.trim():"",m=typeof l?.defaultAgent=="string"?l.defaultAgent.trim():"";return{defaultModel:d.length>0?d:void 0,defaultVariant:u.length>0?u:void 0,defaultAgent:m.length>0?m:void 0,autoCreateWorktree:typeof l?.autoCreateWorktree=="boolean"?l.autoCreateWorktree:void 0}}}catch{}const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(!r.ok)return{};const t=await r.json(),n=typeof t?.defaultModel=="string"?t.defaultModel.trim():"",o=typeof t?.defaultVariant=="string"?t.defaultVariant.trim():"",a=typeof t?.defaultAgent=="string"?t.defaultAgent.trim():"";return{defaultModel:n.length>0?n:void 0,defaultVariant:o.length>0?o:void 0,defaultAgent:a.length>0?a:void 0,autoCreateWorktree:typeof t?.autoCreateWorktree=="boolean"?t.autoCreateWorktree:void 0}}catch{return{}}},Zl=s=>{if(!s||typeof s!="string")return null;const r=s.split("/");return r.length!==2||!r[0]||!r[1]?null:{providerId:r[0],modelId:r[1]}},Gg=s=>s?.toLowerCase?.()??"",Kg=s=>s==="primary"||s==="all"||s===void 0||s===null,Qn=s=>typeof s=="object"&&s!==null,Ko=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),qg=s=>{if(!Qn(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!Ko(t)||n&&!Ko(n))return!1}return!0},Yg=s=>{if(!Qn(s))return!1;const r=s;return r.models===void 0||Qn(r.models)},Iu=(s,r)=>{const t=Gg(s);return!t||!r?"":`${t}/${r}`},Xg=s=>{const r=new Map;if(!Qn(s))return r;for(const[t,n]of Object.entries(s)){if(!Yg(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!Qn(a)))for(const[i,l]of Object.entries(a)){if(!qg(l))continue;const d=typeof i=="string"&&i.length>0?i:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:Ko(l.modalities.input)?l.modalities.input:void 0,output:Ko(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=Iu(o,d);m&&r.set(m,u)}}return r},Qg=async()=>{if(typeof fetch!="function")return new Map;const s=[Ug,Hg];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(r,a);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const l=await i.json();return Xg(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let Pa=null;const Jg=(s,r)=>{s().size>0||Pa||(Pa=Qg().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{Pa=null}))},Zg=s=>new Promise(r=>setTimeout(r,s)),el="__global__",hn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:el},on=s=>s===el?null:s,ex=()=>{if(typeof window>"u")return el;const s=ke.getDirectory()??ct.getState().currentDirectory;return hn(s)},et=Bt()(Xt(Ts((s,r)=>({activeDirectoryKey:ex(),directoryScoped:{},providers:[],agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{},isConnected:!1,isInitialized:!1,modelsMetadata:new Map,settingsDefaultModel:void 0,settingsDefaultVariant:void 0,settingsDefaultAgent:void 0,settingsAutoCreateWorktree:!1,activateDirectory:async t=>{const n=hn(t);s(o=>{const a=o.directoryScoped[n];return a?{activeDirectoryKey:n,providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentVariant:a.currentVariant,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders}:{activeDirectoryKey:n,providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}}}),r().isConnected&&(await r().loadProviders({directory:on(n)}),await r().loadAgents({directory:on(n)}))},loadProviders:async t=>{const n=hn(t?.directory??on(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),i=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{Jg(()=>r().modelsMetadata,g=>s({modelsMetadata:g}));const u=await ke.withDirectory(on(n),()=>ke.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(g=>{const w=g.models??{},h=Object.keys(w).map(j=>w[j]);return{...g,models:h}});s(g=>{const h={...g.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},j={directoryScoped:{...g.directoryScoped,[n]:h}};return g.activeDirectoryKey===n&&(j.providers=p,j.defaultProviders=f),j});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:i},f={directoryScoped:{...d.directoryScoped,[n]:m}};return d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=i),f})},setProvider:t=>{const{providers:n}=r(),o=n.find(l=>l.id===t);if(!o)return;const i=o.models[0]?.id||"";s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:t,currentModelId:i,selectedProviderId:t};return{currentProviderId:t,currentModelId:i,selectedProviderId:t,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:t};return{currentModelId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},setCurrentVariant:t=>{s(n=>{if(n.currentVariant===t)return n;const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:t};return{currentVariant:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const t=r().getCurrentModelVariants();if(t.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(t[0]);return}const o=t.indexOf(n);if(o===-1||o===t.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(t[o+1])},setSelectedProvider:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:t};return{selectedProviderId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const i=a.activeDirectoryKey,l={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[i]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[i]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=hn(t?.directory??on(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let i=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([ke.withDirectory(on(n),()=>ke.listAgents()),Vg()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(y=>{const D={...y.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},M={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,directoryScoped:{...y.directoryScoped,[n]:D}};return y.activeDirectoryKey===n&&(M.agents=m),M}),m.length===0)return s(y=>{const D={...y.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},M={directoryScoped:{...y.directoryScoped,[n]:D}};return y.activeDirectoryKey===n&&(M.currentAgentName=void 0),M}),!0;const p=(y,S)=>{const D=f.find(M=>M.id===y);return D?D.models.some(M=>M.id===S):!1},g=m.filter(y=>Kg(y.mode));let j=g.find(y=>y.name==="build")||g[0]||m[0];const b={};if(u.defaultAgent){const y=m.find(S=>S.name===u.defaultAgent);y?j=y:b.defaultAgent=""}let x,v,N;if(u.defaultModel){const y=Zl(u.defaultModel);if(y&&p(y.providerId,y.modelId)){if(x=y.providerId,v=y.modelId,u.defaultVariant){const M=f.find(C=>C.id===y.providerId)?.models.find(C=>C.id===y.modelId)?.variants;M&&Object.prototype.hasOwnProperty.call(M,u.defaultVariant)?N=u.defaultVariant:b.defaultVariant=""}}else b.defaultModel=""}if(!x&&j?.model?.providerID&&j?.model?.modelID&&p(j.model.providerID,j.model.modelID)&&(x=j.model.providerID,v=j.model.modelID),!x)if(p(Ql,Jl))x=Ql,v=Jl;else{const y=f[0];y&&y.models[0]&&(x=y.id,v=y.models[0].id)}return s(y=>{const S=y.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},D={...S,providers:f,agents:m,currentAgentName:j.name,currentProviderId:x??S.currentProviderId,currentModelId:v??S.currentModelId,currentVariant:N},M={directoryScoped:{...y.directoryScoped,[n]:D}};return y.activeDirectoryKey===n&&(M.currentAgentName=j.name,x&&v&&(M.currentProviderId=x,M.currentModelId=v,M.currentVariant=N)),M}),Object.keys(b).length>0&&(s({settingsDefaultModel:b.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:b.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:b.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),ns(b).catch(()=>{})),!0}catch(d){i=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",i),s(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:i}=r();if(s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...l.directoryScoped,[d]:m}}}),t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const d=l.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&l.setState(g=>{const w=new Map(g.currentAgentContext);return w.set(u,t),{currentAgentContext:w}}),u&&m(u)&&(p(u,t)||f(u,n))}}if(t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const{currentSessionId:u,getAgentModelForSession:m}=l.getState();if(u&&m(u,t))return}if(a){const u=Zl(a);if(u&&o.find(f=>f.id===u.providerId)?.models.some(f=>f.id===u.modelId)){s(f=>{const p=f.activeDirectoryKey,g=f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentVariant:f.currentVariant,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders};let w;if(i){const x=o.find(v=>v.id===u.providerId)?.models.find(v=>v.id===u.modelId)?.variants;x&&Object.prototype.hasOwnProperty.call(x,i)&&(w=i)}const h={...g,currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:w};return{currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:w,directoryScoped:{...f.directoryScoped,[p]:h}}});return}}const d=n.find(u=>u.name===t);if(d?.model?.providerID&&d?.model?.modelID){const u=o.find(m=>m.id===d.model.providerID);u&&u.models.find(f=>f.id===d.model.modelID)&&s(f=>{const p=f.activeDirectoryKey,w={...f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders},currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID};return{currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID,directoryScoped:{...f.directoryScoped,[p]:w}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultVariant:t=>{s({settingsDefaultVariant:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await ke.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await Zg(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=qt();t&&console.log("Starting app initialization...");const n=await r().checkConnection();if(t&&console.log("Connection check result:",n),!n){t&&console.log("Server not connected"),s({isConnected:!1});return}t&&console.log("Initializing app..."),await ke.initApp(),t&&console.log("Loading providers..."),await r().loadProviders(),t&&console.log("Loading agents..."),await r().loadAgents(),s({isInitialized:!0,isConnected:!0}),t&&console.log("App initialized successfully")}catch(t){console.error("Failed to initialize app:",t),s({isInitialized:!1,isConnected:!1})}},getCurrentProvider:()=>{const{providers:t,currentProviderId:n}=r();return t.find(o=>o.id===n)},getCurrentModel:()=>{const t=r().getCurrentProvider(),{currentModelId:n}=r();if(t)return t.models.find(o=>o.id===n)},getCurrentAgent:()=>{const{agents:t,currentAgentName:n}=r();if(n)return t.find(o=>o.name===n)},getModelMetadata:(t,n)=>{const o=Iu(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return Eu(t)}}),{name:"config-store",storage:Fs(()=>us()),partialize:()=>({})}),{name:"config-store"}));typeof window<"u"&&(window.__zustand_config_store__=et);let ec=null;ec||(ec=ua(async s=>{const r=[];if(Xn(s,"agents")){const{loadAgents:t}=et.getState();r.push(t().then(()=>{}))}if(Xn(s,"providers")){const{loadProviders:t}=et.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let tc=null;typeof window<"u"&&!tc&&(tc=ct.subscribe((s,r)=>{const t=hn(s.currentDirectory),n=hn(r.currentDirectory);t!==n&&et.getState().activateDirectory(s.currentDirectory)}));const ds={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},tx=180,ks=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function en(s){const r=ks();return r?r.checkIsGitRepository(s):kh(s)}async function sx(s){const r=ks();return r?r.getGitStatus(s):Ch(s)}async function tl(s){const r=ks();return r?r.getGitBranches(s):Oh(s)}async function rx(s,r){const t=ks();return t?t.deleteGitBranch(s,r):Dh(s,r)}async function nx(s,r){const t=ks();return t?t.deleteRemoteBranch(s,r):Ah(s,r)}async function ox(s){const r=ks();return r?r.listGitWorktrees(s):Nh(s)}async function ax(s,r){const t=ks();return t?t.addGitWorktree(s,r):Eh(s,r)}async function Pu(s,r){const t=ks();return t?t.removeGitWorktree(s,r):Mh(s,r)}async function ix(s){const r=ks();return r?r.ensureOpenChamberIgnored(s):_h(s)}async function lx(){const s=ks();return s?s.getGitIdentities():Rh()}async function cx(s){const r=ks();return r?r.createGitIdentity(s):Th(s)}async function dx(s,r){const t=ks();return t?t.updateGitIdentity(s,r):Ph(s,r)}async function ux(s){const r=ks();return r?r.deleteGitIdentity(s):Ih(s)}async function mx(s){const r=ks();return r?r.getCurrentGitIdentity(s):Fh(s)}const fx="openchamber.json",Tu=".openchamber";function Fu(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const px=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Si=(s,r)=>{const t=px(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Ru=s=>Si(Si(s,Tu),fx);async function _u(s){const r=Ru(s);try{const t=Fu();if(t?.readFile)try{const i=await t.readFile(r);if(!i.content.trim())return null;const l=JSON.parse(i.content);return!l||typeof l!="object"?null:l}catch{return null}const n=await fetch(`${$u()}/fs/read?path=${encodeURIComponent(r)}`);if(!n.ok)return n.status===404,null;const o=await n.text();if(!o.trim())return null;const a=JSON.parse(o);return!a||typeof a!="object"?null:a}catch{return null}}async function hx(s,r){const t=Ru(s),n=Si(s,Tu);try{await ke.createDirectory(n);const o=Fu();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(i){return console.error("Failed to write openchamber config via runtime API:",i),!1}return(await fetch(`${$u()}/fs/write`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:t,content:JSON.stringify(r,null,2)})})).ok}catch(o){return console.error("Failed to write openchamber config:",o),!1}}async function gx(s,r){const n={...await _u(s)||{},...r};return hx(s,n)}async function ro(s){return(await _u(s))?.["setup-worktree"]??[]}async function Ou(s,r){const t=r.filter(n=>n.trim().length>0);return gx(s,{"setup-worktree":t})}function xx(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function $u(){const s="/api";return s.startsWith("/"),s}const yx=".openchamber",sc="/api";function bx(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const wr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},rc=(s,r)=>{const t=wr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Lu=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",wx=async s=>{try{await ke.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function vx(s,r){const t=wr(s),n=rc(t,yx);return await wx(n),rc(n,r)}async function Bu(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=wr(r),l=await vx(i,t),d={path:l,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await ax(i,d),{path:l,branch:n,label:Lu(n),projectDirectory:i,relativePath:l.startsWith(`${i}/`)?l.slice(i.length+1):l}}async function jx(s){const{projectDirectory:r,path:t,force:n}=s,o=wr(r);await Pu(o,{path:t,force:n})}async function zu(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,l=wr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Pu(l,{path:t,force:o}),d&&(await rx(l,{branch:d,force:!0}),a))try{await nx(l,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function vn(s){const r=wr(s);return ox(r)}async function sl(s){const r=wr(s),t=await sx(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function jn(s,r){const t=wr(s),n=wr(r.worktree);return{path:n,branch:r.branch??"",label:Lu(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function Wu(s,r,t){const n=t??await ro(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>xx(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=bx();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,s);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const i=await fetch(`${sc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),l=await i.json().catch(()=>null);if(i.status===202&&l&&typeof l.jobId=="string"){const d=l.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(h=>setTimeout(h,u));const p=await fetch(`${sc}/fs/exec/${d}`,{method:"GET"}),g=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(h=>({command:h,success:!1,error:g&&g.error||"Failed to poll exec job"}))};if(g?.status==="done"){const h=Array.isArray(g?.results)?g.results:[];return{success:g?.success===!0,results:h}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!i.ok){const d=l&&l.error||"Request failed";return console.error("[worktreeService] Web exec failed:",l),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",l),l}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(i=>({command:i,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const Hu=us(),Uu="oc.sessionSelectionByDirectory",Ta=".openchamber",Sx=()=>{try{const s=Hu.getItem(Uu);if(!s)return{};const r=JSON.parse(s);return!r||typeof r!="object"?{}:Object.entries(r).reduce((t,[n,o])=>(typeof n=="string"&&typeof o=="string"&&n.length>0&&o.length>0&&(t[n]=o),t),{})}catch{return{}}};let Fo=null;const rl=()=>(Fo||(Fo=Sx()),Fo),Vu=s=>{Fo=s;try{Hu.setItem(Uu,JSON.stringify(s))}catch{}},Gu=s=>{if(!s)return null;const t=rl()[s];return typeof t=="string"?t:null},cr=(s,r)=>{if(!s)return;const t={...rl()};r?t[s]=r:delete t[s],Vu(t)},kx=(s,r)=>{if(!s)return;const t=Gu(s);if(!t)return;if(!new Set(r).has(t)){const o={...rl()};delete o[s],Vu(o)}},nc=async(s,r)=>{const t=s.status??await sl(s.path).catch(()=>{});await zu({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},gt=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},oc=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return gt(r)},Nx=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,co=(...s)=>{qt()&&Nx()&&console.log("[OpenChamber][VSCode][sessions]",...s)},Sr=s=>{const r=new Map;return s.forEach(t=>{if(!t||typeof t.id!="string"||t.id.length===0)return;const n=r.get(t.id);if(!n){r.set(t.id,t);return}const o=n.time?.updated??0;(t.time?.updated??0)>o&&r.set(t.id,t)}),Array.from(r.values())},_s=s=>{const r=new Map;s.forEach(t=>{const n=gt(t.directory??null);if(!n)return;const o=r.get(n);o?o.push(t):r.set(n,[t])});for(const[t,n]of r.entries())r.set(t,Sr(n));return r},an=(s,r)=>{const t=s.find(n=>n.id===r);return t?gt(t.directory??null):null},Cx=async(s,r,t)=>{const n=gt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:gt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await vn(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const i=new Map;a.forEach(u=>{const m=jn(n,u),f=gt(m.path)??m.path;f!==n&&i.set(f,m)});let l=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},it=Bt()(Xt(Ts((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,error:null,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,loadSessions:async()=>{s({isLoading:!0,error:null});try{const t=ct.getState(),n=Pt.getState(),o=ke.getApiClient(),a=oc(),i=!!a;co("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:ke.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async B=>{const re=gt(B)??B,Y=re,_=l.get(Y);if(_)return _;try{const q=await o.path.get({directory:B}),z=gt(q.data?.directory??null)??re;return l.set(Y,z),z}catch{return l.set(Y,re),re}},u=(B,re,Y)=>{const _=gt(re);if(!_)return B;const O=Y?.includeDescendants===!0?`${_}/`:null,z=Y?.includeMissingDirectory===!0;return B.filter(U=>{const ne=gt(U.directory??null);return ne?!!(ne===_||O&&ne.startsWith(O)):z})},m=(B,re,Y)=>{const _=gt(re);if(!_)return B;const q=gt(Y??null);if(!q||q===_)return B.map(U=>gt(U.directory??null)?U:{...U,directory:_});const O=q==="/"?"/":`${q}/`,z=_==="/"?"/":`${_}/`;return B.map(U=>{const ne=gt(U.directory??null);if(!ne)return{...U,directory:_};if(ne===q)return{...U,directory:_};if(O!=="/"&&ne.startsWith(O)){const oe=ne.slice(O.length);return{...U,directory:`${z}${oe}`}}return U})},f=async B=>{const re=gt(B);if(!re)try{const ne=await o.session.list(void 0);return Array.isArray(ne.data)?ne.data:[]}catch(ne){throw console.debug("Failed to list sessions (global):",ne),ne}const Y=await d(re),_=async()=>{const ne=await o.session.list({directory:re});return Array.isArray(ne.data)?ne.data:[]};let q=[],O=null,z=!1;try{q=await _()}catch(ne){console.debug("Failed to list sessions for directory:",re,ne),O=ne,q=[]}if(q.length===0){z=!0;try{const ne=await o.session.list(void 0),oe=Array.isArray(ne.data)?ne.data:[];q=u(oe,Y,{includeDescendants:i,includeMissingDirectory:!1})}catch(ne){throw console.debug("Failed to list sessions (global fallback):",ne),O||ne}}const U=u(q,Y,{includeDescendants:i,includeMissingDirectory:!z});return co("fetchSessionsForDirectory",{requestedDirectory:re,canonicalDirectory:Y,fetched:q.length,filtered:U.length}),m(U,re,Y)},p=gt(t.currentDirectory??ke.getDirectory()??null),g=n.projects.find(B=>B.id===n.activeProjectId)??null,w=gt(g?.path??null),h=w??p??null,j=n.projects.length>0?n.projects:h?[{id:"legacy",path:h}]:[];if(j.length===0){s({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const b=await Promise.all(j.map(async B=>{const re=gt(B.path);if(!re)return{projectId:B.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const Y=await en(re).catch(()=>!1),_=await f(re||null);co("projectSessions",{projectId:B.id,projectPath:re,isGitRepo:Y,parentSessions:_.length});const q=[];let O=[];const z=new Set;if(z.add(re),Y){const ne=`${re}/${Ta}`;try{const oe=new Set;(await ke.listLocalDirectory(re)).some(W=>W.isDirectory&&W.name===Ta)&&(await ke.listLocalDirectory(ne)).filter(F=>F.isDirectory).forEach(F=>{const L=/^([A-Za-z]:)?\//.test(F.path)?F.path:`${ne}/${F.name}`,J=gt(L)??L;oe.add(J)});const I=await vn(re);Array.isArray(I)&&(O=I.map(W=>jn(re,W)).filter(W=>W.path.includes(`/${Ta}/`)),O.forEach(W=>oe.add(W.path))),oe.forEach(W=>{const F=gt(W)??W;z.add(F)}),oe.size>0&&(await Promise.allSettled(Array.from(oe).map(F=>f(F)))).forEach(F=>{F.status==="fulfilled"&&Array.isArray(F.value)&&q.push(...F.value)})}catch{O=[]}}const U=Sr([..._,...q]);return{projectId:B.id,projectPath:re,sessions:U,discoveredWorktrees:O,validPaths:z}})),x=new Map;b.forEach(B=>{B.projectPath&&B.validPaths.forEach(re=>{const Y=gt(re)??re,_=B.sessions.filter(q=>(gt(q.directory??null)??Y)===Y);x.set(Y,Sr(_))})});const v=Sr(Array.from(x.values()).flat()),N=r();let y=N.worktreeMetadata;for(const B of b)if(B.projectPath)try{const re=await Cx(B.sessions,B.projectPath,y);re&&(y=re)}catch(re){console.debug("Failed to refresh worktree metadata during session load:",re)}const S=new Map;b.forEach(B=>{B.projectPath&&S.set(B.projectPath,B.discoveredWorktrees)});const D=new Set;b.forEach(B=>{B.validPaths.forEach(re=>{const Y=gt(re)??re;Y&&D.add(Y)})});const M=p??w??null,C=M&&D.has(M)?M:w??M,k=C?x.get(C)??[]:v,A=new Set(v.map(B=>B.id));for(const[B,re]of x.entries())kx(B,re.map(Y=>Y.id));const E=(C??null)!==(N.lastLoadedDirectory??null);let R=N.currentSessionId;if((!R||!A.has(R)||E)&&(R=k[0]?.id??v[0]?.id??null),C){const B=Gu(C);B&&A.has(B)&&(R=B)}const V=(()=>{if(!R)return C??null;const B=y.get(R)?.path;if(B)return gt(B)??B;const re=an(v,R);return re||(C??null)})();try{ke.setDirectory(V??void 0)}catch(B){console.warn("Failed to sync OpenCode directory after session load:",B)}const T=w?b.find(B=>B.projectPath===w)?.discoveredWorktrees??[]:[];s({sessions:v,sessionsByDirectory:x,currentSessionId:R,lastLoadedDirectory:C??null,isLoading:!1,worktreeMetadata:y,availableWorktrees:T,availableWorktreesByProject:S}),C&&cr(C,R),V&&V!==C&&cr(V,R)}catch(t){s({error:t instanceof Error?t.message:"Failed to load sessions",isLoading:!1})}},createSession:async(t,n,o)=>{s({error:null});const a=ct.getState(),i=gt(a.currentDirectory),l=oc(),d=l??gt(n??ke.getDirectory()??i);co("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(h=>h.id)),p={id:u,title:t||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(h=>{const j=[p,...h.sessions],b=new Map(h.sessionsByDirectory);if(d){const x=b.get(d)??[];b.set(d,Sr([p,...x]))}return{sessions:j,sessionsByDirectory:b,currentSessionId:u,webUICreatedSessions:new Set([...h.webUICreatedSessions,u]),isLoading:!1}}),d)try{ke.setDirectory(d)}catch(h){console.warn("Failed to sync OpenCode directory after session creation:",h)}const g=h=>{const j=d??null,b=j?{...h,directory:j}:h;s(x=>{const v=x.sessions.map(y=>y.id===u?b:y),N=new Map(x.sessionsByDirectory);if(d){const S=(N.get(d)??[]).map(D=>D.id===u?b:D);N.set(d,Sr(S))}return{sessions:v,sessionsByDirectory:_s(v),currentSessionId:b.id,webUICreatedSessions:new Set([...Array.from(x.webUICreatedSessions).filter(y=>y!==u),b.id])}}),cr(d??null,b.id)},w=async()=>{const h=ke.getApiClient(),j=20;for(let b=0;b<j;b+=1){try{const x=await h.session.list(d?{directory:d}:void 0),N=(Array.isArray(x.data)?x.data:[]).find(y=>!(f.has(y.id)||t&&y.title&&y.title!==t));if(N)return N}catch(x){console.debug("Session poll attempt failed:",x)}await new Promise(x=>setTimeout(x,2e3))}return null};try{const h=()=>ke.createSession({title:t,parentID:o??void 0});let j=null;try{j=d?await ke.withDirectory(d,h):await h()}catch(b){console.warn("Direct session create failed or timed out, falling back to polling:",b)}return j||(j=await w()),j?(g(j),j):(s(b=>({sessions:b.sessions.filter(x=>x.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(x=>x!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(h){return s(j=>({sessions:j.sessions.filter(b=>b.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(j.webUICreatedSessions).filter(b=>b!==u)),isLoading:!1,error:h instanceof Error?h.message:"Failed to create session"})),null}},deleteSession:async(t,n)=>{s({isLoading:!0,error:null});const o=r().worktreeMetadata.get(t),a=an(r().sessions,t),i=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await nc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>ke.deleteSession(t);if(!(i?await ke.withDirectory(i,d):await d()))return s(p=>{const g={isLoading:!1,error:"Failed to delete session"};if(l){const w=new Map(p.worktreeMetadata);w.delete(t),g.worktreeMetadata=w}return g}),!1;let m=null;s(p=>{const g=p.sessions.filter(b=>b.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const w=new Map(p.worktreeMetadata);w.delete(t);const h=n?.archiveWorktree&&o?p.availableWorktrees.filter(b=>gt(b.path)!==gt(o.path)):p.availableWorktrees,j=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const b=gt(o.projectDirectory)??o.projectDirectory,x=j.get(b)??[];j.set(b,x.filter(v=>gt(v.path)!==gt(o.path)))}return{sessions:g,sessionsByDirectory:_s(g),currentSessionId:m,isLoading:!1,worktreeMetadata:w,availableWorktrees:h,availableWorktreesByProject:j}});const f=i??ke.getDirectory()??null;return cr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(l?m=>{const f=new Map(m.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(j=>typeof j=="string"&&j.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const i=[],l=[],d=new Set,u=[],m=new Set;for(const j of o)try{const b=r().worktreeMetadata.get(j),x=an(r().sessions,j),v=b?.path??x;b&&n?.archiveWorktree&&!m.has(b.path)&&(await nc(b,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(j),u.push({path:b.path,projectDirectory:b.projectDirectory}),m.add(b.path));const N=()=>ke.deleteSession(j);(v?await ke.withDirectory(v,N):await N())?(i.push(j),b?.path&&!u.some(S=>S.path===b.path)&&u.push({path:b.path,projectDirectory:b.projectDirectory})):l.push(j)}catch{l.push(j)}const f=ct.getState();u.forEach(({path:j,projectDirectory:b})=>{f.currentDirectory===j&&f.setDirectory(b,{showOverlay:!1})});const p=new Set(i),g=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let w=null;s(j=>{const b=j.sessions.filter(S=>!p.has(S.id));j.currentSessionId&&p.has(j.currentSessionId)?w=null:w=j.currentSessionId;const x=new Map(j.worktreeMetadata);for(const S of p)x.delete(S);for(const S of d)x.delete(S);const v=new Set(u.map(S=>gt(S.path)).filter(S=>!!S)),N=v.size>0?j.availableWorktrees.filter(S=>!v.has(gt(S.path)??S.path)):j.availableWorktrees,y=new Map(j.availableWorktreesByProject);return u.length>0&&u.reduce((D,M)=>{const C=gt(M.projectDirectory)??M.projectDirectory,k=gt(M.path)??M.path;return D.has(C)||D.set(C,new Set),D.get(C)?.add(k),D},new Map).forEach((D,M)=>{const k=(y.get(M)??[]).filter(A=>!D.has(gt(A.path)??A.path));y.set(M,k)}),{sessions:b,sessionsByDirectory:_s(b),currentSessionId:w,...a?{}:{isLoading:!1,error:g},worktreeMetadata:x,availableWorktrees:N,availableWorktreesByProject:y}});const h=ke.getDirectory()??null;return cr(h,w),{deletedIds:i,failedIds:l}},updateSessionTitle:async(t,n)=>{try{const o=an(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>ke.updateSession(t,n),l=a?.path??o,d=l?await ke.withDirectory(l,i):await i();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:_s(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=an(r().sessions,t),o=ke.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??ke.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=i?await ke.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=an(r().sessions,t),o=ke.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??ke.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=i?await ke.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{s({currentSessionId:t,error:null});const n=ke.getDirectory()??null;cr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=gt(t)??t,{sessionsByDirectory:o,sessions:a}=r(),i=o.get(n);return i||a.filter(l=>(gt(l.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return gt(n.path)??n.path;const o=r().sessions.find(i=>i.id===t);return gt(o?.directory??null)},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(g=>g.id===t);if(a===-1)return o;const i=o.sessions[a],l=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,m={...i,...n,time:l,summary:d,share:u},f=m.title!==i.title||m.parentID!==i.parentID||m.directory!==i.directory||m.version!==i.version||m.projectID!==i.projectID||JSON.stringify(m.time)!==JSON.stringify(i.time)||JSON.stringify(m.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=f?m:i,{sessions:p,sessionsByDirectory:_s(p)}})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=r();return n.has(t)},markSessionAsOpenChamberCreated:t=>{s(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=r();n(t)},setWorktreeMetadata:(t,n)=>{t&&s(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return r().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=r().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const l=o[a].directory??null,d=n??void 0;l!==(d??null)&&(s(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:_s(m)}}),l&&cr(l,null),n&&cr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(l=>l.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(l=>l.id===t.id?t:l),i=Sr(a);return{sessions:i,sessionsByDirectory:_s(i)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=gt(o?.directory??null),i=n.sessions.filter(u=>u.id!==t);if(i.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&cr(a,null),{sessions:i,sessionsByDirectory:_s(i),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Fs(()=>us()),partialize:s=>({currentSessionId:s.currentSessionId,sessions:s.sessions,lastLoadedDirectory:s.lastLoadedDirectory,webUICreatedSessions:Array.from(s.webUICreatedSessions),worktreeMetadata:Array.from(s.worktreeMetadata.entries()),availableWorktrees:s.availableWorktrees,availableWorktreesByProject:Array.from(s.availableWorktreesByProject.entries())}),merge:(s,r)=>{if(!(p=>typeof p=="object"&&p!==null)(s))return r;const n=Array.isArray(s.sessions)?s.sessions:r.sessions,o=typeof s.currentSessionId=="string"||s.currentSessionId===null?s.currentSessionId:r.currentSessionId,a=Array.isArray(s.webUICreatedSessions)?s.webUICreatedSessions:[],i=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],l=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=Array.isArray(s.availableWorktreesByProject)?s.availableWorktreesByProject:[],u=new Map(d),m=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null,f=Sr(n);return{...r,...s,sessions:f,sessionsByDirectory:_s(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),Ku="This message comes from an AI assistant in another session. The user wants you to respond according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed. Always clearly state what you understand your task to be, and wait for the user's approval of your conclusions before taking any further actions.",Mx="This message bellow comes from an AI agent in another session. I want you to act according to its content: if it is an implementation plan, your task is to implement that plan; if it is a conclusion or summary, your task is to verify it, explain whether you agree or disagree, and correct it if needed; if it is a bug description, find the root cause and fix it. Proceed with actions right away based on your understanding of the task. Here is the content of the message: ",Fa=s=>typeof s=="string"&&s.trim()===Ku.trim(),Ra=(s,r)=>{const t=Date.now(),n=s.get(r),o=new Map(s);return o.set(r,{phase:"streaming",startedAt:n?.startedAt??t,lastUpdateAt:t}),o},Pn=(s,r)=>{const t=Array.from(r);if(!t.some(a=>s.has(a)))return s;const o=new Map(s);return t.forEach(a=>{o.delete(a)}),o},ac=new Map,qu=s=>{const r=ac.get(s);r&&(clearTimeout(r),ac.delete(s))},Or=s=>{for(const r of s)qu(r)},Jn=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>Jn(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>Jn(r)).join("")}return""},Un=s=>{if(!s)return"";const r=s;if(typeof r.text=="string")return r.text;if(Array.isArray(r.text))return r.text.map(n=>typeof n=="string"?n:Un(n)).join("");const t=Jn(r.delta);return t||(typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(n=>{if(typeof n=="string")return n;if(n&&typeof n=="object"){const o=n;return o.text||Jn(o.delta)||""}return""}).join(""):"")},Tn=(s,r)=>{const t={...s};if(t.type=t.type||"text",t.type==="text"){const n=r&&typeof r.text=="string"?r.text:"",o=typeof t.text=="string"?t.text:"",a=Jn(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},ic=10*1024*1024,Dx=s=>{const r=(s||"").toLowerCase();switch(r.includes(".")&&r.split(".").pop()||""){case"png":return"image/png";case"jpg":case"jpeg":return"image/jpeg";case"gif":return"image/gif";case"webp":return"image/webp";case"svg":return"image/svg+xml";case"bmp":return"image/bmp";case"ico":return"image/x-icon";case"pdf":return"application/pdf";default:return"text/plain"}},Ax=s=>{if(s.type&&s.type.trim().length>0)return s.type;const r=(s.name||"").toLowerCase(),t=r.includes(".")&&r.split(".").pop()||"";if(new Set(["license","readme","changelog","notice","authors","copying"]).has(r))return"text/plain";switch(t){case"md":case"markdown":return"text/markdown";case"txt":return"text/plain";case"json":return"application/json";case"yaml":case"yml":return"application/x-yaml";case"ts":case"tsx":case"js":case"jsx":case"mjs":case"cjs":case"py":case"rb":case"sh":case"bash":case"zsh":return"text/plain";default:return"application/octet-stream"}},Ex=s=>{const r=s.replace(/\s+/g,"");if(!r)return 0;const t=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(r.length*3/4)-t},Ix=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],i=s[n+2],l=o<<16|(a??0)<<8|(i??0);t+=r[l>>18&63],t+=r[l>>12&63],t+=typeof a=="number"?r[l>>6&63]:"=",t+=typeof i=="number"?r[l&63]:"="}return t},er=Bt()(Xt(Ts((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(w=>w.filename===t.name&&w.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=ic;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=Ax(t);!i.some(w=>l.startsWith(w)||l===w||l==="")&&l!==""&&console.warn(`File type "${l}" might not be supported`);const u=new FileReader,m=await new Promise((w,h)=>{u.onload=()=>w(u.result),u.onerror=h,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${l}`):m,p=w=>{const h=w.replace(/\\/g,"/").split("/");return h[h.length-1]||w},g={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:l,filename:p(t.name),size:t.size,source:"local"};s(w=>({attachedFiles:[...w.attachedFiles,g]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=r();if(a.some(b=>b.serverPath===t&&b.source==="server")){console.log(`Server file "${n}" is already attached`);return}let l=o,d,u;if(!l)try{const b=ke.getApiClient(),x=t.lastIndexOf("/"),v=x>0?t.substring(0,x):"/",N=x>0?t.substring(x+1):t,y=await b.file.read({path:N,directory:v});y.data&&"content"in y.data?(l=y.data.content,d=y.data.encoding??void 0,u=y.data.mimeType??void 0):l=""}catch(b){console.error("Failed to read server file:",b),l=`[File: ${n}]`}const m=u||Dx(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const x=new TextEncoder().encode(l||"");return Ix(x)})(),g=d==="base64"?Ex(p):new TextEncoder().encode(l||"").length;if(g>ic)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const w=new File([],n,{type:f}),h=`data:${f};base64,${p}`,j={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:w,dataUrl:h,mimeType:f,filename:n,size:g,source:"server",serverPath:t};s(b=>({attachedFiles:[...b.attachedFiles,j]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:Fs(()=>us()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),Px=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Tx=s=>s?Px.has(s.toLowerCase()):!1,Fx=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Rx=s=>{if(s)try{const r=Fx();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},_x=(s,r)=>{if(!s||s.length===0)return"ask";for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission===r&&n.pattern==="*")return n.action}for(let t=s.length-1;t>=0;t-=1){const n=s[t];if(n.permission==="*"&&n.pattern==="*")return n.action}return"ask"},Ro=s=>{const r=Rx(s);return r?_x(r.permission,"edit"):"ask"},lc=s=>{if(!s||typeof s!="object")return 0;const r=s.input??0,t=s.output??0,n=s.reasoning??0,o=s.cache&&typeof s.cache=="object"?s.cache.read??0:0,a=s.cache&&typeof s.cache=="object"?s.cache.write??0:0;return r+t+n+o+a},_a=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return lc(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:lc(t.tokens)},Oa=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),l=Math.min(i,n),d=n>0?Math.max(n-l,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},Fn=["ask","allow","full"],xt=Bt()(Xt(Ts((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(i=>{const l=new Map(i.sessionAgentModelSelections);let d=l.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(t,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},saveAgentModelVariantForSession:(t,n,o,a,i)=>{s(l=>{const d=new Map(l.sessionAgentModelVariantSelections);let u=d.get(t);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return i===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,m),d.set(t,u))):(m.set(f,i),u.set(n,m),d.set(t,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(t,n,o,a)=>{const{sessionAgentModelVariantSelections:i}=r(),l=i.get(t);if(!l)return;const d=l.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:i}=r(),l=new Map,d=(p,g)=>{if("mode"in p&&p.mode&&typeof p.mode=="string"&&n.find(b=>b.name===p.mode))return p.mode;if(p.providerID&&p.modelID){const j=n.find(b=>b.model?.providerID===p.providerID&&b.model?.modelID===p.modelID);if(j)return j.name}const{currentAgentContext:w}=r(),h=w.get(t);if(h&&n.find(j=>j.name===h))return h;if(g>0&&p.providerID&&p.modelID){const b=(o.get(t)||[]).filter(x=>x.info.role==="assistant").sort((x,v)=>x.info.time.created-v.info.time.created);for(let x=g-1;x>=0;x--){const N=b[x].info;if(N.providerID===p.providerID&&N.modelID===p.modelID){if(N.mode&&typeof N.mode=="string"&&n.find(D=>D.name===N.mode))return N.mode;const y=n.find(S=>S.model?.providerID===N.providerID&&S.model?.modelID===N.modelID);if(y)return y.name}}}return p.providerID&&p.modelID&&n.find(b=>b.name==="build")?"build":null},u=o.get(t)||[],m=u.filter(p=>p.info.role==="assistant"||p.info.role==="user").sort((p,g)=>p.info.time.created-g.info.time.created),f=u.filter(p=>p.info.role==="assistant").sort((p,g)=>p.info.time.created-g.info.time.created);for(let p=0;p<m.length;p++){const g=m[p],{info:w}=g,h=w;if(h.providerID&&h.modelID){const j=d(h,f.indexOf(g));if(j&&n.find(b=>b.name===j)){const b=typeof h.variant=="string"&&h.variant.trim().length>0?h.variant:void 0;b&&i(t,j,h.providerID,h.modelID,b);const x={providerId:h.providerID,modelId:h.modelID,timestamp:w.time.created},v=l.get(j);(!v||x.timestamp>v.timestamp)&&l.set(j,x)}}}for(const[p,g]of l)a(t,p,g.providerId,g.modelId);return l},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=Oa(0,n,o),l=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(l===0||u===0)return null;const f=(a.get(t)||[]).filter(v=>v.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],g=p.info.id,w=v=>{const N=()=>{s(y=>{const S=y.sessionContextUsage.get(t);if(S&&S.totalTokens===v.totalTokens&&S.percentage===v.percentage&&S.contextLimit===v.contextLimit&&(S.outputLimit??0)===(v.outputLimit??0)&&(S.normalizedOutput??0)===(v.normalizedOutput??0)&&S.thresholdLimit===v.thresholdLimit&&S.lastMessageId===v.lastMessageId)return y;const D=new Map(y.sessionContextUsage);return D.set(t,v),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},h=r().sessionContextUsage.get(t);if(h&&h.lastMessageId===g){const v=h.normalizedOutput??h.outputLimit??0,N=h.contextLimit!==l||v!==d||h.thresholdLimit!==u;if(N&&h.totalTokens>0){const y=h.totalTokens/u*100,S={totalTokens:h.totalTokens,percentage:Math.min(y,100),contextLimit:l,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:g};return w(S),S}if(!N&&h.totalTokens>0)return h}const j=_a(p);if(j===0)return h||null;const b=Oa(j,n,o),x={totalTokens:j,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:g};return w(x),x},updateSessionContextUsage:(t,n,o,a)=>{const l=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=_a(d);if(u===0)return;const m=Oa(u,n,o);s(f=>{const p=new Map(f.sessionContextUsage);return p.set(t,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const l=r().sessionContextUsage.get(t);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const l=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&_a(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Ro(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Ro(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||Fn.includes(o)&&s(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Ro(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),l=Fn.indexOf(i),d=Fn.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%Fn.length,f=Fn[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Fs(()=>us()),partialize:s=>({sessionModelSelections:Array.from(s.sessionModelSelections.entries()),sessionAgentSelections:Array.from(s.sessionAgentSelections.entries()),sessionAgentModelSelections:Array.from(s.sessionAgentModelSelections.entries()).map(([r,t])=>[r,Array.from(t.entries())]),sessionAgentModelVariantSelections:Array.from(s.sessionAgentModelVariantSelections.entries()).map(([r,t])=>[r,Array.from(t.entries()).map(([n,o])=>[n,Array.from(o.entries())])]),currentAgentContext:Array.from(s.currentAgentContext.entries()),sessionContextUsage:Array.from(s.sessionContextUsage.entries()),sessionAgentEditModes:Array.from(s.sessionAgentEditModes.entries()).map(([r,t])=>[r,Array.from(t.entries())])}),merge:(s,r)=>{const t=new Map;s?.sessionAgentModelSelections&&s.sessionAgentModelSelections.forEach(([a,i])=>{t.set(a,new Map(i))});const n=new Map;s?.sessionAgentModelVariantSelections&&s.sessionAgentModelVariantSelections.forEach(([a,i])=>{const l=new Map;i.forEach(([d,u])=>{l.set(d,new Map(u))}),n.set(a,l)});const o=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([a,i])=>{o.set(a,new Map(i))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),cc=(s,r)=>{const t=new Map(s);return t.delete(r),t};let $a=[],La=null;const Ox=50,$x=3e4,$r=new Map,uo=new Map,ln=new Map,Lx=10,qo=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.indexOf("_"),n=t>=0?r.slice(t+1):r;return!n||n.length<Lx?null:n},mo=(s,r)=>{const t=qo(s),n=qo(r);return!t||!n||t.length!==n.length?!0:t>n},Bx=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},fn=s=>!Array.isArray(s)||s.length===0?0:s.reduce((r,t)=>{if(!t||t.type!=="text")return r;const n=t.text??t.content;return typeof n=="string"?r+n.length:r},0),Yo=s=>s?.finish==="stop",dc=s=>{if(s){if(typeof s.id=="string"&&s.id.length>0)return s.id;if(s.type){const r=s.reason,t=s.callID;return`${s.type}-${r??""}-${t??""}`}}},uc=new Set,Xo=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(dc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=dc(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},zx=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=fn(t),a=fn(n),i=Yo(s.info),l=Yo(r.info);let d=n;return i&&o>=a?d=Xo(t,n):l&&a>=o?d=Xo(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},Ba=s=>{const r=[],t=new Map;for(const n of s){const o=typeof n?.info?.id=="string"?n.info.id:null;if(!o){r.push(n);continue}const a=t.get(o);if(a===void 0){t.set(o,r.length),r.push(n);continue}r[a]=zx(r[a],n)}return r},Wx=(s,r)=>{let t=r,n=r?qo(r):null;for(const o of s){const a=o?.info?.id,i=qo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Ys=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return t?o.set(r,t):o.delete(r),o},cn=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},fo=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},Hx=(s,r)=>{const t=new Set,n=s.streamingMessageIds.get(r);return n&&t.add(n),s.messageStreamStates.forEach((o,a)=>{s.messageSessionIndex.get(a)===r&&t.add(a)}),t},mc=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),Ux=async s=>{if(s)try{return it.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},fc=s=>{if(!s)return null;try{return it.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},pc=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},za=async(s,r)=>{const t=await Ux(s);return t?ke.withDirectory(t,r):r()},ft=Bt()(Xt(Ts((s,r)=>({messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,messageSessionIndex:new Map,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,pendingAssistantParts:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,pendingAssistantHeaderSessions:new Set,pendingUserMessageMetaBySession:new Map,loadMessages:async(t,n=ds.VIEWPORT_MESSAGES)=>{const o=await za(t,()=>ke.getSessionMessages(t)),a=fc(t),i=pc(o,a),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(l?i.filter(m=>{const f=m?.info?.id;return f?mo(f,l):!0}):i).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],g=new Map(p.filter(C=>typeof C.info?.id=="string").map(C=>[C.info.id,C])),w=u.map(C=>{const k={...C.info,clientRole:C.info?.clientRole??C.info.role,userMessageMarker:C.info.role==="user"?!0:C.info?.userMessageMarker},A=(Array.isArray(C.parts)?C.parts:[]).map(R=>{if(R?.type==="text"){const V=R.text??R.content??"";if(Fa(V))return{...R,synthetic:!0}}return R}),E=k?.id?g.get(k.id):void 0;if(E&&E.info.role==="assistant"){const R=Array.isArray(E.parts)?E.parts:[],V=fn(R),T=fn(A);if(Yo(E.info)&&V>T){const re=Xo(R,A);return{...C,info:k,parts:re}}}return{...C,info:k,parts:A}}),h=Ba(w),j=new Set(p.map(C=>C.info.id)),b=new Set(h.map(C=>C.info.id)),x=[];j.forEach(C=>{b.has(C)||x.push(C)}),f.set(t,h);const v=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);v.set(t,{...N,viewportAnchor:h.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0,totalAvailableMessages:o.length,hasMoreAbove:o.length>u.length,trimmedHeadMaxId:N?.trimmedHeadMaxId,streamingCooldownUntil:void 0});const y={messages:f,sessionMemoryState:v};Or(x);const S=Pn(m.messageStreamStates,x);if(S!==m.messageStreamStates&&(y.messageStreamStates=S),x.length>0){const C=m.streamingMessageIds.get(t);C&&x.includes(C)&&(y.streamingMessageIds=Ys(y.streamingMessageIds??m.streamingMessageIds,t,null))}if(x.length>0){const C=fo(y.messageSessionIndex??m.messageSessionIndex,x);C!==(y.messageSessionIndex??m.messageSessionIndex)&&(y.messageSessionIndex=C)}if(x.length>0){const C=new Map(m.pendingAssistantParts);let k=!1;x.forEach(A=>{C.delete(A)&&(k=!0)}),k&&(y.pendingAssistantParts=C)}const D=y.messageSessionIndex??m.messageSessionIndex;let M=D;return h.forEach(C=>{const k=C?.info?.id;typeof k=="string"&&k.length>0&&(M=cn(M,k,t))}),M!==D&&(y.messageSessionIndex=M),y})},sendMessage:async(t,n,o,a,i,l,d,u,m)=>{if(!i)throw new Error("No session selected");const f=i;r().sessionAbortFlags.has(f)&&s(p=>{const g=new Map(p.sessionAbortFlags);return g.delete(f),{sessionAbortFlags:g}}),await za(f,async()=>{try{let p=t;if(t.startsWith("/")){const w=t.indexOf(" "),h=w===-1?t.substring(1):t.substring(1,w),j=w===-1?"":t.substring(w+1).trim(),b=ke.getApiClient(),x=ke.getDirectory();if(h==="init"){const v=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({sessionID:f,...x?{directory:x}:{},messageID:v,providerID:n,modelID:o});return}if(h==="summarize"){await b.session.summarize({sessionID:f,...x?{directory:x}:{},providerID:n,modelID:o});return}try{const v=await ke.getCommandDetails(h);v?.template?p=v.template.replace(/\$ARGUMENTS/g,j):p=t}catch(v){console.error("Command template resolution failed:",v),p=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(w=>{const h=w.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},j=ln.get(f);j&&(clearTimeout(j),ln.delete(f));const b=new Map(w.sessionMemoryState);return b.set(f,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const w=new AbortController;s(b=>{const x=new Map(b.abortControllers);return x.set(f,w),{abortControllers:x}});const h=(l??[]).map(b=>({type:"file",mime:b.mimeType,filename:b.filename,url:b.dataUrl}));s(b=>{const x=new Set(b.pendingAssistantHeaderSessions);x.add(f);const v=new Map(b.pendingUserMessageMetaBySession);return v.set(f,{mode:typeof a=="string"&&a.trim().length>0?a.trim():void 0,providerID:n,modelID:o,variant:typeof m=="string"&&m.trim().length>0?m:void 0}),{pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}});const j=u?.map(b=>({text:b.text,files:b.attachments?.map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}))}));if(await ke.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:h.length>0?h:void 0,additionalParts:j,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{er.getState().clearAttachedFiles()}catch(b){console.error("Failed to clear attached files after send",b)}s(b=>{const x=new Map(b.abortControllers);return x.delete(f),{abortControllers:x}})}catch(w){let h="Network error while sending message. The message may still be processing.";if(w.name==="AbortError")h="Request timed out. The message may still be processing.";else if(w.message?.includes("504")||w.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",s(j=>{const b=new Map(j.abortControllers);return b.delete(f),{abortControllers:b}});return}else w.message&&(h=w.message);throw s(j=>{const b=new Map(j.abortControllers);b.delete(f);const x=new Set(j.pendingAssistantHeaderSessions);x.delete(f);const v=new Map(j.pendingUserMessageMetaBySession);return v.delete(f),{abortControllers:b,pendingAssistantHeaderSessions:x,pendingUserMessageMetaBySession:v}}),new Error(h)}}catch(p){let g="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?g="Request timed out. The message may still be processing.":p.response?.status===401?g="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?g="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?g="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(g=p.message),s(w=>{const h=new Map(w.abortControllers);h.delete(f);const j=new Set(w.pendingAssistantHeaderSessions);j.delete(f);const b=new Map(w.pendingUserMessageMetaBySession);return b.delete(f),{abortControllers:h,pendingAssistantHeaderSessions:j,pendingUserMessageMetaBySession:b}}),new Error(g)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const l=Hx(n,t);if(l.size===0){const u=t?a.get(t)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(w=>w.type==="reasoning"||w.type==="tool"||w.type==="step-start")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=$r.get(u);m&&(clearTimeout(m),$r.delete(u),uo.delete(u))}l.size>0&&Or(l);const d=Date.now();s(u=>{const m=Pn(u.messageStreamStates,l),f=u.messages.get(t)??[];let p=!1,g=u.messages;if(f.length>0&&l.size>0){const b=f.map(x=>{if(!l.has(x.info.id)&&l.size>0)return x;const v=(x.parts??[]).map(N=>{if(N.type==="reasoning"){const y=N,S={...y.time??{}};return typeof S.end!="number"&&(S.end=d),{...y,time:S}}if(N.type==="tool"){const y=N,S={...y.state??{}};return(S.status==="running"||S.status==="pending")&&(S.status="aborted"),{...y,state:S}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...x,info:{...x.info,abortedAt:d,streaming:!1,status:"aborted"},parts:v}});p&&(g=new Map(u.messages),g.set(t,b))}const w=u.sessionMemoryState.get(t);let h=u.sessionMemoryState;if(w){const b=new Map(u.sessionMemoryState);b.set(t,{...w,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),h=b}const j=new Map(u.sessionAbortFlags);return j.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:h,sessionAbortFlags:j,abortControllers:(()=>{const b=new Map(u.abortControllers);return b.delete(t),b})(),streamingMessageIds:Ys(u.streamingMessageIds,t,null),...p?{messages:g}:{}}}),ke.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const l=r();if(uc.has(n))return;const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!mo(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.messages.get(t)||[],m=u.find(g=>g.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(t);if(p?.streamStartTime&&Date.now()-p.streamStartTime>ds.ZOMBIE_TIMEOUT){p.isZombie||s(w=>{const h=new Map(w.sessionMemoryState);return h.set(t,{...p,isZombie:!0}),{sessionMemoryState:h}}),setTimeout(()=>{r().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}s(g=>{const h=[...g.messages.get(t)||[]],j={},b=cn(g.messageSessionIndex,n,t);b!==g.messageSessionIndex&&(j.messageSessionIndex=b);const x=C=>{if(!((f==="assistant"||f==="user")&&g.sessionAbortFlags.has(t)))return C;const A=new Map(g.sessionAbortFlags);return A.delete(t),{...C,sessionAbortFlags:A}},v=C=>{const k=C||"",A=uo.get(n);if(k&&A===k){const V=r();if(mc(V,t,n)){const T=$r.get(n);T&&(clearTimeout(T),$r.delete(n)),setTimeout(()=>{const B=r();typeof B.forceCompleteMessage=="function"&&B.forceCompleteMessage(t,n,"timeout"),B.completeStreamingMessage(t,n)},100)}}uo.set(n,k);const E=$r.get(n);E&&clearTimeout(E);const R=setTimeout(()=>{const V=r();typeof V.forceCompleteMessage=="function"&&V.forceCompleteMessage(t,n,"timeout"),mc(V,t,n)&&V.completeStreamingMessage(t,n),$r.delete(n),uo.delete(n)},8e3);$r.set(n,R)},N=t!==i,y=g.sessionMemoryState.get(t);if(N&&y?.isStreaming){h.length>=ds.BACKGROUND_STREAMING_BUFFER&&h.shift();const C=new Map(g.sessionMemoryState);C.set(t,{...y,backgroundMessageCount:(y.backgroundMessageCount||0)+1}),g.sessionMemoryState=C}if(f==="assistant"){const C=g.sessionMemoryState.get(t);if(C){const k=Date.now(),A=new Map(g.sessionMemoryState);A.set(t,{...C,isStreaming:!0,streamStartTime:C.streamStartTime??k,lastAccessedAt:k,isZombie:!1}),g.sessionMemoryState=A}}const S=Un(o);if(Fa(S)&&(o.synthetic=!0),Bx()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:S.length,snapshotParts:u.length})}catch{}const D=j.streamingMessageIds??g.streamingMessageIds;if(f==="assistant"){const C=Ys(D,t,n);C!==D&&(j.streamingMessageIds=C,window.__messageTracker?.(n,"streamingId_set_latest"))}const M=h.findIndex(C=>C.info.id===n);if(M!==-1&&f==="user"){const C=h[M],k=C.parts.findIndex(T=>T.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),g;const A=Tn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const E={...C};k!==-1?E.parts=E.parts.map((T,B)=>B===k?A:T):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const V=new Map(g.messages);return V.set(t,R),x({messages:V})}if(f==="assistant"&&M!==-1){const C=h[M],k=C.parts.findIndex(B=>B.id===o.id),A=Tn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const E={...C};k!==-1?E.parts=E.parts.map((B,re)=>re===k?A:B):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const V=new Map(g.messages);V.set(t,R),j.messageStreamStates=Ra(g.messageStreamStates,n);const T=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);return T!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?v(A.text||""):v(""),x({messages:V,...j})}if(M===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const Q=Tn(o);window.__messageTracker?.(n,`new_user_part_type:${Q.type||"unknown"}`);const de=g.pendingUserMessageMetaBySession.get(t),I=xt.getState(),W=de?.mode??I.getSessionAgentSelection(t)??I.getCurrentAgent(t),F=typeof W=="string"&&W.trim().length>0?W.trim():void 0,$=de?.providerID??(g.lastUsedProvider?.providerID||void 0),L=de?.modelID??(g.lastUsedProvider?.modelID||void 0);de&&(j.pendingUserMessageMetaBySession=cc(g.pendingUserMessageMetaBySession,t));const J={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...F?{mode:F}:{},...$?{providerID:$}:{},...L?{modelID:L}:{},time:{created:Date.now()}},parts:[Q]},pe=[...h,J];pe.sort((he,Ae)=>{const je=he.info?.time?.created||0,Te=Ae.info?.time?.created||0;return je-Te});const be=new Map(g.messages);return be.set(t,pe),x({messages:be})}if(o?.type==="text"){const Q=Un(o).trim();if(Q.length>0){const de=[...h].reverse().find(I=>I.info.role==="user");if(de){const I=de.parts.map(W=>Un(W)).join("").trim();if(I.length>0&&I===Q)return uc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const C=Tn(o);window.__messageTracker?.(n,`part_type:${C.type||"unknown"}`),C.type==="text"?v(C.text||""):v("");const k=g.pendingAssistantParts.get(n),A=k?[...k.parts]:[],E=A.findIndex(Q=>Q.id===C.id);E!==-1?A[E]=C:A.push(C);const R=new Map(g.pendingAssistantParts);R.set(n,{sessionId:t,parts:A});const V=g.lastUsedProvider?.providerID||"",T=g.lastUsedProvider?.modelID||"",B=Date.now(),re=ke.getDirectory()??"/",Y=xt.getState(),_=Y.getSessionAgentSelection(t)??Y.getCurrentAgent(t),q=typeof _=="string"&&_.trim().length>0?_.trim():void 0,O=g.pendingAssistantHeaderSessions.has(t);if(O){const Q=new Set(g.pendingAssistantHeaderSessions);Q.delete(t),j.pendingAssistantHeaderSessions=Q}const U={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:B},agent:q||"default",model:{providerID:V,modelID:T},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:B},parentID:n,modelID:T,providerID:V,mode:q||"default",...O?{openchamberHeaderAnchor:!0}:{},path:{cwd:re,root:re},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:A},ne=[...h,U],oe=new Map(g.messages);if(oe.set(t,ne),f==="assistant"){j.messageStreamStates=Ra(g.messageStreamStates,n);const Q=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);Q!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=Q,window.__messageTracker?.(n,"streamingId_set"))}return x({messages:oe,pendingAssistantParts:R,...j})}else{const C=h[M],k=C.parts.findIndex(T=>T.id===o.id),A=Tn(o,k!==-1?C.parts[k]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const E={...C};k!==-1?E.parts=E.parts.map((T,B)=>B===k?A:T):E.parts=[...E.parts,A];const R=[...h];R[M]=E;const V=new Map(g.messages);if(V.set(t,R),E.info.role==="assistant"){j.messageStreamStates=Ra(g.messageStreamStates,n);const T=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);T!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=T,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?v(A.text||""):v(""),x({messages:V,...j})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}$a.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),La||(La=setTimeout(()=>{const l=[...$a];$a=[],La=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Ox))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[l,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};s(i=>{const l=a(i);if(!l)return i;const d=i.messages.get(l)??[],u=d.findIndex(y=>y.info.id===n);if(u===-1)return i;const m=d[u];if(!m)return i;const f=Date.now(),p=m.info,g=typeof p?.time?.completed=="number"&&p.time.completed>0;let w=!1;const h={...p};g||(h.time={...p.time??{},completed:f},w=!0),h.status!=="completed"&&(h.status="completed",w=!0),h.streaming&&(h.streaming=!1,w=!0);let j=!1;const b=m.parts.map(y=>{if(!y)return y;if(y.type==="tool"){const S=y.state;if(!S)return y;const D=S.status,M=D==="running"||D==="pending"||D==="started",C=!S.time||typeof S.time?.end!="number";if(M||C){const k={...S};return M&&(k.status="completed"),C&&(k.time={...S.time??{},end:f}),j=!0,{...y,state:k}}return y}if(y.type==="reasoning"){const S=y.time;return!S||typeof S.end!="number"?(j=!0,{...y,time:{...S??{},end:f}}):y}if(y.type==="text"){const S=y.time;return S&&typeof S.end!="number"?(j=!0,{...y,time:{...S,end:f}}):y}return y});if(!w&&!j)return i;window.__messageTracker?.(n,`force_complete:${o}`);const x={...m,info:h,parts:j?b:m.parts},v=[...d];v[u]=x;const N=new Map(i.messages);return N.set(l,v),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{qu(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const m=d.findIndex(h=>h.info.id===t);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},g=[...d];g[m]=p;const w=new Map(n.messages);w.set(u,g),a=w,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Or([t])},updateMessageInfo:(t,n,o)=>{s(l=>{const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!mo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(t)??[]],f=m.findIndex(M=>M.info.id===n),p=l.pendingAssistantParts.get(n),g=(M=[],C=[])=>{if(!C.length)return M;const k=[...M];return C.forEach(A=>{const E=k.findIndex(R=>R.id===A.id);E===-1?k.push(A):k[E]=A}),k},w=M=>{if(!M)return M;const C=M.clientRole??M.role,k=C==="user"?!0:M.userMessageMarker;return{...M,clientRole:C,...k?{userMessageMarker:!0}:{}}};if(f===-1){if(console.info("[MESSAGE-DEBUG] updateMessageInfo: messageIndex === -1",{sessionId:t,messageId:n,messageInfo:o,existingCount:m.length}),m.length>0){const re=m[0]?.info,Y=typeof re?.time?.created=="number"?re.time.created:null,_=typeof re?.id=="string"?re.id:null,q=o,O=typeof q?.time?.created=="number"?q.time.created:null,z=typeof q?.id=="string"?q.id:n;let U=!1;if(O!==null&&Y!==null&&(U=O<Y),!U&&z&&_&&(U=z.localeCompare(_)<0),U)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const M=w(o);if(M&&M.role==="user"){const B=p?.parts??[],re=l.pendingUserMessageMetaBySession.get(t),Y={info:{...M,userMessageMarker:!0,clientRole:"user",...re?.mode?{mode:re.mode}:{},...re?.providerID?{providerID:re.providerID}:{},...re?.modelID?{modelID:re.modelID}:{}},parts:B.length>0?[...B]:[]},_=new Map(l.messages),q=[...m,Y];q.sort((U,ne)=>{const oe=U.info?.time?.created||0,Q=ne.info?.time?.created||0;return oe-Q}),_.set(t,q);const O={messages:_,...re?{pendingUserMessageMetaBySession:cc(l.pendingUserMessageMetaBySession,t)}:{}},z=cn(O.messageSessionIndex??l.messageSessionIndex,n,t);if(z!==(O.messageSessionIndex??l.messageSessionIndex)&&(O.messageSessionIndex=z),p){const U=new Map(l.pendingAssistantParts);U.delete(n),O.pendingAssistantParts=U}return O}if(!M||M.role!=="assistant")return l;const C=p?.parts??[],k=l.pendingAssistantHeaderSessions.has(t),A={info:{...M,animationSettled:M?.animationSettled??!1,...k?{openchamberHeaderAnchor:!0}:{}},parts:C.length>0?[...C]:[]},E=new Map(l.messages),R=[...m,A];E.set(t,R);const V={messages:E,...k?{pendingAssistantHeaderSessions:(()=>{const B=new Set(l.pendingAssistantHeaderSessions);return B.delete(t),B})()}:{}},T=cn(V.messageSessionIndex??l.messageSessionIndex,n,t);if(T!==(V.messageSessionIndex??l.messageSessionIndex)&&(V.messageSessionIndex=T),p){const B=new Map(l.pendingAssistantParts);B.delete(n),V.pendingAssistantParts=B}return V}const h=m[f],j=h.info;if(j.userMessageMarker===!0||j.clientRole==="user"||j.role==="user"){const M={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:j.providerID||void 0,modelID:j.modelID||void 0},C=l.pendingUserMessageMetaBySession.get(t);C&&!M.mode&&C.mode&&(M.mode=C.mode);const k={...h,info:M},A=new Map(l.messages),E=[...m];if(E[f]=k,A.set(t,E),C){const R=new Map(l.pendingUserMessageMetaBySession);return R.delete(t),{messages:A,pendingUserMessageMetaBySession:R}}return{messages:A}}const x={...h.info,...o};o.role&&o.role!==h.info.role&&(x.role=h.info.role),x.clientRole=x.clientRole??h.info.clientRole??h.info.role,x.clientRole==="user"&&(x.userMessageMarker=!0);const v=p?.parts?g(h.parts,p.parts):h.parts,N={...h,info:x,parts:v},y=new Map(l.messages),S=[...m];S[f]=N,y.set(t,S);const D={messages:y};if(p){const M=new Map(l.pendingAssistantParts);M.delete(n),D.pendingAssistantParts=M}return D});const a=o?.finish,i=o?.role;typeof a=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=Ys(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&s(i),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Or([n]);let l=!1;if(s(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(t,p),l=!0,{sessionMemoryState:m}}),l){const d=ln.get(t);d&&(clearTimeout(d),ln.delete(t));const u=setTimeout(()=>{s(m=>{const f=m.sessionMemoryState.get(t);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:g,...w}=f;return p.set(t,w),{sessionMemoryState:p}}),ln.delete(t)},2e3);ln.set(t,u)}},syncMessages:(t,n)=>{const o=fc(t),a=pc(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,l=i?a.filter(d=>{const u=d?.info?.id;return u?mo(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(y=>typeof y.info?.id=="string").map(y=>[y.info.id,y])),p=l.map(y=>{const S={...y.info,clientRole:y.info?.clientRole??y.info.role,userMessageMarker:y.info.role==="user"?!0:y.info?.userMessageMarker,animationSettled:y.info.role==="assistant"?y.info?.animationSettled??!0:y.info?.animationSettled},D=(Array.isArray(y.parts)?y.parts:[]).map(k=>{if(k?.type==="text"){const A=k.text??k.content??"";if(Fa(A))return{...k,synthetic:!0}}return k}),M=typeof S?.id=="string"?S.id:void 0,C=M?f.get(M):void 0;if(C&&C.info.role==="assistant"){const k=Array.isArray(C.parts)?C.parts:[],A=fn(k),E=fn(D);if(Yo(C.info)&&A>E){const V=Xo(k,D);return{...y,info:S,parts:V}}}return{...y,info:S,parts:D}}),g=Ba(p),w=new Set(m.map(y=>y.info.id)),h=new Set(g.map(y=>y.info.id)),j=[];w.forEach(y=>{h.has(y)||j.push(y)}),u.set(t,g);const b={messages:u,isSyncing:!0};Or(j);const x=Pn(d.messageStreamStates,j);if(x!==d.messageStreamStates&&(b.messageStreamStates=x),j.length>0){const y=d.streamingMessageIds.get(t);y&&j.includes(y)&&(b.streamingMessageIds=Ys(b.streamingMessageIds??d.streamingMessageIds,t,null))}if(j.length>0){const y=fo(b.messageSessionIndex??d.messageSessionIndex,j);y!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=y)}if(j.length>0){const y=new Map(d.pendingAssistantParts);let S=!1;j.forEach(D=>{y.delete(D)&&(S=!0)}),S&&(b.pendingAssistantParts=y)}const v=b.messageSessionIndex??d.messageSessionIndex;let N=v;return g.forEach(y=>{const S=y?.info?.id;typeof S=="string"&&S.length>0&&(N=cn(N,S,t))}),N!==v&&(b.messageSessionIndex=N),b}),setTimeout(()=>{s({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{s(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+$x;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const i=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(a.sessionMemoryState);return l.set(t,{...i,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:l}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=ds.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const l=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(l.isStreaming&&t===o)return;const d=l.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(i.length,u+n);m===i.length&&m-u<n&&(u=Math.max(0,m-n));const f=i.slice(u,m),p=i.slice(0,u),g=new Set(f.map(h=>h.info.id)),w=i.filter(h=>!g.has(h.info.id)).map(h=>h.info.id);s(h=>{const j=new Map(h.messages);j.set(t,f);const b=new Map(h.sessionMemoryState),x={...l,viewportAnchor:d-u,trimmedHeadMaxId:Wx(p,l.trimmedHeadMaxId)};b.set(t,x);const v={messages:j,sessionMemoryState:b};Or(w);const N=Pn(h.messageStreamStates,w);if(N!==h.messageStreamStates&&(v.messageStreamStates=N),w.length>0){const D=h.streamingMessageIds.get(t);D&&w.includes(D)&&(v.streamingMessageIds=Ys(v.streamingMessageIds??h.streamingMessageIds,t,null))}if(w.length>0){const D=fo(v.messageSessionIndex??h.messageSessionIndex,w);D!==(v.messageSessionIndex??h.messageSessionIndex)&&(v.messageSessionIndex=D)}const y=v.messageSessionIndex??h.messageSessionIndex;let S=y;return f.forEach(D=>{const M=D?.info?.id;typeof M=="string"&&M.length>0&&(S=cn(S,M,t))}),S!==y&&(v.messageSessionIndex=S),v})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=ds.MAX_SESSIONS)return;const a=[];n.messages.forEach((d,u)=>{const m=n.sessionMemoryState.get(u)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:0,backgroundMessageCount:0};a.push([u,m])});const i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=i[0][0];s(d=>{const m=(d.messages.get(l)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l),p.delete(l);const g={messages:f,sessionMemoryState:p},w=new Map(d.pendingAssistantParts);let h=!1;w.forEach((N,y)=>{N.sessionId===l&&(w.delete(y),h=!0)}),h&&(g.pendingAssistantParts=w);const j=new Map(d.sessionCompactionUntil);j.delete(l)&&(g.sessionCompactionUntil=j),Or(m);const b=Pn(d.messageStreamStates,m);b!==d.messageStreamStates&&(g.messageStreamStates=b);const x=fo(g.messageSessionIndex??d.messageSessionIndex,m);x!==(g.messageSessionIndex??d.messageSessionIndex)&&(g.messageSessionIndex=x);const v=Ys(d.streamingMessageIds,l,null);if(v!==d.streamingMessageIds&&(g.streamingMessageIds=v),d.abortControllers.has(l)){const N=new Map(d.abortControllers);N.delete(l),g.abortControllers=N}return g})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const l=await za(t,()=>ke.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=l.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(ds.VIEWPORT_MESSAGES,u),f=l.slice(u-m,u);s(p=>{const g=[...f,...a],w=Ba(g),h=new Map(p.messages);h.set(t,w);const j=Math.max(0,w.length-a.length),b=new Map(p.sessionMemoryState);return b.set(t,{...i,viewportAnchor:i.viewportAnchor+j,hasMoreAbove:u-m>0,totalAvailableMessages:l.length}),{messages:h,sessionMemoryState:b}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:Fs(()=>us()),partialize:s=>({lastUsedProvider:s.lastUsedProvider,sessionMemoryState:Array.from(s.sessionMemoryState.entries()).map(([r,t])=>[r,{viewportAnchor:t.viewportAnchor,isStreaming:t.isStreaming,lastAccessedAt:t.lastAccessedAt,backgroundMessageCount:t.backgroundMessageCount,totalAvailableMessages:t.totalAvailableMessages,hasMoreAbove:t.hasMoreAbove,trimmedHeadMaxId:t.trimmedHeadMaxId}]),sessionAbortFlags:Array.from(s.sessionAbortFlags.entries()).map(([r,t])=>[r,{timestamp:t.timestamp,acknowledged:t.acknowledged}])}),merge:(s,r)=>{if(!s)return r;let t=r.sessionMemoryState;Array.isArray(s.sessionMemoryState)&&(t=new Map(s.sessionMemoryState.map(o=>o)));let n=r.sessionAbortFlags;return Array.isArray(s.sessionAbortFlags)&&(n=new Map(s.sessionAbortFlags)),{...r,lastUsedProvider:s.lastUsedProvider??r.lastUsedProvider,sessionMemoryState:t,sessionAbortFlags:n}}}),{name:"message-store"})),Vx=s=>typeof s=="object"&&s!==null,Gx=s=>{if(!Array.isArray(s))return[];const r=[];return s.forEach(t=>{if(!Array.isArray(t)||t.length!==2)return;const[n,o]=t;typeof n!="string"||!Array.isArray(o)||r.push([n,o])}),r},Kx=async(s,r)=>{try{const n=it.getState().getDirectoryForSession(s);if(n)return ke.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},Zn=Bt()(Xt(Ts((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===t.id))return;const i=t.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=Ro(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if(u==="full"||u==="allow"&&Tx(i)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(f=>{const p=f.permissions.get(o)||[],g=new Map(f.permissions);return g.set(o,[...p,t]),{permissions:g}})},respondToPermission:async(t,n,o)=>{await Kx(t,()=>ke.replyToPermission(n,o)),o==="reject"&&await ft.getState().abortCurrentOperation(t),s(a=>{const l=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,l),{permissions:d}})}}),{name:"permission-store",storage:Fs(()=>us()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!Vx(s))return r;const t=Gx(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),nl=s=>s.filter(n=>n?.type==="text").map(n=>(n.text||n.content||"").trim()).filter(n=>n.length>0).join(`
9
+ `).replace(/\n\s*\n+/g,`
10
+ `),Vn=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t},hc=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Vn(n);const o=s.find(a=>a.id===r);return o?Vn(o.directory??null):null},me=Bt()(Xt((s,r)=>({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,messages:new Map,sessionMemoryState:new Map,messageStreamStates:new Map,sessionCompactionUntil:new Map,sessionAbortFlags:new Map,permissions:new Map,attachedFiles:[],isLoading:!1,error:null,streamingMessageIds:new Map,abortControllers:new Map,lastUsedProvider:null,isSyncing:!1,sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,webUICreatedSessions:new Set,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,abortPromptSessionId:null,abortPromptExpiresAt:null,sessionActivityPhase:new Map,userSummaryTitles:new Map,pendingInputText:null,newSessionDraft:{open:!0,directoryOverride:null,parentID:null},getSessionAgentEditMode:(t,n,o)=>xt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>xt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>xt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>it.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=Pt.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=et.getState(),a=o.getVisibleAgents();let i;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(i=l.name)}i||(i=a.find(l=>l.name==="build")?.name||a[0]?.name),i&&o.setAgent(i)}catch{}},closeNewSessionDraft:()=>{const t=it.getState().currentSessionId;s({newSessionDraft:{open:!1,directoryOverride:null,parentID:null,title:void 0},currentSessionId:t})},createSession:async(t,n,o)=>{r().closeNewSessionDraft();const a=await it.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=ft.getState(),{messages:o,lastUsedProvider:a}=n;let i,l;if(o.forEach((b,x)=>{const v=b.find(N=>N.info?.id===t);v&&!i&&(i=v,l=x)}),!i||i.info.role!=="assistant")return;const d=nl(i.parts);if(!d.trim())return;const u=it.getState(),m=hc(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:g,currentAgentName:w}=et.getState(),h=p||a?.providerID,j=g||a?.modelID;!h||!j||await ke.sendMessage({id:f.id,providerID:h,modelID:j,text:d,prefaceText:Ku,agent:w??void 0})},deleteSession:(t,n)=>it.getState().deleteSession(t,n),deleteSessions:(t,n)=>it.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>it.getState().updateSessionTitle(t,n),shareSession:t=>it.getState().shareSession(t),unshareSession:t=>it.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=it.getState().currentSessionId,o=hc(it.getState().sessions,t,it.getState().getWorktreeMetadata),a=ke.getDirectory()??ct.getState().currentDirectory??null,i=o??a;try{ke.setDirectory(i??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}if(n&&n!==t&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,ds.VIEWPORT_MESSAGES)}it.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,tx)),r().evictLeastRecentlyUsed()},loadMessages:t=>ft.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,l,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=x=>{s(v=>{const N=new Map(v.sessionActivityPhase??new Map);return N.set(x,"busy"),{sessionActivityPhase:N}})},g=x=>{s(v=>{const N=new Map(v.sessionActivityPhase??new Map);return N.set(x,"idle"),{sessionActivityPhase:N}})};if(m?.open){const x=await it.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!x?.id)throw new Error("Failed to create session");const v=et.getState(),N=v.currentAgentName,y=f??N,S=v.currentProviderId,D=v.currentModelId;if(S&&D)try{xt.getState().saveSessionModelSelection(x.id,S,D)}catch{}if(y){try{xt.getState().saveSessionAgentSelection(x.id,y)}catch{}if(S&&D){try{xt.getState().saveAgentModelForSession(x.id,y,S,D)}catch{}if(u!==void 0)try{xt.getState().saveAgentModelVariantForSession(x.id,y,S,D,u)}catch{}}}try{it.getState().initializeNewOpenChamberSession(x.id,v.agents)}catch{}r().closeNewSessionDraft(),p(x.id);try{return await ft.getState().sendMessage(t,n,o,y,x.id,i,l,d,u)}catch(M){throw g(x.id),M}}const w=it.getState().currentSessionId,h=w?xt.getState().getSessionAgentSelection(w):null,j=et.getState().currentAgentName,b=f||h||j||void 0;if(w&&b){try{xt.getState().saveSessionAgentSelection(w,b)}catch{}if(u!==void 0)try{xt.getState().saveAgentModelVariantForSession(w,b,n,o,u)}catch{}}w&&p(w);try{return await ft.getState().sendMessage(t,n,o,b,w||void 0,i,l,d,u)}catch(x){throw w&&g(w),x}},abortCurrentOperation:()=>{const t=it.getState().currentSessionId;return ft.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=it.getState().currentSessionId;if(!n)return null;const o=Date.now()+t;return s({abortPromptSessionId:n,abortPromptExpiresAt:o}),o},clearAbortPrompt:()=>{s({abortPromptSessionId:null,abortPromptExpiresAt:null})},acknowledgeSessionAbort:t=>{t&&ft.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const l=it.getState().currentSessionId||t;return ft.getState().addStreamingPart(t,n,o,a,l)},completeStreamingMessage:(t,n)=>ft.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>ft.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>ft.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>ft.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:xt.getState().currentAgentContext,sessionAgentSelections:xt.getState().sessionAgentSelections,getSessionAgentEditMode:xt.getState().getSessionAgentEditMode};return Zn.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>Zn.getState().respondToPermission(t,n,o),clearError:()=>it.getState().clearError(),getSessionsByDirectory:t=>it.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>it.getState().getDirectoryForSession(t),getLastMessageModel:t=>ft.getState().getLastMessageModel(t),getCurrentAgent:t=>xt.getState().getCurrentAgent(t),syncMessages:(t,n)=>ft.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>it.getState().applySessionMetadata(t,n),addAttachedFile:t=>er.getState().addAttachedFile(t),addServerFile:(t,n,o)=>er.getState().addServerFile(t,n,o),removeAttachedFile:t=>er.getState().removeAttachedFile(t),clearAttachedFiles:()=>er.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>ft.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>ft.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>ft.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=it.getState().currentSessionId;return ft.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=it.getState().currentSessionId;return ft.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>ft.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>xt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>xt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>xt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>xt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>xt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>xt.getState().getAgentModelForSession(t,n),saveAgentModelVariantForSession:(t,n,o,a,i)=>xt.getState().saveAgentModelVariantForSession(t,n,o,a,i),getAgentModelVariantForSession:(t,n,o,a)=>xt.getState().getAgentModelVariantForSession(t,n,o,a),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=ft.getState().messages;return xt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>it.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>it.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>it.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>it.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>it.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>it.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=it.getState().currentSessionId;if(!o)return null;const a=ft.getState().messages;return xt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=ft.getState().messages;return xt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=ft.getState().messages;return xt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=ft.getState().messages.get(t)||[],o=it.getState().sessions.find(a=>a.id===t);console.log(`Debug session ${t}:`,{session:o,messageCount:n.length,messages:n.map(a=>({id:a.info.id,role:a.info.role,parts:a.parts.length,tokens:a.info.tokens}))})},pollForTokenUpdates:(t,n,o)=>{const a=ft.getState().messages;return xt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>it.getState().updateSession(t),removeSessionFromStore:t=>it.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(ft.getState().messages.get(t)||[]).find(m=>m.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
+ `).trim());const l=await ke.revertSession(t,n);it.getState().updateSession(l);const d=ft.getState().messages.get(t)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);ft.getState().syncMessages(t,f)}}i&&s({pendingInputText:i})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),i=r().sessions.find(p=>p.id===t);if(o.length===0)return;const l=i?.revert?.messageID;let d;if(l){const p=o.findIndex(g=>g.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await is(async()=>{const{toast:p}=await import("./vendor-.bun-B2HtLj-d.js").then(g=>g.cq);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async t=>{const a=r().sessions.find(m=>m.id===t)?.revert?.messageID;if(!a)return;const l=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(g=>g.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,u.info.id);const{toast:p}=await is(async()=>{const{toast:g}=await import("./vendor-.bun-B2HtLj-d.js").then(w=>w.cq);return{toast:g}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await ke.unrevertSession(t);await it.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await is(async()=>{const{toast:p}=await import("./vendor-.bun-B2HtLj-d.js").then(g=>g.cq);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(i=>i.id===t);if(a)try{const i=await ke.forkSession(t,n);if(!i||!i.id){const{toast:f}=await is(async()=>{const{toast:p}=await import("./vendor-.bun-B2HtLj-d.js").then(g=>g.cq);return{toast:p}},__vite__mapDeps([0,1]));f.error("Failed to fork session");return}const d=(r().messages.get(t)||[]).find(f=>f.info.id===n);if(!d){const{toast:f}=await is(async()=>{const{toast:p}=await import("./vendor-.bun-B2HtLj-d.js").then(g=>g.cq);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(i.id),u&&s({pendingInputText:u}),await r().loadMessages(i.id);const{toast:m}=await is(async()=>{const{toast:f}=await import("./vendor-.bun-B2HtLj-d.js").then(p=>p.cq);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:l}=await is(async()=>{const{toast:d}=await import("./vendor-.bun-B2HtLj-d.js").then(u=>u.cq);return{toast:d}},__vite__mapDeps([0,1]));l.error("Failed to fork session")}},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));it.subscribe((s,r)=>{if(s.sessions===r.sessions&&s.sessionsByDirectory===r.sessionsByDirectory&&s.currentSessionId===r.currentSessionId&&s.lastLoadedDirectory===r.lastLoadedDirectory&&s.isLoading===r.isLoading&&s.error===r.error&&s.webUICreatedSessions===r.webUICreatedSessions&&s.worktreeMetadata===r.worktreeMetadata&&s.availableWorktrees===r.availableWorktrees&&s.availableWorktreesByProject===r.availableWorktreesByProject)return;const t=me.getState().newSessionDraft?.open;me.setState({sessions:s.sessions,sessionsByDirectory:s.sessionsByDirectory,currentSessionId:t?null:s.currentSessionId,lastLoadedDirectory:s.lastLoadedDirectory,isLoading:s.isLoading,error:s.error,webUICreatedSessions:s.webUICreatedSessions,worktreeMetadata:s.worktreeMetadata,availableWorktrees:s.availableWorktrees,availableWorktreesByProject:s.availableWorktreesByProject})});ft.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const l=i.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),me.setState({messages:s.messages,sessionMemoryState:s.sessionMemoryState,messageStreamStates:s.messageStreamStates,sessionCompactionUntil:s.sessionCompactionUntil,sessionAbortFlags:s.sessionAbortFlags,streamingMessageIds:s.streamingMessageIds,abortControllers:s.abortControllers,lastUsedProvider:s.lastUsedProvider,isSyncing:s.isSyncing,userSummaryTitles:t})});er.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&me.setState({attachedFiles:s.attachedFiles})});xt.subscribe((s,r)=>{s.sessionModelSelections===r.sessionModelSelections&&s.sessionAgentSelections===r.sessionAgentSelections&&s.sessionAgentModelSelections===r.sessionAgentModelSelections&&s.currentAgentContext===r.currentAgentContext&&s.sessionContextUsage===r.sessionContextUsage&&s.sessionAgentEditModes===r.sessionAgentEditModes||me.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});Zn.subscribe((s,r)=>{s.permissions!==r.permissions&&me.setState({permissions:s.permissions})});ct.subscribe((s,r)=>{const t=Vn(s.currentDirectory??null),n=Vn(r.currentDirectory??null);if(t===n)return;const o=me.getState().newSessionDraft;if(!o?.open)return;const a=Vn(o.directoryOverride);a&&a!==n||me.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const qx=me.getState().newSessionDraft?.open;me.setState({sessions:it.getState().sessions,currentSessionId:qx?null:it.getState().currentSessionId,lastLoadedDirectory:it.getState().lastLoadedDirectory,isLoading:it.getState().isLoading,error:it.getState().error,webUICreatedSessions:it.getState().webUICreatedSessions,worktreeMetadata:it.getState().worktreeMetadata,availableWorktrees:it.getState().availableWorktrees,availableWorktreesByProject:it.getState().availableWorktreesByProject,messages:ft.getState().messages,sessionMemoryState:ft.getState().sessionMemoryState,messageStreamStates:ft.getState().messageStreamStates,sessionCompactionUntil:ft.getState().sessionCompactionUntil,sessionAbortFlags:ft.getState().sessionAbortFlags,streamingMessageIds:ft.getState().streamingMessageIds,abortControllers:ft.getState().abortControllers,lastUsedProvider:ft.getState().lastUsedProvider,isSyncing:ft.getState().isSyncing,permissions:Zn.getState().permissions,attachedFiles:er.getState().attachedFiles,sessionModelSelections:xt.getState().sessionModelSelections,sessionAgentSelections:xt.getState().sessionAgentSelections,sessionAgentModelSelections:xt.getState().sessionAgentModelSelections,currentAgentContext:xt.getState().currentAgentContext,sessionContextUsage:xt.getState().sessionContextUsage,sessionAgentEditModes:xt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=me);const ol=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=c.useState(!1),[l,d]=c.useState({length:0,offset:0}),[u,m]=c.useState({length:0,offset:0}),f=c.useRef(null),p=c.useRef(null),g=c.useRef(!1),w=c.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),h=c.useRef(null),j=c.useCallback(()=>{const C=s.current;if(!C)return;const{scrollHeight:k,clientHeight:A,scrollTop:E,scrollWidth:R,clientWidth:V,scrollLeft:T}=C,B=8;if(k>A){const re=Math.max(A-B*2,0),Y=A/k*re,_=Math.max(r,Math.min(re,Y)),q=Math.max(re-_,0),O=Math.max(k-A,1),z=E/O*q;d({length:_,offset:z})}else d({length:0,offset:0});if(!o&&R>V){const re=Math.max(V-B*2,0),Y=V/R*re,_=Math.max(r,Math.min(re,Y)),q=Math.max(re-_,0),O=Math.max(R-V,1),z=T/O*q;m({length:_,offset:z})}else m({length:0,offset:0})},[s,r,o]),b=c.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),x=c.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{j(),i(!0),b()})},[b,j]);c.useEffect(()=>{const C=s.current;if(!C)return;j(),i(!0),b(),C.addEventListener("scroll",x,{passive:!0});const k=typeof ResizeObserver<"u"?new ResizeObserver(()=>j()):null;k?.observe(C);const A=typeof MutationObserver<"u"?new MutationObserver(()=>j()):null;return A?.observe(C,{childList:!0,subtree:!0,characterData:!0}),()=>{C.removeEventListener("scroll",x),k?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,x,b,j]);const v=(C,k)=>{const A=s.current;A&&(g.current=!0,w.current={pointerX:C.clientX,pointerY:C.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},h.current=k,i(!0),f.current&&clearTimeout(f.current),C.currentTarget.setPointerCapture(C.pointerId))},N=C=>{if(!g.current)return;const k=s.current;if(!k)return;const A=h.current;if(A==="vertical"){const{pointerY:E,scrollTop:R}=w.current,V=C.clientY-E,T=k.clientHeight,B=Math.max(T-l.length,1),re=Math.max(k.scrollHeight-k.clientHeight,1),Y=V/B*re;k.scrollTop=R+Y}else if(A==="horizontal"){const{pointerX:E,scrollLeft:R}=w.current,V=C.clientX-E,T=k.clientWidth,B=Math.max(T-u.length,1),re=Math.max(k.scrollWidth-k.clientWidth,1),Y=V/B*re;k.scrollLeft=R+Y}},y=C=>{g.current&&(g.current=!1,C.currentTarget.releasePointerCapture(C.pointerId),b())},S=l.length>0,D=u.length>0;if(!S&&!D)return null;const M=8;return e.jsxs("div",{className:P("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[S&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${l.length}px`,top:`${M+l.offset}px`,right:`${M/2}px`},onPointerDown:C=>v(C,"vertical"),onPointerMove:N,onPointerUp:y,onPointerCancel:y}),D&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${M+u.offset}px`,bottom:`${M/2}px`},onPointerDown:C=>v(C,"horizontal"),onPointerMove:N,onPointerUp:y,onPointerCancel:y})]})},dt=c.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:l,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const g=c.useRef(null);return c.useImperativeHandle(p,()=>g.current,[]),e.jsxs("div",{className:P("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:g,className:P("overlay-scrollbar-target overlay-scrollbar-container overscroll-none",u?"flex-1 min-h-0 w-full h-full":"flex-none w-full h-auto",d?"overflow-y-auto overflow-x-hidden":"overflow-auto",s),style:n,...f,children:t}),e.jsx(ol,{containerRef:g,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});dt.displayName="ScrollableOverlay";const gc="mobile-overlay-root",Yx=()=>{if(typeof document>"u")return null;let s=document.getElementById(gc);return s||(s=document.createElement("div"),s.id=gc,document.body.appendChild(s)),s},ws=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:l})=>{const d=c.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Yx()),c.useEffect(()=>{if(!s)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=g=>{g.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[s,t]),!s||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:P("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(Ht,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(dt,{outerClassName:u,className:"px-2 py-2 pwa-overlay-scroll",children:n}),o?e.jsx("div",{className:"border-t border-border/40 px-3 py-2",children:o}):null]})});return Pf.createPortal(m,d.current)},ki=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,l]=c.useState(!1),d=c.useRef(void 0),u=j=>j>=1e6?`${(j/1e6).toFixed(1)}M`:j>=1e3?`${(j/1e3).toFixed(1)}K`:j.toFixed(1).replace(/\.0$/,""),m=j=>j>=90?"text-status-error":j>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(s)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],g=c.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!0)},500)},[]),w=c.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);c.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const h=e.jsxs("div",{className:P("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?g:void 0,onTouchEnd:a?w:void 0,children:[e.jsx(Tf,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:P(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[h,e.jsx(ws,{open:i,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:P("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:h}),e.jsx(tt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(j=>e.jsx("p",{className:"typography-micro leading-tight",children:j},j))})})]})},Rn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Yu=(s,r,t)=>{if(typeof window>"u")return;const n=document.documentElement,o=r==="mobile",a=r==="tablet";n.classList.remove("device-mobile","device-tablet","device-desktop"),n.classList.add(r==="mobile"?"device-mobile":r==="tablet"?"device-tablet":"device-desktop"),s?(n.classList.add("desktop-runtime"),n.style.setProperty("--is-mobile","0"),n.style.setProperty("--device-type","desktop"),n.style.setProperty("--font-scale","1"),n.style.setProperty("--has-coarse-pointer","0"),n.style.setProperty("--has-touch-input","0"),n.classList.remove("mobile-pointer")):(n.classList.remove("desktop-runtime"),n.style.setProperty("--is-mobile",o?"1":"0"),n.style.setProperty("--device-type",r),n.style.setProperty("--font-scale",o?"0.9":a?"0.95":"1"),n.style.setProperty("--has-coarse-pointer",t?"1":"0"),n.style.setProperty("--has-touch-input",t?"1":"0"),t?n.classList.add("mobile-pointer"):n.classList.remove("mobile-pointer"))};function Wa(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=s>Rn.md&&s<=Rn.lg,m=s<=Rn.md;let f=d&&m,p=d&&!f&&u,g=!d||s>Rn.lg,w="desktop";l?(f=!1,p=!1,g=!0,w="desktop"):f?w="mobile":p?w="tablet":(g=!0,w="desktop"),Yu(l,w,d);let h="xs";for(const[j,b]of Object.entries(Rn))s>=b&&(h=j);return{isMobile:f,isTablet:p,isDesktop:g,deviceType:w,screenWidth:s,breakpoint:h,hasTouchInput:d}}function Ft(){const[s,r]=c.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Wa());return c.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(Wa())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Wa())},a=[],i=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return i(t),i(n),()=>{a.forEach(l=>l())}},[]),c.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||l||d>0;Yu(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const po=5e3,Xx=1e4,Qx=5e3,Jx=1e4,Zx=25,ey=4,xc=15e3,Xs=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),ty=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=new Set([...Object.keys(s),...Object.keys(r)]);for(const n of t){const o=s[n],a=r[n];if(!(!o&&!a)&&(!o||!a||o.insertions!==a.insertions||o.deletions!==a.deletions))return!0}return!1},sy=(s,r)=>{if(!s&&!r)return!1;if(!s||!r)return!0;const t=s.files??[],n=r.files??[];if(t.length!==n.length||s.ahead!==r.ahead||s.behind!==r.behind||s.current!==r.current||s.tracking!==r.tracking||s.isClean!==r.isClean)return!0;const o=new Set(t.map(a=>`${a.path}:${a.index}:${a.working_dir}`));for(const a of n)if(!o.has(`${a.path}:${a.index}:${a.working_dir}`))return!0;return!!ty(s.diffStats,r.diffStats)},ry=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...i.keys()]);for(const f of l){const p=a.get(f),g=i.get(f);if(!p||!g){t.add(f);continue}if(p.index!==g.index||p.working_dir!==g.working_dir){t.add(f);continue}}const d=s?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],g=u[f];if(!p||!g){t.add(f);continue}(p.insertions!==g.insertions||p.deletions!==g.deletions)&&t.add(f)}return t},Yt=Bt()(Xt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:po,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Xs()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=r();let l=i.get(t);l||(l=Xs()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(sy(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??Xs(),g=ry(p.status,m),w=new Set((p.status?.files??[]).map(x=>x.path)),h=new Set((m.files??[]).map(x=>x.path)),j=new Map(p.diffCache);for(const x of w)h.has(x)||j.delete(x);for(const x of g)j.delete(x);const b=g.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:j,lastStatusFetch:Date.now(),lastStatusChange:b?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??Xs();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),i=a.get(t)??Xs();a.set(t,{...i,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),i=a.get(t),l=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:l}),u=new Map(r().directories),m=u.get(t)??Xs();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),s({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{s({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{s({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(r().directories),i=a.get(t)??Xs();a.set(t,{...i,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let i=a.get(t);if(!i){i=Xs();const f=new Map(a);f.set(t,i),s({directories:f})}const{force:l=!1}=o,d=Date.now();await r().fetchStatus(t,n);const u=r().directories.get(t);if(!u?.isGitRepo)return;await r().fetchBranches(t,n);const m=d-(u.lastLogFetch||0);(l||m>Jx||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),i=a.get(t)??Xs(),l=new Map(i.diffCache);l.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:l}),s({directories:a})},clearDiffCache:t=>{const n=new Map(r().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),s({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=r().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const l=o.status.files.filter(x=>!o.diffCache.has(x.path)).slice(0,Zx);if(l.length===0)return;let d=0;const u=[],m=()=>{const x=d;return d+=1,x<l.length?l[x]:null},f=async x=>{const v=n.getGitFileDiff(t,{path:x}),N=new Promise((S,D)=>{setTimeout(()=>D(new Error(`Timed out after ${xc}ms`)),xc)}),y=await Promise.race([v,N]);return{path:x,diff:{original:y.original??"",modified:y.modified??""}}},p=async()=>{for(;;){const x=m();if(!x)return;try{u.push(await f(x.path))}catch{}}},g=Math.min(ey,l.length);await Promise.allSettled(Array.from({length:g},()=>p()));const w=new Map(r().directories),h=w.get(t);if(!h)return;const j=new Map(h.diffCache),b=Date.now();u.forEach(x=>{j.set(x.path,{...x.diff,fetchedAt:b})}),w.set(t,{...h,diffCache:j}),s({directories:w})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??Xs();o.set(t,{...a,logMaxCount:n}),s({directories:o})},startPolling:t=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){s({pollIntervalId:o()});return}const{activeDirectory:l}=r();if(!l){s({pollIntervalId:o()});return}if(await r().fetchStatus(l,t,{silent:!0}))await r().fetchLog(l,t),r().fetchAllDiffs(l,t),s({currentPollInterval:po});else{const m=Math.min(a+Qx,Xx);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:po})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:po}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),Xu=s=>Yt(r=>s?r.directories.get(s)?.status??null:null),Qu=s=>Yt(r=>s?r.directories.get(s)?.branches??null:null),ny=s=>Yt(r=>s?r.directories.get(s)?.log??null:null),oy=s=>Yt(r=>s?r.directories.get(s)?.identity??null:null),al=s=>Yt(r=>s?r.directories.get(s)?.isGitRepo??null:null),ay=s=>Yt(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Ut({...s}){return e.jsx(Ff,{"data-slot":"dropdown-menu",...s})}function Vt({...s}){return e.jsx(Rf,{"data-slot":"dropdown-menu-trigger",...s})}function Gt({className:s,sideOffset:r=4,...t}){return e.jsx(_f,{children:e.jsx(Of,{"data-slot":"dropdown-menu-content",sideOffset:r,className:P("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-visible rounded-xl border p-1 shadow-none",s),...t})})}function vt({className:s,inset:r,variant:t="default",...n}){return e.jsx(zf,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:P("hover:bg-muted data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-destructive/10 dark:data-[variant=destructive]:hover:bg-destructive/20 data-[variant=destructive]:hover:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...n})}function Ju({...s}){return e.jsx($f,{"data-slot":"dropdown-menu-radio-group",...s})}function Zu({className:s,children:r,...t}){return e.jsxs(Lf,{"data-slot":"dropdown-menu-radio-item",className:P("relative flex cursor-default items-start gap-2 rounded-lg py-1 pl-2 pr-8 typography-ui-label outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 hover:bg-muted [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-3.5",s),...t,children:[e.jsx("span",{className:"pointer-events-none absolute right-2 flex size-3.5 items-center justify-center text-primary",children:e.jsx(Bf,{children:e.jsx(At,{className:"size-3"})})}),r]})}function Wr({className:s,inset:r,...t}){return e.jsx(Hf,{"data-slot":"dropdown-menu-label","data-inset":r,className:P("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Ms({className:s,...r}){return e.jsx(Wf,{"data-slot":"dropdown-menu-separator",className:P("bg-border -mx-1 my-0.5 h-px",s),...r})}const iy={read:{displayName:"Read File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"offset",label:"Start Line",type:"text"},{key:"limit",label:"Lines to Read",type:"text"}]},write:{displayName:"Write File",category:"file",outputLanguage:"auto",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"content",label:"Content",type:"code"}]},edit:{displayName:"Edit File",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"oldString",label:"Find",type:"code"},{key:"newString",label:"Replace",type:"code"},{key:"replaceAll",label:"Replace All",type:"text"}]},multiedit:{displayName:"Multi-Edit",category:"file",outputLanguage:"diff",inputFields:[{key:"filePath",label:"File Path",type:"file"},{key:"edits",label:"Edits",type:"code",language:"json"}]},bash:{displayName:"Shell Command",category:"system",outputLanguage:"text",inputFields:[{key:"command",label:"Command",type:"command",language:"bash"},{key:"description",label:"Description",type:"text"},{key:"timeout",label:"Timeout (ms)",type:"text"}]},grep:{displayName:"Search Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"},{key:"include",label:"Include Pattern",type:"pattern"}]},glob:{displayName:"Find Files",category:"search",outputLanguage:"text",inputFields:[{key:"pattern",label:"Pattern",type:"pattern"},{key:"path",label:"Directory",type:"file"}]},list:{displayName:"List Directory",category:"file",outputLanguage:"text",inputFields:[{key:"path",label:"Directory",type:"file"},{key:"ignore",label:"Ignore Patterns",type:"pattern"}]},task:{displayName:"Agent Task",category:"ai",outputLanguage:"markdown",inputFields:[{key:"description",label:"Task",type:"text"},{key:"prompt",label:"Instructions",type:"text"},{key:"subagent_type",label:"Agent Type",type:"text"}]},webfetch:{displayName:"Fetch URL",category:"web",outputLanguage:"auto",inputFields:[{key:"url",label:"URL",type:"text"},{key:"format",label:"Format",type:"text"},{key:"timeout",label:"Timeout",type:"text"}]},websearch:{displayName:"Web Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"numResults",label:"Results Count",type:"text"},{key:"type",label:"Search Type",type:"text"}]},codesearch:{displayName:"Code Search",category:"web",outputLanguage:"markdown",inputFields:[{key:"query",label:"Search Query",type:"text"},{key:"tokensNum",label:"Tokens",type:"text"}]},todowrite:{displayName:"Update Todo List",category:"system",outputLanguage:"json",inputFields:[{key:"todos",label:"Todo Items",type:"code",language:"json"}]},todoread:{displayName:"Read Todo List",category:"system",outputLanguage:"json",inputFields:[]},skill:{displayName:"Load Skill",category:"ai",outputLanguage:"markdown",inputFields:[{key:"name",label:"Skill Name",type:"text"}]}};function il(s){return iy[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function ly(s,r,t){const n=il(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=tn(o);if(a)return a}if(s==="webfetch"){if(r.trim().startsWith("{")||r.trim().startsWith("["))try{return JSON.parse(r),"json"}catch{}if(r.trim().startsWith("<"))return"html";if(r.includes("```"))return"markdown"}return"text"}return n.outputLanguage||"text"}function tn(s){const r=s.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[r||""]||null}const cy=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function em(s){const r=s.split(".").pop()?.toLowerCase();return cy.includes(r||"")}function dy(s){const r=s.split(".").pop()?.toLowerCase();return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",svg:"image/svg+xml",webp:"image/webp",ico:"image/x-icon",bmp:"image/bmp",avif:"image/avif"}[r||""]||"image/png"}function uy(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${i}: ${l}`}).join(`
12
+ `):String(s)}const ll=c.createContext(null),An=()=>{const s=c.useContext(ll);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},tm=s=>{const r=An();return s(r)},my=()=>tm(s=>s.runtime.isDesktop),sm=()=>tm(s=>s.runtime.isVSCode),fy=Uf("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg typography-ui-label font-medium transition-[background-color,border-color,color,box-shadow,opacity] duration-150 ease-in-out disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-none hover:bg-primary/90",destructive:"bg-destructive text-white shadow-none hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-none hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-none hover:bg-secondary/80",ghost:"text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-lg gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-lg px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function Ne({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?Jd:"button";return e.jsx(a,{"data-slot":"button",className:P(fy({variant:r,size:t,className:s})),...o})}const py=({mode:s,onModeChange:r,className:t})=>{const n=c.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(Ne,{size:"sm",variant:"ghost",className:P("h-5 w-5 p-0 opacity-60 hover:opacity-100",t),onClick:n,title:s==="side-by-side"?"Switch to unified view":"Switch to side-by-side view",children:s==="side-by-side"?e.jsx(Vf,{className:"h-3 w-3"}):e.jsx(Gf,{className:"h-3 w-3"})})},cl=Ce.createContext(void 0);function sn(){const s=Ce.useContext(cl);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function fa(){return Ce.useContext(cl)}const hy="Flexoki",gy="dark",xy={"editor.background":"#100F0F","editor.foreground":"#CECDC3","editor.hoverHighlightBackground":"#343331","editor.lineHighlightBackground":"#1C1B1A","editor.selectionBackground":"#CECDC333","editor.selectionHighlightBackground":"#CECDC333","editor.findMatchBackground":"#AD8301","editor.findMatchHighlightBackground":"#AD8301cc","editor.findRangeHighlightBackground":"#1C1B1A","editor.inactiveSelectionBackground":"#282726","editor.lineHighlightBorder":"#282726","editor.rangeHighlightBackground":"#403E3C","notifications.background":"#282726","editorInlayHint.typeBackground":"#343331","editorInlayHint.typeForeground":"#CECDC3","editorWhitespace.foreground":"#403E3C","editorIndentGuide.background1":"#343331","editorHoverWidget.background":"#282726","editorLineNumber.activeForeground":"#CECDC3","editorLineNumber.foreground":"#403E3C","editorGutter.background":"#100F0F","editorGutter.modifiedBackground":"#3AA99F","editorGutter.addedBackground":"#879A39","editorGutter.deletedBackground":"#D14D41","editorBracketMatch.background":"#282726","editorBracketMatch.border":"#343331","editorError.foreground":"#D14D41","editorWarning.foreground":"#DA702C","editorInfo.foreground":"#4385BE","diffEditor.insertedTextBackground":"#66800B99","diffEditor.removedTextBackground":"#AF302999","editorGroupHeader.tabsBackground":"#100F0F","editorGroup.border":"#343331","tab.activeBackground":"#100F0F","tab.inactiveBackground":"#1C1B1A","tab.inactiveForeground":"#878580","tab.activeForeground":"#CECDC3","tab.hoverBackground":"#343331","tab.unfocusedHoverBackground":"#343331","tab.border":"#343331","tab.activeModifiedBorder":"#D0A215","tab.inactiveModifiedBorder":"#4385BE","tab.unfocusedActiveModifiedBorder":"#AD8301","tab.unfocusedInactiveModifiedBorder":"#205EA6","editorWidget.background":"#1C1B1A","editorWidget.border":"#343331","editorSuggestWidget.background":"#100F0F","editorSuggestWidget.border":"#343331","editorSuggestWidget.foreground":"#CECDC3","editorSuggestWidget.highlightForeground":"#878580","editorSuggestWidget.selectedBackground":"#343331","peekView.border":"#343331","peekViewEditor.background":"#100F0F","peekViewEditor.matchHighlightBackground":"#403E3C","peekViewResult.background":"#1C1B1A","peekViewResult.fileForeground":"#CECDC3","peekViewResult.lineForeground":"#878580","peekViewResult.matchHighlightBackground":"#403E3C","peekViewResult.selectionBackground":"#282726","peekViewResult.selectionForeground":"#575653","peekViewTitle.background":"#343331","peekViewTitleDescription.foreground":"#878580","peekViewTitleLabel.foreground":"#CECDC3","merge.currentHeaderBackground":"#879A39","merge.currentContentBackground":"#66800B","merge.incomingHeaderBackground":"#3AA99F","merge.incomingContentBackground":"#24837B","merge.border":"#343331","merge.commonContentBackground":"#403E3C","merge.commonHeaderBackground":"#343331","panel.background":"#100F0F","panel.border":"#343331","panelTitle.activeBorder":"#403E3C","panelTitle.activeForeground":"#CECDC3","panelTitle.inactiveForeground":"#878580","statusBar.background":"#100F0F","statusBar.foreground":"#CECDC3","statusBar.border":"#343331","statusBar.debuggingBackground":"#D14D41","statusBar.debuggingForeground":"#CECDC3","statusBar.noFolderBackground":"#403E3C","statusBar.noFolderForeground":"#575653","titleBar.activeBackground":"#100F0F","titleBar.activeForeground":"#CECDC3","titleBar.inactiveBackground":"#1C1B1A","titleBar.inactiveForeground":"#878580","titleBar.border":"#343331","menu.foreground":"#CECDC3","menu.background":"#100F0F","menu.selectionForeground":"#CECDC3","menu.selectionBackground":"#343331","menu.border":"#343331","editorInlayHint.foreground":"#878580","editorInlayHint.background":"#343331","terminal.foreground":"#CECDC3","terminal.background":"#100F0F","terminalCursor.foreground":"#CECDC3","terminalCursor.background":"#100F0F","terminal.ansiRed":"#D14D41","terminal.ansiGreen":"#879A39","terminal.ansiYellow":"#D0A215","terminal.ansiBlue":"#4385BE","terminal.ansiMagenta":"#3AA99F","terminal.ansiCyan":"#3AA99F","activityBar.background":"#100F0F","activityBar.foreground":"#CECDC3","activityBar.inactiveForeground":"#878580","activityBar.activeBorder":"#CECDC3","activityBar.border":"#343331","sideBar.background":"#100F0F","sideBar.foreground":"#CECDC3","sideBar.border":"#343331","sideBarTitle.foreground":"#CECDC3","sideBarSectionHeader.background":"#1C1B1A","sideBarSectionHeader.foreground":"#CECDC3","sideBarSectionHeader.border":"#343331","sideBar.activeBackground":"#403E3C","sideBar.activeForeground":"#CECDC3","sideBar.hoverBackground":"#343331","sideBar.hoverForeground":"#878580","sideBar.folderIcon.foreground":"#879A39","sideBar.fileIcon.foreground":"#4385BE","list.warningForeground":"#DA702C","list.errorForeground":"#D14D41","list.inactiveSelectionBackground":"#343331","list.activeSelectionBackground":"#403E3C","list.inactiveSelectionForeground":"#CECDC3","list.activeSelectionForeground":"#CECDC3","list.hoverForeground":"#CECDC3","list.hoverBackground":"#343331","input.background":"#1C1B1A","input.foreground":"#CECDC3","input.border":"#343331","input.placeholderForeground":"#878580","inputOption.activeBorder":"#343331","inputOption.activeBackground":"#282726","inputOption.activeForeground":"#CECDC3","inputValidation.infoBackground":"#3AA99F","inputValidation.infoBorder":"#24837B","inputValidation.warningBackground":"#DA702C","inputValidation.warningBorder":"#BC5215","inputValidation.errorBackground":"#D14D41","inputValidation.errorBorder":"#AF3029","dropdown.background":"#1C1B1A","dropdown.foreground":"#CECDC3","dropdown.border":"#343331","dropdown.listBackground":"#100F0F","badge.background":"#3AA99F","activityBarBadge.background":"#3AA99F","button.background":"#3AA99F","button.foreground":"#100F0F","badge.foreground":"#100F0F","activityBarBadge.foreground":"#100F0F"},yy=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#CECDC3"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#DA702C"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#D0A215"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#DA702C"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#DA702C"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#DA702C"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#879A39"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#DA702C",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#CECDC3"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#879A39"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#CE5D97"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#282726"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#CECDC3"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#4385BE"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#3AA99F"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#CECDC3"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#879A39"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#D14D41"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#4385BE"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#878580"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#575653"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#8B7EC8"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#D0A215"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#D14D41"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#4385BE"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#CE5D97"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#4385BE"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#4385BE"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#CE5D97"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#D0A215"}},{name:"types",scope:["support.type"],settings:{foreground:"#D0A215"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#CECDC3"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#CE5D97"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#D0A215"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#D14D41"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#DA702C"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#CE5D97"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#D0A215"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#CECDC3"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#878580"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#D0A215"}},{name:"green",scope:[],settings:{foreground:"#879A39"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#3AA99F"}},{name:"blue",scope:[],settings:{foreground:"#4385BE"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#8B7EC8"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#CE5D97"}},{name:"red",scope:[],settings:{foreground:"#D14D41"}},{name:"orange",scope:[],settings:{foreground:"#DA702C"}}],by={name:hy,type:gy,colors:xy,tokenColors:yy},wy="Flexoki",vy="light",jy={"editor.background":"#FFFCF0","editor.foreground":"#100F0F","editor.hoverHighlightBackground":"#DAD8CE","editor.lineHighlightBackground":"#F2F0E5","editor.selectionBackground":"#100F0F44","editor.selectionHighlightBackground":"#100F0F44","editor.findMatchBackground":"#D0A215","editor.findMatchHighlightBackground":"#D0A215cc","editor.findRangeHighlightBackground":"#F2F0E5","editor.inactiveSelectionBackground":"#E6E4D9","editor.lineHighlightBorder":"#E6E4D9","editor.rangeHighlightBackground":"#CECDC3","notifications.background":"#E6E4D9","editorInlayHint.typeBackground":"#DAD8CE","editorInlayHint.typeForeground":"#100F0F","editorWhitespace.foreground":"#CECDC3","editorIndentGuide.background1":"#DAD8CE","editorHoverWidget.background":"#E6E4D9","editorLineNumber.activeForeground":"#100F0F","editorLineNumber.foreground":"#CECDC3","editorGutter.background":"#FFFCF0","editorGutter.modifiedBackground":"#24837B","editorGutter.addedBackground":"#66800B","editorGutter.deletedBackground":"#AF3029","editorBracketMatch.background":"#E6E4D9","editorBracketMatch.border":"#DAD8CE","editorError.foreground":"#AF3029","editorWarning.foreground":"#BC5215","editorInfo.foreground":"#205EA6","diffEditor.insertedTextBackground":"#879A3999","diffEditor.removedTextBackground":"#D14D4199","editorGroupHeader.tabsBackground":"#FFFCF0","editorGroup.border":"#DAD8CE","tab.activeBackground":"#FFFCF0","tab.inactiveBackground":"#F2F0E5","tab.inactiveForeground":"#6F6E69","tab.activeForeground":"#100F0F","tab.hoverBackground":"#DAD8CE","tab.unfocusedHoverBackground":"#DAD8CE","tab.border":"#DAD8CE","tab.activeModifiedBorder":"#AD8301","tab.inactiveModifiedBorder":"#205EA6","tab.unfocusedActiveModifiedBorder":"#D0A215","tab.unfocusedInactiveModifiedBorder":"#4385BE","editorWidget.background":"#F2F0E5","editorWidget.border":"#DAD8CE","editorSuggestWidget.background":"#FFFCF0","editorSuggestWidget.border":"#DAD8CE","editorSuggestWidget.foreground":"#100F0F","editorSuggestWidget.highlightForeground":"#6F6E69","editorSuggestWidget.selectedBackground":"#DAD8CE","peekView.border":"#DAD8CE","peekViewEditor.background":"#FFFCF0","peekViewEditor.matchHighlightBackground":"#CECDC3","peekViewResult.background":"#F2F0E5","peekViewResult.fileForeground":"#100F0F","peekViewResult.lineForeground":"#6F6E69","peekViewResult.matchHighlightBackground":"#CECDC3","peekViewResult.selectionBackground":"#E6E4D9","peekViewResult.selectionForeground":"#B7B5AC","peekViewTitle.background":"#DAD8CE","peekViewTitleDescription.foreground":"#6F6E69","peekViewTitleLabel.foreground":"#100F0F","merge.currentHeaderBackground":"#66800B","merge.currentContentBackground":"#879A39","merge.incomingHeaderBackground":"#24837B","merge.incomingContentBackground":"#3AA99F","merge.border":"#DAD8CE","merge.commonContentBackground":"#CECDC3","merge.commonHeaderBackground":"#DAD8CE","panel.background":"#FFFCF0","panel.border":"#DAD8CE","panelTitle.activeBorder":"#CECDC3","panelTitle.activeForeground":"#100F0F","panelTitle.inactiveForeground":"#6F6E69","statusBar.background":"#FFFCF0","statusBar.foreground":"#100F0F","statusBar.border":"#DAD8CE","statusBar.debuggingBackground":"#AF3029","statusBar.debuggingForeground":"#100F0F","statusBar.noFolderBackground":"#CECDC3","statusBar.noFolderForeground":"#B7B5AC","titleBar.activeBackground":"#FFFCF0","titleBar.activeForeground":"#100F0F","titleBar.inactiveBackground":"#F2F0E5","titleBar.inactiveForeground":"#6F6E69","titleBar.border":"#DAD8CE","menu.foreground":"#100F0F","menu.background":"#FFFCF0","menu.selectionForeground":"#100F0F","menu.selectionBackground":"#DAD8CE","menu.border":"#DAD8CE","editorInlayHint.foreground":"#6F6E69","editorInlayHint.background":"#DAD8CE","terminal.foreground":"#100F0F","terminal.background":"#FFFCF0","terminalCursor.foreground":"#100F0F","terminalCursor.background":"#FFFCF0","terminal.ansiRed":"#AF3029","terminal.ansiGreen":"#66800B","terminal.ansiYellow":"#AD8301","terminal.ansiBlue":"#205EA6","terminal.ansiMagenta":"#24837B","terminal.ansiCyan":"#24837B","activityBar.background":"#FFFCF0","activityBar.foreground":"#100F0F","activityBar.inactiveForeground":"#6F6E69","activityBar.activeBorder":"#100F0F","activityBar.border":"#DAD8CE","sideBar.background":"#FFFCF0","sideBar.foreground":"#100F0F","sideBar.border":"#DAD8CE","sideBarTitle.foreground":"#100F0F","sideBarSectionHeader.background":"#F2F0E5","sideBarSectionHeader.foreground":"#100F0F","sideBarSectionHeader.border":"#DAD8CE","sideBar.activeBackground":"#CECDC3","sideBar.activeForeground":"#100F0F","sideBar.hoverBackground":"#DAD8CE","sideBar.hoverForeground":"#6F6E69","sideBar.folderIcon.foreground":"#66800B","sideBar.fileIcon.foreground":"#205EA6","list.warningForeground":"#BC5215","list.errorForeground":"#AF3029","list.inactiveSelectionBackground":"#DAD8CE","list.activeSelectionBackground":"#CECDC3","list.inactiveSelectionForeground":"#100F0F","list.activeSelectionForeground":"#100F0F","list.hoverForeground":"#100F0F","list.hoverBackground":"#DAD8CE","input.background":"#F2F0E5","input.foreground":"#100F0F","input.border":"#DAD8CE","input.placeholderForeground":"#6F6E69","inputOption.activeBorder":"#DAD8CE","inputOption.activeBackground":"#E6E4D9","inputOption.activeForeground":"#100F0F","inputValidation.infoBackground":"#24837B","inputValidation.infoBorder":"#3AA99F","inputValidation.warningBackground":"#BC5215","inputValidation.warningBorder":"#DA702C","inputValidation.errorBackground":"#AF3029","inputValidation.errorBorder":"#D14D41","dropdown.background":"#F2F0E5","dropdown.foreground":"#100F0F","dropdown.border":"#DAD8CE","dropdown.listBackground":"#FFFCF0","badge.background":"#24837B","activityBarBadge.background":"#24837B","button.background":"#24837B","button.foreground":"#FFFCF0","badge.foreground":"#FFFCF0","activityBarBadge.foreground":"#FFFCF0"},Sy=[{name:"plain",scope:["source","support.type.property-name.css"],settings:{foreground:"#100F0F"}},{name:"classes",scope:["entity.name.type.class"],settings:{foreground:"#BC5215"}},{name:"interfaces",scope:["entity.name.type.interface","entity.name.type"],settings:{foreground:"#AD8301"}},{name:"structs",scope:["entity.name.type.struct"],settings:{foreground:"#BC5215"}},{name:"enums",scope:["entity.name.type.enum"],settings:{foreground:"#BC5215"}},{name:"keys",scope:["meta.object-literal.key","support.type.property-name"],settings:{foreground:"#BC5215"}},{name:"methods",scope:["entity.name.function.method","meta.function.method"],settings:{foreground:"#66800B"}},{name:"functions",scope:["entity.name.function","support.function","meta.function-call.generic"],settings:{foreground:"#BC5215",fontStyle:"bold"}},{name:"variables",scope:["variable","meta.variable","variable.other.object.property"],settings:{foreground:"#100F0F"}},{name:"variablesOther",scope:["variable.other.object","variable.other.readwrite.alias"],settings:{foreground:"#66800B"}},{name:"globalVariables",scope:["variable.other.global","variable.language.this"],settings:{foreground:"#A02F6F"}},{name:"localVariables",scope:["variable.other.local"],settings:{foreground:"#E6E4D9"}},{name:"parameters",scope:["variable.parameter","meta.parameter"],settings:{foreground:"#100F0F"}},{name:"properties",scope:["variable.other.property","meta.property"],settings:{foreground:"#205EA6"}},{name:"strings",scope:["string","string.other.link","markup.inline.raw.string.markdown"],settings:{foreground:"#24837B"}},{name:"stringEscapeSequences",scope:["constant.character.escape","constant.other.placeholder"],settings:{foreground:"#100F0F"}},{name:"keywords",scope:["keyword"],settings:{foreground:"#66800B"}},{name:"keywordsControl",scope:["keyword.control.import","keyword.control.from","keyword.import"],settings:{foreground:"#AF3029"}},{name:"storageModifiers",scope:["storage.modifier","keyword.modifier","storage.type"],settings:{foreground:"#205EA6"}},{name:"comments",scope:["comment","punctuation.definition.comment"],settings:{foreground:"#6F6E69"}},{name:"docComments",scope:["comment.documentation","comment.line.documentation"],settings:{foreground:"#B7B5AC"}},{name:"numbers",scope:["constant.numeric"],settings:{foreground:"#5E409D"}},{name:"booleans",scope:["constant.language.boolean","constant.language.json"],settings:{foreground:"#AD8301"}},{name:"operators",scope:["keyword.operator"],settings:{foreground:"#AF3029"}},{name:"macros",scope:["entity.name.function.preprocessor","meta.preprocessor"],settings:{foreground:"#205EA6"}},{name:"preprocessor",scope:["meta.preprocessor"],settings:{foreground:"#A02F6F"}},{name:"urls",scope:["markup.underline.link"],settings:{foreground:"#205EA6"}},{name:"tags",scope:["entity.name.tag"],settings:{foreground:"#205EA6"}},{name:"jsxTags",scope:["support.class.component"],settings:{foreground:"#A02F6F"}},{name:"attributes",scope:["entity.other.attribute-name","meta.attribute"],settings:{foreground:"#AD8301"}},{name:"types",scope:["support.type"],settings:{foreground:"#AD8301"}},{name:"constants",scope:["variable.other.constant","variable.readonly"],settings:{foreground:"#100F0F"}},{name:"labels",scope:["entity.name.label","punctuation.definition.label"],settings:{foreground:"#A02F6F"}},{name:"namespaces",scope:["entity.name.namespace","storage.modifier.namespace","markup.bold.markdown"],settings:{foreground:"#AD8301"}},{name:"modules",scope:["entity.name.module","storage.modifier.module"],settings:{foreground:"#AF3029"}},{name:"typeParameters",scope:["variable.type.parameter","variable.parameter.type"],settings:{foreground:"#BC5215"}},{name:"exceptions",scope:["keyword.control.exception","keyword.control.trycatch"],settings:{foreground:"#A02F6F"}},{name:"decorators",scope:["meta.decorator","punctuation.decorator","entity.name.function.decorator"],settings:{foreground:"#AD8301"}},{name:"calls",scope:["variable.function"],settings:{foreground:"#100F0F"}},{name:"punctuation",scope:["punctuation","punctuation.terminator","punctuation.definition.tag","punctuation.separator","punctuation.definition.string","punctuation.section.block"],settings:{foreground:"#6F6E69"}},{name:"yellow",scope:["storage.type.numeric.go","storage.type.byte.go","storage.type.boolean.go","storage.type.string.go","storage.type.uintptr.go","storage.type.error.go","storage.type.rune.go","constant.language.go","support.class.dart","keyword.other.documentation","storage.modifier.import.java","punctuation.definition.list.begin.markdown","punctuation.definition.quote.begin.markdown","meta.separator.markdown","entity.name.section.markdown"],settings:{foreground:"#AD8301"}},{name:"green",scope:[],settings:{foreground:"#66800B"}},{name:"cyan",scope:["markup.italic.markdown","support.type.python","variable.legacy.builtin.python","support.constant.property-value.css","storage.modifier.attribute.swift"],settings:{foreground:"#24837B"}},{name:"blue",scope:[],settings:{foreground:"#205EA6"}},{name:"purple",scope:["keyword.channel.go","keyword.other.platform.os.swift"],settings:{foreground:"#5E409D"}},{name:"magenta",scope:["punctuation.definition.heading.markdown"],settings:{foreground:"#A02F6F"}},{name:"red",scope:[],settings:{foreground:"#AF3029"}},{name:"orange",scope:[],settings:{foreground:"#BC5215"}}],ky={name:wy,type:vy,colors:jy,tokenColors:Sy},dl="flexoki-dark",ul="flexoki-light",Ny=by,Cy=ky;function rm(s,r){return Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0}),Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0}),s}function nm(s,r,t){const n=s.colors?.["editor.background"],o=s.colors?.["editor.foreground"];if(!n||!o)throw new Error(`Flexoki Shiki theme "${r}" is missing editor.background/editor.foreground`);const a=s.tokenColors??[];return{...s,name:r,type:t,fg:o,bg:n,settings:a}}const ml=nm(Ny,dl,"dark"),fl=nm(Cy,ul,"light");rm(ml,dl);rm(fl,ul);const Sn={dark:dl,light:ul},yc=[fl,ml];let bc=!1;function om(){bc||(Pl(Sn.dark,async()=>ml),Pl(Sn.light,async()=>fl),bc=!0)}const My=`
13
+ :host {
14
+ font-family: var(--font-mono);
15
+ font-size: var(--text-code);
16
+ }
17
+
18
+ :host, pre, [data-diffs], [data-code] {
19
+ transform: translateZ(0);
20
+ -webkit-transform: translateZ(0);
21
+ -webkit-backface-visibility: hidden;
22
+ backface-visibility: hidden;
23
+ }
24
+
25
+ pre, [data-code] {
26
+ font-family: var(--font-mono);
27
+ font-size: var(--text-code);
28
+ }
29
+
30
+ [data-code] {
31
+ -webkit-overflow-scrolling: touch;
32
+ }
33
+ /* Reduce hunk separator height */
34
+ [data-separator-content] {
35
+ height: 24px !important;
36
+ }
37
+ [data-expand-button] {
38
+ height: 24px !important;
39
+ width: 24px !important;
40
+ }
41
+ [data-separator-multi-button] {
42
+ row-gap: 0 !important;
43
+ }
44
+ [data-expand-up] {
45
+ height: 12px !important;
46
+ min-height: 12px !important;
47
+ max-height: 12px !important;
48
+ margin: 0 !important;
49
+ margin-top: 3px !important;
50
+ padding: 0 !important;
51
+ border-radius: 4px 4px 0 0 !important;
52
+ }
53
+ [data-expand-down] {
54
+ height: 12px !important;
55
+ min-height: 12px !important;
56
+ max-height: 12px !important;
57
+ margin: 0 !important;
58
+ margin-top: -3px !important;
59
+ padding: 0 !important;
60
+ border-radius: 0 0 4px 4px !important;
61
+ }
62
+ `;function Dy(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}const wc=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const l=fa()?.currentTheme?.metadata?.variant==="dark";om();const d=Ce.useRef(null),u=Ce.useMemo(()=>{const f=Dy(n,s,r);if(d.current?.key===f)return d.current.fileDiff;const p={name:n,contents:s,cacheKey:`old-${f}`},g={name:n,contents:r,cacheKey:`new-${f}`},w=fi(p,g);return d.current={key:f,fileDiff:w},w},[n,s,r,t]),m=Ce.useMemo(()=>({theme:{dark:Sn.dark,light:Sn.light},themeType:l?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:My}),[l,o,a]);return typeof window>"u"?null:e.jsx(dt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(Kf,{fileDiff:u,options:m})})},Ay=1100,Ey=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},vc=(s,r)=>{const t=s??0,n=r??0;return!t&&!n?null:e.jsxs("span",{className:"typography-meta flex flex-shrink-0 items-center gap-1 text-xs whitespace-nowrap",children:[t?e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",t]}):null,n?e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",n]}):null]})},Iy=c.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=c.useCallback(i=>{if(!o)return i;const l=i.lastIndexOf("/");return l>=0?i.slice(l+1):i},[o]);return s.length===0?null:e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(t.path)}),vc(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Mt,{className:"size-4 opacity-50"})]})}),e.jsx(Gt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(Ju,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(Zu,{value:i.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(i.path)}),e.jsx("span",{className:"ml-auto",children:vc(i.insertions,i.deletions)})]})},i.path))})})]})}),Py=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Ty=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=c.useMemo(()=>tn(s)||"text",[s]);return em(s)?e.jsx(Py,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(wc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})}):e.jsx("div",{className:"absolute inset-0 hidden",children:e.jsx(wc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),Fy=c.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Yt(c.useCallback(l=>l.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=c.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(Ty,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Ry=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=me(),{currentDirectory:n}=ct(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},_y=()=>{const{git:s}=An(),r=Ry(),{screenWidth:t,isMobile:n}=Ft(),o=al(r??null),a=Xu(r??null),i=Yt(_=>_.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=Yt(),[m,f]=c.useState(null),[p,g]=c.useState(0),[w,h]=c.useState(null),j=c.useRef(null),b=_e(_=>_.pendingDiffFile),x=_e(_=>_.setPendingDiffFile),v=_e(_=>_.diffLayoutPreference),N=_e(_=>_.diffFileLayout),y=_e(_=>_.setDiffFileLayout),S=_e(_=>_.diffWrapLines),D=_e(_=>_.setDiffWrapLines),M=n||S,C=c.useMemo(()=>{if(!a?.files)return[];const _=a.diffStats??{};return a.files.map(q=>({...q,insertions:_[q.path]?.insertions??0,deletions:_[q.path]?.deletions??0,isNew:Ey(q)})).sort((q,O)=>q.path.localeCompare(O.path))},[a]),k=c.useMemo(()=>m?C.find(_=>_.path===m)??null:null,[C,m]),A=c.useMemo(()=>{if(!k)return null;const _=N[k.path];if(_)return _;if(v==="inline")return"inline";if(v==="side-by-side")return"side-by-side";const q=t<Ay;return k.isNew||q?"inline":"side-by-side"},[k,N,v,t]);c.useEffect(()=>{r&&(l(r),Yt.getState().directories.get(r)?.status||d(r,s))},[r,l,d,s]),c.useEffect(()=>{b&&(f(b),x(null))},[b,x]),c.useEffect(()=>{!m&&!b&&C.length>0&&f(C[0].path)},[C,m,b]),c.useEffect(()=>{m&&C.length>0&&(C.some(q=>q.path===m)||f(C[0]?.path??null))},[C,m]);const E=c.useCallback(_=>{f(_)},[]),R=(A??"side-by-side")==="side-by-side",V=Yt(c.useCallback(_=>!r||!m?null:_.directories.get(r)?.diffCache.get(m)??null,[r,m])),T=!!V,B=!!m&&!T;c.useEffect(()=>{if(h(null),!r||!m){j.current=null;return}if(V){j.current=null;return}const _=`${r}::${m}::${p}`;if(j.current===_)return;j.current=_;let q=!1;return(async()=>{try{const O=s.getGitFileDiff(r,{path:m}),z=15e3,U=new Promise((oe,Q)=>{setTimeout(()=>Q(new Error(`Timed out after ${z}ms`)),z)}),ne=await Promise.race([O,U]);if(q)return;u(r,m,{original:ne.original??"",modified:ne.modified??""})}catch(O){if(q)return;const z=O instanceof Error?O.message:String(O);h(z)}})(),()=>{q=!0,j.current===_&&(j.current=null)}},[r,m,V,s,u,p]);const re=()=>!r||C.length===0?null:C.map(_=>e.jsx(Fy,{directory:r,filePath:_.path,isVisible:_.path===m,renderSideBySide:R,wrapLines:M},_.path)),Y=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading repository status…"]}):o===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):C.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[re(),B&&!T&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:w?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:w}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{h(null),g(_=>_+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading diff…"]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(Bi,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${C.length} ${C.length===1?"file":"files"} changed`})]}),e.jsx(Iy,{changedFiles:C,selectedFile:m,selectedFileEntry:k,onSelectFile:E,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),k&&e.jsx("button",{type:"button",onClick:()=>D(!S),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${M?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:M?"Disable line wrap":"Enable line wrap",children:e.jsx(qf,{className:"size-4"})}),k&&A&&e.jsx(py,{mode:A==="side-by-side"?"side-by-side":"unified",onModeChange:_=>{if(!k)return;const q=_==="side-by-side"?"side-by-side":"inline";y(k.path,q)}})]}),Y()]})},Oy=()=>{const{git:s}=An(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=me(),{currentDirectory:o}=ct(),a=r?n.get(r)??void 0:void 0,l=t.find(p=>p.id===r)?.directory,d=a?.path??l??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Yt(),f=ay(d??null);return c.useEffect(()=>{d&&(u(d),Yt.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},am=Ce.forwardRef(({className:s,...r},t)=>e.jsx(Zd,{className:P("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...r,ref:t,children:e.jsx(Yf,{className:P("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));am.displayName=Zd.displayName;const $y={},_o=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},jc=s=>_o(s)??"__global__",Ly=s=>{const r=Object.entries(s??{}),t=r.filter(([,i])=>i?.status==="connected").length,n=r.length,o=r.some(([,i])=>i?.status==="failed"),a=r.some(([,i])=>i?.status==="needs_auth"||i?.status==="needs_client_registration");return{connected:t,total:n,hasFailed:o,hasAuthRequired:a}},$n=Bt()(Xt((s,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:t=>{const n=jc(t??ct.getState().currentDirectory);return r().byDirectory[n]??$y},refresh:async t=>{const n=_o(t?.directory??ct.getState().currentDirectory),o=jc(n);t?.silent||s(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const l=(await ke.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};s(d=>({byDirectory:{...d.byDirectory,[o]:l},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const i=a instanceof Error?a.message:"Failed to load MCP status";s(l=>({loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:i}}))}},connect:async(t,n)=>{const o=_o(n??ct.getState().currentDirectory);await ke.getApiClient().mcp.connect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(t,n)=>{const o=_o(n??ct.getState().currentDirectory);await ke.getApiClient().mcp.disconnect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function By(s){return e.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",stroke:"currentColor",strokeWidth:"0.5",fillRule:"evenodd",viewBox:"-0.5 -0.5 25 25",...s,children:[e.jsx("path",{d:"M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"}),e.jsx("path",{d:"M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"})]})}const zy=s=>{if(!s)return"Unknown";switch(s.status){case"connected":return"Connected";case"failed":return`Failed: ${s.error||"Unknown error"}`;case"needs_auth":return"Needs authentication";case"needs_client_registration":return`Needs registration: ${s.error||""}`;default:return s.status}},Wy=s=>{switch(s?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Ni=({headerIconButtonClass:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(!1),{isMobile:i}=Ft(),d=ct(M=>M.currentDirectory)??null,u=$n(M=>M.getStatusForDirectory(d)),m=$n(M=>M.refresh),f=$n(M=>M.connect),p=$n(M=>M.disconnect),g=c.useCallback(M=>{M||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),t(M)},[]),w=c.useCallback(M=>{a.current||o(M)},[]),[h,j]=c.useState(!1),[b,x]=c.useState(null);c.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),c.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const v=c.useMemo(()=>Ly(u),[u]),N=c.useMemo(()=>Object.keys(u).sort((M,C)=>M.localeCompare(C)),[u]),y=c.useCallback(M=>{if(M?.preventDefault(),h)return;j(!0);const C=new Promise(k=>setTimeout(k,500));Promise.all([m({directory:d}),C]).finally(()=>{j(!1)})},[h,m,d]),S=()=>e.jsxs(e.Fragment,{children:[N.map(M=>{const C=u[M],k=Wy(C),A=C?.status==="connected",E=b===M,R=zy(C);return e.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 py-1.5 rounded-lg hover:bg-muted/50",children:[e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[i?e.jsx("span",{className:P("h-2 w-2 rounded-full flex-shrink-0",k==="success"&&"bg-status-success",k==="error"&&"bg-status-error",k==="warning"&&"bg-status-warning",k==="default"&&"bg-muted-foreground/40"),"aria-label":R}):e.jsxs(rt,{delayDuration:300,children:[e.jsx(nt,{asChild:!0,children:e.jsx("span",{className:P("h-2 w-2 rounded-full flex-shrink-0",k==="success"&&"bg-status-success",k==="error"&&"bg-status-error",k==="warning"&&"bg-status-warning",k==="default"&&"bg-muted-foreground/40"),"aria-label":R})}),e.jsx(tt,{side:"left",children:e.jsx("p",{children:R})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:M})]})}),e.jsx(am,{checked:A,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async V=>{x(M);try{V?await f(M,d):await p(M,d)}finally{x(null)}}})]},M)}),N.length===0&&e.jsx("div",{className:"px-2 py-3 typography-ui-label text-muted-foreground text-center",children:"Configure MCP servers in settings."})]}),D=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:P(s,"relative"),onClick:i?()=>t(!0):void 0,children:[e.jsx(By,{className:"h-[1.0625rem] w-[1.0625rem]"}),v.total>0&&e.jsx("span",{className:P("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",v.hasFailed?"bg-status-error":v.hasAuthRequired?"bg-status-warning":v.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return i?e.jsxs(e.Fragment,{children:[D,e.jsxs(ws,{open:r,title:"MCP Servers",onClose:()=>t(!1),renderHeader:M=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:"MCP Servers"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:h,onClick:y,"aria-label":"Refresh",children:e.jsx(Dr,{className:P("h-4 w-4",h&&"animate-spin")})}),M]})]}),children:[e.jsx("div",{className:"py-1",children:S()}),d&&e.jsx("div",{className:"px-2 py-1 border-t border-border/40 mt-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]}):e.jsxs(Ut,{open:r,onOpenChange:g,children:[e.jsxs(rt,{delayDuration:1e3,open:r?!1:n,onOpenChange:w,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:D})}),e.jsx(tt,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(Gt,{align:"end",className:"w-72",children:[e.jsxs("div",{className:"flex items-center justify-between px-2 py-1",children:[e.jsx("span",{className:"typography-ui-label font-semibold",children:"MCP Servers"}),e.jsx("button",{type:"button",className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",disabled:h,onClick:y,"aria-label":"Refresh",children:e.jsx(Dr,{className:P("h-4 w-4",h&&"animate-spin")})})]}),e.jsx(Ms,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:S()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{}),e.jsx("div",{className:"px-2 py-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]})]})},Hy=()=>{const s=_e(d=>d.setSessionSwitcherOpen),r=_e(d=>d.toggleSidebar),{isMobile:t}=Ft(),[n,o]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=c.useCallback(()=>{t?s(!0):r()},[t,s,r]),l="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:l,children:e.jsx(na,{className:"h-5 w-5"})})})},Sc=()=>{const s=_e(O=>O.setSessionSwitcherOpen),r=_e(O=>O.toggleSidebar),t=_e(O=>O.setSettingsDialogOpen),n=_e(O=>O.toggleCommandPalette),o=_e(O=>O.toggleHelpDialog),a=_e(O=>O.isSidebarOpen),i=_e(O=>O.sidebarWidth),l=_e(O=>O.activeMainTab),d=_e(O=>O.setActiveMainTab),{getCurrentModel:u}=et(),m=me(O=>O.getContextUsage),{isMobile:f}=Ft(),p=Oy(),g=da(O=>O.available),w=c.useRef(null),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ce.useEffect(()=>{if(typeof window>"u")return;const O=typeof window.opencodeDesktop<"u";j(O)},[]);const x=u(),v=x&&typeof x.limit=="object"&&x.limit!==null?x.limit:null,N=v&&typeof v.context=="number"?v.context:0,y=v&&typeof v.output=="number"?v.output:0,S=m(N,y),D=_e(O=>O.isSessionSwitcherOpen),M=c.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const z=O.tagName;(z==="INPUT"||z==="TEXTAREA"||z==="SELECT"||O.isContentEditable)&&O.blur()},[]),C=c.useCallback(()=>{if(f){M(),s(!D);return}r()},[M,f,D,s,r]),k=c.useCallback(()=>{f&&M(),s(!1),t(!0)},[M,f,s,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",E=c.useMemo(()=>h&&b?a?"pl-0":"pl-[8.0rem]":"pl-3",[h,b,a]),R=c.useCallback(()=>{if(typeof document>"u")return;const O=w.current?.getBoundingClientRect().height;O&&document.documentElement.style.setProperty("--oc-header-height",`${O}px`)},[]);Ce.useEffect(()=>{if(typeof window>"u")return;R();const O=w.current;if(!O||typeof ResizeObserver>"u")return()=>{};const z=new ResizeObserver(()=>{R()});return z.observe(O),window.addEventListener("resize",R),window.addEventListener("orientationchange",R),()=>{z.disconnect(),window.removeEventListener("resize",R),window.removeEventListener("orientationchange",R)}},[R]),Ce.useEffect(()=>{R()},[R,f]);const V=c.useCallback(async O=>{if(!O.target.closest("button, a, input, select, textarea")&&O.button===0&&h)try{const{getCurrentWindow:z}=await is(async()=>{const{getCurrentWindow:ne}=await import("./vendor-.bun-B2HtLj-d.js").then(oe=>oe.cr);return{getCurrentWindow:ne}},__vite__mapDeps([0,1]));await z().startDragging()}catch(z){console.error("Failed to start window dragging:",z)}},[h]),T=c.useCallback(async O=>{if(O.button===0&&h)try{const{getCurrentWindow:z}=await is(async()=>{const{getCurrentWindow:ne}=await import("./vendor-.bun-B2HtLj-d.js").then(oe=>oe.cr);return{getCurrentWindow:ne}},__vite__mapDeps([0,1]));await z().startDragging()}catch(z){console.error("Failed to start window dragging:",z)}},[h]),B=c.useMemo(()=>[{id:"chat",label:"Chat",icon:Xf},{id:"diff",label:"Diff",icon:nr,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Er},{id:"git",label:"Git",icon:Ot,showDot:f&&p>0}],[p,f]);Ce.useEffect(()=>{const O=z=>{if(Cs(z)&&!z.shiftKey&&!z.altKey){const U=parseInt(z.key,10);U>=1&&U<=B.length&&(z.preventDefault(),d(B[U-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[B,d]);const re=(O,z)=>{const U=l===O.id,ne=O.icon,oe=O.id==="chat",Q=O.id==="git";return e.jsxs(c.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(O.id),onMouseDown:U?T:void 0,className:P("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",U?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",U?"text-foreground":"text-muted-foreground",U&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",U&&oe&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",oe&&!(h&&b&&a)&&"border-l",Q&&"border-r",oe&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...U&&oe&&a?{"--sidebar-w":h&&b?`${i}px`:"64px"}:{},...oe&&!(h&&b&&a)||Q?{borderColor:"var(--interactive-border)"}:{}},"aria-label":O.label,"aria-selected":U,role:"tab",children:[f?e.jsx(ne,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(ne,{size:16}),e.jsx("span",{className:"header-tab-label",children:O.label})]}),oe&&!f&&S&&S.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(ki,{totalTokens:S.totalTokens,percentage:S.percentage,contextLimit:S.contextLimit,outputLimit:S.outputLimit??0,size:"compact"})}),O.badge!==void 0&&O.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:O.badge})]}),!z&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},O.id)},Y=()=>e.jsxs("div",{onMouseDown:V,className:P("app-region-drag relative flex h-12 select-none items-center",E),role:"tablist","aria-label":"Main navigation",children:[!(h&&b)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:C,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(na,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:B.map((O,z)=>re(O,z===B.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:A,children:e.jsx(Qr,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Command Palette (",Zt(),"+K)"]})})]}),e.jsx(Ni,{headerIconButtonClass:A}),e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:A,children:e.jsx(yn,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Zt(),"+.)"]})})]})]})]}),_=()=>e.jsxs("div",{className:"app-region-drag relative flex items-center justify-between gap-2 px-3 py-2 select-none",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:C,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open sessions",children:e.jsx(Qf,{className:"h-5 w-5"})}),S&&S.totalTokens>0&&l==="chat"&&e.jsx(ki,{totalTokens:S.totalTokens,percentage:S.percentage,contextLimit:S.contextLimit,outputLimit:S.outputLimit??0,size:"compact",isMobile:!0})]}),e.jsxs("div",{className:"app-region-no-drag flex items-center gap-1.5",children:[e.jsx("div",{className:"flex items-center",role:"tablist","aria-label":"Main navigation",children:B.map(O=>{const z=l===O.id,U=O.icon;return e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&M(),d(O.id)},"aria-label":O.label,"aria-selected":z,role:"tab",className:P(A,"relative",z&&"text-foreground"),children:[e.jsx(U,{className:"h-5 w-5"}),O.badge!==void 0&&O.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),e.jsx(tt,{children:e.jsx("p",{children:O.label})})]},O.id)})}),e.jsx(Ni,{headerIconButtonClass:A}),e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:k,"aria-label":"Open settings",className:P(A,"relative"),children:[e.jsx(Kr,{className:"h-5 w-5"}),g&&e.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Update available"})]})}),e.jsx(tt,{children:e.jsx("p",{children:g?"Settings (Update available)":"Settings"})})]})]})]}),q=P("header-safe-area border-b relative z-10",h?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:w,className:q,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?_():Y()})};function pl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:P("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function im({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:P("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",s),...r})}function lm({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:P("leading-none font-semibold",s),...r})}function cm({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:P("px-6",s),...r})}class as extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(pl,{className:"w-full max-w-md",children:[e.jsx(im,{className:"text-center",children:e.jsxs(lm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(pi,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(cm,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The application encountered an unexpected error. This has been logged for debugging."}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let ho=0;function ms({...s}){return e.jsx(Jf,{"data-slot":"dialog",...s})}function Uy({...s}){return e.jsx(tp,{"data-slot":"dialog-portal",...s})}const dm=Ce.forwardRef(({className:s,...r},t)=>(Ce.useEffect(()=>(ho+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{ho=Math.max(0,ho-1),ho===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(eu,{ref:t,"data-slot":"dialog-overlay",className:P("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));dm.displayName=eu.displayName;function fs({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(Uy,{"data-slot":"dialog-portal",children:[e.jsx(dm,{className:"rounded-none"}),e.jsxs(Zf,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:P("bg-background text-foreground fixed top-[50%] left-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border p-6 shadow-none overflow-hidden pwa-dialog-content",s),...o,children:[r,t&&e.jsxs(ep,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-2 right-2 rounded-lg opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none text-muted-foreground hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[e.jsx(Ht,{}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function xs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:P("flex flex-col gap-2 text-center sm:text-left",s),...r})}function qs({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:P("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function ys({className:s,...r}){return e.jsx(sp,{"data-slot":"dialog-title",className:P("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Ns({className:s,...r}){return e.jsx(rp,{"data-slot":"dialog-description",className:P("text-muted-foreground typography-ui-label",s),...r})}const kc="https://github.com/btriapitsyn/openchamber/releases";async function Vy(){try{const s=await fetch("/api/openchamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return s.ok?{success:!0}:{success:!1,error:(await s.json().catch(()=>({}))).error||`Server error: ${s.status}`}}catch(s){return{success:!1,error:s instanceof Error?s.message:"Failed to install update"}}}async function Gy(s=30,r=2e3){for(let t=0;t<s;t++){try{if((await fetch("/health",{method:"GET"})).ok)return!0}catch{}await new Promise(n=>setTimeout(n,r))}return!1}const Ci=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ce.useState(!1),[p,g]=Ce.useState("idle"),[w,h]=Ce.useState(null),j=t?.version?`${kc}/tag/v${t.version}`:kc,b=a?.total?Math.round(a.downloaded/a.total*100):0,x=u==="web",v=t?.updateCommand||"openchamber update";Ce.useEffect(()=>{s||(g("idle"),h(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(v),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},y=Ce.useCallback(async()=>{g("updating"),h(null);const D=await Vy();if(!D.success){g("error"),h(D.error||"Update failed");return}g("restarting"),await new Promise(C=>setTimeout(C,2e3)),g("reconnecting"),await Gy()?window.location.reload():(g("error"),h("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),S=p!=="idle"&&p!=="error";return e.jsx(ms,{open:s,onOpenChange:S?void 0:r,children:e.jsxs(fs,{className:"max-w-md",children:[e.jsx(xs,{children:e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(np,{className:"h-5 w-5 text-primary"}),p==="restarting"||p==="reconnecting"?"Updating...":"Update Available"]})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[(t?.currentVersion||t?.version)&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[t?.currentVersion&&e.jsx("span",{className:"font-mono",children:t.currentVersion}),t?.currentVersion&&t?.version&&e.jsx("span",{className:"text-muted-foreground",children:"→"}),t?.version&&e.jsx("span",{className:"font-mono text-primary",children:t.version})]}),x&&S&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Co,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"text-sm",children:[p==="updating"&&"Installing update...",p==="restarting"&&"Server restarting...",p==="reconnecting"&&"Waiting for server..."]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),t?.body&&!S&&e.jsx(dt,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,M)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
63
+ `]},M):D.replace(/^- /gm,"• ").trim()+`
64
+
65
+ `)})}),x&&p==="error"&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(op,{className:"h-4 w-4"}),e.jsx("span",{children:"Or update via terminal:"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 px-3 py-2 bg-muted rounded-md font-mono text-sm text-foreground overflow-x-auto",children:v}),e.jsx("button",{onClick:N,className:P("flex items-center justify-center p-2 rounded-md","text-muted-foreground hover:text-foreground hover:bg-accent","transition-colors",m&&"text-primary"),title:m?"Copied!":"Copy command",children:m?e.jsx(At,{className:"h-4 w-4"}):e.jsx(ap,{className:"h-4 w-4"})})]})]}),!x&&n&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Downloading..."}),e.jsxs("span",{className:"font-mono",children:[b,"%"]})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all duration-300",style:{width:`${b}%`}})})]}),(i||w)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:i||w})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:P("flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md","text-sm text-muted-foreground","hover:text-foreground hover:bg-accent","transition-colors"),children:[e.jsx(zo,{className:"h-4 w-4"}),"GitHub"]}),!x&&!o&&!n&&e.jsxs("button",{onClick:l,className:P("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(bn,{className:"h-4 w-4"}),"Download Update"]}),!x&&n&&e.jsxs("button",{disabled:!0,className:P("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(Co,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!x&&o&&e.jsxs("button",{onClick:d,className:P("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(Es,{className:"h-4 w-4"}),"Restart to Update"]}),x&&!S&&e.jsxs("button",{onClick:y,className:P("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(bn,{className:"h-4 w-4"}),"Update Now"]}),x&&S&&e.jsxs("button",{disabled:!0,className:P("flex-1 flex items-center justify-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary/50 text-primary-foreground","cursor-not-allowed"),children:[e.jsx(Co,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Nc=264,Cc=200,Mc=500,Ky=40,Dc="openchamber:check-for-updates",qy=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=_e(),[l,d]=c.useState(!1),u=c.useRef(0),m=c.useRef(n||Nc),[f,p]=c.useState(!1),g=da(),w=c.useRef(!1),h=g.checkForUpdates,{available:j,downloaded:b,checking:x}=g,[v,N]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),y=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const k=typeof window.opencodeDesktop<"u";N(k)},[]),c.useEffect(()=>{if(typeof window>"u")return;const k=()=>{typeof window.opencodeDesktop<"u"&&(w.current=!0,h())};return window.addEventListener(Dc,k),()=>{window.removeEventListener(Dc,k)}},[h]),c.useEffect(()=>{w.current&&(x||(j||b?p(!0):se.success("No updates available",{description:"You are running the latest version."}),w.current=!1))},[j,b,x]),c.useEffect(()=>{if(r||!l)return;const k=E=>{const R=E.clientX-u.current,V=Math.min(Mc,Math.max(Cc,m.current+R));o(V)},A=()=>{d(!1)};return window.addEventListener("pointermove",k),window.addEventListener("pointerup",A,{once:!0}),()=>{window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",A)}},[r,l,o]),c.useEffect(()=>{r&&l&&d(!1)},[r,l]);const S=c.useCallback(async k=>{if(k.button===0&&v)try{const{getCurrentWindow:A}=await is(async()=>{const{getCurrentWindow:R}=await import("./vendor-.bun-B2HtLj-d.js").then(V=>V.cr);return{getCurrentWindow:R}},__vite__mapDeps([0,1]));await A().startDragging()}catch(A){console.error("Failed to start window dragging from sidebar:",A)}},[v]);if(r)return null;const D=s?Math.min(Mc,Math.max(Cc,n||Nc)):0,M=v&&y,C=k=>{s&&(d(!0),u.current=k.clientX,m.current=D,k.preventDefault())};return e.jsxs("aside",{className:P("relative flex h-full overflow-hidden border-r",v?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",l?"transition-none":"",!s&&"border-r-0"),style:{width:`${D}px`,minWidth:`${D}px`,maxWidth:`${D}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||D===0,children:[s&&e.jsx("div",{className:P("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",l?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:C,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:P("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!s&&"pointer-events-none select-none opacity-0"),style:{width:`${D}px`,overflowX:"hidden"},"aria-hidden":!s,children:[M&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Ky}px`},onMouseDown:S,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(as,{children:t})}),e.jsx("div",{className:"flex-shrink-0 border-t border-border p-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("button",{onClick:()=>a(!0),className:P("flex items-center gap-2 rounded-md px-3 py-2","text-sm font-semibold text-muted-foreground","hover:text-foreground","transition-colors"),children:[e.jsx(Kr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),j||b?e.jsxs("button",{onClick:()=>p(!0),className:P("flex items-center gap-1.5 rounded-md px-2.5 py-1.5","text-xs font-medium","bg-primary/10 text-primary","hover:bg-primary/20","transition-colors"),children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!v&&e.jsxs(rt,{children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:P("flex items-center justify-center rounded-md p-1.5","text-muted-foreground","hover:text-foreground hover:bg-muted/50","transition-colors"),children:e.jsx(ls,{className:"h-4 w-4"})})}),e.jsx(tt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Ci,{open:f,onOpenChange:p,info:g.info,downloading:g.downloading,downloaded:g.downloaded,progress:g.progress,error:g.error,onDownload:g.downloadUpdate,onRestart:g.restartToUpdate,runtimeType:g.runtimeType})]})]})};function um({className:s,...r}){return e.jsx(Jr,{"data-slot":"command",className:P("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function Yy({title:s="Command Palette",description:r="Search for a command to run...",children:t,className:n,showCloseButton:o=!0,...a}){return e.jsxs(ms,{...a,children:[e.jsxs(xs,{className:"sr-only",children:[e.jsx(ys,{children:s}),e.jsx(Ns,{children:r})]}),e.jsx(fs,{className:P("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(um,{className:"[&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-4 [&_[cmdk-input-wrapper]_svg]:w-4 [&_[cmdk-input]]:h-8 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]_svg]:h-4 [&_[cmdk-item]_svg]:w-4 [&_[cmdk-item]]:typography-meta",children:t})})]})}function mm({className:s,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(yr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(Jr.Input,{"data-slot":"command-input",className:P("placeholder:text-muted-foreground flex h-8 w-full rounded-lg bg-transparent py-2 typography-meta outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",s),...r})]})}function fm({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(dt,{as:Jr.List,"data-slot":"command-list",outerClassName:"max-h-[min(600px,calc(100vh-10rem))] overflow-x-hidden p-0 w-full h-full min-h-0",className:P("scroll-py-1 overflow-x-hidden h-full min-h-0",s),scrollbarClassName:t??"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:n??!0,...o,children:r})}function pm({...s}){return e.jsx(Jr.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function gn({className:s,...r}){return e.jsx(Jr.Group,{"data-slot":"command-group",className:P("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:typography-meta [&_[cmdk-group-heading]]:font-medium",s),...r})}function Qo({className:s,...r}){return e.jsx(Jr.Separator,{"data-slot":"command-separator",className:P("bg-border -mx-1 h-px",s),...r})}function ss({className:s,...r}){return e.jsx(Jr.Item,{"data-slot":"command-item",className:P("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...r})}function dr({className:s,...r}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(Qr,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(to,{className:"size-3.5"}):e.jsx("span",{className:"text-xs font-medium",children:a})},n=typeof r.children=="string"?r.children:"",o=n?n.split("+").map(a=>a.trim()).filter(Boolean):[];return e.jsx("span",{"data-slot":"command-shortcut",className:P("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(Ce.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const Ac=["artful","bionic","cosmic","disco","focal","groovy","jammy","kinetic","lunar","noble","bold","brave","calm","eager","gentle","happy","keen","lively","merry","swift","warm","wise","bright","clever","daring","agile","crisp","fresh","lucid","quick","sharp","vivid","zealous"],Ec=["aardvark","beaver","chipmunk","dolphin","falcon","gopher","hedgehog","jackal","koala","lemur","mongoose","narwhal","otter","pangolin","quokka","raccoon","salamander","toucan","walrus","yak","zebra","badger","condor","dingo","egret","ferret","gecko","heron","iguana"];function Xy(){const s=Ac[Math.floor(Math.random()*Ac.length)],r=Ec[Math.floor(Math.random()*Ec.length)];return`${s}-${r}`}function Ic(s){const r=Xy();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function Qy(s,r,t=10){let n;try{const o=await tl(s);n=new Set(o?.all??[])}catch{return Ic(r)}for(let o=0;o<t;o++){const a=Ic(r);if(!n.has(a))return a}return null}const Jy=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Ha=!1;async function pa(){if(Ha)return null;const s=Pt.getState().getActiveProject();if(!s?.path)return se.error("No active project",{description:"Please select a project first."}),null;const r=s.path;let t=!1;try{t=await en(r)}catch{}if(!t)return se.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Ha=!0,Vs("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,i=await Qy(r,o);if(!i)return se.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const l=Jy(i),u=await Bu({projectDirectory:r,worktreeSlug:l,branch:i,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await sl(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=me.getState(),g=await p.createSession(void 0,u.path);if(!g)return await jx({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),se.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const w=et.getState(),h=w.agents;p.initializeNewOpenChamberSession(g.id,h),p.setSessionDirectory(g.id,u.path),p.setWorktreeMetadata(g.id,f);try{const x=w.getVisibleAgents();let v;if(w.settingsDefaultAgent){const N=x.find(y=>y.name===w.settingsDefaultAgent);N&&(v=N.name)}if(v||(v=x.find(N=>N.name==="build")?.name||x[0]?.name),v){w.setAgent(v),xt.getState().saveSessionAgentSelection(g.id,v);const N=w.settingsDefaultModel;if(N){const y=N.split("/");if(y.length===2){const[S,D]=y;if(w.getModelMetadata(S,D)){xt.getState().saveSessionModelSelection(g.id,S,D),xt.getState().saveAgentModelForSession(g.id,v,S,D);const C=w.settingsDefaultVariant;if(C){const E=w.providers.find(R=>R.id===S)?.models.find(R=>R.id===D)?.variants;E&&Object.prototype.hasOwnProperty.call(E,C)&&(w.setCurrentVariant(C),xt.getState().saveAgentModelVariantForSession(g.id,v,S,D,C))}}}}}}catch{}ct.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const b=(await ro(r)).filter(x=>x.trim().length>0);return b.length>0?(se.success("Worktree created",{description:`Branch: ${i}. Running ${b.length} setup command${b.length===1?"":"s"}...`}),Wu(u.path,r,b).then(x=>{if(x.success)se.success("Setup commands completed",{description:`All ${x.results.length} command${x.results.length===1?"":"s"} succeeded.`});else{const v=x.results.filter(y=>!y.success),N=x.results.filter(y=>y.success);se.error("Setup commands failed",{description:`${v.length} of ${x.results.length} command${x.results.length===1?"":"s"} failed.`+(N.length>0?` ${N.length} succeeded.`:"")})}}).catch(()=>{se.error("Setup commands failed",{description:"Could not execute setup commands."})})):se.success("Worktree created",{description:`Branch: ${i}`}),g}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return se.error("Failed to create worktree",{description:o}),null}finally{Ds(),Ha=!1}}const Zy=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:i,toggleSidebar:l}=_e(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=me(),f=et(T=>T.settingsAutoCreateWorktree),{currentDirectory:p}=ct(),{themeMode:g,setThemeMode:w}=sn(),h=()=>{r(!1)},j=async()=>{n("chat"),a(!1),d(),h()},b=T=>{u(T),h()},x=T=>{w(T),h()},v=()=>{t(!0),h()},N=()=>{h(),pa()},{isMobile:y}=Ft(),S=()=>{if(y){const{isSessionSwitcherOpen:T}=_e.getState();a(!T)}else l();h()},D=()=>{n("diff"),h()},M=()=>{n("git"),h()},C=()=>{n("terminal"),h()},k=()=>{o(!0),h()},A=()=>{Hn(),h()},E=()=>{i(!0),h()},R=m(p??""),V=c.useMemo(()=>R.slice(0,5),[R]);return e.jsxs(Yy,{open:s,onOpenChange:r,children:[e.jsx(mm,{placeholder:"Type a command or search..."}),e.jsxs(fm,{children:[e.jsx(pm,{children:"No results found."}),e.jsxs(gn,{heading:"Actions",children:[e.jsxs(ss,{onSelect:S,children:[e.jsx(na,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(dr,{children:[Zt()," + L"]})]}),e.jsxs(ss,{onSelect:j,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(dr,{children:f?`Shift + ${Zt()} + N`:`${Zt()} + N`})]}),e.jsxs(ss,{onSelect:N,children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(dr,{children:f?`${Zt()} + N`:`Shift + ${Zt()} + N`})]}),e.jsxs(ss,{onSelect:v,children:[e.jsx(yn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(dr,{children:[Zt()," + ."]})]}),e.jsxs(ss,{onSelect:D,children:[e.jsx(nr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(dr,{children:[Zt()," + 2"]})]}),e.jsxs(ss,{onSelect:C,children:[e.jsx(Er,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(dr,{children:[Zt()," + 3"]})]}),e.jsxs(ss,{onSelect:M,children:[e.jsx(Ot,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(dr,{children:[Zt()," + 4"]})]}),e.jsxs(ss,{onSelect:E,children:[e.jsx(or,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(dr,{children:[Zt()," + T"]})]}),e.jsxs(ss,{onSelect:k,children:[e.jsx(Kr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(dr,{children:[Zt()," + ,"]})]}),e.jsxs(ss,{onSelect:A,children:[e.jsx(Es,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(Qo,{}),e.jsxs(gn,{heading:"Theme",children:[e.jsxs(ss,{onSelect:()=>x("light"),children:[e.jsx(ip,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(At,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ss,{onSelect:()=>x("dark"),children:[e.jsx(lp,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(At,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ss,{onSelect:()=>x("system"),children:[e.jsx(tu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(At,{className:"ml-auto h-4 w-4"})]})]}),V.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Qo,{}),e.jsx(gn,{heading:"Recent Sessions",children:V.map(T=>e.jsxs(ss,{onSelect:()=>b(T.id),children:[e.jsx(zi,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:T.title||"Untitled Session"})]},T.id))})]})]})]})},eb=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(oa,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(Qr,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},tb=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(c.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),eb(t,n)]},`${t}-${n}`))},sb=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=_e(),t=et(a=>a.settingsAutoCreateWorktree),n=Zt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:Qr},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:yn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:na},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:qr},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:su},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:ar}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create New Session in Worktree":"Create New Session",icon:t?Ot:Kt},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create New Session in Worktree",icon:t?Kt:Ot},{keys:[`${n} + I`],description:"Focus Chat Input",icon:ru},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:wn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:cp},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:nr},{keys:[`${n} + 3`],description:"Open Terminal",icon:Er},{keys:[`${n} + 4`],description:"Open Git Panel",icon:Ot},{keys:[`${n} + T`],description:"Open Timeline",icon:or},{keys:[`${n} + ,`],description:"Open Settings",icon:Kr}]}];return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl w-[min(42rem,calc(100vw-1.5rem))] max-h-[calc(100dvh-2rem)] flex flex-col overflow-hidden",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(Kr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.icon&&e.jsx(i.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:i.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(i.keys)?i.keys:i.keys.split(" / ")).map((d,u)=>e.jsxs(c.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:tb(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(yn,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[e.jsx("p",{className:"font-medium mb-1",children:"Pro Tips:"}),e.jsxs("ul",{className:"space-y-0.5 typography-meta",children:[e.jsxs("li",{children:["• Use Command Palette (",n," + K) to quickly access all actions"]}),e.jsx("li",{children:"• The 5 most recent sessions appear in the Command Palette"}),e.jsx("li",{children:"• Theme cycling remembers your preference across sessions"})]})]})]})})]})]})})},Ua=new Set,Va=new Set,Ga=new Set,kn={onDeleteRequest(s){return Ua.add(s),()=>{Ua.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||Ua.forEach(r=>r(s))},onCreateRequest(s){return Va.add(s),()=>{Va.delete(s)}},requestCreate(s){const r=s??{};Va.forEach(t=>t(r))},onDirectoryRequest(s){return Ga.add(s),()=>{Ga.delete(s)}},requestDirectoryDialog(){Ga.forEach(s=>s())}};function hm(s){return e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",fill:"currentColor",viewBox:"0 0 256 256",...s,children:e.jsx("path",{d:"M232.49,192.49l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,0,1,17-17L180,187V141L128,89,76,141V187l11.51-11.52a12,12,0,0,1,17,17l-32,32a12,12,0,0,1-17,0l-32-32a12,12,0,1,1,17-17L52,187V136a12,12,0,0,1,3.51-8.49L116,67V24a12,12,0,0,1,24,0V67l60.49,60.48A12,12,0,0,1,204,136v51l11.51-11.52a12,12,0,0,1,17,17Z",transform:"rotate(180 128 128)"})})}const Pc="oc.sessions.projectCollapse",Tc="oc.sessions.expandedParents",Fc=s=>{const r=new Date(s),t=new Date,n=(i,l)=>i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(r,t)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},Qs=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Rc=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),rb=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:i,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:g,onOpenMultiRunLauncher:w,onClose:h,sentinelRef:j,children:b})=>{const{attributes:x,listeners:v,setNodeRef:N,isDragging:y}=jp({id:s});return e.jsxs("div",{ref:N,className:P("relative",y&&"opacity-40"),children:[l&&e.jsx("div",{ref:j,"data-project-id":s,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:P("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:i?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...x,children:[e.jsxs(rt,{delayDuration:1500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...v,className:"flex-1 min-w-0 flex items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-sm cursor-grab active:cursor-grabbing",children:e.jsx("span",{className:P("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(tt,{side:"right",sideOffset:8,children:t})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:P("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",m?"opacity-70":"opacity-0 group-hover/project:opacity-100"),"aria-label":"Project menu",onClick:S=>S.stopPropagation(),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&e.jsxs(vt,{onClick:w,children:[e.jsx(hm,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(vt,{onClick:h,className:"text-destructive focus:text-destructive",children:[e.jsx(Ht,{className:"mr-1.5 h-4 w-4"}),"Close Project"]})]})]}),e.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),g()},className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground hover:text-foreground flex-shrink-0 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"New session",children:e.jsx(Kt,{className:"h-4 w-4"})})]})}),b]})},nb=({projectLabel:s,isActiveProject:r})=>e.jsx("div",{className:"bg-sidebar border border-border rounded-md shadow-lg px-2 py-1.5",style:{width:"max-content",maxWidth:"280px"},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:P("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:s}),e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground ml-auto",children:e.jsx(Kt,{className:"h-4 w-4"})})]})}),Mi=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=c.useState(null),[l,d]=c.useState(""),[u,m]=c.useState(null),f=c.useRef(null),[p,g]=c.useState(new Set),[w,h]=c.useState(()=>new Map),j=c.useRef(new Set),b=c.useMemo(()=>us(),[]),[x,v]=c.useState(new Set),[N,y]=c.useState(new Map),[S,D]=c.useState(new Set),[M,C]=c.useState(null),[k,A]=c.useState(null),[E,R]=c.useState(new Set),V=c.useRef(new Map),T=c.useRef(0),B=ct(ee=>ee.homeDirectory),re=ct(ee=>ee.currentDirectory),Y=ct(ee=>ee.setDirectory),_=Pt(ee=>ee.projects),q=Pt(ee=>ee.activeProjectId),O=Pt(ee=>ee.addProject),z=Pt(ee=>ee.removeProject),U=Pt(ee=>ee.setActiveProject),ne=Pt(ee=>ee.setActiveProjectIdOnly),oe=Pt(ee=>ee.reorderProjects),Q=_e(ee=>ee.setActiveMainTab),de=_e(ee=>ee.setSessionSwitcherOpen),I=_e(ee=>ee.openMultiRunLauncher),W=et(ee=>ee.settingsAutoCreateWorktree),F=me(ee=>ee.sessions),$=me(ee=>ee.sessionsByDirectory),L=me(ee=>ee.currentSessionId),J=me(ee=>ee.setCurrentSession),pe=me(ee=>ee.updateSessionTitle),be=me(ee=>ee.shareSession),he=me(ee=>ee.unshareSession),Ae=me(ee=>ee.sessionMemoryState),je=me(ee=>ee.sessionActivityPhase),Te=me(ee=>ee.permissions),K=me(ee=>ee.worktreeMetadata),X=me(ee=>ee.availableWorktreesByProject),te=me(ee=>ee.getSessionsByDirectory),fe=me(ee=>ee.openNewSessionDraft),[ue,ae]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),H=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{try{const ee=b.getItem(Tc);if(ee){const ge=JSON.parse(ee);Array.isArray(ge)&&g(new Set(ge.filter(Oe=>typeof Oe=="string")))}const we=b.getItem(Pc);if(we){const ge=JSON.parse(we);Array.isArray(ge)&&v(new Set(ge.filter(Oe=>typeof Oe=="string")))}}catch{}},[b]),c.useEffect(()=>{typeof window>"u"||ae(typeof window.opencodeDesktop<"u")},[]);const xe=c.useMemo(()=>[...F].sort((ee,we)=>(we.time?.created||0)-(ee.time?.created||0)),[F]);c.useEffect(()=>{let ee=!1;const we=_.map(ge=>({id:ge.id,path:Qs(ge.path)})).filter(ge=>!!ge.path);return y(new Map),we.length===0?()=>{ee=!0}:(we.forEach(ge=>{en(ge.path).then(Oe=>{ee||y(Be=>{const Qe=new Map(Be);return Qe.set(ge.id,Oe),Qe})}).catch(()=>{ee||y(Oe=>{const Be=new Map(Oe);return Be.set(ge.id,null),Be})})}),()=>{ee=!0})},[_]);const G=c.useMemo(()=>{const ee=new Map;return xe.forEach(we=>{const ge=we.parentID;ge&&ee.set(we.id,ge)}),ee},[xe]),ye=c.useMemo(()=>{const ee=new Map;return xe.forEach(we=>{const ge=we.parentID;if(!ge)return;const Oe=ee.get(ge)??[];Oe.push(we),ee.set(ge,Oe)}),ee.forEach(we=>we.sort((ge,Oe)=>(Oe.time?.created||0)-(ge.time?.created||0))),ee},[xe]);c.useEffect(()=>{L&&g(ee=>{const we=new Set(ee);let ge=G.get(L)||null,Oe=!1;for(;ge;)we.has(ge)||(we.add(ge),Oe=!0),ge=G.get(ge)||null;return Oe?we:ee})},[L,G]),c.useEffect(()=>{const ee=new Set;xe.forEach(we=>{const ge=Qs(we.directory??null);ge&&ee.add(ge)}),_.forEach(we=>{const ge=Qs(we.path);ge&&ee.add(ge)}),ee.forEach(we=>{const ge=w.get(we);ge&&ge!=="unknown"||j.current.has(we)||(j.current.add(we),ke.listLocalDirectory(we).then(()=>{h(Oe=>{const Be=new Map(Oe);return Be.get(we)==="exists"?Oe:(Be.set(we,"exists"),Be)})}).catch(()=>{h(Oe=>{const Be=new Map(Oe);return Be.get(we)==="missing"?Oe:(Be.set(we,"missing"),Be)})}).finally(()=>{j.current.delete(we)}))})},[xe,_,w]),c.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const Fe=e.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-ui-label font-semibold",children:"No sessions yet"}),e.jsx("p",{className:"typography-meta mt-1",children:"Create your first session to start coding."})]}),qe=c.useCallback((ee,we,ge,Oe)=>{if(!ge){if(Oe&&Oe!==q&&ne(Oe),we&&we!==re&&Y(we,{showOverlay:!1}),s&&(Q("chat"),de(!1)),!t&&ee===L){r?.(ee);return}J(ee),r?.(ee)}},[q,t,re,L,s,r,Q,ne,J,Y,de]),Re=c.useCallback(async()=>{a&&l.trim()&&(await pe(a,l.trim()),i(null),d(""))},[a,l,pe]),Ee=c.useCallback(()=>{i(null),d("")},[]),Ye=c.useCallback(async ee=>{const we=await be(ee.id);we&&we.share?.url?se.success("Session shared",{description:"You can copy the link from the menu."}):se.error("Unable to share session")},[be]),ot=c.useCallback((ee,we)=>{navigator.clipboard.writeText(ee).then(()=>{m(we),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{se.error("Failed to copy URL")})},[]),ut=c.useCallback(async ee=>{await he(ee)?se.success("Session unshared"):se.error("Unable to unshare session")},[he]),kt=c.useCallback(ee=>{const we=[],ge=Oe=>{(ye.get(Oe)??[]).forEach(Qe=>{we.push(Qe),ge(Qe.id)})};return ge(ee),we},[ye]),Rt=me(ee=>ee.deleteSession),Et=me(ee=>ee.deleteSessions),Nt=c.useCallback(async ee=>{const we=kt(ee.id),ge=K.get(ee.id);if(ge){const Oe=ge.path,Be=[],Qe=new Set;F.forEach(It=>{const wt=K.get(It.id);wt&&wt.path===Oe&&!Qe.has(It.id)&&(Be.push(It),Qe.add(It.id),kt(It.id).forEach(Ct=>{Qe.has(Ct.id)||(Be.push(Ct),Qe.add(Ct.id))}))}),kn.requestDelete({sessions:Be,mode:"worktree",worktree:ge});return}if(we.length===0)await Rt(ee.id)?se.success("Session deleted"):se.error("Failed to delete session");else{const Oe=[ee.id,...we.map(It=>It.id)],{deletedIds:Be,failedIds:Qe}=await Et(Oe);Be.length>0&&se.success(`Deleted ${Be.length} session${Be.length===1?"":"s"}`),Qe.length>0&&se.error(`Failed to delete ${Qe.length} session${Qe.length===1?"":"s"}`)}},[kt,Rt,Et,K,F]),Qt=c.useCallback(()=>{ue&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(ee=>{ee.success&&ee.path?O(ee.path,{id:ee.projectId})||se.error("Failed to add project",{description:"Please select a valid directory."}):ee.error&&ee.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:ee.error})}).catch(ee=>{console.error("Desktop: Error selecting directory:",ee),se.error("Failed to select directory")}):kn.requestDirectoryDialog()},[O,ue]),Tt=c.useCallback(ee=>{g(we=>{const ge=new Set(we);ge.has(ee)?ge.delete(ee):ge.add(ee);try{b.setItem(Tc,JSON.stringify(Array.from(ge)))}catch{}return ge})},[b]),Se=c.useCallback(ee=>{const we=ye.get(ee.id)??[];return{session:ee,children:we.map(ge=>Se(ge)),worktree:K.get(ee.id)??null}},[ye,K]),Pe=c.useCallback((ee,we,ge)=>{const Oe=Qs(we??null),Be=[...ee].sort(($e,Ve)=>(Ve.time?.created||0)-($e.time?.created||0)),Qe=new Map(Be.map($e=>[$e.id,$e])),It=new Map;Be.forEach($e=>{const Ve=$e.parentID;if(!Ve)return;const yt=It.get(Ve)??[];yt.push($e),It.set(Ve,yt)}),It.forEach($e=>$e.sort((Ve,yt)=>(yt.time?.created||0)-(Ve.time?.created||0)));const wt=new Map;ge.forEach($e=>{if($e.path){const Ve=Qs($e.path)??$e.path;wt.set(Ve,$e)}});const Dt=$e=>{const Ve=Qs($e.directory??null),yt=K.get($e.id)??null;if(yt)return yt;if(Ve){const $t=wt.get(Ve)??null;if($t&&Ve!==Oe)return $t}return null},Ct=$e=>{const Ve=It.get($e.id)??[];return{session:$e,children:Ve.map(yt=>Ct(yt)),worktree:Dt($e)}},Je=Be.filter($e=>{const Ve=$e.parentID;return Ve?!Qe.has(Ve):!0}).map($e=>Ct($e));return[{id:"all",label:"All sessions",description:Oe?Hr(Oe,B):null,isMain:!0,worktree:null,directory:Oe,sessions:Je}]},[B,K]),We=c.useCallback(ee=>{D(we=>{const ge=new Set(we);return ge.has(ee)?ge.delete(ee):ge.add(ee),ge})},[]),at=c.useCallback(ee=>{T.current=Date.now()+150,v(we=>{const ge=new Set(we);ge.has(ee)?ge.delete(ee):ge.add(ee);try{b.setItem(Pc,JSON.stringify(Array.from(ge)))}catch{}return ge})},[b]),jt=c.useMemo(()=>_.map(ee=>({...ee,normalizedPath:Qs(ee.path)})).filter(ee=>!!ee.normalizedPath),[_]),zt=c.useCallback(ee=>{const we=H?[]:X.get(ee.normalizedPath)??[],ge=[ee.normalizedPath,...we.map(Qe=>Qs(Qe.path)??Qe.path).filter(Qe=>!!Qe)],Oe=new Set,Be=[];return ge.forEach(Qe=>{($.get(Qe)??te(Qe)).forEach(wt=>{Oe.has(wt.id)||(Oe.add(wt.id),Be.push(wt))})}),Be},[X,te,$,H]),Jt=c.useMemo(()=>jt.map(ee=>{const we=zt(ee),ge=X.get(ee.normalizedPath)??[],Oe=Pe(we,ee.normalizedPath,ge);return{project:ee,groups:Oe}}),[jt,zt,Pe,X]);c.useEffect(()=>{if(!ue)return;const ee=new IntersectionObserver(we=>{we.forEach(ge=>{const Oe=ge.target.dataset.projectId;Oe&&R(Be=>{const Qe=new Set(Be);return ge.isIntersecting?Qe.delete(Oe):Qe.add(Oe),Qe})})},{threshold:0});return V.current.forEach(we=>{we&&ee.observe(we)}),()=>ee.disconnect()},[ue,Jt]);const He=c.useCallback((ee,we=0,ge,Oe)=>{const Be=ee.session,Qe=Qs(Be.directory??null)??Qs(ge??null),wt=(Qe?w.get(Qe):null)==="missing",Dt=Ae.get(Be.id),Ct=L===Be.id,Ie=Be.title||"Untitled Session",Je=ee.children.length>0,$e=p.has(Be.id),Ve=Be.summary?.additions,yt=Be.summary?.deletions,$t=typeof Ve=="number"||typeof yt=="number";if(a===Be.id)return e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",we>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsxs("form",{className:"flex w-full items-center gap-2","data-keyboard-avoid":"true",onSubmit:_t=>{_t.preventDefault(),Re()},children:[e.jsx("input",{value:l,onChange:_t=>d(_t.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename session",onKeyDown:_t=>{_t.key==="Escape"&&Ee()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(At,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Ee,className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Ht,{className:"size-4"})})]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Je?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:$e?e.jsx(Mt,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Fc(Be.time?.created||Date.now())}),Be.share?e.jsx(Na,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,$t&&((Ve??0)!==0||(yt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ve??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,yt??0)]})]}):null,Je?e.jsxs("span",{className:"truncate",children:[ee.children.length," ",ee.children.length===1?"task":"tasks"]}):null]})]})},Be.id);const ts=je?.get(Be.id)??"idle",es=ts==="busy"||ts==="cooldown",ps=Te.get(Be.id)?.length??0,lr=Dt&&Dt.isZombie?e.jsx(pi,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(c.Fragment,{children:[e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1",Ct?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",wt?"opacity-75":"",we>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:wt,onClick:()=>qe(Be.id,Qe,wt,Oe),className:P("flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("span",{className:P("truncate typography-ui-label font-normal text-foreground",es&&"animate-pulse [animation-duration:1.8s]"),children:Ie}),ps>0?e.jsxs("span",{className:"inline-flex items-center gap-1 rounded bg-destructive/10 px-1 py-0.5 text-[0.7rem] text-destructive flex-shrink-0",title:"Permission required","aria-label":"Permission required",children:[e.jsx(dp,{className:"h-3 w-3"}),e.jsx("span",{className:"leading-none",children:ps})]}):null]}),e.jsxs("div",{className:"flex items-center gap-2 typography-micro text-muted-foreground/60 min-w-0 overflow-hidden leading-tight",children:[Je?e.jsx("span",{role:"button",tabIndex:0,onClick:_t=>{_t.stopPropagation(),Tt(Be.id)},onKeyDown:_t=>{(_t.key==="Enter"||_t.key===" ")&&(_t.preventDefault(),_t.stopPropagation(),Tt(Be.id))},className:"inline-flex items-center justify-center text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 flex-shrink-0 rounded-sm","aria-label":$e?"Collapse subsessions":"Expand subsessions",children:$e?e.jsx(Mt,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Fc(Be.time?.created||Date.now())}),Be.share?e.jsx(Na,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,ee.worktree?e.jsxs(rt,{delayDuration:700,children:[e.jsx(nt,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(Ot,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(tt,{side:"top",className:"text-xs",children:ee.worktree.branch||ee.worktree.label||"Worktree"})]}):null,$t&&((Ve??0)!==0||(yt??0)!==0)?e.jsxs("span",{className:"flex-shrink-0 text-[0.7rem] leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,Ve??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,yt??0)]})]}):null,Je?e.jsxs("span",{className:"truncate",children:[ee.children.length," ",ee.children.length===1?"task":"tasks"]}):null,wt?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(pi,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[lr,e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:P("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s?"opacity-70":"opacity-0 group-hover:opacity-100"),"aria-label":"Session menu",onClick:_t=>_t.stopPropagation(),onKeyDown:_t=>_t.stopPropagation(),children:e.jsx(Ir,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(vt,{onClick:()=>{i(Be.id),d(Ie)},className:"[&>svg]:mr-1",children:[e.jsx(mr,{className:"mr-1 h-4 w-4"}),"Rename"]}),Be.share?e.jsxs(e.Fragment,{children:[e.jsx(vt,{onClick:()=>{Be.share?.url&&ot(Be.share.url,Be.id)},className:"[&>svg]:mr-1",children:u===Be.id?e.jsxs(e.Fragment,{children:[e.jsx(At,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(vt,{onClick:()=>ut(Be.id),className:"[&>svg]:mr-1",children:[e.jsx(up,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(vt,{onClick:()=>Ye(Be),className:"[&>svg]:mr-1",children:[e.jsx(Na,{className:"mr-1 h-4 w-4"}),"Share"]}),ee.worktree?e.jsxs(vt,{onClick:()=>{Oe&&Oe!==q&&U(Oe),Q("chat"),s&&de(!1),fe({directoryOverride:ee.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(Ot,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(vt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Nt(Be),children:[e.jsx(Ks,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),Je&&$e?ee.children.map(_t=>He(_t,we+1,Qe??ge,Oe)):null]},Be.id)},[w,Ae,je,Te,L,p,a,l,Re,Ee,Tt,qe,Ye,ot,ut,Nt,u,s,q,U,Q,de,fe]),Ge=c.useCallback((ee,we,ge)=>{const Oe=S.has(we),Be=n?10:5,Qe=ee.sessions.length,It=Oe?ee.sessions:ee.sessions.slice(0,Be),wt=Qe-It.length;return e.jsxs(e.Fragment,{children:[It.map(Dt=>He(Dt,0,ee.directory,ge)),Qe===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,wt>0&&!Oe?e.jsxs("button",{type:"button",onClick:()=>We(we),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:["Show ",wt," more ",wt===1?"session":"sessions"]}):null,Oe&&Qe>Be?e.jsx("button",{type:"button",onClick:()=>We(we),className:"mt-0.5 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show fewer sessions"}):null]})},[S,n,He,We]),st=mp(Tl(vp,{activationConstraint:{distance:8}}),Tl(wp,{coordinateGetter:bp})),Ke=c.useCallback(ee=>{A(ee.active.id)},[]),lt=c.useCallback(ee=>{const{active:we,over:ge}=ee;if(A(null),!ge||we.id===ge.id)return;const Oe=jt.findIndex(Qe=>Qe.id===we.id),Be=jt.findIndex(Qe=>Qe.id===ge.id);Oe!==-1&&Be!==-1&&oe(Oe,Be)},[jt,oe]),Ze=c.useCallback(()=>{A(null)},[]),mt=c.useMemo(()=>{if(!k)return null;const ee=Jt.find(ge=>ge.project.id===k);if(!ee)return null;const we=ee.project;return{id:we.id,label:Rc(we.label?.trim()||_l(we.normalizedPath,B)||we.normalizedPath),isActive:we.id===q}},[k,Jt,B,q]);return e.jsxs("div",{className:P("flex h-full flex-col text-foreground overflow-x-hidden",s?"":ue?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:_.length})]}),e.jsx("button",{type:"button",onClick:Qt,className:P("inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",!ue&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(fp,{className:"h-4.5 w-4.5"})})]})}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:P("space-y-1 pb-1 pl-2.5 pr-1",""),children:Jt.length===0?Fe:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const ee=Jt.find(Oe=>Oe.project.id===q)??Jt[0];if(!ee)return Fe;const we=ee.groups.find(Oe=>Oe.isMain&&Oe.sessions.length>0)??ee.groups.find(Oe=>Oe.sessions.length>0)??ee.groups.find(Oe=>Oe.isMain)??ee.groups[0];if(!we)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ge=`${ee.project.id}:${we.id}`;return Ge(we,ge,ee.project.id)})()}):e.jsxs(pp,{sensors:st,collisionDetection:hp,onDragStart:Ke,onDragEnd:lt,onDragCancel:Ze,children:[e.jsx(gp,{items:jt.map(ee=>ee.id),strategy:xp,children:Jt.map(ee=>{const we=ee.project,ge=we.id,Oe=Rc(we.label?.trim()||_l(we.normalizedPath,B)||we.normalizedPath),Be=Hr(we.normalizedPath,B),Qe=x.has(ge),It=ge===q,wt=N.get(ge),Dt=M===ge;return e.jsx(rb,{id:ge,projectLabel:Oe,projectDescription:Be,isCollapsed:Qe,isActiveProject:It,isRepo:!!wt,isHovered:Dt,isDesktopRuntime:ue,isStuck:E.has(ge),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>at(ge),onHoverChange:Ct=>C(Ct?ge:null),onNewSession:()=>{ge!==q&&U(ge),Q("chat"),s&&de(!1),W&&wt?pa():fe({directoryOverride:we.normalizedPath})},onOpenMultiRunLauncher:()=>{ge!==q&&U(ge),I()},onClose:()=>z(ge),sentinelRef:Ct=>{V.current.set(ge,Ct)},children:Qe?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:ee.groups[0]?Ge(ee.groups[0],`${ge}:all`,ge):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ge)})}),e.jsx(yp,{children:mt?e.jsx(nb,{projectLabel:mt.label,isActiveProject:mt.isActive}):null})]})})]})};function pt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:P("text-foreground border-input file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 appearance-none hover:border-input focus:border-ring flex h-9 w-full min-w-0 rounded-lg border bg-transparent px-3 py-1 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:typography-ui-label file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",s),...t})}const ha=()=>{const[s,r]=Ce.useState(!1);Ce.useEffect(()=>{r(os())},[]);const t=Ce.useCallback(async a=>s?await zh(a):{success:!0,path:a},[s]),n=Ce.useCallback(async a=>s?await Wh(a):{success:!0},[s]),o=Ce.useCallback(async a=>s?await Hh(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},_c=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=c.useMemo(()=>os(),[]),{isMobile:p}=Ft(),[g,w]=c.useState([]),[h,j]=c.useState(new Set),[b,x]=c.useState(!0),[v,N]=c.useState(!1),[y,S]=c.useState(""),[D,M]=c.useState(new Set),[C,k]=c.useState(null),[A,E]=c.useState(""),[R,V]=c.useState(!0),T=c.useRef(null),{requestAccess:B,startAccessing:re,isDesktop:Y}=ha(),_=c.useRef(l),q=c.useCallback(K=>{if(!K)return K;if(K==="/"||K.length===0)return"/";let X=K;for(;X.length>1&&X.endsWith("/");)X=X.slice(0,-1);return X.length===0?"/":X},[]),O=c.useMemo(()=>{if(!y)return null;const K=y.replace(/\\/g,"/");return q(K)},[y,q]),z=c.useMemo(()=>{if(typeof d=="string"&&d.length>0){const K=d.replace(/\\/g,"/"),X=q(K);if(X&&X!=="/")return X}return O&&O!=="/"?O:null},[d,O,q]),U=c.useMemo(()=>typeof u=="boolean"?!!(u&&z):!!z,[u,z]);c.useEffect(()=>{U||(x(!0),w([]))},[U]);const ne=c.useCallback(K=>{if(!K||!U||!z)return!1;const X=K.replace(/\\/g,"/"),te=q(X)??X;if(te===z)return!0;const fe=`${z}/`;return te.startsWith(fe)},[U,z,q]),oe=async K=>{if(U){if(a==="deferred"){r(K);return}if(Y){const X=await B(K);X.success&&X.path?(await re(X.path),r(X.path)):(console.error("Failed to get directory access:",X.error),r(K))}else r(K)}};c.useEffect(()=>{let K=!1;const X=ue=>{if(!ue)return!1;const ae=q(ue.replace(/\\/g,"/"));return!ae||ae==="/"?!1:(S(typeof ae=="string"?ae:ue.replace(/\\/g,"/")),!0)};return d&&X(d)||(async()=>{try{const ue=await ke.getFilesystemHome();if(!K&&X(ue))return}catch(ue){console.warn("Failed to resolve filesystem home directory:",ue)}try{const ue=await ke.getSystemInfo();if(!K&&X(ue?.homeDirectory))return}catch(ue){console.warn("Failed to resolve home directory from system info:",ue)}})(),()=>{K=!0}},[d,q]),c.useEffect(()=>{let K=!1;const X=ae=>{if(K)return;const H=ae.filter(xe=>typeof xe=="string"&&xe.length>0).map(xe=>{const G=xe.replace(/\\/g,"/");return q(G)??G});M(new Set(H))},te=()=>{try{const ae=localStorage.getItem("pinnedDirectories");if(!ae)return;const H=JSON.parse(ae);Array.isArray(H)&&X(H)}catch(ae){console.warn("Failed to load pinned directories from local storage:",ae)}},fe=async()=>{try{let ae=[];if(f){const H=await Dn();ae=Array.isArray(H?.pinnedDirectories)?H.pinnedDirectories:[]}else{const H=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(H.ok){const xe=await H.json();ae=Array.isArray(xe?.pinnedDirectories)?xe.pinnedDirectories:[]}}if(K)return;X(ae)}catch(ae){console.warn("Failed to load pinned directories:",ae)}};te();const ue=ae=>{const H=ae.detail;H&&Array.isArray(H.pinnedDirectories)&&X(H.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",ue),fe(),()=>{K=!0,window.removeEventListener("openchamber:settings-synced",ue)}},[f,q]);const Q=c.useRef(!0);c.useEffect(()=>{if(Q.current){Q.current=!1;return}const K={pinnedDirectories:Array.from(D)};ns(K)},[D]),c.useEffect(()=>{z&&M(K=>{const X=Array.from(K).map(te=>q(te.replace(/\\/g,"/"))??te).filter(te=>ne(te));return new Set(X)})},[z,ne,q]),c.useEffect(()=>{_.current!==l&&(_.current=l)},[l]);const de=K=>{M(X=>{if(!ne(K))return X;const te=q(K.replace(/\\/g,"/"))??K.replace(/\\/g,"/"),fe=new Set(X);return fe.has(te)?fe.delete(te):fe.add(te),fe})},I=c.useMemo(()=>Array.from(D).map(K=>q(K.replace(/\\/g,"/"))??K).filter(K=>ne(K)).map(K=>({path:K,name:K.split("/").pop()||K})).sort((K,X)=>K.name.localeCompare(X.name)),[D,ne,q]),W=c.useCallback(async K=>{const X=H=>l||!H.startsWith("."),te=z;if(!U||!te)return[];const fe=K&&K.length>0?K:te,ue=fe?fe.replace(/\\/g,"/"):null,ae=ue?q(ue)??ue:null;if(ae){const H=`${te}/`;if(!(ae===te||ae.startsWith(H)))return[]}try{return(await ke.listLocalDirectory(K)).filter(xe=>{if(!xe.isDirectory||!X(xe.name))return!1;const G=xe.path.replace(/\\/g,"/"),ye=q(G)??G,Fe=ye===te?te:`${te}/`;return ye===te||ye.startsWith(Fe)}).map(xe=>({name:xe.name,path:xe.path.replace(/\\/g,"/"),isDirectory:!0})).sort((xe,G)=>xe.name.localeCompare(G.name))}catch{try{const xe=await ke.getApiClient().file.list({path:".",directory:K});return xe.data?xe.data.filter(G=>{if(G.type!=="directory"||!G.name||!X(G.name))return!1;const ye=String(G.absolute||G.path||G.name).replace(/\\/g,"/"),Fe=q(ye)??ye,qe=Fe===te?te:`${te}/`;return Fe===te||Fe.startsWith(qe)}).map(G=>({name:G.name||"",path:String(G.absolute||G.path||G.name).replace(/\\/g,"/"),isDirectory:!0})).filter(G=>G.name!=="").sort((G,ye)=>G.name.localeCompare(ye.name)):[]}catch{return[]}}},[l,z,q,U]),F=c.useRef(!1),$=c.useCallback(async()=>{if(!U||!z){x(!0),w([]);return}F.current||x(!0);try{const K=await W(z);w(K),F.current=!0}catch{}finally{x(!1)}},[U,z,W]);c.useEffect(()=>{U&&(n==="inline"||v)&&$()},[n,v,U,$]);const L=async K=>{if(!U)return;const X=h.has(K.path),te=new Set(h);if(X){te.delete(K.path),j(te);return}te.add(K.path),j(te);const fe=await W(K.path),ue=ae=>ae.map(H=>H.path===K.path?{...H,children:fe}:H.children?{...H,children:ue(H.children)}:H);w(ae=>ue(ae))};c.useEffect(()=>{C&&T.current&&(T.current.focus(),T.current.select())},[C]);const J=(K,X=[])=>{const te="new_directory",fe=X.map(xe=>xe.name);if(!fe.includes(te))return te;let ue=1;const ae=new RegExp(`^${te}(\\d+)$`);for(const xe of fe){const G=xe.match(ae);if(G){const ye=parseInt(G[1],10);ye>ue&&(ue=ye)}}let H=2;for(;fe.includes(`${te}${H}`);)H++;return`${te}${Math.max(H,ue+1)}`},pe=async K=>{if(U){if(h.has(K.path)){const X=J(K.path,K.children);E(X)}else{const X=new Set(h);if(X.add(K.path),j(X),K.children){const te=J(K.path,K.children);E(te)}else{const te=await W(K.path),fe=ae=>ae.map(H=>H.path===K.path?{...H,children:te}:H.children?{...H,children:fe(H.children)}:H);w(ae=>fe(ae));const ue=J(K.path,te);E(ue)}}k(K.path)}},be=async()=>{if(!C||!U)return;const K=A.trim()||"new_directory",X=`${C}/${K}`;try{await ke.createDirectory(X);const te=await W(C),fe=ue=>ue.map(ae=>ae.path===C?{...ae,children:te}:ae.children?{...ae,children:fe(ae.children)}:ae);w(ue=>fe(ue)),k(null),E("")}catch(te){console.error("Failed to create directory:",te)}},he=()=>{k(null),E("")},Ae=(K,X=0)=>{const te=h.has(K.path),fe=K.isDirectory,ue=D.has(K.path),ae=s===K.path,H=n==="inline",xe=e.jsxs(e.Fragment,{children:[fe&&e.jsx("button",{onClick:G=>{G.stopPropagation(),L(K)},className:P("hover:bg-accent rounded","p-0.5"),children:te?e.jsx(Mt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!fe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:G=>{G.stopPropagation(),oe(K.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:G=>{G.stopPropagation(),i&&i(K.path)},className:P("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",H&&ae?"text-primary":"text-foreground"),children:[e.jsx(ur,{className:P("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",H&&ae&&"text-primary")}),e.jsx("span",{className:P("font-medium truncate","typography-ui-label",H&&ae?"text-primary":"text-foreground"),children:K.name})]}),e.jsx("button",{onClick:G=>{G.stopPropagation(),pe(K)},className:P("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Kt,{className:P("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:G=>{G.stopPropagation(),de(K.path)},className:P("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:ue?"Unpin directory":"Pin directory",children:ue?e.jsx(Ca,{className:P("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Sp,{className:P("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})})]});return n==="inline"?e.jsxs("div",{children:[e.jsx("div",{className:P("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",ae?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${X*(p?12:14)+(p?4:6)}px`},children:xe}),te&&e.jsxs(e.Fragment,{children:[C===K.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(X+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{ref:T,value:A,onChange:G=>E(G.target.value),onKeyDown:G=>{G.key==="Enter"?(G.preventDefault(),G.stopPropagation(),be()):G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),he())},onBlur:be,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),be()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(At,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),K.children&&K.children.map(G=>Ae(G,X+1))]})]},K.path):e.jsxs("div",{children:[e.jsxs(vt,{className:P("flex items-center gap-1 cursor-pointer group",s===K.path&&"bg-accent"),style:{paddingLeft:`${X*12+8}px`},onSelect:G=>{G.preventDefault()},children:[fe&&e.jsx("button",{onClick:G=>{G.stopPropagation(),L(K)},className:"p-0.5 hover:bg-accent rounded",children:te?e.jsx(Mt,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}),!fe&&e.jsx("div",{className:"w-4"}),xe]}),te&&e.jsxs("div",{children:[C===K.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(X+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{ref:T,value:A,onChange:G=>E(G.target.value),onKeyDown:G=>{G.key==="Enter"?(G.preventDefault(),G.stopPropagation(),be()):G.key==="Escape"&&(G.preventDefault(),G.stopPropagation(),he())},onBlur:be,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),be()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(At,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:G=>{G.preventDefault(),G.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),K.children&&K.children.map(G=>Ae(G,X+1))]})]},K.path)},je=(K,X)=>{if(n==="inline"){const te=s===X;return e.jsxs("div",{className:P("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",te?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>oe(X),onDoubleClick:fe=>{fe.stopPropagation(),i&&i(X)},className:P("flex flex-1 items-center gap-1.5 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded min-w-0",te?"text-primary":"text-foreground"),children:[e.jsx(ur,{className:P("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",te?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:P("typography-ui-label font-medium truncate flex-shrink-0",te?"text-primary":"text-foreground"),children:K}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Hr(X,y)})]}),e.jsx("button",{onClick:()=>de(X),className:P("hover:bg-accent rounded-md transition-opacity",p?"p-1.5 opacity-60":"p-1 opacity-0 group-hover:opacity-100"),title:"Unpin directory",children:e.jsx(Ca,{className:P("text-primary","h-3.5 w-3.5")})})]},X)}return e.jsxs(vt,{onSelect:te=>{te.preventDefault(),oe(X),a==="immediate"&&N(!1)},className:P("flex items-start gap-2 cursor-pointer group py-2",s===X&&"bg-accent"),children:[e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:K}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Hr(X,y)})]}),e.jsx("button",{onClick:te=>{te.stopPropagation(),te.preventDefault(),de(X)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Ca,{className:"h-3 w-3 text-primary"})})]},X)},Te=e.jsx(e.Fragment,{children:U?e.jsxs(e.Fragment,{children:[I.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>V(K=>!K),className:P("flex w-full items-center gap-1.5 typography-meta font-medium text-muted-foreground/80 hover:bg-accent/30 rounded transition-colors uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:[R?e.jsx(Mt,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:I.length})]}),R&&I.map(({name:K,path:X})=>je(K,X)),n==="dropdown"&&e.jsx(Ms,{}),n==="inline"&&R&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:P("typography-meta font-medium text-muted-foreground/80 flex items-center gap-1.5 uppercase tracking-wide",p?"px-1.5 py-1":"px-2 py-1.5"),children:"Browse"}),b?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):g.map(K=>Ae(K)),!b&&g.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No directories found"})]}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Locating home directory..."})});return n==="inline"?e.jsx("div",{className:P("overflow-hidden flex flex-col",o),children:e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Te})}):e.jsxs(Ut,{open:v,onOpenChange:N,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",className:P("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(ur,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Hr(s,y)})]}),e.jsx(Mt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{align:"start",className:"w-[350px]",children:e.jsx(dt,{outerClassName:"h-full",className:"w-full",children:Te})})]})},hl=(s,r=200)=>{const[t,n]=Ce.useState(s);return Ce.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},gm=c.forwardRef(({inputValue:s,homeDirectory:r,onSelectSuggestion:t,visible:n,onClose:o,showHidden:a},i)=>{const[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(0),g=c.useRef(null),w=c.useRef([]),h=c.useCallback((y,S)=>{const D=y.trim().toLowerCase();if(!D)return 0;const M=S.toLowerCase();let C=0,k=-1,A=0;for(let E=0;E<D.length;E+=1){const R=D[E];if(!R||R===" ")continue;const V=M.indexOf(R,k+1);if(V===-1)return null;const T=V-k-1;if(T===0?A+=1:A=0,C+=10,C+=Math.max(0,18-V),C-=Math.max(0,T),V===0)C+=12;else{const B=M[V-1];(B==="/"||B==="_"||B==="-"||B==="."||B===" ")&&(C+=10)}C+=A>0?12:0,k=V}return C+=Math.max(0,24-Math.round(M.length/3)),C},[]),j=c.useCallback(y=>y.startsWith("~")&&r?y.replace(/^~/,r):y,[r]),b=c.useCallback(y=>{const S=j(y);if(S.endsWith("/"))return S;const D=S.lastIndexOf("/");return D===-1?"":D===0?"/":S.substring(0,D+1)},[j]),x=c.useCallback(y=>{const S=j(y);if(S.endsWith("/"))return"";const D=S.lastIndexOf("/");return D===-1?S:S.substring(D+1)},[j]),v=hl(s,150);c.useEffect(()=>{if(!n||!v){d([]);return}const y=b(v),S=x(v).toLowerCase();if(!y){d([]);return}let D=!1;return m(!0),ke.listLocalDirectory(y).then(M=>{if(D)return;const C=M.filter(A=>!(!A.isDirectory||!a&&A.name.startsWith("."))),k=S?C.map(A=>{const E=h(S,A.name);return E!==null?{entry:A,score:E}:null}).filter(A=>A!==null).sort((A,E)=>E.score-A.score||A.entry.name.localeCompare(E.entry.name)).map(A=>A.entry):C.sort((A,E)=>A.name.localeCompare(E.name));d(k.slice(0,10)),p(0)}).catch(()=>{D||d([])}).finally(()=>{D||m(!1)}),()=>{D=!0}},[n,v,b,x,a,h]),c.useEffect(()=>{w.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),c.useEffect(()=>{if(!n)return;const y=S=>{const D=S.target;!D||!g.current||g.current.contains(D)||o()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[n,o]);const N=c.useCallback(y=>{const S=y.path.endsWith("/")?y.path:y.path+"/";t(S)},[t]);return c.useImperativeHandle(i,()=>({handleKeyDown:y=>{if(!n||l.length===0)return!1;const S=l.length;if(y.key==="Tab"){if(y.preventDefault(),y.shiftKey)p(D=>(D-1+S)%S);else if(S===1){const D=l[0];D&&N(D)}else p(D=>(D+1)%S);return!0}if(y.key==="ArrowDown")return y.preventDefault(),p(D=>(D+1)%S),!0;if(y.key==="ArrowUp")return y.preventDefault(),p(D=>(D-1+S)%S),!0;if(y.key==="Enter"){y.preventDefault();const D=(f%S+S)%S,M=l[D];return M&&N(M),o(),!0}return y.key==="Escape"?(y.preventDefault(),o(),!0):!1}}),[n,l,f,N,o]),!n||l.length===0&&!u?null:e.jsxs("div",{ref:g,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:l.map((y,S)=>{const D=f===S;return e.jsxs("div",{ref:M=>{w.current[S]=M},className:P("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",D&&"bg-muted"),onClick:()=>{N(y),o()},onMouseEnter:()=>p(S),children:[e.jsx(ir,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:y.name})]},y.path)})}),e.jsx("div",{className:"px-3 py-1.5 border-t typography-meta text-muted-foreground bg-sidebar/50",children:"Tab cycle • ↑↓ navigate • Enter select"})]})});gm.displayName="DirectoryAutocomplete";const Oc="directoryTreeShowHidden",ob=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=ct(),{addProject:a,getActiveProject:i}=Pt(),[l,d]=c.useState(null),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(!1),[h,j]=c.useState(()=>{if(typeof window>"u")return!1;try{const Q=window.localStorage.getItem(Oc);if(Q==="true")return!0;if(Q==="false")return!1}catch{}return!1}),{isDesktop:b,requestAccess:x,startAccessing:v}=ha(),{isMobile:N}=Ft(),[y,S]=c.useState(!1),D=c.useRef(null),M=c.useCallback(Q=>Q?Hr(Q,n):"",[n]);c.useEffect(()=>{if(s){p(!1),w(!1),S(!1);const de=i()?.path||t||n||"";d(de),m(M(de))}},[s,t,n,M,i]),c.useEffect(()=>{!s||f||l||n&&o&&(d(n),p(!0),m("~"))},[s,f,l,n,o]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Oc,h?"true":"false")}catch{}},[h]);const C=c.useCallback(()=>{r(!1)},[r]),k=c.useCallback(async Q=>{if(!(!Q||g)){w(!0);try{let de=Q,I;if(b){const F=await x(Q);if(!F.success){se.error("Unable to access directory",{description:F.error||"Desktop denied directory access."});return}de=F.path??Q,I=F.projectId;const $=await v(de);if(!$.success){se.error("Failed to open directory",{description:$.error||"Desktop could not grant file access."});return}}if(!a(de,{id:I})){se.error("Failed to add project",{description:"Please select a valid directory path."});return}C()}catch(de){se.error("Failed to select directory",{description:de instanceof Error?de.message:"Unknown error occurred."})}finally{w(!1)}}},[a,C,b,x,v,g]),A=c.useCallback(async()=>{const Q=u.trim()||l;Q&&await k(Q)},[k,u,l]),E=c.useCallback(Q=>{d(Q),p(!0),m(M(Q))},[M]),R=c.useCallback(async Q=>{d(Q),p(!0),m(M(Q)),await k(Q)},[k,M]),V=c.useCallback(Q=>{const de=Q.target.value;if(m(de),p(!0),S(de.startsWith("/")||de.startsWith("~")),de.startsWith("/")||de.startsWith("~")){const I=de.startsWith("~")&&n?de.replace(/^~/,n):de;d(I)}},[n]),T=c.useCallback(Q=>{D.current?.handleKeyDown(Q)||Q.key==="Enter"&&(Q.preventDefault(),A())},[A]),B=c.useCallback(Q=>{d(Q),p(!0),m(M(Q))},[M]),re=c.useCallback(()=>{S(!1)},[]),Y=c.useCallback(()=>{j(Q=>!Q)},[]),_=e.jsxs("button",{type:"button",onClick:Y,className:"flex items-center gap-2 px-2 py-1 rounded-lg hover:bg-accent/40 transition-colors typography-meta text-muted-foreground flex-shrink-0",children:[h?e.jsx(Wi,{className:"h-4 w-4 text-primary"}):e.jsx(Hi,{className:"h-4 w-4"}),"Show hidden"]}),q=e.jsxs(xs,{className:"flex-shrink-0 px-4 pb-2 pt-[calc(var(--oc-safe-area-top,0px)+0.5rem)] sm:px-0 sm:pb-3 sm:pt-0",children:[e.jsx(ys,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),_]})]}),O=e.jsxs("div",{className:"relative",children:[e.jsx(pt,{value:u,onChange:V,onKeyDown:T,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(gm,{ref:D,inputValue:u,homeDirectory:n,onSelectSuggestion:B,visible:y,onClose:re,showHidden:h})]}),z=e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(_c,{variant:"inline",currentPath:l??t,onSelectPath:E,onDoubleClickPath:R,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o})}),U=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:O}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:_}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(_c,{variant:"inline",currentPath:l??t,onSelectPath:E,onDoubleClickPath:R,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),ne=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[O,z]}),oe=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:C,disabled:g,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Ne,{onClick:A,disabled:g||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:g?"Adding...":"Add Project"})]});return N?e.jsx(ws,{open:s,onClose:()=>r(!1),title:"Add project directory",className:"max-w-full",contentMaxHeightClassName:"max-h-[min(70vh,520px)] h-[min(70vh,520px)]",footer:e.jsx("div",{className:"flex flex-row gap-2",children:oe()}),children:U}):e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:P("flex w-full max-w-[min(560px,100vw)] max-h-[calc(100vh-32px)] flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh] sm:max-w-xl sm:p-6"),onOpenAutoFocus:Q=>{Q.preventDefault()},children:[q,ne,e.jsx(qs,{className:"sticky bottom-0 flex w-full flex-shrink-0 flex-row gap-2 border-t border-border/40 bg-sidebar px-4 py-3 sm:static sm:justify-end sm:border-0 sm:bg-transparent sm:px-0 sm:pt-4 sm:pb-0",children:oe()})]})})},go=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,ab=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},ib=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=c.useRef(new Set),[a,i]=c.useState(null),[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(!1),{deleteSession:g,deleteSessions:w,loadSessions:h,getWorktreeMetadata:j}=me(),{currentDirectory:b,homeDirectory:x,isHomeReady:v}=ct(),{projects:N,addProject:y,activeProjectId:S}=Pt(),{requestAccess:D,startAccessing:M}=ha(),{isMobile:C,isTablet:k,hasTouchInput:A}=Ft(),E=C||k||A,R=c.useMemo(()=>{const F=(S?N.find($=>$.id===S)??null:null)?.path??b;return ab(F)},[S,b,N]),V=c.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||l.some(W=>W.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,l]),T=c.useMemo(()=>{const W=a?.worktree;return W&&typeof W.branch=="string"&&W.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:F})=>typeof F.branch=="string"&&F.branch.trim().length>0)},[a?.worktree,l]),B=a?.mode==="worktree",re=B,Y=f||!B||!T;c.useEffect(()=>{R&&(o.current.has(R)||ix(R).then(()=>o.current.add(R)).catch(W=>{console.warn("Failed to ensure .openchamber directory is ignored:",W),o.current.delete(R)}))},[R]),c.useEffect(()=>{h()},[h,b]);const _=c.useMemo(()=>N.map(W=>`${W.id}:${W.path}`).join("|"),[N]),q=c.useRef(_);c.useEffect(()=>{_!==q.current&&(q.current=_,h())},[h,_]),c.useEffect(()=>{if(!(t||!v||N.length>0)){if(n(!0),os()){D("").then(async W=>{if(!W.success||!W.path){W.error&&W.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:W.error});return}const F=await M(W.path);if(!F.success){se.error("Failed to open directory",{description:F.error||"Desktop could not grant file access."});return}y(W.path,{id:W.projectId})||se.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(W=>{console.error("Desktop: Error selecting directory:",W),se.error("Failed to select directory")});return}r(!0)}},[y,t,v,N.length,D,M]);const O=c.useCallback(W=>{i({sessions:W.sessions,dateLabel:W.dateLabel,mode:W.mode??"session",worktree:W.worktree??null})},[]),z=c.useCallback(()=>{i(null),d([]),m(!1),p(!1)},[]);c.useEffect(()=>kn.onDeleteRequest(W=>{O(W)}),[O]),c.useEffect(()=>kn.onDirectoryRequest(()=>{r(!0)}),[]),c.useEffect(()=>{if(!a){d([]),m(!1);return}const W=a.sessions.map($=>{const L=j($.id);return L?{session:$,metadata:L}:null}).filter($=>!!$);if(d(W),m(!1),W.length===0)return;let F=!1;return(async()=>{const $=await Promise.all(W.map(async({metadata:L})=>{if(L.status&&typeof L.status.isDirty=="boolean")return L.status;try{return await sl(L.path)}catch{return L.status}})).catch(L=>(console.warn("Failed to inspect worktree status before deletion:",L),W.map(({metadata:J})=>J.status)));F||!Array.isArray($)||d(L=>L.map((J,pe)=>({session:J.session,metadata:{...J.metadata,status:$[pe]??J.metadata.status}})))})(),()=>{F=!0}},[a,j]),c.useEffect(()=>{T||m(!1)},[T]);const U=c.useCallback(async()=>{if(a){p(!0);try{const W=re,F=W&&u;if(a.sessions.length===0&&B&&a.worktree){const $=u&&T;await zu({projectDirectory:R,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:$});const L=$?"Worktree and remote branch removed.":"Worktree removed.";se.success("Worktree removed",{description:go(L)}),z(),h();return}if(a.sessions.length===1){const $=a.sessions[0];if(!await g($.id,{archiveWorktree:W,deleteRemoteBranch:F})){se.error("Failed to delete session"),p(!1);return}const J=W?F?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;se.success("Session deleted",{description:go(J)})}else{const $=a.sessions.map(pe=>pe.id),{deletedIds:L,failedIds:J}=await w($,{archiveWorktree:W,deleteRemoteBranch:F});if(L.length>0){const pe=W?F?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,he=[J.length>0?`${J.length} session${J.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,pe].filter(Boolean).join(" ");se.success(`Deleted ${L.length} session${L.length===1?"":"s"}`,{description:go(he||void 0)})}if(J.length>0&&(se.error(`Failed to delete ${J.length} session${J.length===1?"":"s"}`,{description:go("Please try again in a moment.")}),L.length===0)){p(!1);return}}z()}finally{p(!1)}}},[a,u,g,w,z,re,B,T,R,h]),ne=a?.worktree??l[0]?.metadata??null,oe=a?a.mode==="worktree"?a.sessions.length===0?"This removes the selected worktree.":`This removes the selected worktree and ${a.sessions.length===1?"1 linked session":`${a.sessions.length} linked sessions`}.`:`This action permanently removes ${a.sessions.length===1?"1 session":`${a.sessions.length} sessions`}${a.dateLabel?` from ${a.dateLabel}`:""}.`:"",Q=a?e.jsxs("div",{className:"space-y-2",children:[a.sessions.length>0&&e.jsxs("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[B&&e.jsx("span",{className:"typography-meta font-medium text-foreground",children:a.sessions.length===1?"Linked session":"Linked sessions"}),e.jsxs("ul",{className:"space-y-0.5",children:[a.sessions.slice(0,5).map(W=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:W.title||"Untitled Session"},W.id)),a.sessions.length>5&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",a.sessions.length-5," more"]})]})]}),B?e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Worktree"}),ne?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:ne.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:ne?Hr(ne.path,x):"Worktree path unavailable."}),V&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),T?e.jsxs("button",{type:"button",onClick:()=>{Y||m(W=>!W)},disabled:Y,className:P("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",Y?"cursor-not-allowed opacity-60":"hover:bg-sidebar/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[e.jsx("span",{className:"mt-0.5 flex size-5 items-center justify-center text-muted-foreground",children:u?e.jsx(Wi,{className:"size-4 text-primary"}):e.jsx(Hi,{className:"size-4"})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Delete remote branch"}),e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:u?"Remote branch on origin will also be removed.":"Keep the remote branch intact."})]})]}):e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Remote branch information unavailable for this worktree."})]}):e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,de=e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",onClick:z,disabled:f,children:"Cancel"}),e.jsx(Ne,{variant:"destructive",onClick:U,disabled:f,children:f?"Deleting…":B?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),I=B?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx(ws,{open:!!a,onClose:()=>{f||z()},title:I,footer:e.jsx("div",{className:"flex justify-end gap-2",children:de}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[oe&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:oe}),Q]})}):e.jsx(ms,{open:!!a,onOpenChange:W=>{if(!W){if(f)return;z()}},children:e.jsxs(fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:I}),oe&&e.jsx(Ns,{children:oe})]}),Q,e.jsx(qs,{className:"mt-2 gap-2 pt-1 pb-1",children:de})]})}),e.jsx(ob,{open:s,onOpenChange:r})]})};function lb(){return new Worker(kp,{type:"module"})}const cb=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function db(s,r,t){const n=r.length>100?`${r.slice(0,50)}${r.slice(-50)}`:r,o=t.length>100?`${t.slice(0,50)}${t.slice(-50)}`:t;return`${s}:${r.length}:${t.length}:${n.length}:${o.length}`}function $c(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const ub=({children:s})=>{const r=Cp(),t=Yt(l=>l.activeDirectory),n=Yt(l=>t?l.directories.get(t)?.lastStatusChange??0:0),o=Yt(l=>t?l.directories.get(t)?.diffCache.size??0:0),a=Ce.useRef(!1),i=Ce.useRef(new Map);return Ce.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=fi(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ce.useEffect(()=>{if(!r||!t||!n||o===0)return;const l=Yt.getState().directories.get(t);if(!l||l.diffCache.size===0||(i.current.get(t)??0)>=l.lastStatusChange)return;i.current.set(t,l.lastStatusChange);let u=!1,m=null;const f=Array.from(l.diffCache.entries());let p=0;const g=w=>{if(u)return;const h=Date.now();for(;p<f.length&&!(w&&w.timeRemaining()<8||!w&&Date.now()-h>8);){const[j,b]=f[p];p+=1,tn(j);const x=db(j,b.original,b.modified),v={name:j,contents:b.original,cacheKey:`old-${x}`},N={name:j,contents:b.modified,cacheKey:`new-${x}`},y=fi(v,N),S={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(S,y)}p<f.length&&(m=$c(g))};return g(void 0),p<f.length&&(m=$c(g)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},mb=({children:s})=>{const t=fa()?.currentTheme?.metadata?.variant==="dark";om();const n=Ce.useMemo(()=>({theme:{dark:Sn.dark,light:Sn.light},themeType:t?"dark":"light",langs:cb}),[t]);return e.jsx(Np,{poolOptions:{workerFactory:lb,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(ub,{children:s})})},Is=Ce.forwardRef(({className:s,...r},t)=>e.jsx(dt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:P("text-foreground border-input placeholder:text-muted-foreground appearance-none hover:border-input focus:border-ring focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-lg border bg-transparent px-3 py-2 typography-markdown shadow-none transition-[color,box-shadow,border-color] outline-none focus-visible:outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:typography-ui-label",s),...r}));Is.displayName="Textarea";const ga=Mp,gl=({className:s,...r})=>e.jsx(Dp,{className:P("flex w-full items-center justify-between rounded-lg px-2 py-1.5 text-left text-foreground hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",s),...r}),xa=({className:s,...r})=>e.jsx(Ap,{className:P("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),Di=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),fb=(s,r)=>{const t=Di(s),n=Di(r);return`${t}-${n}`.substring(0,60)},Lc=(s,r)=>`${s}/${r}`,pb=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),hb=()=>{const s=Pt.getState(),r=s.activeProjectId,t=r?s.projects.find(l=>l.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=ct.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,i=o.indexOf("/.openchamber/");return i>0?o.slice(0,i):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},Gn=Bt()(Xt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i,setupCommands:l}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<1)return s({error:"Select at least 1 model"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const d=hb();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await en(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=Di(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,g=[],w=l?.filter(y=>y.trim().length>0)??[],h=new Map;for(const y of o){const S=`${y.providerID}:${y.modelID}`;h.set(S,(h.get(S)||0)+1)}const j=new Map;for(const y of o){const S=`${y.providerID}:${y.modelID}`,D=h.get(S)||1,M=(j.get(S)||0)+1;j.set(S,M);const C=fb(y.providerID,y.modelID),k=D>1?Lc(m,`${C}/${M}`):Lc(m,C);if(!k)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=pb(k);if(!A)return s({error:`Invalid branch name: ${k}`,isLoading:!1}),null;try{const E=await Bu({projectDirectory:d,worktreeSlug:A,branch:k,createBranch:!0,startPoint:p}),R=D>1?`${m}/${y.providerID}/${y.modelID}/${M}`:`${m}/${y.providerID}/${y.modelID}`,V=await ke.withDirectory(E.path,()=>ke.createSession({title:R}));it.getState().setWorktreeMetadata(V.id,E),g.push({sessionId:V.id,worktreePath:E.path,providerID:y.providerID,modelID:y.modelID,variant:y.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const b=l?.filter(y=>y.trim().length>0)??[];b.length>0&&Ou(d,b).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const x=g.map(y=>y.sessionId),v=g[0]?.sessionId??null;if(x.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const N=i?.map(y=>({type:"file",mime:y.mime,filename:y.filename,url:y.url}));try{await it.getState().loadSessions()}catch{}if(w.length>0)for(const y of g)Wu(y.worktreePath,d,w).then(S=>{if(!S.success){const D=S.results.filter(M=>!M.success);console.warn(`[MultiRun] Setup commands failed for ${y.worktreePath}:`,D)}}).catch(S=>{console.warn(`[MultiRun] Setup commands error for ${y.worktreePath}:`,S)});return(async()=>{try{await Promise.allSettled(g.map(async y=>{try{await ke.withDirectory(y.worktreePath,()=>ke.sendMessage({id:y.sessionId,providerID:y.providerID,modelID:y.modelID,variant:y.variant,text:n,agent:a,files:N}))}catch(S){console.warn("[MultiRun] Failed to start run:",S)}}))}catch(y){console.warn("[MultiRun] Failed to start runs:",y)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:x,firstSessionId:v}}catch(d){return s({error:d instanceof Error?d.message:"Failed to create Multi-Run",isLoading:!1}),null}},clearError:()=>{s({error:null})}}),{name:"multirun-store"}));function vs({...s}){return e.jsx(Ep,{"data-slot":"select",...s})}function Vr({...s}){return e.jsx(Op,{"data-slot":"select-group",...s})}function Yr({...s}){return e.jsx(Tp,{"data-slot":"select-value",...s})}function js({className:s,size:r="default",children:t,...n}){return e.jsxs(Ip,{"data-slot":"select-trigger","data-size":r,className:P("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none focus-visible:outline-none hover:bg-muted data-[state=open]:bg-muted focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-6 data-[size=sm]:h-6 data-[size=lg]:h-8 data-[size=lg]:py-1.5 data-[size=chip]:h-7 data-[size=chip]:py-1 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...n,children:[t,e.jsx(Pp,{asChild:!0,children:e.jsx(Mt,{className:"size-4 opacity-50"})})]})}function Ss({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(Fp,{children:e.jsx(Rp,{"data-slot":"select-content",className:P("bg-background text-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden rounded-xl border shadow-none transform-gpu will-change-transform",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n&&"w-max min-w-0",s),position:t,...o,children:e.jsx(dt,{as:_p,outerClassName:P("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:P("p-1",t==="popper"&&(n?"h-[var(--radix-select-trigger-height)] w-max min-w-0 scroll-my-1":"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1")),children:r})})})}function xn({className:s,...r}){return e.jsx($p,{"data-slot":"select-label",className:P("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Lt({className:s,children:r,...t}){return e.jsxs(Lp,{"data-slot":"select-item",className:P("hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 typography-ui-label outline-none select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",s),...t,children:[e.jsx("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:e.jsx(Bp,{children:e.jsx(At,{className:"size-4"})})}),e.jsx(zp,{children:r})]})}function Jo({className:s,...r}){return e.jsx(Wp,{"data-slot":"select-separator",className:P("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}const gb="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!--%20Uploaded%20to:%20SVG%20Repo,%20www.svgrepo.com,%20Generator:%20SVG%20Repo%20Mixer%20Tools%20--%3e%3csvg%20fill='%23000000'%20width='800px'%20height='800px'%20viewBox='0%200%2024%2024'%20role='img'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M20.702%202.29c-2.494-1.554-5.778-1.187-8.706.654C9.076%201.104%205.79.736%203.3%202.29c-3.941%202.463-4.42%208.806-1.07%2014.167%202.47%203.954%206.333%206.269%209.77%206.226%203.439.043%207.301-2.273%209.771-6.226%203.347-5.361%202.872-11.704-1.069-14.167zM4.042%2015.328a12.838%2012.838%200%200%201-1.546-3.541%2010.12%2010.12%200%200%201-.336-3.338c.15-1.98.956-3.524%202.27-4.345%201.315-.822%203.052-.87%204.903-.137.281.113.556.24.825.382A15.11%2015.11%200%200%200%207.5%207.54c-2.035%203.255-2.655%206.878-1.945%209.765a13.247%2013.247%200%200%201-1.514-1.98zm17.465-3.541a12.866%2012.866%200%200%201-1.547%203.54%2013.25%2013.25%200%200%201-1.513%201.984c.635-2.589.203-5.76-1.353-8.734a.39.39%200%200%200-.563-.153l-4.852%203.032a.397.397%200%200%200-.126.546l.712%201.139a.395.395%200%200%200%20.547.126l3.145-1.965c.101.306.203.606.28.916.296%201.086.41%202.214.335%203.337-.15%201.982-.956%203.525-2.27%204.347a4.437%204.437%200%200%201-2.25.65h-.101a4.432%204.432%200%200%201-2.25-.65c-1.314-.822-2.121-2.365-2.27-4.347a10.153%2010.153%200%200%201%20.335-3.337%2013.212%2013.212%200%200%201%204.05-6.482%2010.148%2010.148%200%200%201%202.849-1.765c1.845-.733%203.586-.685%204.9.137%201.316.822%202.122%202.365%202.271%204.345a10.146%2010.146%200%200%201-.33%203.334z'/%3e%3c/svg%3e",xb=Object.assign({"../assets/provider-logos/gocode.svg":gb}),Ai=new Map;for(const[s,r]of Object.entries(xb)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Ai.set(t[1].toLowerCase(),r)}function xm(s){const r=s?.toLowerCase()??null,t=r?Ai.has(r):!1,n=r?Ai.get(r)??null:null,[o,a]=Ce.useState(t?"local":"remote");Ce.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=Ce.useCallback(()=>{a(l=>l==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const rs=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=xm(s),l=c.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:P("dark:invert",t),onError:l})},xl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,yl=()=>{const{providers:s}=et(),{favoriteModels:r,recentModels:t}=_e(),n=c.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=c.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(l=>l.providerID===a&&l.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},ym="h-7",Zo=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,yb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),bb=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=yb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},wb=({model:s,instanceIndex:r,totalSameModel:t,onRemove:n})=>{const o=s.displayName||`${s.providerID}/${s.modelID}`,a=t>1?`${o} (${r})`:o;return e.jsxs("div",{className:P("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",ym),children:[e.jsx(rs,{providerId:s.providerID,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium truncate max-w-[140px]",children:a}),e.jsx("button",{type:"button",onClick:n,className:"text-muted-foreground hover:text-foreground ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]})},bm=({selectedModels:s,onAdd:r,onRemove:t,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:i=!0,maxModels:l})=>{const{providers:d,modelsMetadata:u}=et(),{favoriteModelsList:m,recentModelsList:f}=yl(),[p,g]=c.useState(!1),[w,h]=c.useState(""),[j,b]=c.useState(0),[x,v]=c.useState(null),N=c.useRef(null),y=c.useRef(null),S=c.useRef(null),D=c.useRef([]),M=c.useMemo(()=>{const Y=new Map;for(const _ of s){const q=`${_.providerID}:${_.modelID}`;Y.set(q,(Y.get(q)||0)+1)}return Y},[s]),C=c.useCallback(Y=>s.filter(q=>q.providerID===Y.providerID&&q.modelID===Y.modelID).findIndex(q=>q.instanceId===Y.instanceId)+1,[s]),k=(Y,_)=>{const q=`${Y}/${_}`;return u.get(q)},A=Y=>{const _=Y?.name||Y?.id||"",q=String(_);return q.length>40?q.substring(0,37)+"...":q},E=c.useCallback((Y,_)=>{if(!w.trim())return!0;const q=w.toLowerCase();return Y.toLowerCase().includes(q)||_.toLowerCase().includes(q)},[w]),R=c.useMemo(()=>m.filter(({model:Y,providerID:_})=>{const O=d.find(U=>U.id===_)?.name||_,z=A(Y);return E(z,O)}),[m,d,E]),V=c.useMemo(()=>f.filter(({model:Y,providerID:_})=>{const O=d.find(U=>U.id===_)?.name||_,z=A(Y);return E(z,O)}),[f,d,E]),T=c.useMemo(()=>d.map(Y=>{const q=(Array.isArray(Y.models)?Y.models:[]).filter(O=>{const z=A(O);return E(z,Y.name||Y.id||"")});return{...Y,models:q}}).filter(Y=>Y.models.length>0),[d,E]),B=R.length>0||V.length>0||T.length>0;c.useEffect(()=>{if(p&&S.current){const _=S.current.getBoundingClientRect().top-100;v(Math.max(150,Math.min(400,_)))}},[p]),c.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),c.useEffect(()=>{if(!p)return;const Y=_=>{y.current&&!y.current.contains(_.target)&&(g(!1),h(""),b(0))};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[p]),c.useEffect(()=>{b(0)},[w]);const re=(Y,_,q,O,z,U)=>{const ne=`${_}:${q}`,oe=M.get(ne)||0,Q=k(_,q),de=bb(Q?.limit?.context);return e.jsxs("button",{ref:I=>{D.current[z]=I},type:"button",onClick:()=>{r({providerID:_,modelID:q,displayName:Y.name||q,instanceId:Zo()})},onMouseEnter:()=>b(z),className:P("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",U?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(Y)}),de&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:de})]}),oe>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",oe]})]},`${O}-${ne}`)};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 items-center",children:[e.jsxs("div",{className:"relative",ref:y,children:[e.jsxs(Ne,{ref:S,type:"button",variant:"outline",size:"sm",className:ym,onClick:()=>g(!p),children:[e.jsx(Kt,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const Y=[];R.forEach(({model:z,providerID:U,modelID:ne})=>{Y.push({model:z,providerID:U,modelID:ne,section:"fav"})}),V.forEach(({model:z,providerID:U,modelID:ne})=>{Y.push({model:z,providerID:U,modelID:ne,section:"recent"})}),T.forEach(z=>{z.models.forEach(U=>{Y.push({model:U,providerID:z.id,modelID:U.id,section:"provider"})})});const _=Y.length,q=z=>{if(!xl(z))if(z.key==="ArrowDown"){z.preventDefault(),z.stopPropagation();const U=(j+1)%Math.max(1,_);b(U),setTimeout(()=>{D.current[U]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(z.key==="ArrowUp"){z.preventDefault(),z.stopPropagation();const U=(j-1+Math.max(1,_))%Math.max(1,_);b(U),setTimeout(()=>{D.current[U]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(z.key==="Enter"){z.preventDefault(),z.stopPropagation();const U=Y[j];U&&r({providerID:U.providerID,modelID:U.modelID,displayName:U.model.name||U.modelID,instanceId:Zo()})}else z.key==="Escape"&&(z.preventDefault(),z.stopPropagation(),g(!1),h(""),b(0))};let O=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{ref:N,type:"text",placeholder:"Search models",value:w,onChange:z=>h(z.target.value),onKeyDown:q,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(dt,{outerClassName:"flex-1",style:{maxHeight:x?`${x}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!B&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),R.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),R.map(({model:z,providerID:U,modelID:ne})=>{const oe=O++;return re(z,U,ne,"fav",oe,j===oe)})]}),V.length>0&&e.jsxs(e.Fragment,{children:[R.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),V.map(({model:z,providerID:U,modelID:ne})=>{const oe=O++;return re(z,U,ne,"recent",oe,j===oe)})]}),(R.length>0||V.length>0)&&T.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),T.map((z,U)=>e.jsxs(c.Fragment,{children:[U>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(rs,{providerId:z.id,className:"h-4 w-4 flex-shrink-0"}),z.name]}),z.models.map(ne=>{const oe=O++;return re(ne,z.id,ne.id,"provider",oe,j===oe)})]},z.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),i&&s.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:s.map((Y,_)=>{const q=`${Y.providerID}:${Y.modelID}`,O=M.get(q)||1,z=C(Y),ne=d.find(W=>W.id===Y.providerID)?.models.find(W=>W.id===Y.modelID),oe=ne?.variants?Object.keys(ne.variants):[],Q=oe.length>0,de="__default__",I=Y.variant??de;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(wb,{model:Y,instanceIndex:z,totalSameModel:O,onRemove:()=>t(_)}),Q&&e.jsxs(vs,{value:I,onValueChange:W=>{if(!n)return;n(_,{...Y,variant:W===de?void 0:W})},children:[e.jsxs(js,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-accent/50 border-border/30 hover:bg-accent/60 typography-meta font-medium text-foreground",children:[e.jsx(ar,{className:P("h-3.5 w-3.5 flex-shrink-0",I===de?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(Yr,{placeholder:"Thinking"})]}),e.jsxs(Ss,{fitContent:!0,children:[e.jsx(Lt,{value:de,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),oe.map(W=>e.jsx(Lt,{value:W,className:"pr-2 [&>span:first-child]:hidden",children:W},W))]})]})]},Y.instanceId)})})]}),o!==void 0&&s.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})};function bl(s){const[r,t]=c.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=c.useState(!1),[a,i]=c.useState(null);return c.useEffect(()=>{let l=!1;if(!s){i(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const d=await en(s);if(l)return;if(i(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await tl(s).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(w=>!w.startsWith("remotes/")).sort((w,h)=>w.localeCompare(h)).forEach(w=>{m.push({value:w,label:w,group:"local"})}),u.all.filter(w=>w.startsWith("remotes/")).map(w=>w.replace(/^remotes\//,"")).sort((w,h)=>w.localeCompare(h)).forEach(w=>{m.push({value:w,label:w,group:"remote"})})),t(m)}finally{l||o(!1)}})(),()=>{l=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const wm=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:i,isLoading:l,isGitRepository:d}=bl(s),u=c.useMemo(()=>i.find(f=>f.value===r)?.label??null,[i,r]);c.useEffect(()=>{!i.some(p=>p.value===r)&&i.length>0&&t("HEAD")},[i,r,t]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(vs,{value:r,onValueChange:t,disabled:m,children:[e.jsx(js,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Yr,{children:u}):e.jsx(Yr,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(Ss,{fitContent:!0,children:[e.jsxs(Vr,{children:[e.jsx(xn,{children:"Default"}),i.filter(f=>f.group==="special").map(f=>e.jsx(Lt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),i.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(Jo,{}),e.jsxs(Vr,{children:[e.jsx(xn,{children:"Local branches"}),i.filter(f=>f.group==="local").map(f=>e.jsx(Lt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,i.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(Jo,{}),e.jsxs(Vr,{children:[e.jsx(xn,{children:"Remote branches"}),i.filter(f=>f.group==="remote").map(f=>e.jsx(Lt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null]})]}),d===!1&&e.jsx("p",{className:"typography-micro text-muted-foreground/70",children:"Not in a git repository."})]})},vm=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=et(f=>f.getVisibleAgents),i=et(f=>f.loadAgents),l=et(f=>f.currentAgentName),d=a(),u=c.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);c.useEffect(()=>{i()},[i]),c.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(w=>w.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(w=>w.name===p)){r(p);return}const g=u[0]?.name;g&&r(g)},[l,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(vs,{value:m,onValueChange:r,disabled:n,children:[e.jsx(js,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(Yr,{placeholder:"Select an agent"})}),e.jsx(Ss,{fitContent:!0,children:u.length>0&&e.jsx(Vr,{children:u.map(f=>e.jsx(Lt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},vb=10*1024*1024,Bc=5,zc=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=c.useState(""),[a,i]=c.useState(()=>s??""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,w]=c.useState(!1),[h,j]=c.useState([]),[b,x]=c.useState(!1),[v,N]=c.useState(!1),y=c.useRef(null),S=ct(F=>F.currentDirectory??null),D=c.useMemo(()=>{if(typeof window>"u")return null;const F=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),M=Pt(F=>F.activeProjectId),C=Pt(F=>F.projects),k=c.useMemo(()=>{if(M){const pe=C.find(be=>be.id===M);if(pe?.path)return pe.path}const F=S??D;if(!F)return null;const $=F.replace(/\\/g,"/").replace(/\/+$/,"")||F,J=$.indexOf("/.openchamber/");return J>0?$.slice(0,J):$.endsWith("/.openchamber")?$.slice(0,$.length-13):$},[M,C,S,D]),A=_e(F=>F.isSidebarOpen),[E,R]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),V=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const F=typeof window.opencodeDesktop<"u";R(F)},[]);const T=c.useMemo(()=>E&&V?A?"pl-0":"pl-[8.0rem]":"pl-3",[E,V,A]),[B,re]=c.useState("HEAD"),{isLoading:Y,isGitRepository:_}=bl(S),q=Gn(F=>F.createMultiRun),O=Gn(F=>F.error),z=Gn(F=>F.clearError);c.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(F=>F.trim().length>0?F:s)},[s]),c.useEffect(()=>{if(!k)return;let F=!1;return N(!0),(async()=>{try{const $=await ro(k);F||j($)}catch{}finally{F||N(!1)}})(),()=>{F=!0}},[k]);const U=F=>{l.length>=Bc||(d($=>[...$,F]),z())},ne=F=>{d($=>$.filter((L,J)=>J!==F)),z()},oe=c.useCallback((F,$)=>{d(L=>L.map((J,pe)=>pe===F?$:J))},[]),Q=async F=>{const $=F.target.files;if(!$)return;let L=0;for(let J=0;J<$.length;J++){const pe=$[J];if(pe.size>vb){se.error(`File "${pe.name}" is too large (max 10MB)`);continue}try{const be=await new Promise((Ae,je)=>{const Te=new FileReader;Te.onload=()=>Ae(Te.result),Te.onerror=je,Te.readAsDataURL(pe)}),he={id:Zo(),filename:pe.name,mimeType:pe.type||"application/octet-stream",size:pe.size,dataUrl:be};p(Ae=>[...Ae,he]),L++}catch(be){console.error("File attach failed",be),se.error(`Failed to attach "${pe.name}"`)}}L>0&&se.success(`Attached ${L} file${L>1?"s":""}`),y.current&&(y.current.value="")},de=F=>{p($=>$.filter(L=>L.id!==F))},I=async F=>{if(F.preventDefault(),!!a.trim()&&!(l.length<2)){w(!0),z();try{const $=l.map(({instanceId:he,...Ae})=>Ae),L=f.map(he=>({mime:he.mimeType,filename:he.filename,url:he.dataUrl})),J=h.filter(he=>he.trim().length>0),pe={name:n.trim(),prompt:a.trim(),models:$,agent:u||void 0,worktreeBaseBranch:B,files:L.length>0?L:void 0,setupCommands:J.length>0?J:void 0},be=await q(pe);be&&(be.firstSessionId&&me.getState().setCurrentSession(be.firstSessionId),r?.())}finally{w(!1)}}},W=!!(n.trim()&&a.trim()&&l.length>=2&&_&&!Y);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:P("flex h-12 items-center justify-between border-b app-region-drag",T),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:P("flex items-center gap-3",E&&V&&A&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),t&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:t,"aria-label":"Close",className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary app-region-no-drag",children:e.jsx(Ht,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsx("p",{children:"Close"})})]})})]}),e.jsx("div",{className:"flex-1 overflow-auto",children:e.jsx("div",{className:"chat-column py-6",children:e.jsxs("form",{onSubmit:I,className:"space-y-6","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:["Group name ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(pt,{id:"group-name",value:n,onChange:F=>o(F.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(wm,{directory:S,value:B,onChange:re,id:"multirun-worktree-base-branch"}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from"," ",e.jsx("code",{className:"font-mono text-xs text-muted-foreground",children:B||"HEAD"}),"."]})]}),e.jsxs(ga,{open:b,onOpenChange:x,children:[e.jsxs(gl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",h.filter(F=>F.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",h.filter(F=>F.trim()).length," configured)"]})]}),e.jsx(Mt,{className:P("h-4 w-4 text-muted-foreground transition-transform duration-200",b&&"rotate-180")})]}),e.jsx(xa,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[h.map((F,$)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pt,{value:F,onChange:L=>{const J=[...h];J[$]=L.target.value,j(J)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const L=h.filter((J,pe)=>pe!==$);j(L)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Ht,{className:"h-4 w-4"})})]},$)),e.jsxs("button",{type:"button",onClick:()=>j([...h,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(vm,{value:u,onChange:m,id:"multirun-agent"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:["Prompt ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Is,{id:"prompt",value:a,onChange:F=>i(F.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:y,type:"file",multiple:!0,className:"hidden",onChange:Q,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>y.current?.click(),children:[e.jsx(Wo,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(F=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[F.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:F.filename,children:F.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",F.size<1024?`${F.size}B`:F.size<1024*1024?`${(F.size/1024).toFixed(1)}KB`:`${(F.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>de(F.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},F.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(bm,{selectedModels:l,onAdd:U,onRemove:ne,onUpdate:oe,minModels:2,maxModels:Bc})]}),O&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:O}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Ne,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(Ne,{type:"submit",disabled:!W||g,children:g?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Hp,{className:"h-4 w-4 mr-2"}),"Start (",l.length," models)"]})})]})]})})})]})},jb=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:l}=_e(),d=Ce.useRef(null),u=Ce.useRef(null);return Ce.useEffect(()=>{if(!o||!a)return;const m=w=>{const h=w.touches[0];if(!h){d.current=null;return}h.clientX<=r?d.current={x:h.clientX,y:h.clientY,time:Date.now()}:d.current=null},f=w=>{if(!d.current)return;const h=w.touches[0];if(!h)return;h.clientX-d.current.x>10&&w.preventDefault()},p=w=>{if(!d.current)return;const h=w.changedTouches[0];if(!h){d.current=null,u.current=null;return}u.current={x:h.clientX,y:h.clientY,time:Date.now()};const{x:j,y:b,time:x}=d.current,{x:v,y:N,time:y}=u.current,S=v-j,D=N-b,M=y-x,C=Math.abs(D)<Math.abs(S),k=M<=n,A=Math.abs(D)<t;S>=t&&C&&k&&A&&!l&&i(!0),d.current=null,u.current=null},g=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",g,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",g,{capture:!0})}},[o,a,r,t,n,i,l]),null},Ln=s=>s==="full"?{text:"var(--status-info)",border:"var(--status-info-border)",background:"var(--status-info-background)",borderWidth:1.5}:s==="allow"?{text:"var(--status-success)",border:"var(--status-success-border)",background:"var(--status-success-background)",borderWidth:1.5}:null;Ce.memo(()=>{const s=Ce.useRef(null),{addAttachedFile:r}=me(),{isMobile:t}=_e(),n=sm(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],g=me.getState().attachedFiles.length;try{await r(p),me.getState().attachedFiles.length>g&&m++}catch(w){console.error("File attach failed",w),se.error(w instanceof Error?w.message:"Failed to attach file")}}m>0&&se.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await i(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const w=p.map(h=>`${h?.name||"file"}: ${h?.reason||"skipped"}`).join(`
66
+ `);se.error(`Some files were skipped:
67
+ ${w}`)}const g=f.map(w=>{if(!w?.dataUrl)return null;try{const[h,j]=w.dataUrl.split(","),b=w.mimeType||h?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!j)return null;const x=atob(j),v=new Uint8Array(x.length);for(let y=0;y<x.length;y++)v[y]=x.charCodeAt(y);const N=new Blob([v],{type:b});return new File([N],w.name||"file",{type:b})}catch(h){return console.error("Failed to decode VS Code picked file",h),null}}).filter(Boolean);g.length>0&&await i(g)}catch(u){console.error("VS Code file pick failed",u),se.error(u instanceof Error?u.message:"Failed to pick files in VS Code")}};return e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:s,type:"file",multiple:!0,className:"hidden",onChange:l,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:P(o,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),title:"Attach files",children:e.jsx(Wo,{className:P(a,"text-current")})})]})});const Sb=Ce.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(aa,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(Up,{className:"h-3 w-3 text-primary"}):e.jsx(tu,{className:"h-3 w-3 text-muted-foreground"})}),t(),e.jsx("span",{title:s.serverPath||a,children:a}),e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["(",n(s.size),")"]}),e.jsx("button",{onClick:r,className:"ml-1 hover:text-destructive p-0.5",title:"Remove file",children:e.jsx(Ht,{className:"h-3 w-3"})})]})}),kb=Ce.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=me();return s.length===0?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Attached:"}),s.map(t=>e.jsx(Sb,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),jm=Ce.memo(({files:s,onShowPopup:r})=>{const t=s.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(aa,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),l=c.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(br,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(tt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Sm=Ce.memo(({message:s,sessionId:r,onEdit:t})=>{const n=Zs(i=>i.removeFromQueue),o=c.useMemo(()=>{const i=s.content.split(`
68
+ `),l=i[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(i.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Vp,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>t(s),className:"flex items-center gap-1.5 hover:text-foreground transition-colors text-left",title:"Click to edit",children:[e.jsx("span",{className:"truncate max-w-[200px]",children:o||"(empty)"}),a>0&&e.jsxs("span",{className:"text-muted-foreground flex-shrink-0",children:["+",a," file",a>1?"s":""]})]}),e.jsx("button",{type:"button",onClick:()=>n(r,s.id),className:"ml-1 hover:text-destructive p-0.5 opacity-60 group-hover:opacity-100 transition-opacity",title:"Remove from queue",children:e.jsx(Ht,{className:"h-3 w-3"})})]})});Sm.displayName="QueuedMessageChip";const Wc=[],km=Ce.memo(({onEditMessage:s})=>{const r=me(a=>a.currentSessionId),t=Zs(c.useCallback(a=>r?a.queuedMessages[r]??Wc:Wc,[r])),n=Zs(a=>a.popToInput),o=c.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const l=er.getState().attachedFiles;er.setState({attachedFiles:[...l,...i.attachments]})}s(i.content,i.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(Sm,{message:a,sessionId:r,onEdit:o},a.id))]})})});km.displayName="QueuedMessageChips";const Nb=c.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=ct(),{addServerFile:a}=me(),i=Qi(A=>A.searchFiles),l=hl(s,180),[d,u]=c.useState([]),[m,f]=c.useState(!1),[p,g]=c.useState(0),[w,h]=c.useState(360),[j,b]=c.useState({}),[x,v]=c.useState({}),N=c.useRef([]),y=c.useRef([]),S=c.useRef([]),D=c.useRef(null),M=c.useCallback((A,E)=>{const R=A.trim().toLowerCase();if(!R)return 0;const V=E.toLowerCase();let T=0,B=-1,re=0;for(let Y=0;Y<R.length;Y+=1){const _=R[Y];if(!_||_===" ")continue;const q=V.indexOf(_,B+1);if(q===-1)return null;const O=q-B-1;if(O===0?re+=1:re=0,T+=10,T+=Math.max(0,18-q),T-=Math.max(0,O),q===0)T+=12;else{const z=V[q-1];(z==="/"||z==="_"||z==="-"||z==="."||z===" ")&&(T+=10)}T+=re>0?12:0,B=q}return T+=Math.max(0,24-Math.round(V.length/3)),T},[]);c.useEffect(()=>{const A=E=>{const R=E.target;!R||!D.current||D.current.contains(R)||t()};return document.addEventListener("pointerdown",A,!0),()=>{document.removeEventListener("pointerdown",A,!0)}},[t]),c.useEffect(()=>{if(!o){u([]);return}const E=(l??"").trim().toLowerCase();let R=!1;return f(!0),i(o,E,80).then(V=>{if(R)return;const T=E?V.map(B=>{const re=B.relativePath||B.name||B.path,Y=M(E,re);return Y===null?null:{file:B,score:Y,labelLength:re.length}}).filter(Boolean):V.map(B=>({file:B,score:0,labelLength:(B.relativePath||B.name||B.path).length}));T.sort((B,re)=>re.score-B.score||B.labelLength-re.labelLength||B.file.path.localeCompare(re.file.path)),u(T.slice(0,15).map(B=>B.file))}).catch(()=>{R||u([])}).finally(()=>{R||f(!1)}),()=>{R=!0}},[o,l,M,i]),c.useEffect(()=>{g(0),b({}),v({})},[d]),c.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),c.useEffect(()=>{let A=null;const E=()=>{A!==null&&cancelAnimationFrame(A),A=requestAnimationFrame(()=>{const R={},V={};y.current.forEach((T,B)=>{if(!T)return;const Y=S.current[B]?.offsetWidth??T.scrollWidth,_=Math.max(0,Y-T.clientWidth),q=_>8;if(R[B]=q,q){const O=Math.max(.6,_/110);V[B]=O}}),b(R),v(V)})};return E(),window.addEventListener("resize",E),()=>{A!==null&&cancelAnimationFrame(A),window.removeEventListener("resize",E)}},[d]),c.useEffect(()=>{const A=y.current[p];if(!A)return;const E=()=>{const V=A.clientWidth;V>0&&h(V)};if(E(),typeof ResizeObserver>"u")return;const R=new ResizeObserver(E);return R.observe(A),()=>{R.disconnect()}},[p]);const C=c.useCallback(async A=>{await a(A.path,A.name),r(A)},[a,r]);c.useImperativeHandle(n,()=>({handleKeyDown:A=>{if(A==="Escape"){t();return}const E=d.length;if(E!==0){if(A==="ArrowDown"){g(R=>(R+1)%E);return}if(A==="ArrowUp"){g(R=>(R-1+E)%E);return}if(A==="Enter"||A==="Tab"){const R=(p%E+E)%E,V=d[R];V&&C(V)}}}}),[d,p,t,C]);const k=A=>{switch(A.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(tr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(aa,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:D,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"px-0",children:m?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((A,E)=>{const R=A.relativePath||A.name,V=yu(R,{maxLength:45}),T=p===E,B=j[E]??!1,re=x[E]??2.6,Y=e.jsxs("div",{ref:_=>{N.current[E]=_},className:P("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",T&&"bg-muted"),onClick:()=>C(A),onMouseEnter:()=>g(E),children:[k(A),e.jsxs("span",{ref:_=>{y.current[E]=_},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:T?{"--file-mention-marquee-width":`${w}px`,"--file-mention-marquee-duration":`${re}s`}:void 0,"aria-label":R,children:[e.jsx("span",{ref:_=>{S.current[E]=_},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:R}),B&&T?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:R}):e.jsx("span",{className:"block truncate",children:V})]})]});return e.jsx(c.Fragment,{children:Y},A.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Nm=c.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=me(Ui(x=>{const v=x.currentSessionId;return{hasMessagesInCurrentSession:(v?x.messages.get(v)?.length??0:0)>0,currentSessionId:v}})),i=!!a,[l,d]=c.useState([]),[u,m]=c.useState(!1),{commands:f,loadCommands:p}=Tr(),[g,w]=c.useState(0),h=c.useRef([]),j=c.useRef(null);c.useEffect(()=>{const x=v=>{const N=v.target;!N||!j.current||j.current.contains(N)||t()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[t]),c.useEffect(()=>{p()},[p]),c.useEffect(()=>{(async()=>{m(!0);try{const v=f.map(C=>({name:C.name,description:C.description,agent:C.agent??void 0,model:C.model??void 0,isBuiltIn:C.name==="init"||C.name==="review",scope:C.scope})),N=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],y=new Map;N.forEach(C=>y.set(C.name,C)),v.forEach(C=>y.set(C.name,C));const S=Array.from(y.values()),D=!o,M=(s?S.filter(C=>As(C.name,s)||C.description&&As(C.description,s)):S).filter(C=>D||C.name!=="init");M.sort((C,k)=>{const A=C.name.toLowerCase().startsWith(s.toLowerCase()),E=k.name.toLowerCase().startsWith(s.toLowerCase());return A&&!E?-1:!A&&E?1:C.name.localeCompare(k.name)}),d(M)}catch{const v=!o,N=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],y=(s?N.filter(S=>As(S.name,s)||S.description&&As(S.description,s)):N).filter(S=>v||S.name!=="init");d(y)}finally{m(!1)}})()},[s,o,i,f]),c.useEffect(()=>{w(0)},[l]),c.useEffect(()=>{h.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),c.useImperativeHandle(n,()=>({handleKeyDown:x=>{const v=l.length;if(x==="Escape"){t();return}if(v!==0){if(x==="ArrowDown"){w(N=>(N+1)%v);return}if(x==="ArrowUp"){w(N=>(N-1+v)%v);return}if(x==="Enter"||x==="Tab"){const N=(g%v+v)%v,y=l[N];y&&r(y)}}}}),[l,g,t,r]);const b=x=>{switch(x.name){case"init":return e.jsx(tr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Kn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(qp,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(or,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(Kp,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Er,{className:"h-3.5 w-3.5 text-cyan-500"});default:return x.isBuiltIn?e.jsx(Gp,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(Qr,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:j,className:"absolute z-[100] min-w-0 w-full max-w-[450px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:u?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Dr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((x,v)=>{const N=x.isBuiltIn,y=x.scope==="project";return e.jsxs("div",{ref:S=>{h.current[v]=S},className:P("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",v===g&&"bg-muted"),onClick:()=>r(x),onMouseEnter:()=>w(v),children:[e.jsx("div",{className:"mt-0.5",children:b(x)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-medium",children:["/",x.name]}),N?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):x.scope?e.jsx("span",{className:P("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",y?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:x.scope}):null,x.agent&&e.jsx("span",{className:"text-[10px] leading-none font-bold tracking-tight bg-[var(--surface-subtle)] text-[var(--surface-foreground)] border-[var(--interactive-border)] px-1.5 py-1 rounded border flex-shrink-0",children:x.agent})]}),x.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:x.description})]})]},x.name)}),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Nm.displayName="CommandAutocomplete";const Cb=s=>s?s!=="primary":!1,Cm=c.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{getVisibleAgents:m}=et(),{agents:f,loadAgents:p}=Fr();c.useEffect(()=>{f.length===0&&p()},[p,f.length]),c.useEffect(()=>{const h=m().filter(x=>Cb(x.mode)).map(x=>{const v=f.find(N=>N.name===x.name);return{name:x.name,description:x.description,mode:x.mode??void 0,scope:v?.scope,isBuiltIn:v?zr(v):!1}}),j=s.trim(),b=j.length?h.filter(x=>As(x.name,j)):h;b.sort((x,v)=>x.name.localeCompare(v.name)),d(b),i(0)},[m,s,f]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const w=h=>{const j=h.target;!j||!o.current||o.current.contains(j)||t()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:w=>{if(w==="Escape"){t();return}if(l.length){if(w==="ArrowDown"){i(h=>(h+1)%l.length);return}if(w==="ArrowUp"){i(h=>(h-1+l.length)%l.length);return}if(w==="Enter"||w==="Tab"){const h=l[(a+l.length)%l.length];h&&r(h.name)}}}}),[l,r,t,a]);const g=(w,h)=>{const j=w.isBuiltIn,b=w.scope==="project";return e.jsx("div",{ref:x=>{u.current[h]=x},className:P("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",h===a&&"bg-muted"),onClick:()=>r(w.name),onMouseEnter:()=>i(h),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",w.name]}),j?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):w.scope?e.jsx("span",{className:P("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",b?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:w.scope}):null]}),w.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:w.description})]})},w.name)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((w,h)=>g(w,h))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No agents found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Cm.displayName="AgentMentionAutocomplete";const Mm=c.forwardRef(({searchQuery:s,onSkillSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{skills:m,loadSkills:f}=Hs();c.useEffect(()=>{f()},[f]),c.useEffect(()=>{const g=s.trim(),h=[...g.length?m.filter(j=>As(j.name,g)):m].sort((j,b)=>j.scope==="project"&&b.scope!=="project"?-1:j.scope!=="project"&&b.scope==="project"?1:j.name.localeCompare(b.name));d(h),i(0)},[m,s]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const g=w=>{const h=w.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){t();return}if(l.length){if(g==="ArrowDown"){i(w=>(w+1)%l.length);return}if(g==="ArrowUp"){i(w=>(w-1+l.length)%l.length);return}if(g==="Enter"||g==="Tab"){const w=l[a];w&&r(w.name)}}}}),[l,r,t,a]);const p=(g,w)=>{const h=g.scope==="project";return e.jsx("div",{ref:j=>{u.current[w]=j},className:P("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",w===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>i(w),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:g.name}),e.jsx("span",{className:P("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0 transition-colors",h?"bg-[var(--status-info-background)] text-[var(--status-info)] border-[var(--status-info-border)]":"bg-[var(--status-success-background)] text-[var(--status-success)] border-[var(--status-success-border)]"),children:g.scope})]}),g.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:g.description})]})},`${g.name}-${g.scope}`)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((g,w)=>p(g,w))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Mm.displayName="SkillAutocomplete";function Mb({className:s,children:r,...t}){return e.jsxs(Yp,{"data-slot":"scroll-area",className:P("relative",s),...t,children:[e.jsx(Xp,{"data-slot":"scroll-area-viewport",className:"focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:outline-none focus-visible:ring-[3px] will-change-scroll",children:r}),e.jsx(Db,{}),e.jsx(Qp,{})]})}function Db({className:s,orientation:r="vertical",...t}){return e.jsx(Jp,{"data-slot":"scroll-area-scrollbar",orientation:r,className:P("flex touch-none p-px select-none",r==="vertical"&&"h-full w-2.5 border-l border-l-transparent",r==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent",s),...t,children:e.jsx(Zp,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Ab=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=Ft(),l=i,{currentDirectory:d}=ct(),u=Qi(K=>K.searchFiles),[m,f]=c.useState(!1),[p,g]=c.useState(!1),[w,h]=c.useState(""),j=hl(w,200),[b,x]=c.useState(new Set),[v,N]=c.useState(new Set),[y,S]=c.useState({}),D=c.useRef(new Set),M=c.useRef(new Set),[C,k]=c.useState([]),[A,E]=c.useState(!1),[R,V]=c.useState(!1),[T,B]=c.useState(!1),[re,Y]=c.useState(null),_=n??m,q=o??f,O=c.useCallback(K=>K.slice().sort((X,te)=>X.type!==te.type?X.type==="directory"?-1:1:X.name.localeCompare(te.name)),[]),z=c.useCallback((K,X)=>O(X.filter(te=>!te.name.startsWith(".")).map(te=>{const fe=te.name,ue=!te.isDirectory&&fe.includes(".")?fe.split(".").pop()?.toLowerCase():void 0;return{name:fe,path:te.path||`${K}/${fe}`,type:te.isDirectory?"directory":"file",size:0,extension:ue}})),[O]),U=c.useCallback(async K=>{V(!0),Y(null);try{const X=await ke.listLocalDirectory(K),te=z(K,X.map(fe=>({name:fe.name,path:fe.path,isDirectory:fe.isDirectory})));D.current=new Set([K]),M.current=new Set,S({[K]:te}),N(new Set)}catch{Y("Failed to load directory contents"),D.current=new Set([K]),M.current=new Set,S({[K]:[]}),N(new Set)}finally{V(!1)}},[z]),ne=c.useCallback(async K=>{const X=K.trim();if(X&&!D.current.has(X)&&!M.current.has(X)){M.current=new Set(M.current),M.current.add(X);try{const te=await ke.listLocalDirectory(X),fe=z(X,te.map(ue=>({name:ue.name,path:ue.path,isDirectory:ue.isDirectory})));D.current=new Set(D.current),D.current.add(X),S(ue=>({...ue,[X]:fe}))}catch{S(te=>te[X]?te:{...te,[X]:[]})}finally{M.current=new Set(M.current),M.current.delete(X)}}},[z]);c.useEffect(()=>{(_||p)&&d&&U(d)},[_,p,d,U]),c.useEffect(()=>{if(!(_||p)||!d){k([]),E(!1);return}const K=j.trim();if(!K){k([]),E(!1);return}let X=!1;return E(!0),u(d,K,150).then(te=>{if(X)return;const fe=te.map(ue=>({name:ue.name,path:ue.path,type:"file",extension:ue.extension,relativePath:ue.relativePath,size:0}));k(fe)}).catch(()=>{X||k([])}).finally(()=>{X||E(!1)}),()=>{X=!0}},[_,p,d,j,u]),c.useEffect(()=>{!_&&!p&&(x(new Set),h(""),k([]),E(!1))},[_,p]);const oe=K=>{if(K.type==="directory")return v.has(K.path)?e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"});switch(K.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(hi,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(hi,{className:"h-3.5 w-3.5 text-muted-foreground"})}},Q=async K=>{v.has(K)?N(te=>{const fe=new Set(te);return fe.delete(K),fe}):(N(te=>{const fe=new Set(te);return fe.add(K),fe}),await ne(K))},de=K=>{x(r?X=>{const te=new Set(X);return te.has(K)?te.delete(K):te.add(K),te}:new Set([K]))},I=async()=>{const K=new Map;Object.values(y).forEach(fe=>{fe.forEach(ue=>{ue.type==="file"&&K.set(ue.path,ue)})});const X=new Map(C.map(fe=>[fe.path,fe])),te=Array.from(b).map(fe=>K.get(fe)??X.get(fe)).filter(fe=>!!fe);B(!0);try{await s(te),x(new Set),q(!1),g(!1)}finally{B(!1)}},W=c.useMemo(()=>d?y[d]??[]:[],[y,d]),F=w.trim().length>0,$=K=>y[K]??[],L=K=>{if(d&&K.startsWith(d)){const X=K.substring(d.length);return X.startsWith("/")?X.substring(1):X}return K.split("/").pop()||K},J=(K,X)=>{const te=F?K.relativePath||L(K.path):K.name,fe=F&&te.includes("/")&&te.length>45,ue=fe?yu(te,{maxLength:l?42:48}):te,ae=e.jsxs("div",{className:P("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded hover:bg-muted cursor-pointer typography-ui-label text-foreground text-left",K.type==="file"&&b.has(K.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:H=>{H.preventDefault(),H.stopPropagation(),K.type==="file"&&de(K.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:oe(K)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":te,children:ue})]}),K.type==="file"&&b.has(K.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return fe?e.jsxs(rt,{delayDuration:120,children:[e.jsx(nt,{asChild:!0,children:ae}),e.jsx(tt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:te})})]},K.path):c.cloneElement(ae,{key:K.path})},pe=(K,X)=>{const te=K.type==="directory",fe=te?$(K.path):[],ue=v.has(K.path),ae=te&&ue&&M.current.has(K.path)&&fe.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:P("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!te&&b.has(K.path)&&"bg-primary/10"),style:{paddingLeft:`${X*12}px`},onClick:H=>{H.preventDefault(),H.stopPropagation(),te?Q(K.path):de(K.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:oe(K)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:K.name}),!te&&b.has(K.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),te&&ue&&fe.length>0&&e.jsx("div",{children:fe.map(H=>pe(H,X+1))}),te&&ue&&ae&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(X+1)*12}px`},children:"Loading…"})]},K.path)},be=b.size>0?`${b.size} file${b.size!==1?"s":""} selected`:"No files selected",he=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:be}),e.jsx(Ne,{size:"sm",onClick:I,disabled:b.size===0||T,className:"h-6 typography-meta",children:T?"Attaching...":"Attach Files"})]}),Ae=l?"flex-1 min-h-[240px]":"h-[300px]",je=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{value:w,onChange:K=>h(K.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:K=>K.stopPropagation()}),w&&e.jsx("button",{onClick:K=>{K.stopPropagation(),h("")},className:"absolute right-2 top-1/2 -translate-y-1/2 p-0.5 hover:bg-muted rounded",children:e.jsx(Ht,{className:"h-3 w-3"})})]})}),e.jsxs(Mb,{className:Ae,children:[R&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Loading files..."})}),re&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:re})}),!R&&!re&&e.jsxs("div",{className:"py-1 px-2",children:[F?A?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):C.map(K=>J(K,0)):W.map(K=>pe(K,0)),!F&&W.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),F&&!A&&C.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Te=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:K=>{K.preventDefault(),K.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:K=>{K.preventDefault(),K.stopPropagation(),q(!0)},children:t}):null,e.jsx(ws,{open:_,onClose:()=>q(!1),title:"Select Project Files",footer:he,children:e.jsx("div",{className:"flex flex-col gap-0",children:je})})]}):l?e.jsxs(e.Fragment,{children:[Te,e.jsx(ws,{open:p,onClose:()=>g(!1),title:"Select Project Files",footer:he,children:e.jsx("div",{className:"flex flex-col gap-0",children:je})})]}):e.jsxs(Ut,{open:_,onOpenChange:q,children:[e.jsx(Vt,{asChild:!0,children:t}),e.jsxs(Gt,{className:P("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[je,e.jsx(Ms,{}),he]})]})},xo=[{var:"--status-success",class:"agent-success"},{var:"--syntax-keyword",class:"agent-keyword"},{var:"--syntax-type",class:"agent-type"},{var:"--syntax-function",class:"agent-function"},{var:"--syntax-number",class:"agent-number"},{var:"--status-info",class:"agent-info"},{var:"--status-warning",class:"agent-warning"},{var:"--syntax-variable",class:"agent-variable"}];function kr(s){if(!s||s==="build")return xo[0];let r=0;for(let n=0;n<s.length;n++){const o=s.charCodeAt(n);r=(r<<5)-r+o,r=r&r}const t=1+Math.abs(r)%(xo.length-1);return xo[t]}const Eb=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),Dm=s=>Eb(s),Ib=s=>s?typeof s=="string"?s==="ask":Dm(s)?Object.values(s).some(r=>r==="ask"):!1:!1,Pb=s=>s?typeof s=="string"?s==="deny":Dm(s)?Object.values(s).some(r=>r==="deny"):!1:!1,Am=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=Ib(t),o=Pb(t),a=!n&&!o,i=r==="allow",l=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&i&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&l&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:l}},yo=s=>s==="primary"||s==="all"||s===void 0||s===null,ea=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},bo=(s,r)=>{const t=ea(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Tb=(s,r)=>{const t=ea(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},Fb=[{key:"tool_call",icon:ia,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:ar,label:"Reasoning",isActive:s=>s?.reasoning===!0}],Rb={text:{icon:ru,label:"Text"},image:{icon:br,label:"Image"},video:{icon:th,label:"Video"},audio:{icon:eh,label:"Audio"},pdf:{icon:aa,label:"PDF"}},_b=s=>s.trim().toLowerCase(),_n=(s,r)=>{const t=r==="input"?s?.modalities?.input:s?.modalities?.output;return!Array.isArray(t)||t.length===0?[]:Array.from(new Set(t.map(o=>_b(o)))).map(o=>{const a=Rb[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Ob=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),$b=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Os=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=Ob.format(s);return r.endsWith(".0")?r.slice(0,-2):r},wo=s=>typeof s!="number"||!Number.isFinite(s)?"—":$b.format(s),Ka=s=>Fb.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Hc=s=>{if(!s)return"—";const r=s.match(/^(\d{4})-(\d{2})$/);if(r){const t=Number.parseInt(r[1],10),n=Number.parseInt(r[2],10)-1,o=new Date(Date.UTC(t,n,1));if(!Number.isNaN(o.getTime()))return new Intl.DateTimeFormat("en-US",{month:"short",year:"numeric"}).format(o)}return s},Uc=s=>{if(!s)return"—";const r=new Date(s);return Number.isNaN(r.getTime())?s:new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(r)},Vc=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:i,setProvider:l,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:g,getCurrentAgent:w,getVisibleAgents:h}=et(),j=h(),{currentSessionId:b,messages:x,saveSessionAgentSelection:v,getSessionAgentSelection:N,saveAgentModelForSession:y,getAgentModelForSession:S,saveAgentModelVariantForSession:D,getAgentModelVariantForSession:M,analyzeAndSaveExternalSessionChoices:C,getSessionAgentEditMode:k,setSessionAgentEditMode:A}=me(),E=xt(Z=>Z.hasHydrated),{toggleFavoriteModel:R,isFavoriteModel:V,addRecentModel:T,isModelSelectorOpen:B,setModelSelectorOpen:re}=_e(),{favoriteModelsList:Y,recentModelsList:_}=yl(),{isMobile:q}=Ft(),O=my(),z=sm(),U=q,[ne,oe]=c.useState(null),[Q,de]=c.useState(null),[I,W]=c.useState(""),F=c.useCallback(()=>oe(null),[]),$=c.useCallback(()=>de(null),[]),L=c.useRef(void 0),[J,pe]=c.useState(()=>{const Z=new Set;return t&&Z.add(t),Z}),[be,he]=c.useState(!1),Ae=B,je=re,[Te,K]=c.useState(!1),X=c.useId(),[te,fe]=c.useState(""),[ue,ae]=c.useState(0),H=c.useRef([]);c.useEffect(()=>{ne==="model"&&pe(()=>{const Z=new Set;return t&&Z.add(t),Z})},[ne,t]),c.useEffect(()=>{ne!=="agent"&&he(!1),ne!=="model"&&W("")},[ne]);const xe=c.useRef(Ae);c.useEffect(()=>{const Z=xe.current;xe.current=Ae,Ae||(K(!1),fe(""),ae(0),Z&&!U&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Ae,U]),c.useEffect(()=>{ae(0)},[te]);const G=w?.(),ye=c.useMemo(()=>G?bo(G.permission,"edit")??"ask":"deny",[G]),Fe=c.useMemo(()=>{if(G)return bo(G.permission,"webfetch")},[G]),qe=c.useMemo(()=>{if(!G)return;const Z=Tb(G.permission,"bash");return Z||void 0},[G]),Re=c.useMemo(()=>Am({agentDefaultEditMode:ye,webfetchPermission:Fe,bashPermission:qe}),[ye,Fe,qe]),{cascadeDefaultMode:Ee,modeAvailability:Ye,autoApproveAvailable:ot}=Re,ut=!!(b&&a),kt=ut&&b&&a?k(b,a,Ee):Ee,Rt={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Et=c.useCallback(Z=>!Ye[Z],[Ye]),Nt=c.useMemo(()=>!ut||Et(kt)&&kt!==Ee?Ee:kt,[Ee,Et,ut,kt]),Qt=[{mode:"ask",label:Rt.ask,disabled:Et("ask")},{mode:"allow",label:Rt.allow,disabled:Et("allow")},{mode:"full",label:Rt.full,disabled:Et("full")}],Tt=c.useMemo(()=>Ln(Nt),[Nt]),Se=!ut||!ot;c.useEffect(()=>{Se&&(he(!1),K(!1))},[Se]);const Pe=q?"mobile":z?"vscode":"default",We=Pe==="mobile"?"h-9":Pe==="vscode"?"h-6":"h-8",at=Pe==="mobile"?"h-5 w-5":"h-4 w-4",jt=Pe==="mobile"?"h-5 w-5":"h-4 w-4",zt=U?"typography-micro":"typography-meta",Jt=Pe==="mobile"?"gap-x-2":Pe==="vscode"?"gap-x-1":"gap-x-3",He=Rt[Nt],Ge=c.useCallback((Z,le=at)=>{const ce=P(le,"flex-shrink-0"),ve=Ln(Z),ze={color:ve?ve.text:"var(--foreground)"};return Z==="full"?e.jsx(mr,{className:ce,style:ze}):Z==="allow"?e.jsx(Mo,{className:ce,style:ze}):Z==="deny"?e.jsx(wn,{className:ce,style:ze}):e.jsx(yn,{className:ce,style:ze})},[at]),st=c.useCallback(Z=>{Se||!b||!a||Et(Z)||(A(b,a,Z,Ee),je(!1),he(!1),K(!1))},[Ee,Se,b,a,A,je,K,Et]),Ke=p(),lt=Array.isArray(Ke?.models)?Ke.models:[],Ze=t&&n?g(t,n):void 0,mt=Ka(Ze),ee=_n(Ze,"input"),we=_n(Ze,"output"),ge=c.useMemo(()=>`${t}/${n}`?m():[],[m,t,n]),Oe=ge.length>0,Be=[{label:"Input",value:wo(Ze?.cost?.input)},{label:"Output",value:wo(Ze?.cost?.output)},{label:"Cache read",value:wo(Ze?.cost?.cache_read)},{label:"Cache write",value:wo(Ze?.cost?.cache_write)}],Qe=[{label:"Context",value:Os(Ze?.limit?.context)},{label:"Output",value:Os(Ze?.limit?.output)}],It=c.useRef(void 0),wt=b?x.get(b)?.length??-1:-1,Dt=c.useRef(null),Ct=c.useCallback((Z,le,ce)=>{if(!Z||!le)return"model-missing";const ve=r.find(Me=>Me.id===Z);return ve?(Array.isArray(ve.models)?ve.models:[]).find(Me=>Me.id===le)?(l(Z),d(le),b&&ce&&y(b,ce,Z,le),"applied"):"model-missing":"provider-missing"},[r,l,d,b,y]);c.useEffect(()=>{if(!b){Dt.current=null;return}if(!E||r.length===0||j.length===0)return;(!Dt.current||Dt.current.sessionId!==b)&&(Dt.current={sessionId:b,resolved:!1,inFlight:!1});const Z=Dt.current;if(!Z||Z.resolved||Z.inFlight)return;let le=!1;const ce=()=>{if(le)return;const Me=Dt.current;Me&&Me.sessionId===b&&(Me.resolved=!0,Me.inFlight=!1)},ve=()=>{const Me=N(b);if(Me){a!==Me&&f(Me);const Ue=S(b,Me);if(Ue){const De=Ct(Ue.providerId,Ue.modelId,Me);if(De==="applied")return"resolved";if(De==="provider-missing")return"waiting"}else return"resolved"}for(const Ue of j){const De=S(b,Ue.name);if(!De)continue;a!==Ue.name&&f(Ue.name),v(b,Ue.name);const Xe=Ct(De.providerId,De.modelId,Ue.name);if(Xe==="applied")return"resolved";if(Xe==="provider-missing")return"waiting"}return"continue"},Le=()=>{if(j.length===0)return;const Me=j.filter(De=>yo(De.mode)),Ue=j.find(De=>De.name==="build")||Me[0]||j[0];Ue&&(v(b,Ue.name),a!==Ue.name&&f(Ue.name),Ue.model?.providerID&&Ue.model?.modelID&&Ct(Ue.model.providerID,Ue.model.modelID,Ue.name))};return(async()=>{try{const Me=ve();if(Me==="resolved"){ce();return}if(Me==="waiting"||wt===-1)return;if(wt>0){Z.inFlight=!0;try{const Ue=await C(b,j);if(le)return;if(Ue.size>0){let De=null,Xe=-1/0;for(const[bt,ht]of Ue)ht.timestamp>Xe&&(Xe=ht.timestamp,De=bt);if(De){v(b,De),a!==De&&f(De);const bt=Ue.get(De);if(bt){const ht=Ct(bt.providerId,bt.modelId,De);if(ht==="applied"){ce();return}if(ht==="provider-missing")return}else{ce();return}}}}catch(Ue){le||console.error("[ModelControls] Error resolving session from messages:",Ue)}finally{const Ue=Dt.current;!le&&Ue&&Ue.sessionId===b&&(Ue.inFlight=!1)}}Le(),ce()}catch(Me){le||console.error("[ModelControls] Error in session switch:",Me)}})(),()=>{le=!0}},[b,wt,j,a,N,S,f,Ct,C,v,E,r]),c.useEffect(()=>{if(!E||!b||r.length===0||j.length===0)return;const le=N(b)||a;if(!le)return;const ce=S(b,le);if(!ce)return;const ve=r.find(Ue=>Ue.id===ce.providerId);if(!ve||!(Array.isArray(ve.models)?ve.models.some(Ue=>Ue.id===ce.modelId):!1))return;const ze=t===ce.providerId,Me=n===ce.modelId;ze&&Me||(le!==a&&f(le),Ct(ce.providerId,ce.modelId,le))},[E,b,a,t,n,r,j,N,S,Ct,f]),c.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==It.current&&(It.current=a,a&&b)){await new Promise(ve=>setTimeout(ve,50));const le=S(b,a);if(le){const ve=Ct(le.providerId,le.modelId,a);if(ve==="applied"||ve==="provider-missing")return}const ce=j.find(ve=>ve.name===a);if(ce?.model?.providerID&&ce?.model?.modelID&&Ct(ce.model.providerID,ce.model.modelID,a)==="provider-missing")return}}catch(le){console.error("[ModelControls] Agent change error:",le)}})()},[a,b,S,Ct,j,E]),c.useEffect(()=>{if(!E||!a){u(void 0);return}if(!t||!n){u(void 0);return}if(ge.length===0){u(void 0);return}if(o&&!ge.includes(o)){u(void 0);return}if(!b){if(!o){const ce=i&&ge.includes(i)?i:void 0;u(ce)}return}const Z=M(b,a,t,n),le=Z&&ge.includes(Z)?Z:void 0;u(le)},[ge,E,b,a,t,n,o,M,u,i]);const Ie=c.useCallback(Z=>{u(Z),b&&a&&t&&n&&D(b,a,t,n,Z)},[a,n,t,b,D,u]),Je=Z=>{try{f(Z),je(!1),b&&v(b,Z),U&&F()}catch(le){console.error("[ModelControls] Handle agent change error:",le)}},$e=(Z,le)=>{try{const ce=Ct(Z,le,a||void 0);if(ce!=="applied"){ce==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",Z):ce==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:Z,modelId:le});return}T(Z,le),je(!1),U&&F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(ce){console.error("[ModelControls] Handle model change error:",ce)}},Ve=Z=>{const le=typeof Z?.name=="string"?Z.name:typeof Z?.id=="string"?Z.id:"";return le.length>40?le.substring(0,37)+"...":le},yt=()=>r.find(le=>le.id===t)?.name||t,$t=()=>{if(!t||!n||lt.length===0)return"Not selected";const Z=lt.find(le=>le.id===n);return Ve(Z)},ts=()=>{if(!a){const le=j.filter(Le=>yo(Le.mode)),ve=le.find(Le=>Le.name==="build")||le[0];return ve?es(ve.name):"Select Agent"}const Z=j.find(le=>le.name===a);return es(Z?Z.name:a)},es=Z=>Z.charAt(0).toUpperCase()+Z.slice(1),ps=(Z,le,ce)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:le,"aria-label":le,role:"img",children:e.jsx(Z,{className:"h-3.5 w-3.5"})},ce),lr=c.useCallback(Z=>{pe(le=>{const ce=new Set(le);return ce.has(Z)?ce.delete(Z):ce.add(Z),ce})},[]),_t=c.useCallback(Z=>{L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{de(Z)},500)},[]),vr=c.useCallback(()=>{L.current&&clearTimeout(L.current)},[]);c.useEffect(()=>()=>{L.current&&clearTimeout(L.current)},[]);const En=()=>!U||Q!=="model"?null:e.jsx(ws,{open:!0,onClose:$,title:Ze?.name||$t(),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Provider"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:yt()})]}),mt.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:mt.map(({key:Z,icon:le,label:ce})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ps(le,ce,`cap-${Z}`),e.jsx("span",{className:"typography-meta text-foreground",children:ce})]},Z))})]}),(ee.length>0||we.length>0)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[ee.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Input"}),e.jsx("div",{className:"flex gap-1",children:ee.map(({key:Z,icon:le,label:ce})=>ps(le,`${ce} input`,`input-${Z}`))})]}),we.length>0&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-12",children:"Output"}),e.jsx("div",{className:"flex gap-1",children:we.map(({key:Z,icon:le,label:ce})=>ps(le,`${ce} output`,`output-${Z}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(Ze?.limit?.context)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(Ze?.limit?.output)})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Metadata"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Hc(Ze?.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Uc(Ze?.release_date)})]})]})]})]})}),wa=()=>{if(!U||Q!=="agent"||!G)return null;const Z=!!(G.prompt&&G.prompt.trim().length>0),le=G.model?.providerID&&G.model?.modelID,ce=G.temperature!==void 0||G.topP!==void 0,ve=Ue=>{const De=ea(G.permission)??[],Xe=De.some(ht=>ht.permission===Ue&&ht.pattern!=="*"),bt=bo(De,Ue)??"ask";return Xe?{mode:"ask",label:"Custom"}:bt==="allow"?{mode:"allow",label:"Allow"}:bt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Le=ve("edit"),ze=ve("bash"),Me=ve("webfetch");return e.jsx(ws,{open:!0,onClose:$,title:es(G.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[G.description&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsx("div",{className:"typography-meta text-foreground",children:G.description})}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-0.5",children:"Mode"}),e.jsx("div",{className:"typography-meta text-foreground font-medium",children:G.mode==="primary"?"Primary":G.mode==="subagent"?"Subagent":G.mode==="all"?"All":"—"})]}),(le||ce)&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Model"}),le&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[G.model.providerID," / ",G.model.modelID]}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[G.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:G.temperature})]}),G.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:G.topP})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Permissions"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(Le.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Le.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(ze.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ze.label})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(Me.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Me.label})]})]})]})]}),Z&&e.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Mo,{className:"h-4 w-4 text-foreground"})]})})]})})},va=()=>{if(!U)return null;const Z=I.trim(),le=r.map(ce=>{const ve=Array.isArray(ce.models)?ce.models:[],Le=Z.length===0?!0:As(ce.name,Z)||As(ce.id,Z),ze=Z.length===0?ve:ve.filter(Me=>{const Ue=Ve(Me),De=typeof Me.id=="string"?Me.id:"";return As(Ue,Z)||As(De,Z)});return{provider:ce,providerModels:ze,matchesProvider:Le}}).filter(({matchesProvider:ce,providerModels:ve})=>ce||ve.length>0);return e.jsx(ws,{open:ne==="model",onClose:F,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{value:I,onChange:ce=>W(ce.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),I&&e.jsx("button",{type:"button",onClick:()=>W(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(wn,{className:"h-4 w-4"})})]})}),le.length===0&&e.jsx("div",{className:"px-3 py-8 text-center typography-meta text-muted-foreground",children:"No providers or models match your search."}),!I&&Y.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(fr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Y.map(({model:ce,providerID:ve,modelID:Le})=>{const ze=ve===t&&Le===n,Me=g(ve,Le);return e.jsxs("button",{type:"button",onClick:()=>$e(ve,Le),className:P("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",ze?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rs,{providerId:ve,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ce)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Me?.limit?.context||Me?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Me?.limit?.context?`${Os(Me?.limit?.context)} ctx`:"",Me?.limit?.context&&Me?.limit?.output?" • ":"",Me?.limit?.output?`${Os(Me?.limit?.output)} out`:""]})})]},`fav-mobile-${ve}-${Le}`)})})]}),!I&&_.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(or,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:_.map(({model:ce,providerID:ve,modelID:Le})=>{const ze=ve===t&&Le===n,Me=g(ve,Le);return e.jsxs("button",{type:"button",onClick:()=>$e(ve,Le),className:P("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 text-left last:border-b-0","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary","first:rounded-t-xl last:rounded-b-xl transition-colors",ze?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(rs,{providerId:ve,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ve(ce)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Me?.limit?.context||Me?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Me?.limit?.context?`${Os(Me?.limit?.context)} ctx`:"",Me?.limit?.context&&Me?.limit?.output?" • ":"",Me?.limit?.output?`${Os(Me?.limit?.output)} out`:""]})})]},`recent-mobile-${ve}-${Le}`)})})]}),le.map(({provider:ce,providerModels:ve})=>{if(ve.length===0&&!Z.length)return null;const Le=ce.id===t,ze=J.has(ce.id)||Z.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>lr(ce.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":ze,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{providerId:ce.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ce.name}),Le&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ze?e.jsx(Mt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),ze&&ve.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:ve.map(Me=>{const Ue=Le&&Me.id===n,De=g(ce.id,Me.id),Xe=Ka(De).slice(0,3),bt=_n(De,"input");return e.jsxs("div",{className:P("flex w-full items-start gap-2 border-b border-border/30 px-2 py-1.5 last:border-b-0","rounded-lg transition-colors",!Ue&&"hover:bg-muted",Ue?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>$e(ce.id,Me.id),className:P("flex flex-1 min-w-0 items-start gap-2 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary"),children:[e.jsx("div",{className:"flex min-w-0 flex-col",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ve(Me)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(De?.limit?.context||De?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[De?.limit?.context?e.jsxs("span",{children:[Os(De?.limit?.context)," ctx"]}):null,De?.limit?.context&&De?.limit?.output?e.jsx("span",{children:"•"}):null,De?.limit?.output?e.jsxs("span",{children:[Os(De?.limit?.output)," out"]}):null]}),(Xe.length>0||bt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...Xe,...bt].map(({key:ht,icon:bs,label:Rs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Rs,"aria-label":Rs,children:e.jsx(bs,{className:"h-3 w-3"})},`meta-${ce.id}-${Me.id}-${ht}`))})]})]}),e.jsx("button",{type:"button",onClick:ht=>{ht.preventDefault(),ht.stopPropagation(),R(ce.id,Me.id)},className:P("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",V(ce.id,Me.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":V(ce.id,Me.id)?"Unfavorite":"Favorite",title:V(ce.id,Me.id)?"Remove from favorites":"Add to favorites",children:V(ce.id,Me.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(Bn,{className:"h-4 w-4"})})]},Me.id)})})]},ce.id)})]})})},Rr=()=>{if(!U||!Oe)return null;const Z=!o,le=ce=>{Ie(ce),F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(ws,{open:ne==="variant",onClose:F,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:P("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",Z?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>le(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),Z&&e.jsx(At,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),ge.map(ce=>{const ve=o===ce,Le=ce.charAt(0).toUpperCase()+ce.slice(1);return e.jsxs("button",{type:"button",className:P("flex w-full items-center justify-between gap-2 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary",ve?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>le(ce),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Le}),ve&&e.jsx(At,{className:"h-4 w-4 text-primary flex-shrink-0"})]},ce)})]})})},_r=()=>{if(!U)return null;const Z=j.filter(le=>yo(le.mode));return e.jsx(ws,{open:ne==="agent",onClose:F,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[Z.map(le=>{const ce=le.name===a,ve=kr(le.name);return e.jsxs("button",{type:"button",className:P("flex w-full flex-col gap-1 rounded-xl border px-2 py-1.5 text-left","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary agent-list-item",ve.class,ce?"active":"border-border/40"),onClick:()=>Je(le.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:P("h-2 w-2 rounded-full",ve.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ce?{color:`var(${ve.var})`}:void 0,children:es(le.name)})]}),le.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:le.description})]},le.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:Se,onClick:()=>{Se||he(le=>!le)},className:P("flex w-full items-center justify-between gap-2 px-2 py-1.5 text-left bg-transparent","focus:outline-none focus-visible:ring-1 focus-visible:ring-primary rounded-t-xl",Se?"cursor-not-allowed opacity-60":void 0),children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:Tt?Tt.text:"var(--foreground)",mixBlendMode:"normal"},children:He})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:P("flex items-center justify-center p-1",!Tt&&"text-muted-foreground"),style:Tt?{color:Tt.text}:void 0,children:Ge(Nt,at)}),e.jsx(Mt,{className:P("h-4 w-4 text-muted-foreground transition-transform",be?"rotate-180":"")})]})]}),be&&!Se&&e.jsx("div",{className:"border-t border-border/40 bg-transparent px-2 py-1.5",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:Qt.map(le=>{const ce=le.mode===Nt,ve=Ln(le.mode);return e.jsxs("button",{type:"button",disabled:le.disabled,onClick:()=>st(le.mode),className:P("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",le.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",ce?"bg-primary/10":void 0),style:ce&&ve?{backgroundColor:ve.background??void 0}:void 0,children:[Ge(le.mode,at),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:ve?ve.text:"var(--foreground)"},children:le.label})})]},le.mode)})})})]})]})})},El=()=>e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ze?e.jsxs("div",{className:"flex min-w-[240px] flex-col gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:Ze.name||$t()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:yt()})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Capabilities"}),e.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:mt.length>0?mt.map(({key:Z,icon:le,label:ce})=>ps(le,ce,`cap-${Z}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Modalities"}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Input"}),e.jsx("div",{className:"flex items-center gap-1.5",children:ee.length>0?ee.map(({key:Z,icon:le,label:ce})=>ps(le,`${ce} input`,`input-${Z}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Output"}),e.jsx("div",{className:"flex items-center gap-1.5",children:we.length>0?we.map(({key:Z,icon:le,label:ce})=>ps(le,`${ce} output`,`output-${Z}`)):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"})})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Cost ($/1M tokens)"}),Be.map(Z=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:Z.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z.value})]},Z.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Limits"}),Qe.map(Z=>e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:Z.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Z.value})]},Z.label))]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Metadata"}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Knowledge"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Hc(Ze.knowledge)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta font-medium text-muted-foreground/80",children:"Release"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Uc(Ze.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),rn=(Z,le,ce,ve,Le,ze)=>{const Me=g(le,ce),Ue=Ka(Me).map(hs=>({...hs,id:`cap-${hs.key}`})),De=[..._n(Me,"input"),..._n(Me,"output")],Xe=Array.from(new Map(De.map(hs=>[hs.key,hs])).values()).map(hs=>({...hs,id:`mod-${hs.key}`})),bt=[...Ue,...Xe],ht=Os(Me?.limit?.context),bs=t===le&&n===ce,Rs=V(le,ce);return e.jsxs("div",{ref:hs=>{H.current[Le]=hs},className:P("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",ze?"bg-accent":"hover:bg-accent/50"),onClick:()=>$e(le,ce),onMouseEnter:()=>ae(Le),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:Ve(Z)}),Me?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:ht}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[bt.length>0&&e.jsx("div",{className:P("items-center gap-0.5",ze?"flex":"hidden group-hover:flex"),children:bt.map(({id:hs,icon:vf,label:Il})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Il,role:"img",title:Il,children:e.jsx(vf,{className:"h-2.5 w-2.5"})},hs))}),bs&&e.jsx(At,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:hs=>{hs.preventDefault(),hs.stopPropagation(),R(le,ce)},className:P("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Rs?"text-yellow-500":"text-muted-foreground"),"aria-label":Rs?"Unfavorite":"Favorite",title:Rs?"Remove from favorites":"Add to favorites",children:Rs?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(Bn,{className:"h-3.5 w-3.5"})})]})]},`${ve}-${le}-${ce}`)},In=(Z,le,ce)=>ce.trim()?As(Z,ce)||As(le,ce):!0,ja=()=>{const Z=Y.filter(({model:De,providerID:Xe})=>{const ht=r.find(Rs=>Rs.id===Xe)?.name||Xe,bs=Ve(De);return In(bs,ht,te)}),le=_.filter(({model:De,providerID:Xe})=>{const ht=r.find(Rs=>Rs.id===Xe)?.name||Xe,bs=Ve(De);return In(bs,ht,te)}),ce=r.map(De=>{const bt=(Array.isArray(De.models)?De.models:[]).filter(ht=>{const bs=Ve(ht);return In(bs,De.name||De.id||"",te)});return{...De,models:bt}}).filter(De=>De.models.length>0),ve=Z.length>0||le.length>0||ce.length>0,Le=[];Z.forEach(({model:De,providerID:Xe,modelID:bt})=>{Le.push({model:De,providerID:Xe,modelID:bt,section:"fav"})}),le.forEach(({model:De,providerID:Xe,modelID:bt})=>{Le.push({model:De,providerID:Xe,modelID:bt,section:"recent"})}),ce.forEach(De=>{De.models.forEach(Xe=>{Le.push({model:Xe,providerID:De.id,modelID:Xe.id,section:"provider"})})});const ze=Le.length,Me=De=>{if(De.key==="ArrowDown")De.preventDefault(),De.stopPropagation(),ae(Xe=>(Xe+1)%Math.max(1,ze)),setTimeout(()=>{const Xe=(ue+1)%Math.max(1,ze);H.current[Xe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(De.key==="ArrowUp")De.preventDefault(),De.stopPropagation(),ae(Xe=>(Xe-1+Math.max(1,ze))%Math.max(1,ze)),setTimeout(()=>{const Xe=(ue-1+Math.max(1,ze))%Math.max(1,ze);H.current[Xe]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(De.key==="Enter"){De.preventDefault(),De.stopPropagation();const Xe=Le[ue];Xe&&$e(Xe.providerID,Xe.modelID)}else De.key==="Escape"&&(De.preventDefault(),De.stopPropagation(),je(!1))};let Ue=0;return e.jsxs(rt,{delayDuration:1e3,children:[U?e.jsxs("button",{type:"button",onClick:()=>oe("model"),onTouchStart:()=>_t("model"),onTouchEnd:vr,onTouchCancel:vr,className:P("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",We),children:[t?e.jsx(rs,{providerId:t,className:P(jt,"flex-shrink-0")}):e.jsx(mr,{className:P(jt,"text-muted-foreground")}),e.jsx("span",{className:P("model-controls__model-label typography-micro font-medium truncate min-w-0",!q&&"max-w-[220px]"),children:$t()})]}):e.jsxs(Ut,{open:Ae,onOpenChange:je,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:P("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",We),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(rs,{providerId:t,className:P(jt,"flex-shrink-0")}),e.jsx(mr,{className:P(jt,"text-primary/60 hidden")})]}):e.jsx(mr,{className:P(jt,"text-muted-foreground")}),e.jsx("span",{className:P("model-controls__model-label",zt,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:$t()},`${t}-${n}`)]})})}),e.jsxs(Gt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"end",alignOffset:-40,children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{type:"text",placeholder:"Search models",value:te,onChange:De=>fe(De.target.value),onKeyDown:Me,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(dt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!ve&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),Z.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),Z.map(({model:De,providerID:Xe,modelID:bt})=>{const ht=Ue++;return rn(De,Xe,bt,"fav",ht,ue===ht)})]}),le.length>0&&e.jsxs(e.Fragment,{children:[Z.length>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),le.map(({model:De,providerID:Xe,modelID:bt})=>{const ht=Ue++;return rn(De,Xe,bt,"recent",ht,ue===ht)})]}),(Z.length>0||le.length>0)&&ce.length>0&&e.jsx(Ms,{}),ce.map((De,Xe)=>e.jsxs(c.Fragment,{children:[Xe>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(rs,{providerId:De.id,className:"h-4 w-4 flex-shrink-0"}),De.name]}),De.models.map(bt=>{const ht=Ue++;return rn(bt,De.id,bt.id,"provider",ht,ue===ht)})]},De.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})]}),El()]})},no=()=>{if(!G)return e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"No agent selected."})});const Z=!!(G.prompt&&G.prompt.trim().length>0),le=G.model?.providerID&&G.model?.modelID,ce=G.temperature!==void 0||G.topP!==void 0,ve=Ue=>{const De=ea(G.permission)??[],Xe=De.some(ht=>ht.permission===Ue&&ht.pattern!=="*"),bt=bo(De,Ue)??"ask";return Xe?{mode:"ask",label:"Custom"}:bt==="allow"?{mode:"allow",label:"Allow"}:bt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Le=ve("edit"),ze=ve("bash"),Me=ve("webfetch");return e.jsx(tt,{align:"start",sideOffset:8,className:"max-w-[280px]",children:e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-2.5",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-micro font-semibold text-foreground",children:es(G.name)}),G.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:G.description})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Mode"}),e.jsx("span",{className:"typography-meta text-foreground",children:G.mode==="primary"?"Primary":G.mode==="subagent"?"Subagent":G.mode==="all"?"All":"—"})]}),(le||ce)&&e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Model"}),le?e.jsxs("span",{className:"typography-meta text-foreground",children:[G.model.providerID," / ",G.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ce&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[G.temperature!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Temperature"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:G.temperature})]}),G.topP!==void 0&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Top P"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:G.topP})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide text-muted-foreground/90",children:"Permissions"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Edit"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(Le.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Le.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"Bash"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(ze.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:ze.label})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80 w-16",children:"WebFetch"}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ge(Me.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Me.label})]})]})]}),Z&&e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Custom Prompt"}),e.jsx(Mo,{className:"h-4 w-4 text-foreground"})]})]})})},Sa=()=>{if(!Oe)return null;const Z=o??"Default",le=!o,ce=le?"text-muted-foreground":"text-[color:var(--status-info)]";return U?e.jsxs("button",{type:"button",onClick:()=>oe("variant"),className:P("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",We,"cursor-pointer hover:opacity-70"),children:[e.jsx(ar,{className:P(jt,"flex-shrink-0",ce)}),e.jsx("span",{className:P("model-controls__variant-label",zt,"font-medium truncate min-w-0",ce),children:Z})]}):e.jsxs(rt,{delayDuration:800,children:[e.jsxs(Ut,{children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:P("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",We),children:[e.jsx(ar,{className:P(jt,"flex-shrink-0",ce)}),e.jsx("span",{className:P("model-controls__variant-label",zt,"font-medium min-w-0 truncate",O?"max-w-[180px]":void 0,ce),children:Z})]})})}),e.jsxs(Gt,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Wr,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(vt,{className:"typography-meta",onSelect:()=>Ie(void 0),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:"Default"}),le&&e.jsx(At,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),ge.length>0&&e.jsx(Ms,{}),ge.map(ve=>{const Le=o===ve,ze=ve.charAt(0).toUpperCase()+ve.slice(1);return e.jsx(vt,{className:"typography-meta",onSelect:()=>Ie(ve),children:e.jsxs("div",{className:"flex items-center justify-between gap-2 w-full min-w-0",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate min-w-0",children:ze}),Le&&e.jsx(At,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},ve)})]})]}),e.jsx(tt,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",Z]})})]})},ka=()=>U?e.jsxs("button",{type:"button",onClick:()=>oe("agent"),onTouchStart:()=>_t("agent"),onTouchEnd:vr,onTouchCancel:vr,className:P("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",We,"cursor-pointer hover:opacity-70",U&&"ml-1"),children:[e.jsx(qr,{className:P(jt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${kr(a).var})`}:void 0}),e.jsx("span",{className:P("model-controls__agent-label",zt,"font-medium truncate min-w-0"),style:a?{color:`var(${kr(a).var})`}:void 0,children:ts()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(rt,{delayDuration:1e3,children:[e.jsxs(Ut,{children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:P("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",We),children:[e.jsx(qr,{className:P(jt,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${kr(a).var})`}:void 0}),e.jsx("span",{className:P("model-controls__agent-label",zt,"font-medium min-w-0 truncate",O?"max-w-[220px]":void 0),style:a?{color:`var(${kr(a).var})`}:void 0,children:ts()})]})})}),e.jsxs(Gt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[j.filter(Z=>yo(Z.mode)).map(Z=>e.jsx(vt,{className:"typography-meta",onSelect:()=>Je(Z.name),children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:P("h-1 w-1 rounded-full agent-dot",kr(Z.name).class)}),e.jsx("span",{className:"font-medium",children:es(Z.name)})]}),Z.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:Z.description})]})},Z.name)),e.jsx(Ms,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:Se,onClick:()=>{Se||K(Z=>!Z)},className:P("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",Se?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Te,"aria-controls":X,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:Tt?Tt.text:"var(--foreground)"},children:He})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:P("flex items-center justify-center p-1",!Tt&&"text-muted-foreground"),style:Tt?{color:Tt.text}:void 0,children:Ge(Nt)}),e.jsx(Mt,{className:P("h-3.5 w-3.5 transition-transform text-muted-foreground",Te?"rotate-180":"")})]})]}),Te&&!Se&&e.jsx("div",{id:X,className:"flex flex-col gap-1 rounded-xl border border-border/40 px-2 py-2 bg-transparent",role:"group","aria-label":"Edit permission options",children:Qt.map(Z=>{const le=Z.mode===Nt,ce=Ln(Z.mode);return e.jsxs("button",{type:"button",disabled:Z.disabled,onClick:()=>st(Z.mode),className:P("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",Z.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",le?"bg-primary/10":void 0),style:le&&ce?{backgroundColor:ce.background??void 0}:void 0,children:[Ge(Z.mode,at),e.jsx("span",{className:"typography-meta font-medium",style:{color:ce?ce.text:"var(--foreground)"},children:Z.label})]},Z.mode)})})]})]})]}),no()]})}),ie=P("@container/model-controls flex items-center min-w-0",q&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:ie,children:e.jsxs("div",{className:P("flex items-center min-w-0 flex-1 justify-end",Jt,q&&"overflow-hidden"),children:[Sa(),ja(),ka()]})}),va(),Rr(),_r(),En(),wa()]})},Lb=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,Gc=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(s))!==null;){const l=i.index,d=l+i[0].length,u=l>0?s[l-1]:null;if(!Lb(u))continue;const m={name:o.name,source:{value:i[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},Em=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),Ei=Bt()(Xt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=me.getState().getDirectoryForSession(t),a=(n?await ke.withDirectory(n,()=>ke.getSessionTodos(t)):await ke.getSessionTodos(t)).map(Em);s(i=>{const l=new Map(i.sessionTodos);return l.set(t,a),{sessionTodos:l,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),s({isLoading:!1})}}},updateTodos:(t,n)=>{s(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>r().sessionTodos.get(t)||[],clearTodos:t=>{s(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),Bb=(s,r)=>{const t=r.map(Em);Ei.getState().updateTodos(s,t)},Kc=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(un.span,{...t,className:P("bg-[linear-gradient(110deg,#bfbfbf,35%,#000,50%,#bfbfbf,75%,#bfbfbf)] dark:bg-[linear-gradient(110deg,#404040,35%,#fff,50%,#404040,75%,#404040)]","bg-[length:200%_100%] bg-clip-text text-transparent",r),initial:{backgroundPosition:"200% 0"},animate:{backgroundPosition:"-200% 0"},transition:{repeat:Number.POSITIVE_INFINITY,duration:2,ease:"linear"},children:s})},{variant:"generate-effect",component:({children:s,className:r,...t})=>typeof s!="string"?null:e.jsx("div",{className:"inline-block whitespace-pre",children:s.split("").map((n,o)=>Ce.createElement(un.span,{...t,key:n+String(o),className:P("inline-block whitespace-pre text-primary-foreground",r),initial:{opacity:0,filter:"blur(4px)",rotateX:90,y:5},whileInView:{opacity:1,filter:"blur(0px)",rotateX:0,y:0},transition:{ease:"easeOut",duration:.3,delay:o*.015},viewport:{once:!0}},n))})},{variant:"glitch",component:({children:s,className:r,...t})=>e.jsxs("div",{className:"group relative overflow-hidden font-medium",children:[e.jsx("span",{...t,className:P("invisible",r),children:s}),e.jsx("span",{...t,className:P("absolute top-0 left-0 text-primary-muted transition-transform duration-500 ease-in-out","group-hover:-translate-y-full hover:duration-300",r),children:s}),e.jsx("span",{...t,className:P("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:s})]})},{variant:"hover-enter",component:({children:s,className:r,...t})=>{if(typeof s!="string")return null;const n=.25,o=.025,a=s.split("").map(i=>i===" "?" ":i);return e.jsxs(un.span,{...t,className:P("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,l)=>e.jsx(un.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))}),e.jsx("div",{className:P("absolute inset-0"),children:a.map((i,l)=>e.jsx(un.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:P("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:P("relative after:absolute after:bottom-0 after:left-0 after:h-px after:w-full after:origin-bottom-right","after:scale-x-0 after:bg-primary-muted after:transition-transform after:duration-300 after:ease-in-out hover:after:origin-bottom-left hover:after:scale-x-100"),children:e.jsx("span",{...t,className:P("text-primary-muted",r),children:s})})}];function qa({variant:s="shine",className:r,...t}){const a=Kc.find(i=>i.variant===s)?.component||Kc[0].component;return e.jsx(Jd,{children:e.jsx(a,{...t,className:r})})}const qc=1500,zb=2e3;function Wb({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[l,d]=Ce.useState("idle"),[u,m]=Ce.useState(null),[f,p]=Ce.useState(!1),g=Ce.useRef(0),w=Ce.useRef(null),h=Ce.useRef(null),j=Ce.useRef(null),b=Ce.useRef(null),x=Ce.useRef(!1),v=Ce.useRef(!1),N=Ce.useRef(!1),y=Ce.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),j.current&&(clearTimeout(j.current),j.current=null)},[]),S=Ce.useCallback((R,V)=>{y(),w.current=null,m(R),p(V),d("showing"),g.current=Date.now(),x.current=!0},[y]),D=Ce.useCallback(()=>{if(h.current)return;const R=Date.now()-g.current,V=Math.max(0,qc-R);h.current=setTimeout(()=>{h.current=null;const T=w.current;T&&S(T.text,T.permission)},V)},[S]),M=Ce.useCallback(R=>{if(y(),w.current=null,!x.current){d("idle"),m(null),i?.(!1);return}if(R==="done"&&o&&b.current===o){d("idle"),m(null),x.current=!1,i?.(!1);return}R==="done"&&o&&(b.current=o),d(R),m(null),i?.(!0),j.current=setTimeout(()=>{j.current=null,d("idle"),x.current=!1,i?.(!1)},zb)},[y,o,i]);if(Ce.useEffect(()=>{if(n&&!N.current){N.current=!0,M("aborted");return}if(N.current=!!n,a&&!v.current){v.current=!0,M("done");return}if(!a&&v.current&&(v.current=!1),!(l==="done"||l==="aborted")&&s){const V=Date.now()-g.current;if(l==="idle"||!u)S(s,!!t);else if(s!==u||!!t!==f){if(r)return;V>=qc?S(s,!!t):(w.current={text:s,permission:!!t},D())}}},[s,t,n,a,l,u,f,S,M,D,r]),Ce.useEffect(()=>()=>y(),[y]),Ce.useEffect(()=>{const R=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(y(),d("idle"),m(null),x.current=!1)};return document.addEventListener("visibilitychange",R),()=>document.removeEventListener("visibilitychange",R)},[l,y]),l==="idle"&&!u)return null;let C,k=!0;l==="done"?(C="Done",k=!1):l==="aborted"?(C="Aborted",k=!1):u?C=u.charAt(0).toUpperCase()+u.slice(1):C="Working";const A=k?`${C}...`:C,E=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${E?"opacity-100":"opacity-0"}`,role:"status","aria-live":f?"assertive":"polite","aria-label":C,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:l==="done"?e.jsx(qa,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(qa,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(qa,{variant:"shine",className:"typography-ui-header",children:A})})})}const Yc={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Hb=({todo:s})=>{const r=Yc[s.status]||Yc.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:P("flex-1 typography-ui-label",r.textClassName),children:s.content})})},Xc=[],Ub=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=c.useState(!1),g=me(V=>V.currentSessionId),w=Ei(V=>g?V.sessionTodos.get(g)??Xc:Xc),h=Ei(V=>V.loadTodos),{isMobile:j}=_e(),b=j||Wt();c.useEffect(()=>{g&&h(g)},[g,h]);const x=c.useMemo(()=>{const V={in_progress:0,pending:1,completed:2,cancelled:3};return[...w].filter(T=>T.status!=="cancelled").sort((T,B)=>V[T.status]-V[B.status])},[w]),v=c.useMemo(()=>x.find(V=>V.status==="in_progress")||x.find(V=>V.status==="pending")||null,[x]),N=c.useMemo(()=>{const V=w.filter(B=>B.status!=="cancelled").length;return{completed:w.filter(B=>B.status==="completed").length,total:V}},[w]),y=x.length>0,S=!m&&(o||!a),[D,M]=c.useState(!1),C=s||l||o||D||y||m,k=c.useRef(null);if(c.useEffect(()=>{if(!f)return;const V=T=>{k.current&&!k.current.contains(T.target)&&p(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[f]),!C)return null;const A=()=>p(V=>!V),E=d&&u?e.jsx("button",{type:"button",onClick:u,className:"flex items-center justify-center h-[1.2rem] w-[1.2rem] text-[var(--status-error)] transition-opacity hover:opacity-80 focus-visible:outline-none flex-shrink-0","aria-label":"Stop generating",children:e.jsx(wn,{size:18,"aria-hidden":"true"})}):null,R=y?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!b&&v?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:v.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(oa,{className:"h-3.5 w-3.5"}):e.jsx(Mt,{className:"h-3.5 w-3.5"})]}):null;return e.jsx("div",{className:"chat-column mb-1",style:{containerType:"inline-size"},children:e.jsxs("div",{className:"flex items-center justify-between pr-[2ch] py-0.5 gap-2 h-[1.2rem]",children:[e.jsx("div",{className:"flex-1 flex items-center overflow-hidden min-w-0",children:m?e.jsx("div",{className:"flex h-full items-center text-[var(--status-error)] pl-[2ch]",children:e.jsxs("span",{className:"flex items-center gap-1.5 typography-ui-label",children:[e.jsx(wn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):S?e.jsx(Wb,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:l,onResultVisibilityChange:M},g??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:k,children:[E,R,f&&y&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:P("absolute right-0 bottom-full mb-1 z-50","w-max min-w-[200px]","rounded-xl border border-border bg-background shadow-md","animate-in fade-in-0 zoom-in-95 slide-in-from-bottom-2","duration-150"),children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"Tasks"}),e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[N.completed,"/",N.total]})]}),e.jsx("div",{className:"px-3 py-2 max-h-[200px] overflow-y-auto divide-y divide-border",children:x.map(V=>e.jsx(Hb,{todo:V},V.id))})]})]})]})})},Ii=s=>!s||typeof s!="object"?!1:!!s.synthetic,Qc=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Ii(r)),Vb=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Ii(t))?s.filter(t=>!Ii(t)):s,Gb={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Kb(s){const r=me(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return c.useMemo(()=>{if(r==="idle")return Gb;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function wl(){const s=me(r=>r.currentSessionId);return Kb(s)}const qb={activity:"idle",hasWorkingContext:!1,hasActiveTools:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,lifecyclePhase:null,statusText:null,isGenericStatus:!0,isWaitingForPermission:!1,canAbort:!1,compactionDeadline:null,activePartType:void 0,activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:!1},Jc=s=>s.role==="assistant",Yb=s=>s.type==="reasoning",Im=s=>s.type==="text",Zc=s=>{if(Im(s))return s.text;const r=s;if(typeof r.text=="string")return r.text;if(typeof r.content=="string")return r.content;if(typeof r.value=="string")return r.value},ed=s=>(Im(s)||Yb(s),s.time),Xb=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function Pm(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=me(Ui(g=>({currentSessionId:g.currentSessionId,messages:g.messages,permissions:g.permissions,sessionAbortFlags:g.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=wl(),l=c.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=c.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=l.filter(C=>Jc(C.info)&&!Qc(C.parts));if(g.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const w=[...g].sort((C,k)=>{const A=typeof C.info.time?.created=="number"?C.info.time.created:null,E=typeof k.info.time?.created=="number"?k.info.time.created:null;return A!==null&&E!==null&&A!==E?A-E:C.info.id.localeCompare(k.info.id)}),h=w[w.length-1];let j,b;const x=new Set(["edit","write"]);for(let C=(h.parts??[]).length-1;C>=0;C-=1){const k=h.parts?.[C];if(k)switch(k.type){case"reasoning":{const A=k.time??ed(k);(!A||typeof A.end>"u")&&!j&&(j="reasoning");break}case"tool":{const A=k.state?.status;if((A==="running"||A==="pending")&&!j){const E=Xb(k);x.has(E)?j="editing":(j="tool",b=E)}break}case"text":{const A=Zc(k)??"";if(typeof A=="string"&&A.trim().length>0){const E=ed(k);(!E||typeof E.end>"u")&&!j&&(j="text")}break}}}const v={read:"reading file",write:"writing file",edit:"editing file",multiedit:"editing files",bash:"running command",grep:"searching content",glob:"finding files",list:"listing directory",task:"delegating task",webfetch:"fetching URL",websearch:"searching web",codesearch:"web code search",todowrite:"updating todos",todoread:"reading todos",skill:"learning skill"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],y=C=>v[C]??`using ${C}`,S=()=>N[Math.floor(Math.random()*N.length)],D=j===void 0,M=j==="editing"?"editing file":j==="tool"&&b?y(b):j==="reasoning"?"thinking":j==="text"?"composing":S();return{activePartType:j,activeToolName:b,statusText:M,isGenericStatus:D}},[l]),u=c.useMemo(()=>{const g=s,w=g?n?.get(g)??null:null,h=!!(w&&!w.acknowledged);return{wasAborted:h,abortActive:h}},[s,n]),m=c.useMemo(()=>{if(u.wasAborted)return{...qb,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const g=a,w=o==="busy",h=i;let j="idle";return g&&(d.activePartType==="tool"||d.activePartType==="editing"?j="tooling":j=h?"cooldown":"streaming"),{activity:j,hasWorkingContext:g,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:g,isStreaming:w,isCooldown:h,lifecyclePhase:w?"streaming":h?"cooldown":null,statusText:g?d.statusText:null,isGenericStatus:g?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:g,compactionDeadline:null,activePartType:g?d.activePartType:void 0,activeToolName:g?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:h}},[o,a,i,d,u]),f=c.useMemo(()=>{const g=a&&d.activePartType==="text";if(!g||l.length===0)return{isActive:g,characterCount:0};const w=l.filter(b=>Jc(b.info)&&!Qc(b.parts));if(w.length===0)return{isActive:g,characterCount:0};const h=w[w.length-1];let j=0;return(h.parts??[]).forEach(b=>{if(b.type!=="text")return;const x=Zc(b)??"";typeof x=="string"&&x.trim().length>0&&(j+=x.length)}),{isActive:g,characterCount:j}},[l,a,d.activePartType]),p=c.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const g=s;return(g?t?.get(g)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[s,t,m]);return{forming:f,working:p}}const Qb=8,td=[],Jb=s=>s==="primary"||s==="all"||s===void 0||s===null,Tm=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},sd=(s,r)=>{const t=Tm(s);if(!(!t||t.length===0)){for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission===r&&o.pattern==="*")return o.action}for(let n=t.length-1;n>=0;n-=1){const o=t[n];if(o.permission==="*"&&o.pattern==="*")return o.action}}},Zb=(s,r)=>{const t=Tm(s);if(!t||t.length===0)return;const n={};for(const o of t)o.permission===r&&(n[o.pattern]=o.action);return Object.keys(n).length>0?n:void 0},vo=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=c.useState(""),[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(""),[m,f]=c.useState(!1),[p,g]=c.useState(""),[w,h]=c.useState(!1),[j,b]=c.useState(""),[x,v]=c.useState(!1),[N,y]=c.useState(""),[S,D]=c.useState(null),M=c.useRef(null),C=c.useRef(null),k=c.useRef(null),A=c.useRef(null),E=c.useRef(null),R=c.useRef(null),V=me(ie=>ie.sendMessage),T=me(ie=>ie.currentSessionId),B=me(ie=>ie.newSessionDraft?.open),re=me(ie=>ie.abortCurrentOperation),Y=me(ie=>ie.acknowledgeSessionAbort),_=me(ie=>ie.abortPromptSessionId),q=me(ie=>ie.abortPromptExpiresAt),O=me(ie=>ie.clearAbortPrompt),z=me(ie=>ie.sessionAbortFlags),U=me(ie=>ie.attachedFiles),ne=me(ie=>ie.addAttachedFile),oe=me(ie=>ie.addServerFile),Q=me(ie=>ie.clearAttachedFiles),de=me(ie=>ie.saveSessionAgentSelection),I=me(ie=>ie.consumePendingInputText),W=me(ie=>ie.pendingInputText),{currentProviderId:F,currentModelId:$,currentVariant:L,currentAgentName:J,setAgent:pe,getVisibleAgents:be}=et(),he=be(),{isMobile:Ae,inputBarOffset:je,isKeyboardOpen:Te,setTimelineDialogOpen:K}=_e(),{working:X}=Pm(),[te,fe]=c.useState(!1),ue=c.useRef(null),ae=c.useRef(!1),H=c.useRef(!1),xe=Zs(ie=>ie.queueModeEnabled),G=Zs(c.useCallback(ie=>T?ie.queuedMessages[T]??td:td,[T])),ye=Zs(ie=>ie.addToQueue),Fe=Zs(ie=>ie.clearQueue),{phase:qe}=wl(),Re=c.useRef(qe),Ee=c.useRef(!1),Ye=c.useCallback(ie=>{if(!Ae||ie.pointerType!=="touch")return;const Z=M.current;if(!Z||document.activeElement===Z)return;ie.preventDefault(),ie.stopPropagation();const le=document.scrollingElement;le&&le.scrollTop!==0&&(le.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{Z.focus({preventScroll:!0})}catch{Z.focus()}const ce=Z.value.length;try{Z.setSelectionRange(ce,ce)}catch{}},[Ae]);c.useEffect(()=>{if(W!==null){const ie=I();ie&&(n(ie),setTimeout(()=>{M.current?.focus()},0))}},[W,I]);const ot=c.useMemo(()=>{if(J)return he.find(ie=>ie.name===J)},[he,J]),ut=c.useMemo(()=>ot?sd(ot.permission,"edit")??"ask":"deny",[ot]),kt=me(c.useCallback(ie=>!T||!J?void 0:ie.sessionAgentEditModes.get(T)?.get(J),[T,J])),Rt=c.useMemo(()=>{if(ot)return sd(ot.permission,"webfetch")},[ot]),Et=c.useMemo(()=>{if(!ot)return;const ie=Zb(ot.permission,"bash");return ie||void 0},[ot]),Nt=c.useMemo(()=>Am({agentDefaultEditMode:ut,webfetchPermission:Rt,bashPermission:Et}),[ut,Rt,Et]),Qt=!!(T&&J),Tt=c.useMemo(()=>Qt&&kt&&Nt.modeAvailability[kt]?kt:Nt.cascadeDefaultMode,[Nt,Qt,kt]),Se=c.useMemo(()=>Ln(Tt),[Tt]),Pe=c.useCallback(ie=>Wt()?`color-mix(in srgb, ${ie} 55%, transparent)`:ie,[]),We=c.useMemo(()=>{const ie=Wt()?1:2;if(!Se)return{borderWidth:ie};const Z=Se.border??Se.text;return{borderColor:Pe(Z),borderWidth:ie}},[Se,Pe]),at=t.trim()||U.length>0,jt=G.length>0,zt=at||jt,Jt=X.isWorking,He=c.useMemo(()=>T?_===T&&!!q:!1,[_,q,T]),Ge=c.useCallback(()=>{if(!at||!T)return;const ie=t.replace(/^\n+|\n+$/g,""),Z=U.map(le=>({...le}));ye(T,{content:ie,attachments:Z.length>0?Z:void 0}),n(""),Z.length>0&&Q(),Ae||M.current?.focus()},[at,T,t,U,ye,Q,Ae]),st=async ie=>{if(ie?.preventDefault(),!zt||!T&&!B)return;if(r?.({instant:!0,force:!0}),!F||!$){console.warn("Cannot send message: provider or model not selected");return}let Z="",le=[],ce;const ve=[];for(let Me=0;Me<G.length;Me++){const Ue=G[Me],{sanitizedText:De,mention:Xe}=Gc(Ue.content,he);!ce&&Xe?.name&&(ce=Xe.name),Me===0?(Z=De,le=Ue.attachments??[]):ve.push({text:De,attachments:Ue.attachments})}if(at){const Me=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Ue,mention:De}=Gc(Me,he),Xe=U.map(bt=>({...bt}));!ce&&De?.name&&(ce=De.name),G.length===0?(Z=Ue,le=Xe):ve.push({text:Ue,attachments:Xe.length>0?Xe:void 0})}if(!Z&&ve.length===0)return;T&&jt&&Fe(T),n(""),U.length>0&&Q(),Ae&&M.current?.blur();const Le=Z.trimStart();if(Le.startsWith("/")){const Me=Le.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Me==="undo"&&T){await me.getState().handleSlashUndo(T),r?.({instant:!0,force:!0});return}else if(Me==="redo"&&T){await me.getState().handleSlashRedo(T),r?.({instant:!0,force:!0});return}else if(Me==="timeline"&&T){K(!0),n("");return}else if(Me==="compact"&&T){try{const{opencodeClient:Ue}=await is(async()=>{const{opencodeClient:bt}=await Promise.resolve().then(()=>rg);return{opencodeClient:bt}},void 0),De=Ue.getDirectory();if((await Ue.getApiClient().session.summarize({sessionID:T,directory:De||void 0,providerID:F,modelID:$})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Ue){console.error("Failed to compact session:",Ue),se.error("Failed to compact session")}n("");return}}const ze=[...le,...ve.flatMap(Me=>Me.attachments??[])];await V(Z,F,$,J,le,ce,ve.length>0?ve:void 0,L).catch(Me=>{const Ue=Me instanceof Error?Me.message:typeof Me=="string"?Me:String(Me??""),De=Ue.toLowerCase();console.error("Message send failed:",Ue||Me),!(De.includes("timeout")||De.includes("timed out")||De.includes("may still be processing")||De.includes("being processed")||De.includes("failed to fetch")||De.includes("networkerror")||De.includes("network error")||De.includes("gateway timeout")||De==="failed to send message")&&(ze.length>0&&er.setState({attachedFiles:ze}),se.error(Ue||"Message failed to send. Attachments restored."))}),Ae||M.current?.focus()},Ke=c.useRef(st);Ke.current=st,c.useEffect(()=>{const ie=Re.current==="busy"||Re.current==="cooldown",Z=qe==="idle",le=T&&z.has(T)&&(()=>{const ce=z.get(T);return ce?Date.now()-ce.timestamp<2e3:!1})();ie&&Z&&G.length>0&&!Ee.current&&!le&&(Ee.current=!0,setTimeout(()=>{T&&F&&$&&Ke.current(),Ee.current=!1},100)),Re.current=qe},[qe,G.length,T,F,$,z]);const lt=ie=>{if(!xl(ie)){if(m&&A.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),A.current.handleKeyDown(ie.key);return}if(w&&E.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),E.current.handleKeyDown(ie.key);return}if(x&&R.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),R.current.handleKeyDown(ie.key);return}if(i&&k.current&&(ie.key==="Enter"||ie.key==="ArrowUp"||ie.key==="ArrowDown"||ie.key==="Escape"||ie.key==="Tab")){ie.preventDefault(),k.current.handleKeyDown(ie.key);return}if(ie.key==="Tab"&&ie.shiftKey&&!m&&!w&&!i){ie.preventDefault(),ee();return}if(ie.key==="Enter"&&!ie.shiftKey&&!Ae){ie.preventDefault();const Z=ie.ctrlKey||ie.metaKey,le=at&&T&&qe!=="idle";xe?Z||!le?st():Ge():Z&&le?Ge():st()}}},Ze=c.useCallback(()=>{ue.current&&(clearTimeout(ue.current),ue.current=null),fe(!0),ue.current=setTimeout(()=>{fe(!1),ue.current=null},1800)},[]),mt=c.useCallback(()=>{O(),Ze(),re()},[re,O,Ze]),ee=()=>{const ie=he.filter(ve=>Jb(ve.mode));if(ie.length<=1)return;const le=(ie.findIndex(ve=>ve.name===J)+1)%ie.length,ce=ie[le];pe(ce.name),T&&de(T,ce.name)},we=c.useCallback(()=>{const ie=M.current;if(!ie)return;ie.style.height="auto";const Z=ie.ownerDocument?.defaultView,le=Z?Z.getComputedStyle(ie):null,ce=le?parseFloat(le.lineHeight):NaN,ve=le?parseFloat(le.paddingTop):NaN,Le=le?parseFloat(le.paddingBottom):NaN,ze=22,Ue=Number.isNaN(ve)||Number.isNaN(Le)?16:ve+Le,Xe=(Number.isNaN(ce)?ze:ce)*Qb+Ue,bt=ie.scrollHeight||ie.offsetHeight,ht=Math.min(bt,Xe);ie.style.height=`${ht}px`,ie.style.maxHeight=`${Xe}px`,D(bs=>bs&&bs.height===ht&&bs.maxHeight===Xe?bs:{height:ht,maxHeight:Xe})},[]);c.useLayoutEffect(()=>{we()},[we,t,Ae]);const ge=c.useCallback((ie,Z)=>{if(ie.startsWith("/")){const ze=ie.indexOf(" "),Me=ie.indexOf(`
69
+ `),Ue=Math.min(ze===-1?ie.length:ze,Me===-1?ie.length:Me);if(Z<=Ue&&ze===-1){const De=ie.substring(1,Ue);g(De),f(!0),l(!1),h(!1),v(!1);return}}f(!1);const le=ie.substring(0,Z),ce=le.lastIndexOf("#");if(ce!==-1){const ze=ce>0?le[ce-1]:null,Me=le.substring(ce+1),Ue=Me.includes(" ")||Me.includes(`
70
+ `);if((!ze||/\s/.test(ze))&&!Ue){b(Me),h(!0),l(!1);return}}h(!1),b("");const ve=le.lastIndexOf("/");if(ve!==-1){const ze=ve>0?le[ve-1]:null,Me=le.substring(ve+1),Ue=Me.includes(" ")||Me.includes(`
71
+ `);if((!ze||/\s/.test(ze))&&!Ue){y(Me),v(!0),l(!1),h(!1);return}}v(!1),y("");const Le=le.lastIndexOf("@");if(Le!==-1){const ze=le.substring(Le+1);!ze.includes(" ")&&!ze.includes(`
72
+ `)?(u(ze),l(!0)):l(!1)}else l(!1)},[b,g,u,h,f,l,v,y]),Oe=c.useCallback(ie=>{if(!ie)return;const Z=M.current;if(!Z){const ze=t+ie;n(ze),ge(ze,ze.length),requestAnimationFrame(()=>we());return}const le=Z.selectionStart??t.length,ce=Z.selectionEnd??t.length,ve=`${t.substring(0,le)}${ie}${t.substring(ce)}`;n(ve);const Le=le+ie.length;requestAnimationFrame(()=>{const ze=M.current;ze&&(ze.selectionStart=Le,ze.selectionEnd=Le),we()}),ge(ve,Le)},[we,t,ge]),Be=ie=>{const Z=ie.target.value,le=ie.target.selectionStart??Z.length;n(Z),we(),ge(Z,le)},Qe=c.useCallback(async ie=>{const Z=new Map;Array.from(ie.clipboardData.files||[]).forEach(Le=>{Le.type.startsWith("image/")&&Z.set(`${Le.name}-${Le.size}`,Le)}),Array.from(ie.clipboardData.items||[]).forEach(Le=>{if(Le.kind==="file"&&Le.type.startsWith("image/")){const ze=Le.getAsFile();ze&&Z.set(`${ze.name}-${ze.size}`,ze)}});const le=Array.from(Z.values());if(le.length===0||!T&&!B)return;ie.preventDefault();const ce=ie.clipboardData.getData("text");ce&&Oe(ce);let ve=0;for(const Le of le){const ze=me.getState().attachedFiles.length;try{await ne(Le),me.getState().attachedFiles.length>ze&&(ve+=1)}catch(Me){console.error("Clipboard image attach failed",Me),se.error(Me instanceof Error?Me.message:"Failed to attach image from clipboard")}}ve>0&&se.success(`Attached ${ve} image${ve>1?"s":""} from clipboard`)},[ne,T,B,Oe]),It=ie=>{const Z=M.current?.selectionStart||0,ce=t.substring(0,Z).lastIndexOf("@");if(ce!==-1){const ve=t.substring(0,ce)+ie.name+t.substring(Z);n(ve)}l(!1),u(""),M.current?.focus()},wt=ie=>{const le=M.current?.selectionStart??t.length,ve=t.substring(0,le).lastIndexOf("#");if(ve!==-1){const Le=t.substring(0,ve)+`#${ie} `+t.substring(le);n(Le);const ze=ve+ie.length+2;requestAnimationFrame(()=>{M.current&&(M.current.selectionStart=ze,M.current.selectionEnd=ze),we(),ge(Le,ze)})}h(!1),b(""),M.current?.focus()},Dt=ie=>{const le=M.current?.selectionStart??t.length,ve=t.substring(0,le).lastIndexOf("/");if(ve!==-1){const Le=t.substring(0,ve)+`${ie} `+t.substring(le);n(Le);const ze=ve+ie.length+1;requestAnimationFrame(()=>{M.current&&(M.current.selectionStart=ze,M.current.selectionEnd=ze),we(),ge(Le,ze)})}v(!1),y(""),M.current?.focus()},Ct=ie=>{n(`/${ie.name} `);const Z=M.current;Z&&(Z._commandMetadata=ie),f(!1),g(""),setTimeout(()=>{M.current&&(M.current.focus(),M.current.setSelectionRange(M.current.value.length,M.current.value.length))},0)};c.useEffect(()=>{T&&M.current&&!Ae&&M.current.focus()},[T,Ae]),c.useEffect(()=>{_&&_!==T&&O()},[_,T,O]);const Ie=ie=>{ie.preventDefault(),ie.stopPropagation(),(T||B)&&!o&&a(!0)},Je=ie=>{ie.preventDefault(),ie.stopPropagation(),ie.currentTarget===ie.target&&a(!1)},$e=async ie=>{if(ie.preventDefault(),ie.stopPropagation(),a(!1),!T&&!B)return;const Z=Array.from(ie.dataTransfer.files);let le=0;for(const ce of Z){const ve=me.getState().attachedFiles.length;try{await ne(ce),me.getState().attachedFiles.length>ve&&(le+=1)}catch(Le){console.error("File attach failed",Le),se.error(Le instanceof Error?Le.message:"Failed to attach file")}}le>0&&se.success(`Attached ${le} file${le>1?"s":""}`)},Ve=c.useCallback(async ie=>{let Z=0;for(const le of ie){const ce=me.getState().attachedFiles.length;try{await oe(le.path,le.name),me.getState().attachedFiles.length>ce&&(Z+=1)}catch(ve){console.error("Server file attach failed",ve),se.error(ve instanceof Error?ve.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[oe]),yt=c.useRef(null),[$t,ts]=c.useState(!1),es=c.useCallback(async ie=>{let Z=0;const le=Array.isArray(ie)?ie:Array.from(ie);for(const ce of le){const ve=me.getState().attachedFiles.length;try{await ne(ce),me.getState().attachedFiles.length>ve&&(Z+=1)}catch(Le){console.error("File attach failed",Le),se.error(Le instanceof Error?Le.message:"Failed to attach file")}}Z>0&&se.success(`Attached ${Z} file${Z>1?"s":""}`)},[ne]),ps=c.useCallback(async()=>{try{const Z=await(await fetch("/api/vscode/pick-files")).json(),le=Array.isArray(Z?.files)?Z.files:[],ce=Array.isArray(Z?.skipped)?Z.skipped:[];if(ce.length>0){const Le=ce.map(ze=>`${ze?.name||"file"}: ${ze?.reason||"skipped"}`).join(`
73
+ `);se.error(`Some files were skipped:
74
+ ${Le}`)}const ve=le.map(Le=>{if(!Le?.dataUrl)return null;try{const[ze,Me]=Le.dataUrl.split(","),Ue=Le.mimeType||ze?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Me)return null;const De=atob(Me),Xe=new Uint8Array(De.length);for(let ht=0;ht<De.length;ht++)Xe[ht]=De.charCodeAt(ht);const bt=new Blob([Xe],{type:Ue});return new File([bt],Le.name||"file",{type:Ue})}catch(ze){return console.error("Failed to decode VS Code picked file",ze),null}}).filter(Boolean);ve.length>0&&await es(ve)}catch(ie){console.error("VS Code file pick failed",ie),se.error(ie instanceof Error?ie.message:"Failed to pick files in VS Code")}},[es]),lr=c.useCallback(()=>{if(Wt()){ps();return}yt.current?.click()},[ps]),_t=c.useCallback(async ie=>{const Z=ie.target.files;Z&&(await es(Z),ie.target.value="")},[es]),vr="gap-x-1.5 gap-y-0",En=Wt(),wa=Ae?"px-1.5 py-1.5":En?"px-1.5 py-1":"px-2.5 py-1.5",va=Ae?"h-9 w-9":En?"h-[22px] w-[22px]":"h-7 w-7",Rr=Ae?"h-5 w-5":En?"h-4 w-4":"h-[18px] w-[18px]",_r=P(va,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),rn=!Ae&&He&&Jt?e.jsx("button",{type:"button",onClick:mt,className:P(_r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(wn,{className:P(Rr)})}):e.jsx("button",{type:Ae?"button":"submit",disabled:!zt||!T&&!B,onPointerDownCapture:ie=>{!Ae||ie.pointerType!=="touch"||!zt||!T&&!B||(H.current=!0,ie.preventDefault(),ie.stopPropagation(),st())},onClick:ie=>{if(Ae){if(H.current){H.current=!1;return}ie.preventDefault(),st()}},className:P(_r,zt&&(T||B)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(nu,{className:P(Rr)})}),In=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:yt,type:"file",multiple:!0,className:"hidden",onChange:_t,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Ab,{onFilesSelected:Ve,multiSelect:!0,presentation:Ae?"modal":"dropdown",open:$t,onOpenChange:ts,children:Ae?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:_r,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(ou,{className:P(Rr,"text-current")})})}),e.jsxs(Gt,{align:"start",children:[e.jsxs(vt,{onSelect:()=>{requestAnimationFrame(()=>lr())},children:[e.jsx(Wo,{}),"Attach files"]}),e.jsxs(vt,{onSelect:()=>{requestAnimationFrame(()=>{ts(!0)})},children:[e.jsx(sh,{}),"Attach from project"]})]})]})]})]}),ja=s?e.jsx("button",{type:"button",onClick:s,className:_r,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(qr,{className:P(Rr,"text-current")})}):null,no=e.jsxs(e.Fragment,{children:[In,ja]}),Sa=X.statusText;c.useEffect(()=>{const ie=!!X.wasAborted;!ae.current&&ie&&!te&&(Ze(),T&&Y(T)),ae.current=ie},[Y,T,te,Ze,X.wasAborted]),c.useEffect(()=>()=>{ue.current&&(clearTimeout(ue.current),ue.current=null)},[]);const ka=Ae&&Jt;return e.jsxs("form",{onSubmit:st,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:Ae&&je>0&&!Te?{marginBottom:`${je}px`}:void 0,children:[e.jsx(Ub,{isWorking:X.isWorking,statusText:Sa,isGenericStatus:X.isGenericStatus,isWaitingForPermission:X.isWaitingForPermission,wasAborted:X.wasAborted,abortActive:X.abortActive,completionId:X.lastCompletionId,isComplete:X.isComplete,showAbort:ka,onAbort:mt,showAbortStatus:te}),e.jsxs("div",{ref:C,className:P("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Ie,onDragLeave:Je,onDrop:$e,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:_r,onClick:()=>lr(),title:"Attach files","aria-label":"Attach files",children:e.jsx(Wo,{className:P(Rr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(kb,{}),e.jsx(km,{onEditMessage:ie=>{n(ie),setTimeout(()=>{M.current?.focus()},0)}}),e.jsxs("div",{className:P("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:We,children:[m&&e.jsx(Nm,{ref:A,searchQuery:p,onCommandSelect:Ct,onClose:()=>f(!1)}),w&&e.jsx(Cm,{ref:E,searchQuery:j,onAgentSelect:wt,onClose:()=>h(!1)}),x&&e.jsx(Mm,{ref:R,searchQuery:N,onSkillSelect:Dt,onClose:()=>v(!1)}),i&&e.jsx(Nb,{ref:k,searchQuery:d,onFileSelect:It,onClose:()=>l(!1)}),e.jsx(Is,{ref:M,"data-chat-input":"true",value:t,onChange:Be,onKeyDown:lt,onPaste:Qe,onPointerDownCapture:Ye,placeholder:T||B?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!T&&!B,className:P("min-h-[52px] resize-none border-0 px-3 shadow-none rounded-t-xl rounded-b-none appearance-none focus:shadow-none focus-visible:shadow-none focus-visible:border-transparent focus-visible:ring-0 focus-visible:ring-transparent hover:border-transparent bg-transparent",Ae?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:S?`${S.height}px`:void 0,maxHeight:S?`${S.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:P("rounded-b-xl bg-transparent",wa,Ae?"flex items-center gap-x-1.5":P("flex items-center justify-between",vr)),"data-chat-input-footer":"true",children:Ae?e.jsxs("div",{className:"flex w-full items-center gap-x-1.5",children:[e.jsx("div",{className:"flex items-center flex-shrink-0 gap-x-1",children:no}),e.jsxs("div",{className:"flex flex-1 items-center justify-end gap-x-1 min-w-0",children:[e.jsx("div",{className:"flex flex-1 min-w-0 justify-end overflow-hidden",children:e.jsx(Vc,{className:P("w-full flex items-center justify-end min-w-0")})}),rn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:P("flex items-center flex-shrink-0",vr),children:no}),e.jsxs("div",{className:P("flex items-center flex-1 justify-end",vr,"md:gap-x-3"),children:[e.jsx(Vc,{className:P("flex-1 min-w-0 justify-end")}),rn]})]})})]})]})]})};function Ya({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:P("bg-accent animate-pulse rounded-xl",s),...r})}const rd=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=i/o,f=(i+1)/o,p=(x,v,N)=>x+(v-x)*N,g=(x,v,N,y,S,D)=>{const M=p(x,v,S),C=p(y,N,S);return p(M,C,D)},w={x:g(s.x,r.x,t.x,n.x,d,m),y:g(s.y,r.y,t.y,n.y,d,m)},h={x:g(s.x,r.x,t.x,n.x,u,m),y:g(s.y,r.y,t.y,n.y,u,m)},j={x:g(s.x,r.x,t.x,n.x,u,f),y:g(s.y,r.y,t.y,n.y,u,f)},b={x:g(s.x,r.x,t.x,n.x,d,f),y:g(s.y,r.y,t.y,n.y,d,f)};a.push({path:`M${w.x} ${w.y} L${h.x} ${h.y} L${j.x} ${j.y} L${b.x} ${b.y} Z`,row:i,col:l})}return a},vl=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=fa();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,g=50,w={x:50,y:g-m},h={x:50-m*f,y:g-m*p},j={x:50+m*f,y:g-m*p},b={x:50,y:g},x={x:50-m*f,y:g+m*p},v={x:50+m*f,y:g+m*p},N={x:50,y:g+m},S=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(w.y+h.y+b.y+j.y)/4})`,D=rd(h,b,N,x),M=rd(b,j,v,N),C=Ce.useMemo(()=>{const k=[];for(let A=0;A<32;A++)k.push(.1+Math.random()*.5);return k},[]);return e.jsxs("svg",{width:r,height:t,viewBox:"0 0 100 100",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:s,role:"img","aria-label":"OpenChamber logo",children:[e.jsx("path",{d:`M${b.x} ${b.y} L${h.x} ${h.y} L${x.x} ${x.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),D.map((k,A)=>e.jsx("path",{d:k.path,fill:u,opacity:C[A]},`left-${A}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${j.x} ${j.y} L${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),M.map((k,A)=>e.jsx("path",{d:k.path,fill:u,opacity:C[A+16]},`right-${A}`)),e.jsx("path",{d:`M${w.x} ${w.y} L${h.x} ${h.y} L${b.x} ${b.y} L${j.x} ${j.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${S} scale(0.75)`,children:[e.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M-16 -20 L16 -20 L16 20 L-16 20 Z M-8 -12 L-8 12 L8 12 L8 -12 Z",fill:d}),e.jsx("path",{d:"M-8 -4 L8 -4 L8 12 L-8 12 Z",fill:d,fillOpacity:"0.4"})]})]})]})};function ew({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:l="popLayout"}){const[d,u]=Ce.useState(0),m=Ce.Children.toArray(s);Ce.useEffect(()=>{if(!i)return;const p=t*1e3,g=setInterval(()=>{u(w=>{const h=(w+1)%m.length;return a?.(h),h})},p);return()=>clearInterval(g)},[m.length,t,a,i]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:P("relative",r),children:[e.jsx("div",{className:"invisible whitespace-nowrap",children:m.map((p,g)=>e.jsx("div",{className:g===0?"":"absolute",children:p},g))}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:e.jsx(rh,{mode:l,initial:!1,children:e.jsx(un.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const tw=["Fix the failing tests","Refactor this to be more readable","Add form validation","Optimize this function","Write tests for this","Explain how this works","Add a new feature","Help me debug this","Review my code","Simplify this logic","Add error handling","Create a new component","Update the documentation","Find the bug here","Improve performance","Add type definitions"],sw=()=>{const s=fa();let r=!0;s?r=s.currentTheme.metadata.variant!=="light":typeof window<"u"&&(r=window.matchMedia("(prefers-color-scheme: dark)").matches);const t=r?"rgba(255,255,255,0.4)":"rgba(0,0,0,0.4)";return e.jsxs("div",{className:"flex flex-col items-center justify-center min-h-full w-full gap-6",children:[e.jsx(vl,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(ew,{className:"text-body-md",interval:4,transition:{duration:.5},children:tw.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},Xa=c.memo(sw),rw={'code[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#cdccc3",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#6b6964",fontStyle:"italic"},prolog:{color:"#6b6964"},doctype:{color:"#6b6964"},cdata:{color:"#6b6964"},punctuation:{color:"#6b6963"},property:{color:"#d29470"},tag:{color:"#d8886d"},boolean:{color:"#d39373"},number:{color:"#d39373"},constant:{color:"#6cacd6"},symbol:{color:"#6cacd6"},deleted:{color:"#d98678"},selector:{color:"#81af6c"},"attr-name":{color:"#c2974d"},string:{color:"#81af6c"},char:{color:"#81af6c"},builtin:{color:"#5aa9d9"},inserted:{color:"#81af6c"},operator:{color:"#d29470"},entity:{color:"#edb449",cursor:"help"},url:{color:"#5aa9d9"},".language-css .token.string":{color:"#81af6c"},".style .token.string":{color:"#81af6c"},variable:{color:"#d29470"},atrule:{color:"#c2974d"},"attr-value":{color:"#81af6c"},function:{color:"#5aa9d9"},"class-name":{color:"#c2974d"},keyword:{color:"#d8886d"},regex:{color:"#81af6c"},important:{color:"#d8886d",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#edb449",fontWeight:"bold"},"code-block":{color:"#81af6c"},"code-snippet":{color:"#81af6c"},list:{color:"#d29470"},hr:{color:"#6b6963"},table:{color:"#5aa9d9"},blockquote:{color:"#6b6964",fontStyle:"italic"},strike:{textDecoration:"line-through"}},nw={'code[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:"#403e3c",background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"1em",margin:"0",overflow:"auto"},comment:{color:"#7a756a",fontStyle:"italic"},prolog:{color:"#7a756a"},doctype:{color:"#7a756a"},cdata:{color:"#7a756a"},punctuation:{color:"#6b6963"},property:{color:"#c07845"},tag:{color:"#b96f55"},boolean:{color:"#b97659"},number:{color:"#b97659"},constant:{color:"#4791ba"},symbol:{color:"#4791ba"},deleted:{color:"#c15748"},selector:{color:"#6a9354"},"attr-name":{color:"#9f7d3e"},string:{color:"#6a9354"},char:{color:"#6a9354"},builtin:{color:"#4791ba"},inserted:{color:"#6a9354"},operator:{color:"#c07845"},entity:{color:"#d09930",cursor:"help"},url:{color:"#4791ba"},".language-css .token.string":{color:"#6a9354"},".style .token.string":{color:"#6a9354"},variable:{color:"#c07845"},atrule:{color:"#9f7d3e"},"attr-value":{color:"#6a9354"},function:{color:"#4791ba"},"class-name":{color:"#9f7d3e"},keyword:{color:"#b96f55"},regex:{color:"#6a9354"},important:{color:"#b96f55",fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},namespace:{opacity:.7},title:{color:"#d09930",fontWeight:"bold"},"code-block":{color:"#6a9354"},"code-snippet":{color:"#6a9354"},list:{color:"#c07845"},hr:{color:"#6b6963"},table:{color:"#4791ba"},blockquote:{color:"#7a756a",fontStyle:"italic"},strike:{textDecoration:"line-through"}};class Cr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Cr.instance||(Cr.instance=new Cr),Cr.instance}recordSessionStart(r){this.sessionStartTimes.set(r,Date.now())}getSessionStartTime(r){return this.sessionStartTimes.get(r)}shouldAnimateMessage(r,t){if(r.role!=="assistant"||this.seenMessageIds.has(r.id))return!1;const n=this.sessionStartTimes.get(t);if(!n)return this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created),!1;const o=r.time.created>n-5e3;return o||(this.seenMessageIds.add(r.id),this.messageCreationTimes.set(r.id,r.time.created)),o}clearSession(r){this.sessionStartTimes.delete(r)}hasSessionTiming(r){return this.sessionStartTimes.has(r)}hasBeenAnimated(r){return this.seenMessageIds.has(r)}markMessageAsAnimated(r,t){this.seenMessageIds.add(r),this.messageCreationTimes.set(r,t)}clearAll(){this.sessionStartTimes.clear(),this.seenMessageIds.clear(),this.messageCreationTimes.clear()}getDebugInfo(){return{sessionStartTimes:new Map(this.sessionStartTimes),seenMessageIds:new Set(this.seenMessageIds),messageCreationTimes:new Map(this.messageCreationTimes)}}}function Fm(s){const r=s.colors.syntax,t=s.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||t.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:s.colors.status.error,backgroundColor:s.colors.status.errorBackground},inserted:{color:s.colors.status.success,backgroundColor:s.colors.status.successBackground},title:{color:s.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:t.mutedForeground},table:{color:r.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const gs=({children:s,className:r})=>{const[t,n]=c.useState(!1);return c.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:P("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},ow=({isUser:s,providerID:r,agentName:t,modelName:n,variant:o,isDarkTheme:a})=>{const{src:i,onError:l,hasLogo:d}=xm(r);return e.jsx(gs,{children:e.jsx("div",{className:P("pl-3","mb-2"),children:e.jsx("div",{className:P("flex items-center justify-between gap-2"),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex-shrink-0",children:s?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-primary/10 flex items-center justify-center",children:e.jsx(Ps,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&i?e.jsx("img",{src:i,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:l}):e.jsx(ar,{className:"h-4 w-4",style:{color:`var(${kr(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:P("font-bold typography-ui-header tracking-tight leading-none",s?"text-primary":"text-foreground"),children:s?"You":n||"Assistant"}),!s&&t&&e.jsxs("div",{className:P("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",kr(t).class),children:[e.jsx(qr,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:t})]}),!s&&o&&e.jsxs("div",{className:P("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(ar,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:o.length>0?o[0].toLowerCase()+o.slice(1):o})]})]})]})})})})},aw=c.memo(ow),nd=(s,r)=>{const t=s[Symbol.toPrimitive];if(typeof t=="function")try{if(t()===r)return s}catch{}try{Object.defineProperty(s,"toString",{value:()=>r,enumerable:!1,configurable:!0})}catch{}try{Object.defineProperty(s,Symbol.toPrimitive,{value:()=>r,enumerable:!1,configurable:!0})}catch{}return s},od=()=>{if(!Wt()||typeof window>"u")return yc;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=nd({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=nd({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return yc},Rm=()=>{const[s,r]=c.useState(od);return c.useEffect(()=>{if(!Wt()||typeof window>"u")return;const t=n=>{r(od())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},_m=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>r.push(i.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const l=i.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},Om=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
75
+ `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return s.length>0&&n.push(s.map(t).join(",")),r.forEach(o=>n.push(o.map(t).join(","))),n.join(`
76
+ `)},iw=({headers:s,rows:r})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return s.length>0&&n.push(s.map(t).join(" ")),r.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
77
+ `)},lw=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((i,l)=>t(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
78
+ `)},cw=(s,r,t)=>{const n=new Blob([r],{type:t}),o=URL.createObjectURL(n),a=document.createElement("a");a.href=o,a.download=s,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(o)},dw=({tableRef:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const i=async l=>{const d=s.current?.querySelector("table");if(d)try{const u=_m(d),m=l==="csv"?Om(u):iw(u);await navigator.clipboard.write([new ClipboardItem({"text/plain":new Blob([m],{type:"text/plain"}),"text/html":new Blob([d.outerHTML],{type:"text/html"})})]),t(!0),o(!1),setTimeout(()=>t(!1),2e3)}catch(u){console.error("Failed to copy table:",u)}};return e.jsxs("div",{className:"relative",ref:a,children:[e.jsx("button",{onClick:()=>o(!n),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy table",children:r?e.jsx(At,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},uw=({tableRef:s})=>{const[r,t]=c.useState(!1),n=c.useRef(null);c.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=s.current?.querySelector("table");if(i)try{const l=_m(i),d=a==="csv"?Om(l):lw(l);cw(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(l){console.error("Failed to download table:",l)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(bn,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},mw=({children:s,className:r})=>{const t=c.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(dw,{tableRef:t}),e.jsx(uw,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:P("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},fw=({children:s,className:r,style:t,...n})=>{const[o,a]=c.useState(!1),i=c.useRef(null),l=c.useMemo(()=>{if(!t)return t;const m={...t},f=w=>{if(typeof w!="string")return{value:void 0,vars:{}};const[h,...j]=w.split(";").map(x=>x.trim()).filter(Boolean),b={};for(const x of j){const v=x.indexOf(":");if(v===-1)continue;const N=x.slice(0,v).trim(),y=x.slice(v+1).trim();!N.startsWith("--")||y.length===0||(b[N]=y)}return{value:h,vars:b}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[w,h]of Object.entries(p.vars))m[w]=h;const g=f(t.color);g.value&&(m.color=g.value,m["--shiki-light"]=g.value);for(const[w,h]of Object.entries(g.vars))m[w]=h;return m},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:P(r),style:l,children:s}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(At,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})})})]})},$m={pre:fw,table:mw},pw=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const l=Rm(),d=c.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:P("break-words",o),children:e.jsx(au,{mode:a?"streaming":"static",shikiTheme:l,className:u,controls:{code:!1,table:!1},components:$m,children:s})});return n?e.jsx(gs,{children:m},d):m},Gr=({content:s,className:r,variant:t="assistant"})=>{const n=Rm(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:P("break-words",r),children:e.jsx(au,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:$m,children:s})})},hw={thinking:{label:"Thinking",Icon:ar},justification:{label:"Justification",Icon:zi}},Lm=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
79
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
80
+ `).trim(),gw=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
81
+ `),n=r.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},jl=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=c.useState(!1),i=c.useMemo(()=>gw(s),[s]),{label:l,Icon:d}=hw[r];return c.useEffect(()=>{s.trim().length!==0&&t?.("structural")},[t,o,s]),!s||s.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:P("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:()=>a(u=>!u),children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:P("absolute inset-0 transition-opacity",o&&"opacity-0",!o&&"group-hover/tool:opacity-0"),children:e.jsx(d,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:P("absolute inset-0 transition-opacity flex items-center justify-center",o&&"opacity-100",!o&&"opacity-0 group-hover/tool:opacity-100"),children:o?e.jsx(Mt,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:P("relative pr-2 pb-2 pt-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:e.jsx(dt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},Bm=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>Lm(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(jl,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},xw=s=>Lm(s),yw=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,l=i.text,d=typeof l=="string"?l:i.content||i.value||"",u=c.useMemo(()=>a?xw(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=c.useRef(m);if(m||f)return p.current=!0,null;const g=i.time;return!(g&&typeof g.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(jl,{text:u,variant:"justification",onContentChange:o,blockId:s.id||`${r}-reasoning-text`},s.id||`${r}-text`):e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(pw,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},bw=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,ww=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useRef(null);c.useEffect(()=>{const g=m.current;if(!g||i)return;const w=()=>{u(g.scrollHeight>g.clientHeight)};w();const h=new ResizeObserver(w);return h.observe(g),()=>h.disconnect()},[a,i]);const f=c.useCallback(()=>{(d||i)&&l(g=>!g)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const g=a.indexOf(t.token),w=a.slice(0,g),h=a.slice(g+t.token.length);return e.jsxs(e.Fragment,{children:[w,e.jsx("a",{href:bw(t.name),className:"text-primary hover:underline",target:"_blank",rel:"noopener noreferrer",onClick:j=>j.stopPropagation(),children:t.token}),h]})};return e.jsx("div",{className:P("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},vw=c.memo(ww),jw=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},zm=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,Sw=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",ad=(s,r)=>!s||typeof s!="object"?String(s):uy(s,r||""),Qa=(s,r,t)=>{let n=jw(s);if((r==="edit"||r==="multiedit")&&zm(n)&&(n=Sw(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},kw=(s,r)=>{try{const t=s.trim().split(`
82
+ `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,l]=a,d=Math.floor(i.length/2),u=!l.endsWith("/");n.push({name:l.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:P("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},Nw=(s,r,t)=>{try{const n=s.trim().split(`
83
+ `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,l,d,u]=i,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:P("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:P("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((l,d)=>!l.lineNum&&!l.content?null:e.jsxs("div",{className:P("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},Cw=(s,r,t)=>{try{const n=s.trim().split(`
84
+ `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const l=i.lastIndexOf("/"),d=l>0?i.substring(0,l):"/",u=l>=0?i.substring(l+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:P("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:P("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:P("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(l=>e.jsxs("div",{className:P("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:l})]},l))})]},i))]})}catch{return null}},Mw=(s,r)=>{try{const t=JSON.parse(s);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:P("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(At,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(At,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},Dw=(s,r,t)=>{try{return e.jsx("div",{className:P("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:pr.tool.popup,children:e.jsx(Gr,{content:s,variant:"tool"})})}catch{return null}},Wm=s=>{const r=s.split(`
85
+ `);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:l,newStart:d,lines:u}),o=f;continue}o++}return n},Pi=(s,r,t)=>ly(r,s,t),Hm=s=>{const r="h-3.5 w-3.5 flex-shrink-0",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(nh,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(iu,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(hi,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Er,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(ur,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(oh,{className:r}):t==="glob"?e.jsx(ah,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(gi,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(gi,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(ih,{className:r}):t==="skill"?e.jsx(lu,{className:r}):t.startsWith("git")?e.jsx(Ot,{className:r}):e.jsx(ia,{className:r})},Aw=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},Ew=({start:s,end:r,active:t})=>{const[n,o]=c.useState(()=>Date.now());return c.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:Aw(s,r,n)})},Iw=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
86
+ `);let t=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},Ti=(s,r,t)=>{if(t)return s.split("/").pop()||s;if(s.startsWith(r)){const n=s.substring(r.length);return n.startsWith("/")?n.substring(1):n}return s},Pw=(s,r,t,n)=>{const o=r,a=o.metadata,i=o.input;if((s.tool==="edit"||s.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return Ti(d,n,t)}if((s.tool==="read"||s.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return Ti(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
87
+ `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);if(s.tool==="skill"&&i?.name&&typeof i.name=="string")return i.name;const l=i?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},Fi=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(dt,{outerClassName:P("w-full min-w-0 flex-none overflow-hidden",r,n),className:P("tool-output-surface p-2 rounded-xl w-full min-w-0 border border-border/20 bg-transparent",t),disableHorizontal:o,children:e.jsx("div",{className:"w-full min-w-0",children:s})}),Tw=s=>{const r=s.state?.title;return typeof r=="string"&&r.trim().length>0?r:typeof s.tool=="string"&&s.tool.trim().length>0?s.tool:"tool"},Fw=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Rw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const i=me(h=>h.setCurrentSession),l=c.useMemo(()=>s.filter(h=>h.state?.status==="completed"),[s]),d=typeof o=="string"?Fw(o):"",u=d.length>0,[m,f]=c.useState(!1),p=h=>{h.stopPropagation(),a&&i(a)};if(l.length===0&&!u&&!a)return null;const g=r?l:l.slice(-6),w=Math.max(0,l.length-g.length);return e.jsxs("div",{className:P("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[l.length>0?e.jsx(Fi,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[w>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",w," more…"]}):null,g.map((h,j)=>{const b=typeof h.tool=="string"&&h.tool.trim().length>0?h.tool:"tool",x=Tw(h),v=il(b).displayName;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{className:"flex-shrink-0 text-foreground/80",children:Hm(b)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:v}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:x})]},h.id??`${b}-${j}`)})]})}):null,a&&e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-primary hover:text-primary/80 w-full",onPointerDown:h=>h.stopPropagation(),onClick:p,children:[e.jsx(zo,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-primary font-medium",children:"Open subAgent session"})]}),u?e.jsxs("div",{className:P("space-y-1",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:h=>h.stopPropagation(),onClick:h=>{h.stopPropagation(),f(j=>!j)},children:[m?e.jsx(Mt,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Us,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(Fi,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:d,variant:"tool"})})}):null]}):null]})},_w=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Wm(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:P("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:tn(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),Ow=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
88
+ `),a=tn(t??"")||Pi(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},$w=({content:s,filePath:r,displayPath:t})=>{const n=dy(r),o=r.toLowerCase().endsWith(".svg"),a=c.useMemo(()=>o&&!s.startsWith("data:")?`data:image/svg+xml;base64,${btoa(s)}`:s.startsWith("data:")?s:`data:${n};base64,${s}`,[s,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},Lw=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const l=r,d=l.metadata,u=l.input,m=l.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",g=typeof d?.diff=="string"?d.diff:null,w=s.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,h=s.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,j=s.tool==="write"&&!!h,b=w?em(w):!1,x=j?w?Ti(w,o,n):"New file":null,v=c.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?ad(u,s.tool):typeof u.content=="string"?u.content??"":ad(u,s.tool),[u,s.tool]),N=v.trim().length>0,y=(D,M)=>e.jsx(Fi,{maxHeightClass:M?.maxHeightClass,className:M?.className,disableHorizontal:M?.disableHorizontal,outerClassName:M?.outerClassName,children:D}),S=()=>{if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const D=Mw(p,{unstyled:!0});return y(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(s.tool==="list"&&f){const D=kw(p,{unstyled:!0});return y(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="grep"&&f){const D=Nw(p,n,{unstyled:!0});return y(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="glob"&&f){const D=Cw(p,n,{unstyled:!0});return y(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="task"&&f)return y(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const D=Dw(p,t,{unstyled:!0});return y(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="codesearch"&&f)return y(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return y(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Gr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&(!f&&g||p.trim().length===0||zm(p))&&g)return y(e.jsx(_w,{diff:g,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const D=Qa(p,s.tool,d),M=D.split(`
89
+ `),C=typeof u?.offset=="number"?u.offset:0,k=typeof u?.limit=="number"?u.limit:void 0,A=E=>E.trim().startsWith("(");return y(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:M.map((E,R)=>{const V=A(E),T=C+R+1,B=!V&&(k===void 0||R<k);return e.jsxs("div",{className:P("typography-code font-mono flex w-full min-w-0",V&&"text-muted-foreground/70 italic"),children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-3 self-start select-none",children:B?T:""}),e.jsx("div",{className:"flex-1 min-w-0",children:V?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(hr,{style:t,language:Pi(D,s.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:E})})]},R)})}),{className:"p-1"})}return y(e.jsx(hr,{style:t,language:Pi(Qa(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...Do.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:Qa(p,s.tool,d)}),{className:"p-1"})}return y(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:P("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"?S():e.jsxs(e.Fragment,{children:[j&&b?e.jsx("div",{className:"my-1",children:y(e.jsx($w,{content:h,filePath:w,displayPath:x??"New file"}))}):j?e.jsx("div",{className:"my-1",children:y(e.jsx(Ow,{content:h,syntaxTheme:t,filePath:w,displayPath:x??"New file"}))}):N?e.jsx("div",{className:"my-1",children:y(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:v}),{maxHeightClass:"max-h-60",className:"tool-input-surface"})}):null,s.tool!=="write"&&r.status==="completed"&&"output"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Result:"}),S()]}),r.status==="error"&&"error"in r&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground/80 mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]})]})})},Oo=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:l=!1})=>{const d=s.state,u=ct(T=>T.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",g=d.status==="error",w=c.useRef(r);c.useEffect(()=>{!f&&!m||w.current!==r&&(w.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const h=d,j=h.metadata,b=h.input,x=h.time,v=c.useRef({}),N=c.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,v.current={}),m){if(typeof x?.start=="number"){const T=v.current.start;(typeof T!="number"||x.start<T)&&(v.current.start=x.start)}typeof x?.end=="number"&&(v.current.end=x.end)}const y=m?v.current.start??x?.start:x?.start,S=m?v.current.end??x?.end:x?.end,D=c.useMemo(()=>{if(!m)return;const T=j;return typeof T?.sessionId=="string"?T.sessionId:void 0},[m,j]),M=c.useMemo(()=>{if(!m)return[];const T=j?.summary;return Array.isArray(T)?T.filter(B=>typeof B=="object"&&B!==null):[]},[m,j]),C=c.useRef(M.length);c.useEffect(()=>{m&&C.current!==M.length&&(C.current=M.length,a?.("structural"))},[m,a,M.length]);const k=s.tool==="edit"||s.tool==="multiedit"?Iw(j):null,A=Pw(s,d,o,u),E=il(s.tool).displayName,R=c.useContext(ll),V=T=>{if(m||!R?.editor){t(s.id);return}let B;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(B=b?.filePath||b?.file_path||b?.path||j?.filePath||j?.file_path||j?.path),typeof B=="string"){T.stopPropagation();let re=B;B.startsWith("/")||(re=u.endsWith("/")?u+B:u+"/"+B),R.editor.openFile(re)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:P("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:V,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",onClick:T=>{T.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:P("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&g?{color:"var(--status-error)"}:{},children:Hm(s.tool)}),e.jsx("div",{className:P("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Mt,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&g?{color:"var(--status-error)"}:{},children:E})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:P("truncate",o&&"max-w-[120px]"),children:A}),k&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",k.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",k.removed]})]}),typeof y=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Ew,{start:y,end:typeof S=="number"?S:void 0,active:!!(m&&p&&typeof S!="number")})})]})]}),m&&(M.length>0||p||f||D)?e.jsx(Rw,{entries:M,isExpanded:r,hasPrevTool:i,hasNextTool:l,output:typeof h.output=="string"?h.output:void 0,sessionId:D}):null,!m&&r?e.jsx(Lw,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:l}):null]})},Bw=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
90
+ `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
91
+ `).trim(),zw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>Bw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(jl,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},Ww=c.memo(zw),Hw=s=>{const r={tools:s.filter(n=>n.kind==="tool").length,reasoning:s.filter(n=>n.kind==="reasoning").length,justifications:s.filter(n=>n.kind==="justification").length},t=[];return r.tools>0&&t.push(`${r.tools} tool${r.tools>1?"s":""}`),r.reasoning>0&&t.push(`${r.reasoning} reasoning`),r.justifications>0&&t.push(`${r.justifications} justification${r.justifications>1?"s":""}`),t.join(", ")},id=s=>[...s].sort((r,t)=>{const n=typeof r.endedAt=="number"?r.endedAt:void 0,o=typeof t.endedAt=="number"?t.endedAt:void 0;return n===void 0&&o===void 0?0:n===void 0?1:o===void 0?-1:n-o}),Uw=s=>{const r={},t=s.filter(n=>n.kind==="tool");return t.forEach((n,o)=>{const a=n.part.id;a&&(r[a]={hasPrev:o>0,hasNext:o<t.length-1})}),r},Vw=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:l,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=c.useRef(r),[p,g]=c.useState(0);c.useEffect(()=>{if(f.current===r)return;const b=f.current===!1;f.current=r,l?.("structural"),r&&b&&g(x=>x+1)},[r,l]);const w=c.useMemo(()=>id(d?s.filter(b=>b.part.id&&u.has(b.id)):s),[s,d,u]),h=Hw(w),j=Uw(w);return w.length===0?null:e.jsx(gs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:P("group/tool flex items-center gap-2 pr-2 pl-px pt-0 pb-1.5 rounded-xl cursor-pointer"),onClick:t,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative h-3.5 w-3.5 flex-shrink-0",children:[e.jsx("div",{className:P("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(qn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:P("absolute inset-0 transition-opacity flex items-center justify-center",r&&"opacity-100",!r&&o&&"opacity-0",!r&&!o&&"opacity-0 group-hover/tool:opacity-100"),children:r?e.jsx(Mt,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),m&&(m.additions>0||m.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,m.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,m.deletions)]})]})]})]}),r&&e.jsx("div",{className:P("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:w.map((b,x)=>{const v=b.part.id||`group-part-${x}`,N=j[v],y=`${v}-exp${p}`;switch(b.kind){case"tool":return e.jsx(gs,{children:e.jsx(Oo,{part:b.part,isExpanded:a.has(v),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},y);case"reasoning":return e.jsx(gs,{children:e.jsx(Bm,{part:b.part,messageId:b.messageId,onContentChange:l})},y);case"justification":return e.jsx(gs,{children:e.jsx(Ww,{part:b.part,messageId:b.messageId,onContentChange:l})},y);default:return null}})})]})})},Gw=c.memo(Vw),Kw=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:P("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),Ja=c.memo(Kw),Um=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},Vm=s=>{if(s.type!=="text")return!1;const r=Um(s);return!r||r.trim().length===0},qw=(s,r={})=>{const{includeReasoning:t=!0}=r,n=s.some(o=>!o.synthetic);return s.filter(o=>!!o.synthetic&&n||!t&&o.type==="reasoning"?!1:!(o.type==="patch"))},Yw=(s,r)=>{const t=c.useRef(null),n=c.useRef(null),[o,a]=c.useState(!1),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useRef(!1),u=r.size>0;return c.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=i.current;if(!m)return;const f=Array.from(l.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),c.useEffect(()=>{s&&(!s.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,s]),c.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Xw=new Set(["task"]),dn=s=>typeof s=="string"&&Xw.has(s.toLowerCase()),Qw=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:l,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=c.useState(!1),g=c.useRef(null),w=c.useMemo(()=>r.filter(M=>M.type!=="text"?!1:!Vm(M)),[r]),h=d?.token;let j=!1;const b=!!a,x=!!i,v=!!(n??t),N=!!o,y=c.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),S=c.useCallback(()=>{!v||!b||!N||typeof window>"u"||(y(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[b,y,N,v]);c.useEffect(()=>{N||(p(!1),y())},[y,N]);const D=c.useCallback(M=>{!a||!N||(M.stopPropagation(),M.preventDefault(),a(),v&&S())},[N,v,a,S]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:v&&b&&N?S:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:w.map((M,C)=>{let k;return d&&h&&!j&&Um(M).includes(h)&&(k=d,j=!0),e.jsx(gs,{children:e.jsx(vw,{part:M,messageId:s,isMobile:t,agentMention:k})},`user-text-${C}`)})}),e.jsx(jm,{files:r,onShowPopup:l}),b&&N||u||m?e.jsxs("div",{className:P("mt-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",f&&"opacity-100 pointer-events-auto"),children:[u&&e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Revert to this message",onPointerDown:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),u()},children:e.jsx(Kn,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:M=>M.stopPropagation(),onClick:M=>{M.stopPropagation(),m()},children:e.jsx(Ot,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Fork from here"})]}),b&&N&&e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":f||x?"true":void 0,className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Copy message text",onPointerDown:M=>M.stopPropagation(),onClick:D,onFocus:()=>p(!0),onBlur:()=>{x||p(!1)},children:x?e.jsx(At,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Copy message"})]})]}):null]})},Jw=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,syntaxTheme:o,isMobile:a,hasTouchInput:i,expandedTools:l,onToggleTool:d,onShowPopup:u,streamPhase:m,allowAnimation:f,onContentChange:p,hasTextContent:g=!1,onCopyMessage:w,copiedMessage:h=!1,onAuxiliaryContentComplete:j,showReasoningTraces:b=!1,turnGroupingContext:x,errorMessage:v})=>{const[N,y]=c.useState(!1),S=c.useRef(null),D=!!w,M=!!h,C=!!(i??a),k=!t,A=c.useMemo(()=>r.filter(He=>!Vm(He)).filter(He=>He.type!=="compaction"),[r]),E=c.useMemo(()=>A.filter(He=>He.type==="tool"),[A]),R=c.useMemo(()=>A.filter(He=>He.type==="text"),[A]),V=me(He=>He.createSessionFromAssistantMessage),T=_e(He=>He.openMultiRunLauncherWithPrompt),B=x?.isLastAssistantInTurn??!1,re=n==="stop",Y=E.length>0,_=c.useMemo(()=>E.some(He=>{const st=(He.state??{})?.status;return st==="pending"||st==="running"||st==="started"}),[E]),q=c.useCallback(He=>{const Ge=He.state??{},st=Ge?.status;if(st==="pending"||st==="running"||st==="started")return!1;const Ke=Ge?.time??{},lt=typeof Ke?.end=="number"?Ke.end:void 0,Ze=typeof Ke?.start=="number"?Ke.start:void 0;return!(typeof lt!="number"||typeof Ze=="number"&&lt<Ze)},[]),O=c.useMemo(()=>E.length===0?!0:_?!1:E.every(He=>q(He)),[E,_,q]),z=c.useMemo(()=>R.length===0?!0:R.every(He=>typeof He.time?.end=="number"),[R]),U=c.useMemo(()=>A.filter(He=>He.type==="reasoning"),[A]),ne=c.useMemo(()=>U.length===0?!0:U.every(He=>typeof He.time?.end=="number"),[U]),oe=typeof n!="string",Q=U.length>0&&Y&&(_||oe||!O),de=c.useMemo(()=>Y?R.length===0?oe||_||!O:!0:R.length>0?Q:!1,[R.length,oe,_,Y,Q,O]),I=k||de&&(!z||!O||_||oe)||Q,W=k||Y&&(_||oe||!O),F=k||Q,$=Y||U.length>0,L=R.length===0,J=$&&L&&!W&&!F&&O&&ne,pe=c.useRef(!1),be=c.useRef(!1);c.useEffect(()=>{be.current=!1},[s]),c.useEffect(()=>{if(!J){pe.current=!1;return}pe.current||(pe.current=!0,j?.())},[J,j]),c.useEffect(()=>{if(k){be.current=!1;return}if(Y){be.current=!1;return}U.length!==0&&(F||!ne||be.current||(be.current=!0,p?.("structural")))},[k,Y,p,ne,U.length,F]);const he=!!g&&!k,Ae=c.useCallback(()=>{S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null)},[]),je=c.useCallback(()=>{!C||!D||!he||typeof window>"u"||(Ae(),y(!0),S.current=window.setTimeout(()=>{y(!1),S.current=null},1800))},[D,Ae,he,C]);c.useEffect(()=>{he||(y(!1),Ae())},[Ae,he]);const Te=c.useCallback(He=>{!w||!he||(He.stopPropagation(),He.preventDefault(),w(),C&&je())},[he,C,w,je]),K=c.useCallback(He=>{He.stopPropagation(),He.preventDefault(),V&&V(s)},[V,s]),X=c.useCallback(He=>{He.stopPropagation(),He.preventDefault();const Ge=nl(R);if(!Ge.trim())return;const st=`${Mx}
92
+
93
+ ${Ge}`;T(st)},[R,T]);c.useEffect(()=>()=>{Ae()},[Ae]);const te=c.useMemo(()=>{const He={},Ge=E.filter(st=>dn(st.tool)||W?!1:q(st));return Ge.forEach((st,Ke)=>{He[st.id]={hasPrev:Ke>0,hasNext:Ke<Ge.length-1}}),He},[E,W,q]),fe=c.useMemo(()=>x?.activityParts??[],[x]),ue=c.useMemo(()=>x?fe.filter(He=>He.messageId===s):[],[fe,s,x]),ae=c.useMemo(()=>x?x.activityGroupSegments.filter(He=>He.anchorMessageId===s):[],[s,x]),H=c.useMemo(()=>{const He=new Map;return ue.forEach(Ge=>{He.set(Ge.part,Ge)}),He},[ue]),xe=c.useMemo(()=>x?(b?fe:fe.filter(Ge=>Ge.kind==="tool")).filter(Ge=>{if(Ge.kind!=="tool")return!0;const st=Ge.part.tool;return!dn(st)}):[],[fe,b,x]),[G,ye]=c.useState(!1);c.useEffect(()=>{if(!x)return;const He=x.activityGroupSegments.some(Ge=>Ge.afterToolPartId!==null);(xe.length>1||He&&xe.length>0)&&ye(!0)},[x,xe.length]);const Fe=!!(x&&G),qe=c.useMemo(()=>{if(!x)return[];if(!Fe)return[];if(!x.isWorking)return[];const He=[];return ue.forEach(Ge=>{if(x.previewedPartIds.has(Ge.id)||!b&&Ge.kind!=="tool")return;const st=Ge.part;if(Ge.kind==="tool"){const Ke=st;if(dn(Ke.tool)||W||!q(Ke))return}else if(Ge.kind==="reasoning"){if(!b||F||typeof st.time?.end!="number")return}else if(Ge.kind==="justification"&&(!b||I||typeof st.time?.end!="number"))return;He.push(Ge)}),He},[ue,q,I,F,W,b,Fe,x]),Re=c.useMemo(()=>{const He=new Set;return qe.forEach(Ge=>{He.add(Ge.id)}),He},[qe]),{isAnimating:Ee}=Yw(x,Re),Ye=!!(x&&Fe&&xe.length>0&&ae.length>0),ot=c.useMemo(()=>E.filter(He=>dn(He.tool)),[E]),ut=c.useMemo(()=>{const He=[],Ge=Ke=>{!x||!Ye||ae.filter(lt=>(lt.afterToolPartId??null)===Ke).forEach(lt=>{const Ze=b?lt.parts:lt.parts.filter(mt=>mt.kind==="tool");Ze.length!==0&&He.push(e.jsx(Gw,{parts:Ze,isExpanded:x.isGroupExpanded,onToggle:x.toggleGroup,syntaxTheme:o,isMobile:a,expandedTools:l,onToggleTool:d,onShowPopup:u,onContentChange:p,isWorking:x.isWorking,previewedPartIds:x.previewedPartIds,diffStats:x.diffStats},`progressive-group-${lt.id}`))})};Ge(null),ot.forEach(Ke=>{He.push(e.jsx(gs,{children:e.jsx(Oo,{part:Ke,isExpanded:l.has(Ke.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ke.id}`)),Ge(Ke.id)});const st=[];return A.forEach((Ke,lt)=>{const Ze=H.get(Ke);if(!Ze||!x)return;let mt=null,ee=null;if(!Fe){if(Ze.kind==="tool"){const ge=Ke;if(dn(ge.tool))return;const Be=ge.state?.time,Qe=q(ge);if(!(!W&&Qe))return;const wt=te[ge.id];ee=e.jsx(gs,{children:e.jsx(Oo,{part:ge,isExpanded:l.has(ge.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:wt?.hasPrev??!1,hasNextTool:wt?.hasNext??!1})},`tool-${ge.id}`),mt=Qe&&typeof Be?.end=="number"?Be.end:null}ee&&st.push({part:Ke,index:lt,endTime:mt,element:ee});return}if(!x.isWorking||x.isGroupExpanded||x.previewedPartIds.has(Ze.id)||!b&&Ze.kind!=="tool")return;const we=Re.has(Ze.id);switch(Ze.kind){case"tool":{const ge=Ke;if(dn(ge.tool))break;const Be=ge.state?.time,Qe=q(ge);if(!(!W&&Qe))break;const wt=te[ge.id],Dt=e.jsx(gs,{children:e.jsx(Oo,{part:ge,isExpanded:l.has(ge.id),onToggle:d,syntaxTheme:o,isMobile:a,onContentChange:p,hasPrevTool:wt?.hasPrev??!1,hasNextTool:wt?.hasNext??!1})},`tool-${ge.id}`);ee=we?e.jsx(Ja,{isMigrating:Ee,children:Dt},`migrating-tool-${ge.id}`):Dt,mt=Qe&&typeof Be?.end=="number"?Be.end:null;break}case"reasoning":{if(!b)break;const ge=Ke.time,Oe=typeof ge?.end=="number";if(!(Oe&&!F))break;const Qe=e.jsx(gs,{children:e.jsx(Bm,{part:Ke,messageId:s,onContentChange:p})},`reasoning-${lt}`);ee=we?e.jsx(Ja,{isMigrating:Ee,children:Qe},`migrating-reasoning-${lt}`):Qe,mt=Oe?ge?.end??null:null;break}case"justification":{if(!b)break;const ge=Ke.time,Oe=typeof ge?.end=="number";if(!(Oe&&!I))break;const Qe=e.jsx(gs,{children:e.jsx(yw,{part:Ke,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:p,renderAsReasoning:!0})},`assistant-text-${lt}`);ee=we?e.jsx(Ja,{isMigrating:Ee,children:Qe},`migrating-text-${lt}`):Qe,mt=Oe?ge?.end??null:null;break}}ee&&st.push({part:Ke,index:lt,endTime:mt,element:ee})}),st.sort((Ke,lt)=>Ke.endTime===null&&lt.endTime===null?Ke.index-lt.index:Ke.endTime===null?1:lt.endTime===null?-1:Ke.endTime-lt.endTime),st.forEach(({element:Ke})=>{He.push(Ke)}),He},[H,ae,l,Ee,a,q,s,p,u,d,Re,I,F,W,Fe,b,o,te,x,A,ot,Ye]),kt=x?.turnId,Rt=me(He=>He.currentSessionId),Et=ft(He=>{if(!kt||!Rt)return;const Ge=He.messages.get(Rt);if(!Ge)return;const st=Ge.find(Ze=>Ze.info?.id===kt);if(!st)return;const lt=st.info.summary?.body;return typeof lt=="string"&&lt.trim().length>0?lt:void 0}),Nt=typeof x?.summaryBody=="string"&&x.summaryBody.trim().length>0?x.summaryBody:Et,Qt=c.useRef(void 0);Nt&&Nt.trim().length>0&&(Qt.current=Nt);const Tt=c.useRef(kt);Tt.current!==kt&&(Tt.current=kt,Qt.current=void 0);const Se=Qt.current,Pe=x?.isLastAssistantInTurn&&Se&&Se.trim().length>0,We=!!v,at=B&&g&&(re||!!v),[jt,zt]=c.useState(!1),Jt=e.jsxs(e.Fragment,{children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:He=>He.stopPropagation(),onClick:K,children:e.jsx(lh,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:He=>He.stopPropagation(),onClick:X,children:e.jsx(hm,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),w&&e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{type:"button",variant:"ghost",size:"icon","data-visible":N||M?"true":void 0,className:P("h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",!he&&"opacity-50"),disabled:!he,"aria-label":"Copy message text","aria-hidden":!he,onPointerDown:He=>He.stopPropagation(),onClick:Te,onFocus:()=>{he&&y(!0)},onBlur:()=>{M||y(!1)},children:M?e.jsx(At,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(tt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:P("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:C&&D&&he?je:void 0,children:e.jsxs("div",{className:"px-3",children:[e.jsxs("div",{className:"leading-normal overflow-hidden text-foreground/90 [&_p:last-child]:mb-0 [&_ul:last-child]:mb-0 [&_ol:last-child]:mb-0",children:[ut,We&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Gr,{content:v??""})})},"assistant-error"),Pe&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>zt(!0),onMouseLeave:()=>zt(!1),children:[e.jsx(Gr,{content:Se}),at&&e.jsx("div",{className:P("mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",jt&&"opacity-100 pointer-events-auto"),children:Jt})]})},"summary-body")]}),e.jsx(jm,{files:r,onShowPopup:u}),!Pe&&at&&e.jsx("div",{className:"mt-2 mb-1 flex items-center justify-end gap-2 opacity-0 pointer-events-none transition-opacity duration-150 group-hover/message:opacity-100 group-hover/message:pointer-events-auto focus-within:opacity-100 focus-within:pointer-events-auto",children:Jt})]})})},Zw=({isUser:s,...r})=>s?e.jsx(Qw,{messageId:r.messageId,parts:r.parts,isMobile:r.isMobile,hasTouchInput:r.hasTouchInput,hasTextContent:r.hasTextContent,onCopyMessage:r.onCopyMessage,copiedMessage:r.copiedMessage,onShowPopup:r.onShowPopup,agentMention:r.agentMention,onRevert:r.onRevert,onFork:r.onFork}):e.jsx(Jw,{...r}),ld=c.memo(Zw),Za=s=>{const r=s,t=r?.clientRole,n=r?.role;return r?.userMessageMarker===!0||t==="user"||n==="user"||r?.origin==="user"||r?.source==="user"?{role:"user",isUser:!0}:{role:t||n||"assistant",isUser:!1}},ev=c.lazy(()=>is(()=>import("./ToolOutputDialog-DYNTzpsQ.js"),__vite__mapDeps([2,0,1,3,4]))),tv=new Set(["task","edit","multiedit","write","bash"]),cd=s=>typeof s=="string"&&tv.has(s.toLowerCase());function ei(s){const r=c.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const Js=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},sv=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:l,hasTouchInput:d}=Ft(),{currentTheme:u}=sn(),m=c.useRef(null),f=me(Ui(Ie=>({lifecyclePhase:Ie.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const Je=s.info.sessionID??Ie.currentSessionId??null;return Je?(Ie.streamingMessageIds.get(Je)??null)===s.info.id:!1})(),currentSessionId:Ie.currentSessionId,getCurrentAgent:Ie.getCurrentAgent,getSessionAgentSelection:Ie.getSessionAgentSelection,getAgentModelForSession:Ie.getAgentModelForSession,getSessionModelSelection:Ie.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:w,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:b,getSessionModelSelection:x}=f,v=et(Ie=>Ie.providers),N=_e(Ie=>Ie.showReasoningTraces),y=_e(Ie=>Ie.toolCallExpansion);c.useEffect(()=>{w&&Cr.getInstance().recordSessionStart(w)},[w]);const[S,D]=c.useState(null),[M,C]=c.useState(!1),[k,A]=c.useState(new Set),[E,R]=c.useState({open:!1,title:"",content:""});c.useEffect(()=>{A(new Set)},[s.info.id,y]);const T=c.useMemo(()=>Za(s.info),[s.info]).isUser,B=c.useMemo(()=>T?s.parts.map(Ie=>Ie.type==="compaction"?{type:"text",text:"/compact"}:Ie):s.parts,[T,s.parts]),re=c.useMemo(()=>{if(T||!r)return null;const Ie=Js(r.info,"clientRole"),Je=Js(r.info,"role");if((typeof Ie=="string"?Ie:typeof Je=="string"?Je:void 0)!=="user")return null;const Ve=Js(r.info,"mode"),yt=Js(r.info,"providerID"),$t=Js(r.info,"modelID"),ts=Js(r.info,"variant"),es=typeof Ve=="string"&&Ve.trim().length>0?Ve:void 0,ps=typeof yt=="string"&&yt.trim().length>0?yt:void 0,lr=typeof $t=="string"&&$t.trim().length>0?$t:void 0,_t=typeof ts=="string"&&ts.trim().length>0?ts:void 0;return!es&&!ps&&!lr&&!_t?null:{agentName:es,providerId:ps,modelId:lr,variant:_t}},[T,r]),Y=c.useMemo(()=>{if(T)return;const Ie=Js(s.info,"mode");if(typeof Ie=="string"&&Ie.trim().length>0)return Ie;if(re?.agentName)return re.agentName;const Je=s.info.sessionID;if(!Je)return;const $e=h(Je);return $e||(j(Je)??void 0)},[T,s.info,re,h,j]),_=s.info.sessionID,q=T?null:Js(s.info,"providerID"),O=T?null:Js(s.info,"modelID"),z=c.useMemo(()=>{if(T||!_)return null;if(re?.providerId&&re?.modelId)return{providerId:re.providerId,modelId:re.modelId};if(Y){const Je=b(_,Y);if(Je?.providerId&&Je?.modelId)return Je}const Ie=x(_);return Ie?.providerId&&Ie?.modelId?Ie:null},[T,_,Y,re,b,x]),U=c.useMemo(()=>T?null:typeof q=="string"&&q.trim().length>0?q:z?.providerId??null,[T,q,z]),ne=c.useMemo(()=>T?null:typeof O=="string"&&O.trim().length>0?O:z?.modelId??null,[T,O,z]),oe=c.useMemo(()=>{if(!T&&U&&ne&&v.length>0){const Ie=v.find(Je=>Je.id===U);if(Ie?.models&&Array.isArray(Ie.models)){const Ve=Ie.models.find(yt=>yt.id===ne)?.name;return typeof Ve=="string"?Ve:void 0}}},[T,U,ne,v]),Q=c.useMemo(()=>{if(T||!U||!ne)return!1;const Ie=v.find(Ve=>Ve.id===U);if(!Ie?.models||!Array.isArray(Ie.models))return!1;const $e=Ie.models.find(Ve=>Ve.id===ne)?.variants;return!!($e&&Object.keys($e).length>0)},[T,ne,U,v]),de=ei(Y),I=ei(U??void 0),W=ei(oe),F=de??void 0,$=I??null,L=W??void 0,J=c.useMemo(()=>{const Ie=s.info.time;return typeof Ie?.completed=="number"?Ie.completed:null},[s.info.time]),pe=c.useMemo(()=>T?!0:!!(J&&J>0),[T,J]),be=c.useMemo(()=>{const Ie=s.info.finish;return typeof Ie=="string"?Ie:void 0},[s.info]),he=c.useMemo(()=>qw(B,{includeReasoning:N}),[B,N]),Ae=c.useMemo(()=>T||pe?he:[],[T,pe,he]),je=c.useMemo(()=>T?[]:he.filter(Ie=>Ie.type==="text"),[T,he]),Te=c.useMemo(()=>T?[]:he.filter(Je=>Je.type==="tool"),[T,he]),K=c.useMemo(()=>{if(y==="collapsed"||y==="activity")return k;const Ie=new Set;for(const $e of Te){const Ve=$e.tool;$e.id&&cd(Ve)&&Ie.add($e.id)}if(i?.isFirstAssistantInTurn)for(const $e of i.activityParts){if($e.kind!=="tool")continue;const Ve=$e.part;Ve.id&&cd(Ve.tool)&&Ie.add(Ve.id)}const Je=new Set(Ie);for(const $e of k)Je.has($e)?Je.delete($e):Je.add($e);return Je},[k,y,Te,i]),X=c.useMemo(()=>{if(!T)return;const Ie=s.parts.find(yt=>yt.type==="agent");if(!Ie)return;const Je=Ie,$e=typeof Je.name=="string"?Je.name:void 0;if(!$e)return;const Ve=Je.source&&typeof Je.source.value=="string"&&Je.source.value.trim().length>0?Je.source.value:`#${$e}`;return{name:$e,token:Ve}},[T,s.parts]),te=typeof be!="string",fe=c.useMemo(()=>T?!1:je.length===0||Te.length===0?te:!0,[je.length,Te.length,te,T]),ue=u?.metadata.variant,ae=c.useMemo(()=>ue?ue==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[ue]),H=c.useMemo(()=>u?Fm(u):ae?rw:nw,[u,ae]),xe=c.useMemo(()=>T?!1:Cr.getInstance().shouldAnimateMessage(s.info,w||s.info.sessionID),[s.info,w,T]),G=c.useRef(!1),ye=c.useMemo(()=>r?Za(r.info):null,[r]),Fe=c.useMemo(()=>t?Za(t.info):null,[t]),qe=c.useMemo(()=>T||!Fe?!1:!Fe.isUser&&Fe.role==="assistant",[T,Fe]),Re=c.useMemo(()=>pe?"completed":p||(g?"streaming":"completed"),[pe,p,g]),Ee=c.useMemo(()=>{if(T)return!0;const Ie=i?.headerMessageId;if(Ie){if(s.info.id===Ie){if(Re==="completed")return!0;const $e=Re==="streaming"||Re==="cooldown",Ve=G.current;return $e&&!Ve&&(G.current=!0),Ve||$e}return!1}return ye?ye.isUser:!0},[T,ye,i,Re,s.info]),Ye=c.useCallback(Ie=>{navigator.clipboard.writeText(Ie),D(Ie),setTimeout(()=>D(null),2e3)},[]),ot=i?.turnId,ut=ft(Ie=>{if(!ot)return;const Je=s.info.sessionID;if(!Je)return;const $e=Ie.messages.get(Je);if(!$e)return;const Ve=$e.find(ts=>ts.info?.id===ot);if(!Ve)return;const $t=Ve.info.summary?.body;return typeof $t=="string"&&$t.trim().length>0?$t:void 0}),kt=ft(Ie=>{if(!ot)return;const Je=s.info.sessionID;if(!Je)return;const $e=Ie.messages.get(Je);if(!$e)return;const Ve=$e.find($t=>$t.info?.id===ot);if(!Ve)return;const yt=Ve.info.variant;return typeof yt=="string"&&yt.trim().length>0?yt:void 0}),Rt=T?void 0:kt??re?.variant,Et=!T&&Q?Rt??"Default":void 0,Nt=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:ut,Qt=c.useRef(void 0);Nt&&Nt.trim().length>0&&(Qt.current=Nt);const Tt=c.useRef(ot);Tt.current!==ot&&(Tt.current=ot,Qt.current=void 0);const Se=Qt.current,Pe=c.useMemo(()=>{if(T)return;const Ie=s.info?.error;if(!Ie)return;const Je=typeof Ie.data?.message=="string"?Ie.data.message:void 0,$e=typeof Ie.message=="string"?Ie.message:void 0,Ve=typeof Ie.name=="string"?Ie.name:void 0,yt=Je||$e||Ve;if(yt)return`Opencode failed to send message with error:
94
+ \`${yt}\``},[T,s.info]),We=c.useMemo(()=>T?Ae.filter($e=>$e.type==="text").map($e=>($e.text||$e.content||"").trim()).filter($e=>$e.length>0).join(`
95
+ `).replace(/\n\s*\n+/g,`
96
+ `):Pe&&Pe.trim().length>0?Pe:Se&&Se.trim().length>0?Se:nl(Ae),[Pe,Se,Ae,T]),at=We.length>0,jt=c.useCallback(()=>{navigator.clipboard.writeText(We),C(!0),setTimeout(()=>C(!1),2e3)},[We]),zt=me(Ie=>Ie.revertToMessage),Jt=me(Ie=>Ie.forkFromMessage),He=c.useCallback(()=>{!_||!s.info.id||zt(_,s.info.id)},[_,s.info.id,zt]),Ge=c.useCallback(()=>{!_||!s.info.id||Jt(_,s.info.id)},[_,s.info.id,Jt]),st=c.useCallback(Ie=>{A(Je=>{const $e=new Set(Je);return $e.has(Ie)?$e.delete(Ie):$e.add(Ie),$e})},[]),Ke=o??null,lt=c.useRef(!1),Ze=c.useRef(!1),mt=c.useRef(!1),ee=c.useRef(!1),we=c.useRef(!1);c.useEffect(()=>{Ze.current=!1,mt.current=!1,ee.current=!1,we.current=!1,lt.current=!1},[s.info.id]);const ge=c.useCallback(()=>{T||lt.current||(lt.current=!0,n?.("structural"))},[T,n]),Oe=c.useCallback(Ie=>{Ie.image&&R(Ie)},[]),Be=c.useCallback(Ie=>{R(Je=>({...Je,open:Ie}))},[]),Qe=!!Js(s.info,"animationSettled"),It=Re==="streaming",wt=c.useMemo(()=>T?!1:he.some(Ie=>Ie.type==="reasoning"),[T,he]),Dt=xe&&!Qe&&!It,Ct=!T&&xe&&je.length>0&&!fe;return c.useEffect(()=>{if(Ke?.onStreamingCandidate){if(!Ct){mt.current&&(wt&&Ke?.onReasoningBlock?Ke.onReasoningBlock():Ke?.onReservationCancelled&&Ke.onReservationCancelled(),mt.current=!1);return}we.current||(we.current=!0,Ke.onStreamingCandidate(),mt.current=!0)}},[Ke,Ct,wt]),c.useEffect(()=>{Ke?.onAnimationStart&&Dt&&(ee.current||(Ke.onAnimationStart(),ee.current=!0))},[Ke,Dt]),c.useEffect(()=>{if(T)return;const Ie=Ke?.onAnimatedHeightChange;if(!Ie||!(Dt||Ct))return;const $e=m.current;if(!$e)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Ie($e.getBoundingClientRect().height);return}let Ve=null;const yt=ts=>{if(typeof window>"u"){Ie(ts);return}Ve!==null&&window.cancelAnimationFrame(Ve),Ve=window.requestAnimationFrame(()=>{Ie(ts)})},$t=new ResizeObserver(ts=>{const es=ts[0];es&&yt(es.contentRect.height)});return $t.observe($e),yt($e.getBoundingClientRect().height),()=>{Ve!==null&&(window.cancelAnimationFrame(Ve),Ve=null),$t.disconnect()}},[Dt,T,Ke,Ct]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:P("group w-full",Ee?"pt-2":"pt-0",T?"pb-2":qe?"pb-0":"pb-2"),"data-message-id":s.info.id,ref:m,style:a?{visibility:"hidden"}:void 0,children:e.jsx("div",{className:"chat-column",children:T?e.jsx(gs,{children:e.jsx("div",{className:"flex justify-end",children:e.jsx("div",{className:"max-w-[85%] rounded-xl rounded-br-xs bg-primary/10 dark:bg-primary/8 px-3.5 pt-2.5 pb-1.5",children:e.jsx(ld,{messageId:s.info.id,parts:he,isUser:T,isMessageCompleted:pe,messageFinish:be,syntaxTheme:H,isMobile:l,hasTouchInput:d,copiedCode:S,onCopyCode:Ye,expandedTools:k,onToggleTool:st,onShowPopup:Oe,streamPhase:Re,allowAnimation:Dt,onContentChange:n,shouldShowHeader:!1,hasTextContent:at,onCopyMessage:jt,copiedMessage:M,showReasoningTraces:N,onAuxiliaryContentComplete:ge,agentMention:X,onRevert:He,onFork:T?Ge:void 0,errorMessage:Pe})})})}):e.jsxs("div",{children:[Ee&&e.jsx(aw,{isUser:T,providerID:$,agentName:F,modelName:L,variant:Et,isDarkTheme:ae}),e.jsx(ld,{messageId:s.info.id,parts:he,isUser:T,isMessageCompleted:pe,messageFinish:be,syntaxTheme:H,isMobile:l,hasTouchInput:d,copiedCode:S,onCopyCode:Ye,expandedTools:K,onToggleTool:st,onShowPopup:Oe,streamPhase:Re,allowAnimation:Dt,onContentChange:n,shouldShowHeader:Ee,hasTextContent:at,onCopyMessage:jt,copiedMessage:M,onAuxiliaryContentComplete:ge,showReasoningTraces:N,agentMention:X,turnGroupingContext:i,errorMessage:Pe})]})})}),e.jsx(c.Suspense,{fallback:null,children:e.jsx(ev,{popup:E,onOpenChange:Be,syntaxTheme:H,isMobile:l})})]})},rv=c.memo(sv),nv=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Wm(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:P("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:tn(t||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),ov=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
97
+ `),o=tn(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},av=s=>{const r="h-3 w-3",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(mr,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(iu,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Er,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(gi,{className:r}):e.jsx(ia,{className:r})},iv=s=>{const r=s.toLowerCase();return r==="edit"||r==="multiedit"||r==="str_replace"||r==="str_replace_based_edit_tool"?"edit":r==="write"||r==="create"||r==="file_write"?"write":r==="bash"||r==="shell"||r==="cmd"||r==="terminal"||r==="shell_command"?"bash":r==="webfetch"||r==="fetch"||r==="curl"||r==="wget"?"webfetch":s},lv=({permission:s,onResponse:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(!1),{respondToPermission:i}=me(),{currentTheme:l}=sn(),d=c.useMemo(()=>Fm(l),[l]),u=async b=>{n(!0);try{await i(s.sessionID,s.id,b),a(!0),r?.(b)}catch{}finally{n(!1)}};if(o)return null;const m=s.permission||"unknown",f=m.toLowerCase(),p=(b,x="")=>{const v=s.metadata[b];return typeof v=="string"?v:typeof v=="number"?String(v):x},g=b=>{const x=s.metadata[b];return typeof x=="number"?x:void 0},w=b=>!!s.metadata[b],h=iv(m),j=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const v=p("command")||p("cmd")||p("script"),N=p("description"),y=p("cwd")||p("working_directory")||p("directory")||p("path"),S=g("timeout");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),y&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Working Directory:"})," ",e.jsx("code",{className:"px-1 py-0.5 bg-muted/30 rounded",children:y})]}),S&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",S,"ms"]}),v&&e.jsx("div",{children:e.jsx(hr,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:v})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const v=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),y=w("replace_all")||w("replaceAll");return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:e.jsx("span",{className:"font-semibold",children:"⚠️ Replace All Occurrences"})}),N&&e.jsx(dt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(nv,{diff:N,syntaxTheme:d,filePath:v})})]})}if(f==="write"||f==="create"||f==="file_write"){const v=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(dt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(ov,{content:N,syntaxTheme:d,filePath:v})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const v=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",y=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,S=p("body")||p("data")||p("payload"),D=g("timeout"),M=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[v&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Request:"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"typography-meta font-semibold px-1.5 py-0.5 bg-primary/20 text-primary rounded",children:N}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded flex-1 break-all",children:v})]})]}),y&&Object.keys(y).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(dt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(hr,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(y,null,2)})})]}),S&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(dt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(hr,{language:typeof S=="object"?"json":"text",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:typeof S=="object"?JSON.stringify(S,null,2):String(S)})})]}),(D||M)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&M&&e.jsx("span",{children:" • "}),M&&e.jsxs("span",{children:["Response format: ",M]})]})]})}const b=p("command")||p("content")||p("action")||p("operation"),x=p("description");return e.jsxs(e.Fragment,{children:[x&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:x}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(dt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:String(b)})})]}),Object.keys(s.metadata).length>0&&!b&&!x&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(dt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx("pre",{className:"typography-meta font-mono px-2 py-1 bg-muted/30 rounded whitespace-pre-wrap break-all",children:JSON.stringify(s.metadata,null,2)})})]})]})};return e.jsx("div",{className:"group w-full pt-0 pb-2",children:e.jsx("div",{className:"chat-column",children:e.jsxs("div",{className:"-mt-1 border border-border/30 rounded-xl bg-muted/10",children:[e.jsx("div",{className:"px-2 py-1.5 border-b border-border/20 bg-muted/5",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yn,{className:"h-3.5 w-3.5 text-yellow-500"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Permission Required"})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[av(m),e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:h})]})]})}),e.jsxs("div",{className:"px-2 py-2",children:[s.patterns.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Patterns:"}),e.jsx("code",{className:"typography-meta px-2 py-1 bg-muted/30 rounded block break-all",children:s.patterns.join(", ")})]}),j()]}),e.jsxs("div",{className:"px-2 pb-1.5 pt-1 flex items-center gap-1.5 border-t border-border/20",children:[e.jsxs("button",{onClick:()=>u("once"),disabled:t,className:P("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-success) / 0.1)",color:"var(--status-success)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(At,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:P("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),(()=>{const b=s.always||s.metadata.always||[];if(b.length===0)return"Always Allow";const v=b.slice(0,2).join(", ");return b.length>2?`Always: ${v}...`:`Always: ${v}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:P("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--muted) / 0.5)",color:"var(--muted-foreground)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:P("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-all","disabled:opacity-50 disabled:cursor-not-allowed"),style:{backgroundColor:"rgb(var(--status-error) / 0.1)",color:"var(--status-error)"},onMouseEnter:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:b=>{b.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.1)"},children:[e.jsx(Ht,{className:"h-3 w-3"}),"Deny"]}),t&&e.jsx("div",{className:"ml-auto typography-meta text-muted-foreground",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})})]})]})})})},cv=new Set(["task"]),dd=s=>typeof s=="string"&&cv.has(s.toLowerCase()),dv=s=>{const r=[];let t=null;return s.forEach(n=>{const o=n.info.clientRole??n.info.role;o==="user"?(t={turnId:n.info.id,userMessage:n,assistantMessages:[]},r.push(t)):o==="assistant"&&t&&t.assistantMessages.push(n)}),r},uv=s=>{for(const r of s.assistantMessages)if(r.info.finish==="stop"){const n=r.parts.find(o=>o.type==="text");if(n){const o=n.text??n.content;if(typeof o=="string"&&o.trim().length>0)return o}}},mv=s=>{const r=uv(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let b=0,x=0,v=0;o.forEach(N=>{if(!N)return;const y=typeof N.additions=="number"?N.additions:0,S=typeof N.deletions=="number"?N.deletions:0;(y!==0||S!==0)&&(v+=1),b+=y,x+=S}),v>0&&(t={additions:b,deletions:x,files:v})}let a=!1,i=!1;s.assistantMessages.forEach(b=>{b.parts.forEach(x=>{x.type==="tool"?a=!0:x.type==="reasoning"&&(i=!0)})});const l=[];let d=0;s.assistantMessages.forEach(b=>{const x=b.info.id;b.info.finish,b.parts.forEach(v=>{const N=typeof v.id=="string"&&v.id.trim().length>0?v.id:`${x}-activity-${d++}`;if(v.type==="tool"){const S=v.state?.time,D=typeof S?.end=="number"?S.end:void 0;l.push({id:N,turnId:s.turnId,messageId:x,kind:"tool",part:v,endedAt:D});return}if(v.type==="reasoning"){const y=v.text??v.content;if(typeof y!="string"||y.trim().length===0)return;const S=v.time,D=typeof S?.end=="number"?S.end:void 0;l.push({id:N,turnId:s.turnId,messageId:x,kind:"reasoning",part:v,endedAt:D});return}})});const u=[],m=new WeakMap;l.forEach(b=>{m.set(b.part,b)});const f=new Map,p=[],g=new Map;let w=null;s.assistantMessages.forEach(b=>{const x=b.info.id;b.parts.forEach(v=>{if(v.type==="tool"){const S=v.tool;if(dd(S)){const D=typeof v.id=="string"&&v.id.trim().length>0?v.id:`${x}-task-${p.length+1}`;f.has(D)||(f.set(D,x),p.push(D)),w=D;return}}const N=m.get(v);if(!N)return;if(N.kind==="tool"){const S=N.part.tool;if(dd(S))return}const y=g.get(w)??[];y.push(N),g.set(w,y)})});const h=b=>{if(b.length===0)return;const x=new Map;b.forEach(y=>{x.set(y.messageId,(x.get(y.messageId)??0)+1)});let v,N=0;for(const y of s.assistantMessages){const S=x.get(y.info.id)??0;if(S>0&&!v&&(v=y.info.id),N+=S,N>=2)return y.info.id}return v};return[null,...p].forEach(b=>{const x=g.get(b)??[];if(x.length===0)return;const v=b===null?h(x):f.get(b);v&&u.push({id:`${s.turnId}:${v}:${b??"start"}`,anchorMessageId:v,afterToolPartId:b,parts:x})}),{activityParts:l,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},fv=s=>{const{isWorking:r}=wl(),t=c.useMemo(()=>dv(s),[s]),n=c.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.userMessage.info.id,j),j.assistantMessages.forEach(b=>{h.set(b.info.id,j)})}),h},[t]),a=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.turnId,mv(j))}),h},[t]),[i,l]=c.useState(()=>new Map),d=_e(h=>h.toolCallExpansion),u=d==="activity"||d==="detailed";c.useEffect(()=>{l(new Map)},[d]);const m=c.useCallback(h=>{const j=i.get(h);return j||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=c.useCallback(h=>{l(j=>{const b=new Map(j),x=b.get(h)??{isExpanded:u,previewedPartIds:new Set};return b.set(h,{...x,isExpanded:!x.isExpanded}),b})},[u]),p=c.useCallback((h,j)=>{j.length!==0&&l(b=>{const x=new Map(b),v=x.get(h)??{isExpanded:u,previewedPartIds:new Set},N=new Set(v.previewedPartIds);return j.forEach(y=>{y&&y.trim().length>0&&N.add(y)}),x.set(h,{...v,previewedPartIds:N}),x})},[u]),g=c.useCallback(h=>o.get(h),[o]),w=c.useCallback(h=>{const j=o.get(h);if(!j||!j.assistantMessages.some(B=>B.info.id===h))return;const x=a.get(j.turnId),v=x?.activityParts??[],N=x?.activityGroupSegments??[],y=!!x?.hasTools,S=!!x?.hasReasoning,D=x?.summaryBody,M=x?.diffStats,C=j.assistantMessages[0]?.info.id,k=h===C,A=j.assistantMessages[j.assistantMessages.length-1]?.info.id,E=h===A,R=C,V=m(j.turnId),T=r&&n===j.turnId;return{turnId:j.turnId,isFirstAssistantInTurn:k,isLastAssistantInTurn:E,summaryBody:D,activityParts:v,activityGroupSegments:N,headerMessageId:R,hasTools:y,hasReasoning:S,diffStats:M,isWorking:T,isGroupExpanded:V.isExpanded,previewedPartIds:V.previewedPartIds,toggleGroup:()=>f(j.turnId),markPartsPreviewed:B=>p(j.turnId,B)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:g,getContextForMessage:w}},pv=({messages:s,permissions:r,onMessageContentChange:t,getAnimationHandlers:n,hasMoreAbove:o,isLoadingOlder:a,onLoadOlder:i,scrollToBottom:l,pendingAnchorId:d})=>{c.useEffect(()=>{r.length!==0&&t("permission")},[r,t]);const u=c.useMemo(()=>{const f=new Set;return s.filter(p=>{const g=p.info?.id;if(typeof g=="string"){if(f.has(g))return!1;f.add(g)}return!0}).map(p=>({...p,parts:Vb(p.parts)}))},[s]),{getContextForMessage:m}=fv(u);return e.jsxs("div",{children:[o&&e.jsx("div",{className:"flex justify-center py-3",children:a?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:i,className:"text-xs uppercase tracking-wide text-muted-foreground/80 hover:text-foreground",children:"Load older messages"})}),e.jsx("div",{className:"flex flex-col",children:u.map((f,p)=>e.jsx(rv,{message:f,previousMessage:p>0?u[p-1]:void 0,nextMessage:p<u.length-1?u[p+1]:void 0,onContentChange:t,animationHandlers:n(f.info.id),scrollToBottom:l,isPendingAnchor:d===f.info.id,turnGroupingContext:m(f.info.id)},f.info.id))}),r.length>0&&e.jsx("div",{children:r.map(f=>e.jsx(lv,{permission:f},f.id))})]})},hv=c.memo(pv);function gv(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const Gm=c.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:l,children:d,...u},m)=>{const f=c.useRef(null),p=c.useRef("none"),g=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const w=c.useMemo(()=>{const x={...i};return x["--scroll-shadow-size"]=`${t}px`,x},[t,i]),h=c.useCallback((x,v,N,y,S)=>{const D=`${y}${S.charAt(0).toUpperCase()}${S.slice(1)}Scroll`;v&&N?(x.dataset[D]="true",x.removeAttribute(`data-${y}-scroll`),x.removeAttribute(`data-${S}-scroll`)):(x.dataset[`${y}Scroll`]=String(v),x.dataset[`${S}Scroll`]=String(N),x.removeAttribute(`data-${y}-${S}-scroll`))},[]),j=c.useCallback(x=>{["top","bottom","top-bottom","left","right","left-right"].forEach(v=>{x.removeAttribute(`data-${v}-scroll`)})},[]),b=c.useCallback(()=>{const x=f.current;if(!x)return;if(!n){j(x);return}const v=s==="vertical"?x.scrollTop>r:x.scrollLeft>r;let N=s==="vertical"?x.scrollTop+x.clientHeight+r<x.scrollHeight:x.scrollLeft+x.clientWidth+r<x.scrollWidth;o&&s==="vertical"&&(N=!1),h(x,v,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const y=v&&N?"both":v?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";y!==p.current&&(p.current=y,a?.(y))},[j,o,n,r,a,s,h]);return c.useEffect(()=>{const x=f.current;if(!x)return;const v=()=>b(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,y=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),x.addEventListener("scroll",v,{passive:!0}),N?.observe(x),y?.observe(x,{childList:!0,subtree:!0,characterData:!0}),()=>{x.removeEventListener("scroll",v),N?.disconnect(),y?.disconnect()}},[b]),e.jsx("div",{...u,ref:gv(f,m),className:l,"data-orientation":s,"data-scroll-shadow":g??!0,style:w,children:d})});Gm.displayName="ScrollShadow";const xv=160,yv=({containerRef:s})=>{const[r,t]=c.useState(!0),n=c.useRef(!0),o=c.useRef(!1),a=c.useRef(null),i=c.useRef(null),l=c.useRef(0),d=c.useRef(0),u=c.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=c.useCallback(v=>{const N=s.current;if(!N){u();return}i.current===null&&(i.current=v);const y=Math.min(1,(v-i.current)/xv),S=1-Math.pow(1-y,3),D=l.current,M=d.current,C=D+(M-D)*S;if(N.scrollTop=C,y<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=M,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=c.useCallback((v,N)=>{const y=s.current;if(!y)return;const S=Math.max(0,v),D=N?.instant??!1;if(o.current=!1,typeof window>"u"||D){u(),y.scrollTop=S;const C=S<=1;n.current!==C&&(n.current=C,t(C));return}if(u(),Math.abs(S-y.scrollTop)<=.5){y.scrollTop=S;const C=S<=1;n.current!==C&&(n.current=C,t(C));return}l.current=y.scrollTop,d.current=S,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=c.useCallback(()=>{o.current=!0},[]),g=c.useCallback(()=>{o.current=!0},[]),w=c.useCallback(()=>o.current,[]),h=c.useCallback(()=>s.current?.scrollTop??0,[s]),j=c.useCallback(()=>s.current?.scrollHeight??0,[s]),b=c.useCallback(()=>s.current?.clientHeight??0,[s]),x=c.useCallback(()=>{const v=s.current;if(!v)return;o.current&&a.current!==null&&u();const N=v.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return c.useEffect(()=>{const v=s.current;if(v)return v.addEventListener("wheel",g,{passive:!0}),v.addEventListener("touchstart",g,{passive:!0}),()=>{v.removeEventListener("wheel",g),v.removeEventListener("touchstart",g)}},[s,g]),c.useEffect(()=>()=>{u()},[u]),c.useMemo(()=>({handleScroll:x,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:w,getScrollTop:h,getScrollHeight:j,getClientHeight:b}),[x,f,p,r,w,h,j,b])},ud=typeof window<"u"?c.useLayoutEffect:c.useEffect,md=50,fd=40,bv=.2,wv=.1,vv=150,$s=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},jv=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},Sv=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:l})=>{const d=c.useRef(null),u=yv({containerRef:d}),[m,f]=c.useState(null),[p,g]=c.useState(0),[w,h]=c.useState(!1),[j,b]=c.useState(null),x=c.useRef(null),v=c.useRef(null),N=c.useRef(r.length),y=c.useRef(r.length>0?$s(r[0]):null),S=c.useRef(r.length>0?$s(r[r.length-1]):null),D=c.useRef(0),M=c.useRef(0),C=c.useRef(void 0),k=c.useRef(null),A=c.useRef(!1),E=c.useRef(!1),R=c.useRef(null),V=s?l?.get(s)??"idle":"idle",T=c.useCallback(I=>{const W=Math.max(0,I);D.current!==W&&(D.current=W,g(W))},[]),B=c.useCallback(()=>{const I=d.current;I&&(M.current=I.clientHeight)},[]),re=c.useCallback(()=>{if(!m)return null;const I=d.current;return I?I.querySelector(`[data-message-id="${m}"]`):null},[m]),Y=c.useCallback(()=>{const I=d.current,W=D.current;if(!I||W<=0)return!0;const F=I.scrollHeight-W;return I.scrollTop+I.clientHeight<F},[]),_=c.useCallback((I,W)=>{const F=I.offsetHeight,$=I.offsetTop;if(F>W*bv){const J=W*wv;return $+F-J}else return $-md},[]),q=c.useCallback(()=>{const I=d.current;if(!I||!k.current)return;const W=re();if(!W)return;const F=I.clientHeight,$=I.scrollHeight,J=_(W,F)+F,pe=D.current,be=$-pe;if(!A.current&&be<J){const he=J-be;he>pe&&(T(he),s&&k.current&&n(s,k.current,he))}},[_,s,re,n,T]),O=c.useCallback(()=>{const I=d.current;if(!I){h(!1);return}if(j){h(!1);return}if(!(I.scrollHeight>I.clientHeight)){h(!1);return}const F=I.scrollHeight-I.scrollTop-I.clientHeight,$=D.current;if($>0){const L=I.scrollHeight-$,J=I.scrollTop+I.clientHeight;h(J<L)}else h(F>fd)},[j]),z=c.useCallback(I=>{const W=d.current;if(!W)return;const F=W.scrollHeight-W.scrollTop-W.clientHeight;if(E.current&&V==="idle"&&!a&&!I?.force&&F>fd)return;I?.force&&(E.current=!1);const L=W.scrollHeight-W.clientHeight;u.scrollToPosition(Math.max(0,L),I)},[V,a,u]),U=c.useCallback(I=>{if(x.current===I)return;x.current=I,b(I);const W=d.current;if(!W){b(null);return}const F=W.scrollHeight,$=D.current,L=F-$,J=M.current>0?M.current:W.clientHeight,be=L-md,he=be+J;let Ae=0;L<he&&(Ae=he-L),Ae!==$&&T(Ae),s&&n(s,I,Ae),A.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(be,{instant:!0}),window.requestAnimationFrame(()=>{b(null)})})},[s,u,n,T]),ne=c.useCallback(I=>{const W=d.current;if(!W||!s)return;I?.isTrusted&&(E.current=!0),u.handleScroll(),O(),V==="idle"&&D.current>0&&Y()&&(T(0),k.current=null,f(null),n(s,null,0));const{scrollTop:F,scrollHeight:$,clientHeight:L}=W,J=(F+L/2)/Math.max($,1),pe=Math.floor(J*r.length);t(s,pe)},[s,V,Y,u,r.length,n,O,T,t]);c.useEffect(()=>{const I=d.current;if(I)return I.addEventListener("scroll",ne,{passive:!0}),()=>{I.removeEventListener("scroll",ne)}},[ne]),ud(()=>{if(typeof window>"u")return;B();const I=()=>{C.current!==void 0&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{B()},vv)};return window.addEventListener("resize",I),()=>{window.removeEventListener("resize",I),C.current!==void 0&&window.clearTimeout(C.current)}},[B]),c.useEffect(()=>{if(s&&s!==v.current){v.current=s,Cr.getInstance().recordSessionStart(s),N.current=r.length,y.current=r.length>0?$s(r[0]):null,S.current=r.length>0?$s(r[r.length-1]):null;const I=o(s);V!=="idle"&&I&&I.anchorId?(k.current=I.anchorId,x.current=I.anchorId,A.current=!0,f(I.anchorId),D.current=I.spacerHeight,g(I.spacerHeight),window.requestAnimationFrame(()=>{const F=d.current;if(!F)return;const $=F.querySelector(`[data-message-id="${I.anchorId}"]`);if($){const L=F.clientHeight,J=_($,L);u.scrollToPosition(J,{instant:!0})}})):(x.current=null,k.current=null,A.current=!1,f(null),D.current=0,g(0),window.requestAnimationFrame(()=>{z({instant:!0,force:!0})})),b(null),h(!1),E.current=!1,R.current=null}},[V,s,z,r.length,o]),ud(()=>{if(a){N.current=r.length,y.current=r.length>0?$s(r[0]):null,S.current=r.length>0?$s(r[r.length-1]):null;return}if(v.current!==s)return;const I=N.current,W=r.length;if(W>I&&I>0){const F=y.current,$=$s(r[0]),L=$s(r[W-1]),J=S.current,pe=F!==null&&$!==F,be=J!==null&&L!==J,he=pe&&!be,Ae=be&&!pe;if(he){k.current=null,A.current=!1,f(null),T(0),N.current=W,y.current=$,S.current=L;return}if(Ae){const Te=r.slice(I,W).find(jv);if(Te){const K=$s(Te);K&&(k.current=K,f(K),U(K))}else q()}}N.current=W,y.current=r.length>0?$s(r[0]):null,S.current=r.length>0?$s(r[r.length-1]):null},[s,a,q,U,r]),c.useEffect(()=>{const I=d.current;if(!I||typeof ResizeObserver>"u")return;const W=new ResizeObserver(()=>{q(),O()});return W.observe(I),()=>{W.disconnect()}},[q,O]),c.useEffect(()=>{if(typeof window>"u"){O();return}const I=window.requestAnimationFrame(()=>{O()});return()=>{window.cancelAnimationFrame(I)}},[s,r.length,O]),c.useEffect(()=>{m&&(q(),O())},[m,q,O]),c.useEffect(()=>{const I=R.current;R.current=V,I!==null&&I!=="idle"&&V==="idle"&&D.current>0&&Y()&&k.current!==null&&(T(0),k.current=null,A.current=!1,f(null),s&&n(s,null,0))},[V,s,Y,n,T]),c.useEffect(()=>{O()},[p,O]);const oe=c.useRef(new Map),Q=c.useCallback(()=>{q(),O()},[q,O]),de=c.useCallback(I=>{const W=oe.current.get(I);if(W)return W;const F={onChunk:()=>{q()},onComplete:()=>{q()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{q()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return oe.current.set(I,F),F},[q]);return{scrollRef:d,handleMessageContentChange:Q,getAnimationHandlers:de,showScrollButton:w,scrollToBottom:z,spacerHeight:p,pendingAnchorId:j,hasActiveAnchor:m!==null}};function kv(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),i=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:i<7?`${i}d ago`:new Date(s).toLocaleDateString()}const Nv=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=me(h=>h.currentSessionId),o=ft(h=>n?h.messages.get(n)||[]:[]),a=me(h=>h.revertToMessage),i=me(h=>h.forkFromMessage),l=me(h=>h.loadSessions),[d,u]=c.useState(null),[m,f]=c.useState(""),p=c.useMemo(()=>o.filter(j=>j.info.role==="user").reverse(),[o]),g=c.useMemo(()=>{if(!m.trim())return p;const h=m.toLowerCase();return p.filter(j=>pd(j.parts).toLowerCase().includes(h))},[p,m]),w=async h=>{if(n){u(h);try{await i(n,h),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(xs,{children:[e.jsxs(ys,{className:"flex items-center gap-2",children:[e.jsx(or,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pt,{placeholder:"Search messages...",value:m,onChange:h=>f(h.target.value),className:"pl-9 w-full"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto",children:g.length===0?e.jsx("div",{className:"text-center text-muted-foreground py-8",children:m?"No messages found":"No messages in this session yet"}):g.map(h=>{const j=pd(h.parts),b=h.info.time.created,x=kv(b),v=p.length-p.indexOf(h);return e.jsxs("div",{className:"group flex items-center gap-2 py-1.5 hover:bg-muted/30 rounded transition-colors cursor-pointer",onClick:()=>{t?.(h.info.id),r(!1)},children:[e.jsxs("span",{className:"typography-meta text-muted-foreground w-5 text-right flex-shrink-0",children:[v,"."]}),e.jsxs("p",{className:"flex-1 min-w-0 typography-small text-foreground truncate ml-0.5",children:[j||"[No text content]",j&&j.length>=80&&"…"]}),e.jsxs("div",{className:"flex-shrink-0 h-5 flex items-center mr-2",children:[e.jsx("span",{className:"typography-meta text-muted-foreground whitespace-nowrap group-hover:hidden",children:x}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors",onClick:async N=>{N.stopPropagation(),await a(n,h.info.id),r(!1)},children:e.jsx(Kn,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:N=>{N.stopPropagation(),w(h.info.id)},disabled:d===h.info.id,children:d===h.info.id?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx(Ot,{className:"h-4 w-4"})})}),e.jsx(tt,{sideOffset:6,children:"Fork from here"})]})]})]})]},h.info.id)})}),e.jsxs("div",{className:"mt-4 p-3 bg-muted/30 rounded-lg",children:[e.jsx("p",{className:"typography-meta text-muted-foreground font-medium mb-2",children:"Actions"}),e.jsxs("div",{className:"flex flex-col gap-1.5 typography-meta text-muted-foreground",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{children:"Click on a message to scroll to it in the conversation"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Kn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Undo to this point (message text will populate input)"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ot,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function pd(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const Km=()=>{const{currentSessionId:s,messages:r,permissions:t,streamingMessageIds:n,isLoading:o,loadMessages:a,loadMoreMessages:i,updateViewportAnchor:l,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,sessionMemoryState:m,openNewSessionDraft:f,isSyncing:p,messageStreamStates:g,trimToViewportWindow:w,sessionActivityPhase:h,newSessionDraft:j}=me(),{isTimelineDialogOpen:b,setTimelineDialogOpen:x}=_e(),v=c.useMemo(()=>s?n.get(s)??null:null,[s,n]),{isMobile:N}=Ft(),y=!!j?.open;c.useEffect(()=>{!s&&!y&&f()},[s,y,f]);const S=c.useMemo(()=>s?r.get(s)||[]:[],[s,r]),D=c.useMemo(()=>s?t.get(s)||[]:[],[s,t]),{scrollRef:M,handleMessageContentChange:C,getAnimationHandlers:k,showScrollButton:A,scrollToBottom:E,spacerHeight:R,pendingAnchorId:V,hasActiveAnchor:T}=Sv({currentSessionId:s,sessionMessages:S,updateViewportAnchor:l,updateActiveTurnAnchor:d,getActiveTurnAnchor:u,isSyncing:p,isMobile:N,sessionActivityPhase:h}),re=!!c.useMemo(()=>s?m.get(s)??null:null,[s,m])?.hasMoreAbove,[Y,_]=c.useState(!1);c.useEffect(()=>{_(!1)},[s]);const q=c.useRef(null);c.useLayoutEffect(()=>{if(!(!s||s===q.current)&&(q.current=s,!T)){const U=M.current;U&&(U.scrollTop=U.scrollHeight-U.clientHeight)}},[s,M,T]);const O=c.useCallback(async()=>{if(!s||Y)return;const U=M.current,ne=U?.scrollHeight??null,oe=U?.scrollTop??null;_(!0);try{if(await i(s,"up"),U&&ne!==null&&oe!==null){const Q=U.scrollHeight-ne;U.scrollTop=oe+Q}}finally{_(!1)}},[s,Y,i,M]),z=c.useCallback(U=>{const ne=M.current;if(!ne)return;const oe=ne.querySelector(`[data-message-id="${U}"]`);if(oe){const Q=ne.getBoundingClientRect(),W=oe.getBoundingClientRect().top-Q.top+ne.scrollTop-50;ne.scrollTo({top:W,behavior:"smooth"})}},[M]);return c.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await a(s)}finally{typeof window>"u"?E():window.requestAnimationFrame(()=>{E()})}})()},[s,a,r,E]),!s&&!y?e.jsx("div",{className:"flex flex-col h-full bg-background",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(Xa,{})}):!s&&y?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Xa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(vo,{scrollToBottom:E})})]}):s?o&&S.length===0&&!v&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-background",children:e.jsx("div",{className:"chat-column space-y-4",children:[1,2,3].map(ne=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(Ya,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ya,{className:"h-4 w-24"}),e.jsx(Ya,{className:"h-20 w-full"})]})]},ne))})}),e.jsx(vo,{scrollToBottom:E})]}):S.length===0&&!v?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(Xa,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(vo,{scrollToBottom:E})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:N?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"relative flex-1 min-h-0",children:e.jsxs("div",{className:"absolute inset-0",children:[e.jsx(Gm,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:M,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!V,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(hv,{messages:S,permissions:D,onMessageContentChange:C,getAnimationHandlers:k,hasMoreAbove:re,isLoadingOlder:Y,onLoadOlder:O,scrollToBottom:E,pendingAnchorId:V}),R>0&&T&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:R},"aria-hidden":"true"})]})}),e.jsx(ol,{containerRef:M})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[A&&S.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>E({force:!0}),className:"rounded-full h-8 w-8 p-0 shadow-none bg-background/95 hover:bg-accent","aria-label":"Scroll to bottom",children:e.jsx(Mn,{className:"h-4 w-4"})})}),e.jsx(vo,{scrollToBottom:E})]}),e.jsx(Nv,{open:b,onOpenChange:x,onScrollToMessage:z})]}):null};class qm extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(pl,{className:"w-full max-w-md",children:[e.jsx(im,{className:"text-center",children:e.jsxs(lm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(ch,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(cm,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data."}),this.props.sessionId&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Session: ",this.props.sessionId]}),this.state.error&&e.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[e.jsx("summary",{className:"cursor-pointer hover:bg-muted/80",children:"Error details"}),e.jsx("pre",{className:"mt-2 overflow-x-auto",children:this.state.error.toString()})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Es,{className:"h-4 w-4 mr-2"}),"Reset Chat"]})}),e.jsx("div",{className:"text-xs text-muted-foreground text-center",children:"If the problem persists, try refreshing the page."})]})]})}):this.props.children}}const Ri=()=>{const s=me(r=>r.currentSessionId);return e.jsx(qm,{sessionId:s||void 0,children:e.jsx(Km,{})})},hd=12,Cv=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],Mv=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=Cv,onComplete:a})=>{const i=Ce.useRef(!1);Ce.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const l=Ce.useMemo(()=>Array.from({length:hd},(d,u)=>{const m=Math.PI*2*u/hd;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:P("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:l.map((m,f)=>{const p=m.x*d.radius,g=m.y*d.radius,w={"--translate-x":`${p}px`,"--translate-y":`${g}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:w},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},Dv=({durationMs:s=3400}={})=>{const[r,t]=Ce.useState({isActive:!1,cycle:0}),n=Ce.useRef(null),o=Ce.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ce.useCallback(()=>{o(),t(l=>l.isActive?{...l,isActive:!1}:l)},[o]),i=Ce.useCallback(()=>{o(),t(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{t(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},s)},[o,s]);return Ce.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},Ym=c.createContext(void 0),gd=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=Dv(),a=c.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(Ym.Provider,{value:a,children:[s,e.jsx(Mv,{isActive:r,burstKey:t})]})},Av=()=>{const s=c.useContext(Ym);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},ya=Bt()(Xt(Ts((s,r)=>({selectedProfileId:null,profiles:[],globalIdentity:null,isLoading:!1,setSelectedProfile:t=>{s({selectedProfileId:t})},loadProfiles:async()=>{s({isLoading:!0});const t=r().profiles;try{const n=await lx();return s({profiles:n,isLoading:!1}),!0}catch(n){return console.error("Failed to load git identity profiles:",n),s({profiles:t,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const t=await mx("");if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,sshKey:t.sshCommand?t.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"house"};s({globalIdentity:n})}else s({globalIdentity:null});return!0}catch(t){return console.error("Failed to load global git identity:",t),s({globalIdentity:null}),!1}},createProfile:async t=>{try{const n={...t,id:t.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:t.color||"keyword",icon:t.icon||"branch"};return await cx(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=r().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await dx(t,a),await r().loadProfiles(),!0}catch(o){return console.error("Failed to update git identity profile:",o),!1}},deleteProfile:async t=>{try{return await ux(t),r().selectedProfileId===t&&s({selectedProfileId:null}),await r().loadProfiles(),!0}catch(n){return console.error("Failed to delete git identity profile:",n),!1}},getProfileById:t=>{const{profiles:n,globalIdentity:o}=r();return t==="global"?o||void 0:n.find(a=>a.id===t)}}),{name:"git-identities-store",storage:Fs(()=>us()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=ya);const Ev=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Iv=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[l,d]=c.useState(!1),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(""),[h,j]=c.useState(!1),b=c.useRef(null),x=c.useMemo(()=>Ev(g),[g]),v=c.useMemo(()=>{const C=u.toLowerCase();return C?r.filter(k=>k.toLowerCase().includes(C)):r},[u,r]),N=c.useMemo(()=>{const C=u.toLowerCase();return C?t.filter(k=>k.toLowerCase().includes(C)):t},[u,t]),y=C=>{if(C===s){d(!1);return}o(C),d(!1),m("")},S=()=>{p(!0),setTimeout(()=>b.current?.focus(),50)},D=async()=>{if(!(!x||h)){j(!0);try{await a(x),w(""),p(!1),d(!1)}finally{j(!1)}}},M=()=>{w(""),p(!1)};return c.useEffect(()=>{l||(m(""),p(!1),w(""))},[l]),e.jsxs(Ut,{open:l,onOpenChange:d,children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx(Ot,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Mt,{className:"size-4 opacity-60"})]})})}),e.jsxs(tt,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Gt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(um,{className:"h-full min-h-0",children:[e.jsx(mm,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(fm,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(pm,{children:"No branches found."}),e.jsx(gn,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:b,placeholder:"New branch name",value:g,onChange:C=>w(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),D()):C.key==="Escape"&&(C.preventDefault(),M())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:D,disabled:!x||h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:h?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Kt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:M,disabled:h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Ht,{className:"size-4"})})]}):e.jsxs(ss,{onSelect:S,children:[e.jsx(Kt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(Qo,{}),e.jsxs(gn,{heading:"Local branches",children:[v.map(C=>e.jsxs(ss,{onSelect:()=>y(C),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:C}),(n?.[C]?.ahead||n?.[C]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[C].ahead||0," ahead ·"," ",n[C].behind||0," behind"]})]}),s===C&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${C}`)),v.length===0&&e.jsx(ss,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(Qo,{}),e.jsxs(gn,{heading:"Remote branches",children:[N.map(C=>e.jsx(ss,{onSelect:()=>y(C),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:C})},`remote-${C}`)),N.length===0&&e.jsx(ss,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Pv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Tv=({currentBranch:s,onRename:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(s||""),[i,l]=c.useState(!1),d=c.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const g=Pv(o);if(g===s){n(!1);return}l(!0);try{await r(s,g),n(!1),a("")}finally{l(!1)}},f=()=>{n(!1),a("")},p=g=>{g.key==="Enter"?(g.preventDefault(),m()):g.key==="Escape"&&(g.preventDefault(),f())};return t?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:g=>{g.preventDefault(),m()},children:[e.jsx(Ot,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:g=>a(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:i?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(At,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Ht,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx(Ot,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate typography-ui-label font-normal text-foreground",children:s||"Detached HEAD"})]}),r&&s&&e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(la,{className:"size-4"})})]})},Fv=({syncAction:s,onFetch:r,onPull:t,onPush:n,disabled:o})=>{const a=o||s!==null;return e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Dr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(tt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Mn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(tt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(to,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(tt,{sideOffset:8,children:"Push changes"})]})]})},Rv={branch:Ot,briefcase:Ki,house:Gi,graduation:Vi,code:nr,heart:cu,user:Ps},_v={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Xm(s){return s&&_v[s]||"var(--primary)"}const xd=({icon:s,className:r,colorToken:t})=>{const n=Rv[s??"branch"]??Ps;return e.jsx(n,{className:r,style:{color:Xm(t)}})},Ov=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Ut,{children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:Xm(s?.color)},disabled:o,children:[n?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(xd,{icon:s?.icon,colorToken:s?.color,className:"size-4"}),e.jsx("span",{className:"max-w-[120px] truncate hidden sm:inline",children:s?.name||"No identity"}),e.jsx(Mt,{className:"size-4 opacity-60"})]})})}),e.jsxs(tt,{sideOffset:8,className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label text-foreground",children:s?.userName||"Unknown user"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:s?.userEmail||"No email configured"})]})]}),e.jsx(Gt,{align:"end",className:"w-64",children:r.length===0?e.jsx("div",{className:"px-2 py-1.5",children:e.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):r.map(a=>e.jsx(vt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(xd,{icon:a.icon,colorToken:a.color,className:"size-4"}),e.jsxs("span",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:a.name}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:a.userEmail})]})]})},a.id))})]})},$v=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:l,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:g,isApplyingIdentity:w,isWorktreeMode:h})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[h?e.jsx(Tv,{currentBranch:s.current,onRename:m}):e.jsx(Iv,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(rt,{delayDuration:800,children:[e.jsx(nt,{asChild:!0,children:e.jsxs("div",{className:"flex items-center gap-2 px-1.5 typography-meta text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(to,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.ahead})]}),!!s.tracking&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Mn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(tt,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(Fv,{syncAction:o,onFetch:a,onPull:i,onPush:l,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(Ov,{activeProfile:f,identities:p,onSelect:g,isApplying:w})]}):null,Lv=({behind:s,onPull:r,isPulling:t})=>e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[e.jsx(Bi,{className:"size-10 text-emerald-500/60 mb-4"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:"Working tree clean"}),e.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:"All changes have been committed"}),s>0&&e.jsxs(Ne,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Mn,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),Qm={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},Bv=Qm.M;function zv(s){const r=s.index?.trim(),t=s.working_dir?.trim();return r&&r!=="?"?r.charAt(0):t?t.charAt(0):r?.charAt(0)||t?.charAt(0)||"M"}function Wv(s){const r=zv(s);return Qm[r]??Bv}const Hv=c.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:l}){const d=Ce.useMemo(()=>Wv(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=Ce.useCallback(h=>{h.key===" "?(h.preventDefault(),n()):h.key==="Enter"&&(h.preventDefault(),o())},[n,o]),g=Ce.useCallback(h=>{h.preventDefault(),h.stopPropagation(),n()},[n]),w=Ce.useCallback(h=>{h.preventDefault(),h.stopPropagation(),a()},[a]);return e.jsx("li",{children:e.jsxs("div",{className:"group flex items-center gap-2 px-3 py-1.5 hover:bg-sidebar/40 cursor-pointer",role:"button",tabIndex:0,onClick:o,onKeyDown:p,children:[e.jsx("button",{type:"button",onClick:g,"aria-pressed":t,"aria-label":`Select ${r.path}`,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:t?e.jsx(Wi,{className:"size-4 text-primary"}):e.jsx(Hi,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:d.color},title:u,"aria-label":u,children:d.code}),e.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path}),e.jsxs("span",{className:"shrink-0 typography-micro",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",m]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",f]})]}),e.jsxs(rt,{delayDuration:200,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:w,disabled:i,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:i?e.jsx(cs,{className:"size-3.5 animate-spin"}):e.jsx(Dr,{className:"size-3.5"})})}),e.jsx(tt,{sideOffset:8,children:"Revert changes"})]})]})})}),Uv=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:l,onRevertFile:d})=>{const u=r.size,m=s.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(dt,{outerClassName:"flex-1 min-h-0 max-h-[30vh]",className:"w-full",children:e.jsx("ul",{className:"divide-y divide-border/60",children:s.map(f=>e.jsx(Hv,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Xr({className:s,variant:r,...t}){return e.jsx(Ne,{variant:r,size:"sm",className:P("h-7 px-2 py-0",s),...t})}const ti=38,yd=200,Vv=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=c.useRef(null);return c.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ti}px`;const i=Math.min(Math.max(a.scrollHeight,ti),yd);a.style.height=`${i}px`},[s]),e.jsx(Is,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:P("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ti,maxHeight:yd}})},Gv=({highlights:s,onInsert:r,onClear:t})=>{if(s.length===0)return null;const n=()=>{r(),t()};return e.jsxs("div",{className:"space-y-2 rounded-xl border border-border/60 bg-background/60 px-3 py-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground",children:"AI highlights"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Mn,{className:"size-4"})})}),e.jsx(tt,{sideOffset:8,children:"Append highlights to commit message"})]})]}),e.jsx("ul",{className:"space-y-1",children:s.map((o,a)=>e.jsx("li",{className:"typography-meta text-foreground",children:o},a))})]})},Kv=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:l,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,g=r.trim()&&p&&m===null;return e.jsxs(ga,{open:p,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex w-full items-center justify-between px-3 py-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Commit"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:p?`${s} file${s===1?"":"s"} selected`:"No files selected"})]}),e.jsx(xa,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(Gv,{highlights:n,onInsert:o,onClear:a}),e.jsx(Vv,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:l||m!==null||s===0||f,"aria-label":"Generate commit message",children:l?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(su,{className:"size-4 text-primary"})})}),e.jsx(tt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Xr,{variant:"outline",onClick:d,disabled:!g||l,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Bi,{className:"size-4"}),"Commit"]})}),e.jsx(Xr,{variant:"default",onClick:u,disabled:!g||l,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(to,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function bd(s){const r=new Date(s);return Number.isNaN(r.getTime())?s:r.toLocaleString(void 0,{hour12:!1,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function qv(s){switch(s){case"A":return"text-emerald-500";case"D":return"text-red-500";case"M":return"text-amber-500";case"R":return"text-blue-500";default:return"text-muted-foreground"}}const Yv=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:P("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",r?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[e.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:s.message}),e.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[e.jsx("span",{className:"truncate min-w-[3ch]",title:s.author_name,children:s.author_name}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("span",{className:"truncate min-w-0",title:bd(s.date),children:bd(s.date)})]}),e.jsx("span",{className:"shrink-0",children:"·"}),e.jsx("code",{className:"shrink-0 font-mono",children:s.hash.slice(0,8)}),e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(Gs,{className:"size-3"})})}),e.jsx(tt,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),r&&e.jsx("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:o?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(cs,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:P("font-semibold w-3 text-center",qv(i.changeType)),children:i.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:i.path,children:i.path}),!i.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",i.deletions]})]}),i.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},i.path))})})]}),Xv=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],Qv=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=c.useState(!0);return s?e.jsxs(ga,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(gl,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"History"}),e.jsxs("div",{className:"flex items-center gap-2",children:[u&&e.jsx("div",{onClick:f=>f.stopPropagation(),onPointerDown:f=>f.stopPropagation(),children:e.jsxs(vs,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(js,{size:"sm",className:"data-[size=sm]:h-auto h-7 min-h-7 w-auto justify-between px-2 py-0",disabled:r,children:e.jsx(Yr,{placeholder:"Commits"})}),e.jsx(Ss,{children:Xv.map(f=>e.jsx(Lt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(oa,{className:"size-4 text-muted-foreground"}):e.jsx(Mt,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(xa,{children:e.jsx(dt,{outerClassName:"min-h-0 max-h-[50vh]",className:"w-full",children:s.all.length===0?e.jsx("div",{className:"flex h-full items-center justify-center p-4",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"No commits found"})}):e.jsx("ul",{className:"divide-y divide-border/60",children:s.all.map(f=>e.jsx(Yv,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let On=null;const Jv=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=me(),{currentDirectory:n}=ct(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},Zv=()=>{const{git:s}=An(),r=Jv(),{currentSessionId:t,worktreeMetadata:n}=me(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:l,loadGlobalIdentity:d}=ya(),u=al(r??null),m=Xu(r??null),f=Qu(r??null),p=ny(r??null),g=oy(r??null),w=Yt(Se=>Se.isLoadingStatus),h=Yt(Se=>Se.isLoadingLog),{setActiveDirectory:j,fetchAll:b,fetchStatus:x,fetchBranches:v,fetchLog:N,fetchIdentity:y,setLogMaxCount:S}=Yt(),D=c.useMemo(()=>!On||On.directory!==r?null:On,[r]),[M,C]=c.useState(D?.commitMessage??""),[k,A]=c.useState(null),[E,R]=c.useState(null),[V,T]=c.useState(25),[B,re]=c.useState(!1),{triggerFireworks:Y}=Av(),[_,q]=c.useState(()=>new Set(D?.selectedPaths??[])),[O,z]=c.useState(!1),[U,ne]=c.useState(new Set),[oe,Q]=c.useState(!1),[de,I]=c.useState([]),W=c.useCallback(()=>{I([])},[]),[F,$]=c.useState(new Set),[L,J]=c.useState(new Map),[pe,be]=c.useState(new Set),he=c.useCallback(Se=>{navigator.clipboard.writeText(Se).then(()=>{se.success("Commit hash copied")}).catch(()=>{se.error("Failed to copy")})},[]),Ae=c.useCallback(Se=>{$(Pe=>{const We=new Set(Pe);return We.has(Se)?We.delete(Se):We.add(Se),We})},[]);c.useEffect(()=>{if(!r||!s)return;const Se=Array.from(F).filter(Pe=>!L.has(Pe)&&!pe.has(Pe));Se.length!==0&&(be(Pe=>{const We=new Set(Pe);return Se.forEach(at=>We.add(at)),We}),Se.forEach(Pe=>{s.getCommitFiles(r,Pe).then(We=>{J(at=>new Map(at).set(Pe,We.files))}).catch(We=>{console.error("Failed to fetch commit files:",We),J(at=>new Map(at).set(Pe,[]))}).finally(()=>{be(We=>{const at=new Set(We);return at.delete(Pe),at})})}))},[F,r,s,L,pe]),c.useEffect(()=>()=>{if(!r){On=null;return}On={directory:r,selectedPaths:Array.from(_),commitMessage:M}},[M,r,_]),c.useEffect(()=>{l(),d()},[l,d]),c.useEffect(()=>{r&&(j(r),Yt.getState().directories.get(r)?.status||b(r,s,{force:!0}))},[r,j,b,s]);const je=c.useCallback(async(Se=!0)=>{if(r)try{await Promise.all([x(r,s),v(r,s)])}catch(Pe){if(Se){const We=Pe instanceof Error?Pe.message:"Failed to refresh repository state";se.error(We)}}},[r,s,x,v]),Te=c.useCallback(async()=>{r&&await N(r,s,V)},[r,s,N,V]),K=c.useCallback(async()=>{r&&await y(r,s)},[r,s,y]),X=c.useMemo(()=>{if(!m)return[];const Se=m.files??[],Pe=new Map;return Se.forEach(We=>{Pe.set(We.path,We)}),Array.from(Pe.values()).sort((We,at)=>We.path.localeCompare(at.path))},[m]);c.useEffect(()=>{if(!m||X.length===0){q(new Set),z(!1);return}q(Se=>{const Pe=new Set,We=Se??new Set;return X.forEach(at=>{We.has(at.path)?Pe.add(at.path):O||Pe.add(at.path)}),Pe})},[m,X,O]);const te=async Se=>{if(r){A(Se);try{if(Se==="fetch")await s.gitFetch(r),se.success("Fetched latest updates");else if(Se==="pull"){const Pe=await s.gitPull(r);se.success(`Pulled ${Pe.files.length} file${Pe.files.length===1?"":"s"}`)}else Se==="push"&&(await s.gitPush(r),se.success("Pushed to remote"));await je(!1),await Te()}catch(Pe){const We=Pe instanceof Error?Pe.message:`Failed to ${Se==="pull"?"pull":Se}`;se.error(We)}finally{A(null)}}},fe=async(Se={})=>{if(!r)return;if(!M.trim()){se.error("Please enter a commit message");return}const Pe=Array.from(_).sort();if(Pe.length===0){se.error("Select at least one file to commit");return}const We=Se.pushAfter?"commitAndPush":"commit";R(We);try{await s.createGitCommit(r,M.trim(),{files:Pe}),se.success("Commit created successfully"),C(""),q(new Set),z(!1),W(),await je(),Se.pushAfter?(await s.gitPush(r),se.success("Pushed to remote"),Y(),await je(!1)):await je(!1),await Te()}catch(at){const jt=at instanceof Error?at.message:"Failed to create commit";se.error(jt)}finally{R(null)}},ue=c.useCallback(async()=>{if(r){if(_.size===0){se.error("Select at least one file to describe");return}Q(!0);try{const{message:Se}=await s.generateCommitMessage(r,Array.from(_)),Pe=Se.subject?.trim()??"",We=Array.isArray(Se.highlights)?Se.highlights:[];Pe&&C(Pe),I(We),se.success("Commit message generated")}catch(Se){const Pe=Se instanceof Error?Se.message:"Failed to generate commit message";se.error(Pe)}finally{Q(!1)}}},[r,_,s]),ae=async Se=>{if(!r||!m)return;const Pe=m.current??null;try{await s.createBranch(r,Se,Pe??"HEAD"),se.success(`Created branch ${Se}`);let We=!1;try{await s.checkoutBranch(r,Se),await s.gitPush(r,{remote:"origin",branch:Se,options:["--set-upstream"]}),We=!0}catch(at){const jt=at instanceof Error?at.message:"Unable to push new branch to origin.";se.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",jt]})})}finally{if(Pe)try{await s.checkoutBranch(r,Pe)}catch(at){console.warn("Failed to restore original branch after creation:",at)}}await je(),await Te(),We&&se.success(`Upstream set for ${Se}`)}catch(We){const at=We instanceof Error?We.message:"Failed to create branch";throw se.error(at),We}},H=async(Se,Pe)=>{if(r)try{await s.renameBranch(r,Se,Pe),se.success(`Renamed branch ${Se} to ${Pe}`),await je(),await Te()}catch(We){const at=We instanceof Error?We.message:`Failed to rename branch ${Se} to ${Pe}`;se.error(at)}},xe=async Se=>{if(!r)return;const Pe=Se.replace(/^remotes\//,"");if(m?.current!==Pe)try{await s.checkoutBranch(r,Pe),se.success(`Checked out ${Pe}`),await je(),await Te()}catch(We){const at=We instanceof Error?We.message:`Failed to checkout ${Pe}`;se.error(at)}},G=async Se=>{if(r){re(!0);try{await s.setGitIdentity(r,Se.id),se.success(`Applied "${Se.name}" to repository`),await K()}catch(Pe){const We=Pe instanceof Error?Pe.message:"Failed to apply git identity";se.error(We)}finally{re(!1)}}},ye=c.useMemo(()=>f?.all?f.all.filter(Se=>!Se.startsWith("remotes/")).sort():[],[f]),Fe=c.useMemo(()=>f?.all?f.all.filter(Se=>Se.startsWith("remotes/")).map(Se=>Se.replace(/^remotes\//,"")).sort():[],[f]),qe=c.useMemo(()=>{const Se=new Map;i&&Se.set(i.id,i);for(const Pe of a)Se.set(Pe.id,Pe);return Array.from(Se.values())},[a,i]),Re=c.useMemo(()=>{if(g?.userName&&g?.userEmail){const Se=a.find(Pe=>Pe.userName===g.userName&&Pe.userEmail===g.userEmail);return Se||(i&&i.userName===g.userName&&i.userEmail===g.userEmail?i:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[g,a,i]),Ee=X.length,Ye=_.size,ot=w||k!==null||E!==null,ut=Ee>0,kt=Se=>{q(Pe=>{const We=new Set(Pe);return We.has(Se)?We.delete(Se):We.add(Se),We}),z(!0)},Rt=()=>{const Se=new Set(X.map(Pe=>Pe.path));q(Se),z(!0)},Et=()=>{q(new Set),z(!0)},Nt=c.useCallback(async Se=>{if(r){ne(Pe=>{const We=new Set(Pe);return We.add(Se),We});try{await s.revertGitFile(r,Se),se.success(`Reverted ${Se}`),await je(!1)}catch(Pe){const We=Pe instanceof Error?Pe.message:"Failed to revert changes";se.error(We)}finally{ne(Pe=>{const We=new Set(Pe);return We.delete(Se),We})}}},[r,je,s]),Qt=c.useCallback(()=>{if(de.length===0)return;const Se=de.map(Pe=>Pe.trim()).filter(Boolean);if(Se.length===0){W();return}C(Pe=>{const We=Pe.trim(),at=We.length>0?`
98
+
99
+ `:"";return`${We}${at}${Se.join(`
100
+ `)}`.trim()})},[de,W]),Tt=c.useCallback(Se=>{T(Se),r&&(S(r,Se),N(r,s,Se))},[r,S,N,s]);return r?w&&u===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(cs,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(Ot,{className:"mb-3 size-6 text-muted-foreground"}),e.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Not a Git repository"}),e.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:"Choose a different directory or initialize Git to use this workspace."})]}):e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background","data-keyboard-avoid":"true",children:[e.jsx($v,{status:m,localBranches:ye,remoteBranches:Fe,branchInfo:f?.branches,syncAction:k,onFetch:()=>te("fetch"),onPull:()=>te("pull"),onPush:()=>te("push"),onCheckoutBranch:xe,onCreateBranch:ae,onRenameBranch:H,activeIdentityProfile:Re,availableIdentities:qe,onSelectIdentity:G,isApplyingIdentity:B,isWorktreeMode:!!o}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"p-3",children:e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-3",children:[ut?e.jsx(Uv,{changeEntries:X,selectedPaths:_,diffStats:m?.diffStats,revertingPaths:U,onToggleFile:kt,onSelectAll:Rt,onClearSelection:Et,onViewDiff:Se=>_e.getState().navigateToDiff(Se),onRevertFile:Nt}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(Lv,{behind:m?.behind??0,onPull:()=>te("pull"),isPulling:k==="pull"})}),X.length>0&&e.jsx(Kv,{selectedCount:Ye,commitMessage:M,onCommitMessageChange:C,generatedHighlights:de,onInsertHighlights:Qt,onClearHighlights:W,onGenerateMessage:ue,isGeneratingMessage:oe,onCommit:()=>fe({pushAfter:!1}),onCommitAndPush:()=>fe({pushAfter:!0}),commitAction:E,isBusy:ot})]}),e.jsx(Qv,{log:p,isLogLoading:h,logMaxCount:V,onLogMaxCountChange:Tt,expandedCommitHashes:F,onToggleCommit:Ae,commitFilesMap:L,loadingCommitHashes:pe,onCopyHash:he})]})})]}):e.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:"Select a session or directory to view repository details."})})},e0=1e6;function Lr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const jo=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),wd=Bt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=Lr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o),u=!l||l.terminalSessionId!==n.sessionId?jo(o):l??jo(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??jo(o);return i.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=Lr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??jo(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>e0&&m.length>1;){const g=m.shift();if(!g)break;f-=g.data.length}const p=m.map(g=>g.data).join("");return i.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=Lr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i&&a.set(n,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=Lr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i?(a.set(n,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=Lr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),Jm=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),t0=[{id:"ibm-plex-sans",label:"IBM Plex Sans",description:"Humanist sans-serif for optimal readability in the interface.",stack:'"IBM Plex Sans", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif'}],s0=[{id:"ibm-plex-mono",label:"IBM Plex Mono",description:"Balanced monospace for code blocks and technical content.",stack:'"IBM Plex Mono", "SFMono-Regular", "Menlo", monospace'}],Zm=s=>Object.fromEntries(s.map(r=>[r.id,r])),vd=Zm(t0),Br=Zm(s0),r0="ibm-plex-sans",$o="ibm-plex-mono";function n0(s){const{colors:r}=s,t=r.syntax.base;return{background:r.surface.background,foreground:t.foreground,cursor:r.interactive.cursor,cursorAccent:r.surface.background,selectionBackground:r.interactive.selection,selectionForeground:r.interactive.selectionForeground,selectionInactiveBackground:r.interactive.selection+"50",black:r.surface.muted,red:r.status.error,green:r.status.success,yellow:r.status.warning,blue:t.function,magenta:t.keyword,cyan:t.type,white:t.foreground,brightBlack:t.comment,brightRed:r.status.error,brightGreen:r.status.success,brightYellow:r.status.warning,brightBlue:t.function,brightMagenta:t.keyword,brightCyan:t.type,brightWhite:r.surface.elevatedForeground}}function o0(s,r,t,n){const a=`${s}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!0,fontSize:r,lineHeight:1.15,fontFamily:a,allowTransparency:!1,theme:{background:t.background,foreground:t.foreground,cursor:t.cursor,cursorAccent:t.cursorAccent,selectionBackground:t.selectionBackground,selectionForeground:t.selectionForeground,black:t.black,red:t.red,green:t.green,yellow:t.yellow,blue:t.blue,magenta:t.magenta,cyan:t.cyan,white:t.white,brightBlack:t.brightBlack,brightRed:t.brightRed,brightGreen:t.brightGreen,brightYellow:t.brightYellow,brightBlue:t.brightBlue,brightMagenta:t.brightMagenta,brightCyan:t.brightCyan,brightWhite:t.brightWhite},scrollback:5e4,ghostty:n}}let si=null;function a0(){return si||(si=mh.load()),si}function i0(s){if(typeof window>"u")return null;const r=[s,...Array.from(s.querySelectorAll("*"))];let t=null;for(const n of r){const a=window.getComputedStyle(n).overflowY;if(!(a!=="auto"&&a!=="scroll")){if(n.scrollHeight-n.clientHeight>2)return n;t||(t=n)}}return t}const _i=c.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:l,enableTouchScroll:d},u)=>{const m=c.useRef(null),f=c.useRef(null),p=c.useRef(null),g=c.useRef(null),w=c.useRef(t),h=c.useRef(n),j=c.useRef(null),b=c.useRef(""),x=c.useRef(null),v=c.useRef(!1),N=c.useRef(null),y=c.useRef(null),S=c.useRef(null),D=c.useRef(0),M=c.useRef(null),[,C]=c.useReducer(_=>_+1,0),[k,A]=c.useReducer(_=>_+1,0);w.current=t,h.current=n;const E=c.useCallback((_,q)=>{const O=M.current,z=m.current;if(!O||!z)return;const U=z.getBoundingClientRect(),ne=U.left+U.width/2,oe=U.top+U.height-12,Q=typeof _=="number"?_:ne,de=typeof q=="number"?q:oe,I=8,W=Math.max(I,Math.min(U.width-I,Q-U.left)),F=Math.max(I,Math.min(U.height-I,de-U.top));O.style.left=`${W}px`,O.style.top=`${F}px`,O.style.bottom="";try{O.focus({preventScroll:!0})}catch{try{O.focus()}catch{}}},[]),R=c.useCallback(()=>{b.current="",x.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(x.current),x.current=null,v.current=!1,N.current=null},[]),V=c.useCallback(()=>{const _=g.current,q=p.current,O=m.current;if(!_||!q||!O)return;const z=O.getBoundingClientRect();if(!(z.width<24||z.height<24))try{_.fit();const U={cols:q.cols,rows:q.rows},ne=j.current;(!ne||ne.cols!==U.cols||ne.rows!==U.rows)&&(j.current=U,h.current(U.cols,U.rows))}catch{}},[]),T=c.useCallback(()=>{if(v.current)return;const _=p.current;if(!_){R();return}if(!b.current)return;const q=b.current;b.current="",v.current=!0,_.write(q,()=>{v.current=!1,b.current&&(typeof window<"u"?x.current=window.requestAnimationFrame(()=>{x.current=null,T()}):T())})},[R]),B=c.useCallback(()=>{x.current===null&&(typeof window<"u"?x.current=window.requestAnimationFrame(()=>{x.current=null,T()}):T())},[T]),re=c.useCallback(_=>{_&&(b.current+=_,B())},[B]),Y=c.useCallback(()=>{if(y.current?.(),y.current=null,S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),!d){D.current=0;return}const _=m.current;if(!_)return;const q=p.current;if(!q)return;D.current=0;const O=2.2,z=2.8,U=25,ne=.25,oe=8,Q=.05,de=.015,I={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},W=()=>typeof performance<"u"?performance.now():Date.now(),F=Math.max(12,Math.round(i*1.35));let $=0;const L=X=>{if(!X)return!1;const te=q.getViewportY(),fe=$+X,ue=Math.trunc(fe/F);return $=fe-ue*F,ue!==0&&q.scrollLines(ue),q.getViewportY()!==te},J=()=>{I.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(I.rafId),I.rafId=null},pe={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const X=Object.assign(I,{pointerId:null,startX:null,startY:null,moved:!1}),te=6,fe=xe=>{if(xe.pointerType==="touch"){J(),X.pointerId=xe.pointerId,X.startX=xe.clientX,X.startY=xe.clientY,X.moved=!1,X.lastY=xe.clientY,X.lastTime=W(),X.velocity=0;try{_.setPointerCapture(xe.pointerId)}catch{}}},ue=xe=>{if(xe.pointerType!=="touch"||X.pointerId!==xe.pointerId)return;if(X.startX!==null&&X.startY!==null&&!X.moved){const ut=xe.clientX-X.startX,kt=xe.clientY-X.startY;Math.hypot(ut,kt)>=te&&(X.moved=!0)}if(X.lastY===null){X.lastY=xe.clientY,X.lastTime=W();return}const G=X.lastY,ye=X.lastTime??W(),Fe=W();X.lastY=xe.clientY,X.lastTime=Fe;const qe=G-xe.clientY;if(Math.abs(qe)<1)return;const Re=Math.max(Fe-ye,8),Ee=O+Math.min(z,Math.abs(qe)/U),Ye=qe*Ee,ot=Ye/Re;X.velocity=X.velocity*(1-ne)+ot*ne,X.velocity>oe?X.velocity=oe:X.velocity<-oe&&(X.velocity=-oe),X.moved&&(xe.cancelable&&xe.preventDefault(),xe.stopPropagation()),L(Ye)},ae=xe=>{if(xe.pointerType!=="touch"||X.pointerId!==xe.pointerId)return;const G=!X.moved;X.pointerId=null,X.startX=null,X.startY=null,X.moved=!1,X.lastY=null,X.lastTime=null;try{_.releasePointerCapture(xe.pointerId)}catch{}if(G){E(xe.clientX,xe.clientY);return}if(typeof window>"u")return;if(Math.abs(X.velocity)<Q){X.velocity=0;return}let ye=W();const Fe=()=>{const qe=W(),Re=Math.max(qe-ye,8);ye=qe;const Ee=L(X.velocity*Re)??!1,Ye=Math.sign(X.velocity),ot=Math.max(0,Math.abs(X.velocity)-de*Re);if(X.velocity=ot*Ye,!Ee||ot<=Q){J(),X.velocity=0;return}X.rafId=window.requestAnimationFrame(Fe)};X.rafId=window.requestAnimationFrame(Fe)};_.addEventListener("pointerdown",fe,pe),_.addEventListener("pointermove",ue,pe),_.addEventListener("pointerup",ae,pe),_.addEventListener("pointercancel",ae,pe);const H=_.style.touchAction;_.style.touchAction="manipulation",y.current=()=>{J(),S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),D.current=0,_.removeEventListener("pointerdown",fe,pe),_.removeEventListener("pointermove",ue,pe),_.removeEventListener("pointerup",ae,pe),_.removeEventListener("pointercancel",ae,pe),_.style.touchAction=H};return}const he=6,Ae=X=>{X.touches.length===1&&(J(),I.lastY=X.touches[0].clientY,I.lastTime=W(),I.velocity=0,I.startX=X.touches[0].clientX,I.startY=X.touches[0].clientY,I.didMove=!1)},je=X=>{if(X.touches.length!==1){I.lastY=null,I.lastTime=null,I.velocity=0,I.startX=null,I.startY=null,I.didMove=!1,J();return}const te=X.touches[0].clientX,fe=X.touches[0].clientY;if(I.startX!==null&&I.startY!==null&&!I.didMove){const Re=te-I.startX,Ee=fe-I.startY;Math.hypot(Re,Ee)>=he&&(I.didMove=!0)}if(I.lastY===null){I.lastY=fe,I.lastTime=W();return}const ue=I.lastY,ae=I.lastTime??W(),H=W();I.lastY=fe,I.lastTime=H;const xe=ue-fe;if(Math.abs(xe)<1)return;const G=Math.max(H-ae,8),ye=O+Math.min(z,Math.abs(xe)/U),Fe=xe*ye,qe=Fe/G;I.velocity=I.velocity*(1-ne)+qe*ne,I.velocity>oe?I.velocity=oe:I.velocity<-oe&&(I.velocity=-oe),I.didMove&&(X.preventDefault(),X.stopPropagation()),L(Fe)},Te=X=>{const te=!I.didMove;I.lastY=null,I.lastTime=null;const fe=I.velocity;if(I.startX=null,I.startY=null,I.didMove=!1,te){const H=X.changedTouches?.[0];E(H?.clientX,H?.clientY);return}if(typeof window>"u")return;if(Math.abs(fe)<Q){I.velocity=0;return}let ue=W();const ae=()=>{const H=W(),xe=Math.max(H-ue,8);ue=H;const G=L(I.velocity*xe)??!1,ye=Math.sign(I.velocity),Fe=Math.max(0,Math.abs(I.velocity)-de*xe);if(I.velocity=Fe*ye,!G||Fe<=Q){J(),I.velocity=0;return}I.rafId=window.requestAnimationFrame(ae)};I.rafId=window.requestAnimationFrame(ae)};_.addEventListener("touchstart",Ae,pe),_.addEventListener("touchmove",je,pe),_.addEventListener("touchend",Te,pe),_.addEventListener("touchcancel",Te,pe);const K=_.style.touchAction;_.style.touchAction="manipulation",y.current=()=>{J(),S.current!==null&&typeof window<"u"&&(window.clearTimeout(S.current),S.current=null),D.current=0,_.removeEventListener("touchstart",Ae,pe),_.removeEventListener("touchmove",je,pe),_.removeEventListener("touchend",Te,pe),_.removeEventListener("touchcancel",Te,pe),_.style.touchAction=K}},[d,E,i]);return c.useEffect(()=>{let _=!1,q=null,O=null,z=[];const U=m.current;return U?(U.tabIndex=0,(async()=>{try{const oe=await a0();if(_)return;const Q=o0(a,i,o,oe),de=new dh(Q),I=new uh;q=de,p.current=de,g.current=I,de.loadAddon(I),de.open(U),A();const W=i0(U);W?(W.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=W,C()):f.current=null,V(),Y(),de.focus(),z=[de.onData(F=>{w.current(F)})],O=new ResizeObserver(()=>{V()}),O.observe(U),typeof window<"u"&&window.setTimeout(()=>{V()},0)}catch{}})(),()=>{_=!0,y.current?.(),y.current=null,z.forEach(oe=>oe.dispose()),O?.disconnect(),q?.dispose(),p.current=null,g.current=null,f.current=null,j.current=null,R()}):void 0},[V,a,i,Y,o,R]),c.useEffect(()=>{const _=p.current;_&&(_.reset(),R(),j.current=null,V(),_.focus())},[s,k,V,R]),c.useEffect(()=>(Y(),()=>{y.current?.(),y.current=null}),[Y,s]),c.useEffect(()=>{const _=p.current;if(!_)return;if(r.length===0){N.current!==null&&(_.reset(),R(),V());return}const q=N.current;let O;if(q===null)O=r;else{const z=r.findIndex(U=>U.id===q);O=z>=0?r.slice(z+1):r}O.length>0&&re(O.map(z=>z.data).join("")),N.current=r[r.length-1].id},[r,k,re,V,R]),c.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const _=p.current;_&&(_.reset(),R(),V())},fit:()=>{V()}}),[d,E,V,R]),e.jsxs("div",{ref:m,className:P("relative h-full w-full",l),style:{backgroundColor:o.background},onClick:_=>{d?E(_.clientX,_.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:M,inputMode:"text",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,"aria-hidden":"true",style:{position:"absolute",left:0,top:0,width:1,height:1,opacity:.001,zIndex:1,background:"transparent",color:"transparent",border:"none",padding:0,margin:0,outline:"none"},onInput:_=>{const q=String(_.currentTarget.value||"");if(!q)return;const O=q.replace(/\r\n|\r|\n/g,"\r");w.current(O),_.currentTarget.value=""},onKeyDown:_=>{_.key==="Backspace"&&(_.currentTarget.value||w.current(""))}}):null,f.current&&!d?e.jsx(ol,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});_i.displayName="TerminalViewport";const jd=13,l0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},So={ctrl:"5",cmd:"3"},c0={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},d0=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${So[r]}A`;case"arrow-down":return`\x1B[1;${So[r]}B`;case"arrow-right":return`\x1B[1;${So[r]}C`;case"arrow-left":return`\x1B[1;${So[r]}D`}return l0[s]??null},u0=()=>{const{terminal:s}=An(),{currentTheme:r}=sn(),{monoFont:t}=Jm(),{isMobile:n,hasTouchInput:o}=Ft(),{currentSessionId:a,sessions:i,worktreeMetadata:l}=me(),d=a?l.get(a)??void 0:void 0,u=c.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const te=i.find(ue=>ue.id===a),fe=typeof te?.directory=="string"?te.directory:null;return fe&&fe.length>0?fe:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=ct(),p=u||m||null,g=c.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),w=wd(),h=w.sessions,j=w.setTerminalSession,b=w.setConnecting,x=w.appendToBuffer,v=w.clearTerminalSession,N=w.removeTerminalSession,y=w.clearBuffer,S=c.useMemo(()=>{if(p)return h.get(p)},[h,p]),D=S?.terminalSessionId??null,M=S?.bufferChunks??[],C=S?.bufferLength??0,k=S?.isConnecting??!1,A=D,[E,R]=c.useState(null),[V,T]=c.useState(!1),[B,re]=c.useState(null),[Y,_]=c.useState(!1),q=c.useRef(null),O=c.useRef(null),z=c.useRef(A),U=c.useRef(p),ne=c.useRef(null),Q=_e(te=>te.activeMainTab)==="terminal";c.useEffect(()=>{z.current=A},[A]),c.useEffect(()=>{U.current=p},[p]),c.useEffect(()=>{!n&&B!==null&&re(null)},[n,B,re]),c.useEffect(()=>{!A&&B!==null&&re(null)},[A,B,re]);const de=c.useCallback(()=>{q.current?.(),q.current=null,O.current=null},[]);c.useEffect(()=>()=>{de(),z.current=null},[de]);const I=c.useCallback(te=>{if(O.current===te)return;de();const fe=s.connect(te,{onEvent:ue=>{const ae=U.current;if(ae)switch(ue.type){case"connected":{(ue.runtime||ue.ptyBackend)&&console.log(`[Terminal] connected runtime=${ue.runtime??"unknown"} pty=${ue.ptyBackend??"unknown"}`),b(ae,!1),R(null),T(!1),ne.current?.focus();break}case"reconnecting":{const H=ue.attempt??0,xe=ue.maxAttempts??3;R(`Reconnecting (${H}/${xe})...`),T(!1);break}case"data":{ue.data&&x(ae,ue.data);break}case"exit":{const H=typeof ue.exitCode=="number"?ue.exitCode:null,xe=typeof ue.signal=="number"?ue.signal:null;x(ae,`\r
101
+ [Process exited${H!==null?` with code ${H}`:""}${xe!==null?` (signal ${xe})`:""}]\r
102
+ `),v(ae),b(ae,!1),R("Terminal session ended"),T(!1),de();break}}},onError:(ue,ae)=>{const H=U.current;if(!H)return;const xe=ae?`Connection failed: ${ue.message}`:ue.message||"Terminal stream connection error";R(xe),T(!!ae),ae&&(b(H,!1),de(),N(H))}},c0);q.current=()=>{fe.close(),O.current=null},O.current=te},[x,v,de,N,b,s,R]);c.useEffect(()=>{let te=!1;if(!p){R(a?"No working directory available for terminal.":"Select a session to open the terminal."),de();return}return(async()=>{const ue=p;if(!U.current||U.current!==ue)return;let H=wd.getState().getTerminalSession(ue)?.terminalSessionId??null;if(!H){R(null),T(!1),b(ue,!0);try{const xe=await s.createSession({cwd:ue});if(te){try{await s.close(xe.sessionId)}catch{}return}j(ue,xe),H=xe.sessionId}catch(xe){te||(R(xe instanceof Error?xe.message:"Failed to start terminal session"),T(!0),b(ue,!1));return}}!H||te||(z.current=H,I(H))})(),()=>{te=!0,z.current=null,de()}},[a,p,A,N,b,j,I,de,s]);const W=c.useCallback(async()=>{if(!p||Y)return;_(!0),R(null),T(!1),de();const te=z.current;try{if(s.restartSession&&te){const fe=await s.restartSession(te,{cwd:p});j(p,fe),z.current=fe.sessionId,I(fe.sessionId)}else{if(te)try{await s.close(te)}catch{}N(p)}}catch(fe){R(fe instanceof Error?fe.message:"Failed to restart terminal"),T(!0)}finally{_(!1)}},[p,Y,de,s,j,I,N]),F=c.useCallback(async()=>{if(p&&!Y){_(!0),R(null),T(!1),de();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),y(p),ne.current?.clear(),await new Promise(te=>setTimeout(te,100));try{b(p,!0);const te=await s.createSession({cwd:p});j(p,te),z.current=te.sessionId,I(te.sessionId)}catch(te){R(te instanceof Error?te.message:"Failed to create terminal"),T(!0),b(p,!1)}finally{_(!1)}}},[p,Y,de,s,N,y,b,j,I]),$=c.useCallback(()=>{if(!p)return;y(p),ne.current?.clear(),ne.current?.focus();const te=z.current;te&&s.sendInput(te,"\f").catch(fe=>{R(fe instanceof Error?fe.message:"Failed to refresh prompt")})},[y,p,R,s]),L=c.useCallback(te=>{if(!te)return;let fe=te,ue=!1;if(B&&te.length>0){const H=te[0];if(H.length===1&&/[a-zA-Z]/.test(H)){const xe=H.toUpperCase();(B==="ctrl"||B==="cmd")&&(fe=String.fromCharCode(xe.charCodeAt(0)&31),ue=!0)}ue||(ue=!0)}const ae=z.current;ae&&(s.sendInput(ae,fe).catch(H=>{R(H instanceof Error?H.message:"Failed to send input")}),ue&&(re(null),ne.current?.focus()))},[B,re,s]),J=c.useCallback((te,fe)=>{const ue=z.current;ue&&s.resize({sessionId:ue,cols:te,rows:fe}).catch(()=>{})},[s]),pe=c.useCallback(te=>{re(fe=>fe===te?null:te),ne.current?.focus()},[re]),be=c.useCallback(te=>{const fe=d0(te,B);fe&&(L(fe),re(null),ne.current?.focus())},[B,L,re]);c.useEffect(()=>{if(!n||!B||!A)return;const te=fe=>{if(fe.repeat)return;const ue=fe.key;if(!ue||ue==="Control"||ue==="Meta"||ue==="Alt"||ue==="Shift")return;const ae=ue.length===1?ue.toLowerCase():ue,H=fe.code??"",xe=H.startsWith("Key")&&H.length===4?H.slice(3).toUpperCase():null,G=ue.length===1&&/[a-zA-Z]/.test(ue)?ue.toUpperCase():xe,ye={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(ae in ye){fe.preventDefault(),fe.stopPropagation(),be(ye[ae]);return}if(B==="ctrl"&&G&&G.length===1&&G>="A"&&G<="Z"){const Fe=String.fromCharCode(G.charCodeAt(0)&31);fe.preventDefault(),fe.stopPropagation(),L(Fe),re(null),ne.current?.focus()}};return window.addEventListener("keydown",te),()=>{window.removeEventListener("keydown",te)}},[B,be,L,n,re,A]);const he=c.useMemo(()=>{const te=Br[$o].stack;if(typeof window>"u")return(Br[t]??Br[$o]).stack;const ue=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return ue&&ue.trim().length>0?ue.trim():(Br[t]??Br[$o]).stack??te},[t]),Ae=c.useMemo(()=>n0(r),[r]),je=c.useMemo(()=>`${p??"no-dir"}::${A??"pending"}`,[p,A]);c.useEffect(()=>{if(!Q)return;const te=ne.current;if(!te)return;const fe=()=>{te.fit()};if(typeof window<"u"){const ue=window.requestAnimationFrame(()=>{fe(),te.focus()}),ae=[220,400].map(H=>window.setTimeout(fe,H));return()=>{window.cancelAnimationFrame(ue),ae.forEach(H=>window.clearTimeout(H))}}fe()},[Q,je,A]);const Te=E?.includes("Reconnecting"),K=E?Te?e.jsx(fh,{size:20,className:"text-amber-400"}):e.jsx(Ht,{size:20,className:"text-destructive"}):A&&!k&&!Y?e.jsx(Mo,{size:20,className:"text-emerald-400"}):k||Y?e.jsx(Rl,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Rl,{size:20,className:"text-muted-foreground"});if(!a)return e.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal"});if(!p)return e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[e.jsx("p",{children:"No working directory available for this session."}),e.jsx("button",{onClick:W,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const X=!A||k||Y;return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"px-3 py-2 text-xs bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"flex min-w-0 items-center gap-2 text-muted-foreground",children:e.jsx("span",{className:"truncate font-mono text-foreground/90",children:g})}),e.jsxs("div",{className:"flex items-center gap-2",children:[K,e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:$,disabled:!C,title:"Clear output",type:"button",children:[e.jsx(Ks,{size:16}),"Clear"]}),e.jsxs(Ne,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:W,disabled:Y,title:"Restart terminal session",type:"button",children:[e.jsx(Es,{size:16,className:P((k||Y)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>be("esc"),disabled:X,children:"Esc"}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("tab"),disabled:X,children:[e.jsx(Fl,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:B==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>pe("ctrl"),disabled:X,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:B==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>pe("cmd"),disabled:X,children:[e.jsx(Qr,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("arrow-up"),disabled:X,children:[e.jsx(to,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("arrow-left"),disabled:X,children:[e.jsx(du,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("arrow-down"),disabled:X,children:[e.jsx(Mn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("arrow-right"),disabled:X,children:[e.jsx(Fl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ne,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>be("enter"),disabled:X,children:[e.jsx(Kn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ae.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:Q?n?e.jsx(_i,{ref:te=>{ne.current=te},sessionKey:je,chunks:M,onInput:L,onResize:J,theme:Ae,fontFamily:he,fontSize:jd,enableTouchScroll:o},je):e.jsx(dt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(_i,{ref:te=>{ne.current=te},sessionKey:je,chunks:M,onInput:L,onResize:J,theme:Ae,fontFamily:he,fontSize:jd,enableTouchScroll:o},je)}):null}),E&&e.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-destructive/90 px-3 py-2 text-xs text-destructive-foreground flex items-center justify-between gap-2",children:[e.jsx("span",{children:E}),V&&e.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:F,disabled:Y,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},ef=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:zi},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:ar},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:Qr},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:lu},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:qn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:Ot},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:Kr}],m0={},f0={},p0={};ef.forEach(s=>{m0[s.id]=s.label,f0[s.id]=s.description,p0[s.id]=s});const h0=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",g0=s=>{if(!Array.isArray(s))return[];const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},Sd=s=>{const r=g0(s);if(r.length===0)return;const t={};for(const i of r)i.permission&&((t[i.permission]||={})[i.pattern]=i.action);const n=t["*"]?.["*"],o=Object.keys(t);if(o.length===1&&o[0]==="*"&&Object.keys(t["*"]||{}).length===1&&t["*"]?.["*"])return t["*"]["*"];const a={};for(const i of o){const l=t[i],d=Object.keys(l);if(d.length===1&&d[0]==="*"&&i!=="*"){const u=l["*"],m=h0(i);if(n){if(u===n)continue}else if(u===m)continue;a[i]=u}else i==="*"&&d.length===1&&d[0]==="*"?a[i]=l["*"]:a[i]=l}return Object.keys(a).length>0?a:void 0},x0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=Fr(),{setSidebarOpen:p}=_e(),{isMobile:g}=Ft(),[w,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const b=w?"bg-transparent":j?"bg-background":"bg-sidebar",x=()=>{const E="new-agent";let R=E,V=1;for(;i.some(T=>T.name===R);)R=`${E}-${V}`,V++;d({name:R,scope:"user"}),l(R),s?.(),g&&p(!1)},v=async E=>{if(zr(E)){se.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?se.success(`Agent "${E.name}" deleted successfully`):se.error("Failed to delete agent"))},N=async E=>{zr(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?se.success(`Agent "${E.name}" reset to default`):se.error("Failed to reset agent"))},y=E=>{const R=E.name;let V=1,T=`${R}-copy`;for(;i.some(_=>_.name===T);)V++,T=`${R}-copy-${V}`;const B=E,re=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,Y=E;d({name:T,scope:B.scope||"user",description:E.description,model:re,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:Sd(E.permission),disable:Y.disable}),l(T),g&&p(!1)},S=E=>{o(E.name),t(E)},D=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){se.error("Agent name is required");return}if(E===r.name){t(null);return}if(i.some(B=>B.name===E)){se.error("An agent with this name already exists");return}const R=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,V=r;await u({name:E,description:r.description,model:R,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:Sd(r.permission),disable:V.disable,scope:V.scope})?await m(r.name)?(se.success(`Agent renamed to "${E}"`),l(E)):se.error("Failed to remove old agent after rename"):se.error("Failed to rename agent"),t(null)},M=E=>{switch(E){case"primary":return e.jsx(qr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(mu,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(uu,{className:"h-3 w-3 text-primary"});default:return null}},C=i.filter(E=>!Au(E)),k=C.filter(zr),A=C.filter(E=>!zr(E));return e.jsxs("div",{className:P("flex h-full flex-col",b),children:[e.jsx("div",{className:P("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",C.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:C.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Yn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No agents configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Agents"}),k.map(E=>e.jsx(kd,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),s?.(),g&&p(!1)},onReset:()=>N(E),onDuplicate:()=>y(E),getAgentModeIcon:M},E.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),A.map(E=>e.jsx(kd,{agent:E,isSelected:a===E.name,onSelect:()=>{l(E.name),s?.(),g&&p(!1)},onRename:()=>S(E),onDelete:()=>v(E),onDuplicate:()=>y(E),getAgentModeIcon:M},E.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:E=>!E&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(pt,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&D()}}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Xr,{onClick:D,children:"Rename"})]})]})})]})},kd=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:l})=>{const d=s;return e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),l(s.mode),(d.scope||zr(s))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:zr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(vt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(la,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(vt,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(vt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(vt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Bs({className:s,variant:r,...t}){return e.jsx(Ne,{variant:r,size:"sm",className:P("h-6 px-2 text-xs",s),...t})}const y0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),b0=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=y0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Sl=({providerId:s,modelId:r,onChange:t,className:n})=>{const{providers:o,modelsMetadata:a}=et(),i=_e(O=>O.isMobile),{toggleFavoriteModel:l,isFavoriteModel:d,addRecentModel:u}=_e(),{favoriteModelsList:m,recentModelsList:f}=yl(),{isMobile:p}=Ft(),g=i||p,[w,h]=c.useState(!1),[j,b]=c.useState(new Set),[x,v]=c.useState(!1),[N,y]=c.useState(""),[S,D]=c.useState(0),M=c.useRef([]),C=()=>h(!1),k=O=>{b(z=>{const U=new Set(z);return U.has(O)?U.delete(O):U.add(O),U})};c.useEffect(()=>{x||(y(""),D(0))},[x]),c.useEffect(()=>{D(0)},[N]);const A=O=>{const z=O?.name||O?.id||"",U=String(z);return U.length>40?U.substring(0,37)+"...":U},E=(O,z)=>{const U=`${O}/${z}`;return a.get(U)},R=(O,z)=>{t(O,z),O&&z&&u(O,z),v(!1)},V=(O,z)=>{if(!N.trim())return!0;const U=N.toLowerCase();return O.toLowerCase().includes(U)||z.toLowerCase().includes(U)},T=(O,z,U,ne,oe,Q)=>{const de=E(z,U),I=b0(de?.limit?.context),W=s===z&&r===U,F=d(z,U);return e.jsxs("div",{ref:$=>{M.current[oe]=$},className:P("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Q?"bg-accent":"hover:bg-accent/50"),onClick:()=>R(z,U),onMouseEnter:()=>D(oe),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(O)}),I?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:I}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[W&&e.jsx(At,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:$=>{$.preventDefault(),$.stopPropagation(),l(z,U)},className:P("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",F?"text-yellow-500":"text-muted-foreground"),"aria-label":F?"Unfavorite":"Favorite",title:F?"Remove from favorites":"Add to favorites",children:F?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(Bn,{className:"h-3.5 w-3.5"})})]})]},`${ne}-${z}-${U}`)},B=m.filter(({model:O,providerID:z})=>{const ne=o.find(Q=>Q.id===z)?.name||z,oe=A(O);return V(oe,ne)}),re=f.filter(({model:O,providerID:z})=>{const ne=o.find(Q=>Q.id===z)?.name||z,oe=A(O);return V(oe,ne)}),Y=o.map(O=>{const U=(Array.isArray(O.models)?O.models:[]).filter(ne=>{const oe=A(ne);return V(oe,O.name||O.id||"")});return{...O,models:U}}).filter(O=>O.models.length>0),_=B.length>0||re.length>0||Y.length>0,q=()=>g?e.jsx(ws,{open:w,onClose:C,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[m.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:m.map(({model:O,providerID:z,modelID:U})=>{const ne=z===s&&U===r;return e.jsxs("div",{className:P("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ne?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(z,U),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{providerId:z,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(O)})]})}),e.jsx("button",{onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),l(z,U)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(fr,{className:"h-4 w-4"})})]},`fav-mobile-${z}-${U}`)})})]}),f.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 mb-2",children:[e.jsx("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:"Recents"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:O,providerID:z,modelID:U})=>{const ne=z===s&&U===r;return e.jsxs("div",{className:P("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ne?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(z,U),C()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{providerId:z,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:A(O)})]})}),e.jsx("button",{onClick:oe=>{oe.preventDefault(),oe.stopPropagation(),l(z,U)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-muted-foreground/50 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Favorite",children:e.jsx(Bn,{className:"h-4 w-4"})})]},`recent-mobile-${z}-${U}`)})})]}),o.map(O=>{const z=Array.isArray(O.models)?O.models:[];if(z.length===0)return null;const U=O.id===s,ne=j.has(O.id);return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95",children:[e.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left",onClick:()=>k(O.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{providerId:O.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:O.name}),U&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ne?e.jsx(Mt,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),ne&&e.jsx("div",{className:"border-t border-border/20",children:z.map(oe=>{const Q=O.id===s&&oe.id===r;return e.jsxs("div",{className:P("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",Q?"bg-primary/10 text-primary":"text-foreground"),children:[e.jsx("button",{type:"button",className:"flex-1 flex flex-col min-w-0 mr-2",onClick:()=>{R(O.id,oe.id),C()},children:e.jsx("span",{className:"font-medium truncate",children:A(oe)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:de=>{de.preventDefault(),de.stopPropagation(),l(O.id,oe.id)},className:P("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",d(O.id,oe.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":d(O.id,oe.id)?"Unfavorite":"Favorite",children:d(O.id,oe.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(Bn,{className:"h-4 w-4"})}),Q&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},oe.id)})})]},O.id)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{R("",""),C()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[g?e.jsxs("button",{type:"button",onClick:()=>h(!0),className:P("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",n),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s?e.jsx(rs,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s&&r?`${s}/${r}`:"Select model..."})]}),e.jsx(Mt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ut,{open:x,onOpenChange:v,children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:P("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",n),children:[s?e.jsxs(e.Fragment,{children:[e.jsx(rs,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(mr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s&&r?`${s}/${r}`:"Not selected"}),e.jsx(Mt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const O=[];B.forEach(({model:oe,providerID:Q,modelID:de})=>{O.push({model:oe,providerID:Q,modelID:de,section:"fav"})}),re.forEach(({model:oe,providerID:Q,modelID:de})=>{O.push({model:oe,providerID:Q,modelID:de,section:"recent"})}),Y.forEach(oe=>{oe.models.forEach(Q=>{O.push({model:Q,providerID:oe.id,modelID:Q.id,section:"provider"})})});const z=O.length,U=oe=>{if(oe.key==="ArrowDown"){oe.preventDefault(),oe.stopPropagation();const Q=(S+1)%Math.max(1,z);D(Q),setTimeout(()=>{M.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(oe.key==="ArrowUp"){oe.preventDefault(),oe.stopPropagation();const Q=(S-1+Math.max(1,z))%Math.max(1,z);D(Q),setTimeout(()=>{M.current[Q]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(oe.key==="Enter"){oe.preventDefault(),oe.stopPropagation();const Q=O[S];Q&&R(Q.providerID,Q.modelID)}else oe.key==="Escape"&&(oe.preventDefault(),oe.stopPropagation(),v(!1))};let ne=0;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(pt,{type:"text",placeholder:"Search models",value:N,onChange:oe=>y(oe.target.value),onKeyDown:U,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(dt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:P("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>R("",""),children:[e.jsx(Ht,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Not selected"}),!s&&!r&&e.jsx(At,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ms,{}),!_&&N&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),B.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),B.map(({model:oe,providerID:Q,modelID:de})=>{const I=ne++;return T(oe,Q,de,"fav",I,S===I)})]}),re.length>0&&e.jsxs(e.Fragment,{children:[B.length>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),re.map(({model:oe,providerID:Q,modelID:de})=>{const I=ne++;return T(oe,Q,de,"recent",I,S===I)})]}),(B.length>0||re.length>0)&&Y.length>0&&e.jsx(Ms,{}),Y.map((oe,Q)=>e.jsxs(c.Fragment,{children:[Q>0&&e.jsx(Ms,{}),e.jsxs(Wr,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(rs,{providerId:oe.id,className:"h-4 w-4 flex-shrink-0"}),oe.name]}),oe.models.map(de=>{const I=ne++;return T(de,oe.id,de.id,"provider",I,S===I)})]},oe.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()})]}),q()]})},w0=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],xr=s=>s==="allow"||s==="ask"||s==="deny",v0=s=>{if(xr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(xr(r))return r}},j0=s=>{if(xr(s))return{entries:{"*":s}};if(!s||typeof s!="object"||Array.isArray(s))return{entries:{}};const r={};for(const[t,n]of Object.entries(s)){const o=v0(n);o!==void 0&&(r[t]=o)}return{entries:r}},S0=s=>{const r={...s},t=r["*"];return xr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},ba=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",Lo=(s,r)=>r==="default"?ba(s):r,Nd=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=Lo(n,r),i=ba(n);if(!(xr(o)&&o!==i)){if(xr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const l=o,d=Object.keys(l),u=l["*"];if(u!==void 0&&u!==i)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},tf=s=>{if(!Array.isArray(s))return null;const r=[];for(const t of s){if(!t||typeof t!="object")continue;const n=t;typeof n.permission!="string"||typeof n.pattern!="string"||typeof n.action!="string"||n.action!=="allow"&&n.action!=="ask"&&n.action!=="deny"||r.push({permission:n.permission,pattern:n.pattern,action:n.action})}return r},k0=s=>{const r=tf(s);if(!r||r.length===0)return{entries:{}};const t={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(t[a.permission]=a.action);const n=t["*"],o={};for(const[a,i]of Object.entries(t)){if(a==="*"){o[a]=i;continue}const l=ba(a);if(n){if(i===n)continue}else if(i===l)continue;o[a]=i}return{entries:o}},N0=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=Fr();et();const l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,w]=c.useState(""),[h,j]=c.useState("subagent"),[b,x]=c.useState(""),[v,N]=c.useState(void 0),[y,S]=c.useState(void 0),[D,M]=c.useState(""),[C,k]=c.useState("default"),[A,E]=c.useState({}),[R,V]=c.useState(""),[T,B]=c.useState(!1),re=ct($=>$.currentDirectory??null),[Y,_]=c.useState([]),q=Zn($=>$.permissions);c.useEffect(()=>{let $=!1;return(async()=>{const J=await ke.listToolIds({directory:re});if($)return;const pe=new Set(["write","patch","multiedit"]),be=J.map(he=>typeof he=="string"?he.trim():"").filter(Boolean).filter(he=>he!=="*").filter(he=>he!=="invalid").filter(he=>!pe.has(he));_(Array.from(new Set(be)).sort((he,Ae)=>he.localeCompare(Ae)))})(),()=>{$=!0}},[re]);const O=c.useMemo(()=>{const $=new Set;for(const L of o){const J=tf(L.permission);if(J)for(const pe of J)pe.permission&&pe.permission!=="*"&&pe.permission!=="invalid"&&$.add(pe.permission)}for(const L of q.values())for(const J of L){const pe=J.permission?.trim();pe&&pe!=="invalid"&&$.add(pe)}for(const L of Y)$.add(L);return Array.from($).sort((L,J)=>L.localeCompare(J))},[o,q,Y]),z=c.useCallback($=>{const L=A[$];if(xr(L))return L;if(L&&typeof L=="object"&&!Array.isArray(L)){const J=L["*"];if(xr(J))return J}},[A]),U=c.useCallback($=>{const L=A[$];return!L||typeof L!="object"||Array.isArray(L)?0:Object.keys(L).filter(pe=>pe!=="*").length},[A]),ne=c.useCallback(($,L)=>{$!=="*"&&E(J=>{const pe={...J},be=pe[$],he=Lo($,C),Ae=ba($),je=L===he&&L===Ae;if(be&&typeof be=="object"&&!Array.isArray(be)){const Te={...be};Te["*"]=L;const K=Object.keys(Te).filter(X=>X!=="*");return je&&K.length===0?(delete pe[$],pe):(pe[$]=Te,pe)}return je?(delete pe[$],pe):(pe[$]=L,pe)})},[C]),oe=c.useCallback($=>{E(L=>{if(!($ in L))return L;const J={...L};return delete J[$],J})},[]),Q=c.useMemo(()=>{const $=Object.entries(A).filter(([L])=>L!=="*");return $.sort(([L],[J])=>L.localeCompare(J)),$},[A]),de=c.useMemo(()=>{const $=new Set;for(const L of w0)$.add(L);for(const L of O)$.add(L);for(const L of Object.keys(A))$.delete(L);return Array.from($).sort((L,J)=>L.localeCompare(J))},[O,A]),I=c.useCallback($=>{const L=R.trim();if(!L)return;const J=Lo(L,C);if($===J){const pe=C==="default"?"OpenCode defaults":`Default Permissions ("${C}")`;se.message(`"${L}" already matches ${pe} (${J}).`),V("");return}ne(L,$),V("")},[R,ne,C]),W=c.useCallback($=>$==="webfetch"?"WebFetch":$==="websearch"?"WebSearch":$==="codesearch"?"CodeSearch":$==="doom_loop"?"Doom Loop":$==="external_directory"?"External Directory":$==="todowrite"?"TodoWrite":$==="todoread"?"TodoRead":$.split(/[_-]+/g).filter(Boolean).map(L=>L.charAt(0).toUpperCase()+L.slice(1)).join(" "),[]);c.useEffect(()=>{V("");const $=L=>{const J=S0(L);k(J.defaultOverride),E(Nd(J.overrides,J.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),w(a.description||""),j(a.mode||"subagent"),x(a.model||""),N(a.temperature),S(a.top_p),M(a.prompt||"");const L=j0(a.permission);$(L.entries);return}if(l&&s===l.name){w(l.description||""),j(l.mode||"subagent"),l.model?.providerID&&l.model?.modelID?x(`${l.model.providerID}/${l.model.modelID}`):x(""),N(l.temperature),S(l.topP),M(l.prompt||"");const L=k0(l.permission);$(L.entries)}},[a,d,l,s]);const F=async()=>{const $=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!$){se.error("Agent name is required");return}if(d&&o.some(L=>L.name===$)){se.error("An agent with this name already exists");return}B(!0);try{const L=b.trim(),J={name:$,description:g.trim()||void 0,mode:h,model:L===""?null:L,temperature:v,top_p:y,prompt:D.trim()||void 0,permission:(()=>{const be=Nd(A,C),he=C==="default"?be:{"*":C,...be},Ae=["doom_loop","external_directory"];for(const Te of Ae)if(!(Te in he)){const K=A[Te];xr(K)?he[Te]=K:he[Te]=Lo(Te,C)}return Object.keys(he).length===0?d?void 0:null:he})(),scope:d?f:void 0};let pe;d?(pe=await t(J),pe&&i(null)):pe=await n($,J),pe?se.success(d?"Agent created successfully":"Agent updated successfully"):se.error(d?"Failed to create agent":"Failed to update agent")}catch(L){console.error("Error saving agent:",L);const J=L instanceof Error&&L.message?L.message:"An error occurred while saving";se.error(J)}finally{B(!1)}};return s?e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Agent":s})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure agent identity and behavior mode"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"@"}),e.jsx(pt,{value:u,onChange:$=>m($.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(vs,{value:f,onValueChange:$=>p($),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Lt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Lt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Is,{value:g,onChange:$=>w($.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Bs,{variant:h==="primary"?"default":"outline",onClick:()=>j("primary"),className:P("gap-2",h==="primary"?void 0:"text-foreground"),children:[e.jsx(qr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Bs,{variant:h==="subagent"?"default":"outline",onClick:()=>j("subagent"),className:P("gap-2",h==="subagent"?void 0:"text-foreground"),children:[e.jsx(uu,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Bs,{variant:h==="all"?"default":"outline",onClick:()=>j("all"),className:P("gap-2",h==="all"?void 0:"text-foreground"),children:[e.jsx(mu,{className:"h-3 w-3"}),"All"]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Primary: main agent, Subagent: helper agent, All: both modes"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and generation parameters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Sl,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:($,L)=>{x($&&L?`${$}/${L}`:"")}})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Temperature",e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Controls randomness in responses.",e.jsx("br",{}),"Higher values make output more creative and unpredictable,",e.jsx("br",{}),"lower values make it more focused and deterministic."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const L=Math.max(0,(v!==void 0?v:.7)-.1);N(parseFloat(L.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Ma,{className:"h-3.5 w-3.5"})}),e.jsx(pt,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:$=>{const L=$.target.value;if(L===""){N(void 0);return}const J=parseFloat(L);!isNaN(J)&&J>=0&&J<=2&&N(J)},onBlur:$=>{const L=$.target.value;if(L!==""){const J=parseFloat(L);if(!isNaN(J)){const pe=Math.max(0,Math.min(2,J));N(parseFloat(pe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const L=Math.min(2,(v!==void 0?v:.7)+.1);N(parseFloat(L.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Kt,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Controls diversity via nucleus sampling.",e.jsx("br",{}),"Lower values focus on most likely tokens,",e.jsx("br",{}),"higher values consider more possibilities."]})]})]}),e.jsxs("div",{className:"relative w-32",children:[e.jsx("button",{type:"button",onClick:()=>{const L=Math.max(0,(y!==void 0?y:.9)-.1);S(parseFloat(L.toFixed(1)))},className:"absolute left-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Ma,{className:"h-3.5 w-3.5"})}),e.jsx(pt,{type:"text",inputMode:"decimal",value:y!==void 0?y:"",onChange:$=>{const L=$.target.value;if(L===""){S(void 0);return}const J=parseFloat(L);!isNaN(J)&&J>=0&&J<=1&&S(J)},onBlur:$=>{const L=$.target.value;if(L!==""){const J=parseFloat(L);if(!isNaN(J)){const pe=Math.max(0,Math.min(1,J));S(parseFloat(pe.toFixed(1)))}}},placeholder:"—",className:"text-center px-10 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),e.jsx("button",{type:"button",onClick:()=>{const L=Math.min(1,(y!==void 0?y:.9)+.1);S(parseFloat(L.toFixed(1)))},className:"absolute right-2 top-1/2 -translate-y-1/2 flex items-center justify-center h-6 w-6 rounded hover:bg-accent text-muted-foreground hover:text-foreground",children:e.jsx(Kt,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(Is,{value:D,onChange:$=>M($.target.value),placeholder:"Custom system prompt for this agent...",rows:8,className:"font-mono typography-meta"})]}),e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Tool Access"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"OpenCode v1.1.1+ configures tool access via the permissions below."})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:'This editor only updates wildcard ("*") rules; existing pattern rules are preserved.'})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Permissions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Set the default behavior for all permissions for this agent."}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:C==="default"?"default":"outline",onClick:()=>k("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(Ne,{size:"sm",variant:C==="allow"?"default":"outline",onClick:()=>k("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:C==="ask"?"default":"outline",onClick:()=>k("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:C==="deny"?"default":"outline",onClick:()=>k("deny"),className:"h-6 px-2 text-xs",children:"Deny"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Default:"})," Follow OpenCode default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block the operation"]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Overrides"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Add overrides for permissions that should behave differently for this agent."}),e.jsx("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsxs(vs,{value:R,onValueChange:V,children:[e.jsx(js,{className:"h-8 w-full sm:w-72",children:R?e.jsx("span",{className:"truncate",children:W(R)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(Ss,{children:de.map($=>e.jsx(Lt,{value:$,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:W($)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$})]})},$))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:"outline",disabled:!R,onClick:()=>I("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),Q.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C==="default"?"No overrides configured. Everything follows OpenCode defaults.":`No overrides configured. All permissions default to "${C}" for this agent.`}):e.jsx("div",{className:"space-y-4",children:Q.map(([$])=>{const L=z($),J=U($),pe=W($);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:[e.jsx("span",{children:pe}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:$}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Allow:"})," Run without confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Ask:"})," Prompt for confirmation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Deny:"})," Block this operation"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Remove:"})," Return to default behavior"]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Note:"}),' Buttons set the "*" rule only']}),J>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",J," pattern rules preserved"]}):null]})})]})]}),e.jsxs(Ne,{size:"sm",variant:"outline",onClick:()=>oe($),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(Ma,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ne,{size:"sm",variant:L==="allow"?"default":"outline",onClick:()=>ne($,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ne,{size:"sm",variant:L==="ask"?"default":"outline",onClick:()=>ne($,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ne,{size:"sm",variant:L==="deny"?"default":"outline",onClick:()=>ne($,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},$)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:F,disabled:T,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ca,{className:"h-3 w-3"}),T?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Yn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select an agent from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},C0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Tr(),{setSidebarOpen:p}=_e(),{isMobile:g}=Ft(),[w,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const b=w?"bg-transparent":j?"bg-background":"bg-sidebar",x=()=>{const k="new-command";let A=k,E=1;for(;i.some(R=>R.name===A);)A=`${k}-${E}`,E++;d({name:A,scope:"user"}),l(A),s?.(),g&&p(!1)},v=async k=>{if(mn(k)){se.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${k.name}"?`)&&(await m(k.name)?se.success(`Command "${k.name}" deleted successfully`):se.error("Failed to delete command"))},N=async k=>{mn(k)&&window.confirm(`Are you sure you want to reset command "${k.name}" to its default configuration?`)&&(await m(k.name)?se.success(`Command "${k.name}" reset to default`):se.error("Failed to reset command"))},y=k=>{const A=k.name;let E=1,R=`${A}-copy`;for(;i.some(V=>V.name===R);)E++,R=`${A}-copy-${E}`;d({name:R,scope:k.scope||"user",description:k.description,template:k.template,agent:k.agent,model:k.model,subtask:k.subtask}),l(R),g&&p(!1)},S=k=>{o(k.name),t(k)},D=async()=>{if(!r)return;const k=n.trim().replace(/\s+/g,"-");if(!k){se.error("Command name is required");return}if(k===r.name){t(null);return}if(i.some(E=>E.name===k)){se.error("A command with this name already exists");return}await u({name:k,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(se.success(`Command renamed to "${k}"`),l(k)):se.error("Failed to remove old command after rename"):se.error("Failed to rename command"),t(null)},M=i.filter(mn),C=i.filter(k=>!mn(k));return e.jsxs("div",{className:P("flex h-full flex-col",b),children:[e.jsx("div",{className:P("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Er,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No commands configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Built-in Commands"}),[...M].sort((k,A)=>k.name.localeCompare(A.name)).map(k=>e.jsx(Cd,{command:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),g&&p(!1)},onReset:()=>N(k),onDuplicate:()=>y(k)},k.name))]}),C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Commands"}),[...C].sort((k,A)=>k.name.localeCompare(A.name)).map(k=>e.jsx(Cd,{command:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),g&&p(!1)},onRename:()=>S(k),onDelete:()=>v(k),onDuplicate:()=>y(k)},k.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:k=>!k&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Command"}),e.jsxs(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(pt,{value:n,onChange:k=>o(k.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:k=>{k.key==="Enter"&&D()}}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Xr,{onClick:D,children:"Rename"})]})]})})]})},Cd=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-ui-label font-normal truncate text-foreground",children:["/",s.name]}),(s.scope||mn(s))&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:mn(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(vt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(la,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(vt,{onClick:l=>{l.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(vt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Es,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(vt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),sf=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=Fr(),a=o(),i=_e(w=>w.isMobile),{isMobile:l}=Ft(),d=i||l,[u,m]=c.useState(!1);c.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=w=>{r(w)},g=()=>d?e.jsx(ws,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(w=>{const h=w.name===s;return e.jsxs("button",{type:"button",className:P("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",h?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(w.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:w.name}),w.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:w.description})]}),h&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},w.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{p(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:P("flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",t),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yn,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s||"Select agent..."})]}),e.jsx(Mt,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("div",{className:P("flex items-center gap-2 px-2 rounded-lg bg-accent/20 border border-border/20 cursor-pointer hover:bg-accent/30 h-6 w-fit",t),children:[e.jsx(Yn,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s||"Not selected"}),e.jsx(Mt,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Gt,{className:"max-w-[300px]",children:[a.map(w=>e.jsx(vt,{className:"typography-meta",onSelect:()=>p(w.name),children:e.jsx("span",{className:"font-medium",children:w.name})},w.name)),e.jsx(vt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),g()]})},M0=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=Tr(),l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,w]=c.useState(""),[h,j]=c.useState(""),[b,x]=c.useState(""),[v,N]=c.useState(""),[y,S]=c.useState(!1),[D,M]=c.useState(!1);c.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),w(a.description||""),j(a.agent||""),x(a.model||""),N(a.template||""),S(a.subtask||!1)):l&&(w(l.description||""),j(l.agent||""),x(l.model||""),N(l.template||""),S(l.subtask||!1))},[l,d,s,o,a]);const C=async()=>{const k=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!k){se.error("Command name is required");return}if(!v.trim()){se.error("Command template is required");return}if(d&&o.some(A=>A.name===k)){se.error("A command with this name already exists");return}M(!0);try{const A=h.trim(),E=b.trim(),R=v.trim(),V={name:k,description:g.trim()||void 0,agent:A===""?null:A,model:E===""?null:E,template:R,subtask:y,scope:d?f:void 0};let T;d?(T=await t(V),T&&i(null)):T=await n(k,V),T?se.success(d?"Command created successfully":"Command updated successfully"):se.error(d?"Failed to create command":"Failed to update command")}catch(A){console.error("Error saving command:",A),se.error("An error occurred while saving")}finally{M(!1)}};return s?e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:d?"New Command":`/${s}`})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure command identity and metadata"})]}),d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Command Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center flex-1",children:[e.jsx("span",{className:"typography-ui-label text-muted-foreground mr-1",children:"/"}),e.jsx(pt,{value:u,onChange:k=>m(k.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(vs,{value:f,onValueChange:k=>p(k),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Lt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Lt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Is,{value:g,onChange:k=>w(k.target.value),placeholder:"What does this command do?",rows:3})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Model & Agent Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure model and agent for command execution"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(sf,{agentName:h,onChange:k=>j(k)}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Agent to execute this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Model"}),e.jsx(Sl,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(k,A)=>{x(k&&A?`${k}/${A}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:y,onChange:k=>S(k.target.checked),className:"sr-only"}),e.jsx("div",{className:P("w-5 h-5 rounded border-2 flex items-center justify-center",y?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:y&&e.jsx(At,{className:"w-3 h-3 text-primary-foreground"})})]}),"Force Subagent Invocation"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Force command to run in a subagent context"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["When enabled, this command will always execute in a subagent context,",e.jsx("br",{}),"even if triggered from main agent.",e.jsx("br",{}),"Useful for isolating command logic and maintaining clean separation of concerns."]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Command Template"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Define the prompt template for this command. Use $ARGUMENTS for user input."})]}),e.jsx(Is,{value:v,onChange:k=>N(k.target.value),placeholder:`Your command template here...
103
+
104
+ Use $ARGUMENTS to reference user input.
105
+ Use !\`shell command\` to inject shell output.
106
+ Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Replaced with everything the user types after the command name.",e.jsx("br",{}),'Example: "/deploy staging" makes $ARGUMENTS = "staging"']})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"!`command`"}),e.jsx("span",{children:"- Inject shell command output"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Executes shell command and replaces this placeholder with its output.",e.jsx("br",{}),"Example: !`git branch --show-current` gets current branch name"]})]})]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"@filename"}),e.jsx("span",{children:"- Include file contents"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Replaces with the full contents of the specified file.",e.jsx("br",{}),"Example: @package.json includes the package.json content in the prompt"]})]})]})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:C,disabled:D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ca,{className:"h-3 w-3"}),D?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Er,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a command from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})},D0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Hs(),{setSidebarOpen:g}=_e(),{isMobile:w}=Ft(),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=h?"bg-transparent":b?"bg-background":"bg-sidebar",v=()=>{const k="new-skill";let A=k,E=1;for(;i.some(R=>R.name===A);)A=`${k}-${E}`,E++;d({name:A,scope:"user",description:""}),l(A),s?.(),w&&g(!1)},N=async k=>{window.confirm(`Are you sure you want to delete skill "${k.name}"?`)&&(await m(k.name)?se.success(`Skill "${k.name}" deleted successfully`):se.error("Failed to delete skill"))},y=async k=>{const A=k.name;let E=1,R=`${A}-copy`;for(;i.some(T=>T.name===R);)E++,R=`${A}-copy-${E}`;const V=await p(k.name);if(!V){se.error("Failed to load skill details for duplication");return}d({name:R,scope:k.scope||"user",description:(V.sources.md.fields.includes("description"),""),instructions:""}),l(R),w&&g(!1)},S=k=>{o(k.name),t(k)},D=async()=>{if(!r)return;const k=n.trim().replace(/\s+/g,"-").toLowerCase();if(!k){se.error("Skill name is required");return}if(k===r.name){t(null);return}if(i.some(R=>R.name===k)){se.error("A skill with this name already exists");return}if(!await p(r.name)){se.error("Failed to load skill details"),t(null);return}await u({name:k,description:"Renamed skill",scope:r.scope})?await m(r.name)?(se.success(`Skill renamed to "${k}"`),l(k)):se.error("Failed to remove old skill after rename"):se.error("Failed to rename skill"),t(null)},M=i.filter(k=>k.scope==="project"),C=i.filter(k=>k.scope==="user");return e.jsxs("div",{className:P("flex h-full flex-col",x),children:[e.jsx("div",{className:P("border-b px-3",w?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(fu,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No skills configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsxs(e.Fragment,{children:[M.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Project Skills"}),M.map(k=>e.jsx(Md,{skill:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),w&&g(!1)},onRename:()=>S(k),onDelete:()=>N(k),onDuplicate:()=>y(k)},k.name))]}),C.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"User Skills"}),C.map(k=>e.jsx(Md,{skill:k,isSelected:a===k.name,onSelect:()=>{l(k.name),s?.(),w&&g(!1)},onRename:()=>S(k),onDelete:()=>N(k),onDuplicate:()=>y(k)},k.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:k=>!k&&t(null),children:e.jsxs(fs,{children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Rename Skill"}),e.jsxs(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(pt,{value:n,onChange:k=>o(k.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:k=>{k.key==="Enter"&&D()}}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Xr,{onClick:D,children:"Rename"})]})]})})]})},Md=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsx("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:s.scope}),s.source==="claude"&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"claude"})]})}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Gt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(vt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(la,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(vt,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(vt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function rf({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const i=c.useRef(null),l=c.useRef(null),d=c.useCallback(()=>{const u=i.current,m=l.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:g}=m,w=Math.max(0,Math.min(100,p/f*100)),h=Math.max(0,Math.min(100,(p+g)/f*100));u.style.clipPath=`inset(0 ${Number(100-h).toFixed(2)}% 0 ${Number(w).toFixed(2)}% round 8px)`},[]);return c.useLayoutEffect(()=>{d()},[d,r,s.length]),c.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:P("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:P("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:s.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?l:null,type:"button",onClick:()=>{o&&t(u.value)},className:P("flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold transition-colors duration-150",m?"text-accent-foreground":"text-muted-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-offset-1 focus-visible:ring-offset-background"),"aria-pressed":m,"aria-disabled":!o,tabIndex:o?0:-1,children:[f?e.jsx(f,{className:P("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const A0=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,E0=s=>{const r=s.trim(),t=r.match(/^git@github\.com:([^/\s]+)\/([^\s#]+)$/i);if(t)return`${t[1]}/${t[2].replace(/\.git$/i,"")}`;const n=r.match(/^https?:\/\/github\.com\/([^/\s]+)\/([^\s#]+)$/i);if(n)return`${n[1]}/${n[2].replace(/\.git$/i,"")}`;const o=r.match(/^([^/\s]+)\/([^/\s]+)(?:\/.+)?$/);return o?`${o[1]}/${o[2].replace(/\.git$/i,"")}`:r},I0=async()=>{try{if(os())return await Dn();const s=Zr()?.settings;if(s)return(await s.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},P0=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=so(),[a,i]=c.useState(""),[l,d]=c.useState(""),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,w]=c.useState(null),[h,j]=c.useState(!1),[b,x]=c.useState([]),[v,N]=c.useState(null);c.useEffect(()=>{s&&(i(""),d(""),m(""),w(null),j(!1),x([]),N(null),(async()=>{const M=await I0(),C=Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[];p(C||[])})())},[s]);const y=c.useMemo(()=>{const M=l.trim(),C=u.trim();return f.some(k=>{const A=(k.source||"").trim(),E=(k.subpath||"").trim();return A===M&&E===C})},[f,l,u]),S=async()=>{const M=l.trim();if(!M){se.error("Repository source is required");return}a.trim()||i(E0(M)),j(!1),w(null);const C=await t({source:M,subpath:u.trim()||void 0,gitIdentityId:v||void 0});if(!C.ok){if(C.error?.kind==="authRequired"){if(Wt()){se.error("Private repositories are not supported in VS Code yet");return}const A=C.error.identities||[];x(A),!v&&A.length>0&&N(A[0].id),se.error("Authentication required. Select a Git identity and scan again.");return}se.error(C.error?.message||"Failed to scan repository");return}const k=C.items?.length||0;if(w(k),k===0){se.error("No skills found in this repository"),j(!1);return}x([]),j(!0),se.success(`Found ${k} skill(s)`)},D=async()=>{const M=a.trim(),C=l.trim(),k=u.trim();if(!M){se.error("Catalog name is required");return}if(!C){se.error("Repository source is required");return}if(!h){se.error("Scan the repository before adding this catalog");return}if(y){se.error("This catalog already exists");return}const A={id:A0(),label:M,source:C,...k?{subpath:k}:{},...v?{gitIdentityId:v}:{}},E=[...f,A];try{await ns({skillCatalogs:E}),p(E),se.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(R){se.error(R instanceof Error?R.message:"Failed to save catalog")}};return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-xl",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Add skills catalog"}),e.jsxs(Ns,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(pt,{value:a,onChange:M=>i(M.target.value),placeholder:"e.g. Team Skills"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Repository"}),e.jsx(pt,{value:l,onChange:M=>{d(M.target.value),j(!1),w(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(pt,{value:u,onChange:M=>{m(M.target.value),j(!1),w(null)},placeholder:"e.g. skills"})]}),b.length>0&&!Wt()?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Authentication required"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:"Select a Git identity (SSH key) that can access this repository."}),e.jsx("div",{className:"mt-2",children:e.jsxs(vs,{value:v||"",onValueChange:M=>N(M),children:[e.jsx(js,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:b.find(M=>M.id===v)?.name||"Choose identity"})}),e.jsx(Ss,{align:"start",children:b.map(M=>e.jsx(Lt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.name},M.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,g!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",g," skill(s) found"]}):null,y?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Ne,{variant:"outline",onClick:()=>{S()},disabled:o||!l.trim(),className:"gap-2",children:[e.jsx(ph,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ne,{variant:"default",onClick:()=>{D()},disabled:!h||y||!a.trim()||!l.trim(),children:"Add catalog"})]})]})})},T0=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=c.useState({});c.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const i=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},l=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Skills already exist"}),e.jsx(Ns,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>i("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:t.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(vs,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(js,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Ss,{align:"end",children:[e.jsx(Lt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Lt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Xr,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},F0=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=so(),[a,i]=c.useState("user"),[l,d]=c.useState(!1),[u,m]=c.useState([]),[f,p]=c.useState(null);c.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const g=async w=>{const h=await n({source:w.source,subpath:w.subpath,gitIdentityId:t?.gitIdentityId,scope:w.scope,selections:[{skillDir:w.skillDir}],conflictPolicy:"prompt",conflictDecisions:w.conflictDecisions});if(h.ok){se.success("Skill installed successfully"),r(!1);return}if(h.error?.kind==="conflicts"){p({source:w.source,subpath:w.subpath,scope:w.scope,skillDir:w.skillDir}),m(h.error.conflicts),d(!0);return}if(h.error?.kind==="authRequired"){se.error(h.error.message||"Authentication required");return}se.error(h.error?.message||"Failed to install skill")};return t?e.jsxs(e.Fragment,{children:[e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-lg",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Install skill"}),e.jsxs(Ns,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:t.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:t.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:t.warnings.map(w=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:w},w))})]}):null}),e.jsxs(qs,{className:"flex flex-col gap-3 sm:flex-row sm:justify-between sm:items-center",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(vs,{value:a,onValueChange:w=>i(w),children:[e.jsx(js,{className:"!h-9 w-full sm:w-36 justify-between",children:e.jsxs("span",{className:"flex flex-1 items-center gap-2 justify-start",children:[a==="user"?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Ss,{align:"start",children:[e.jsx(Lt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Lt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(Ne,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Ne,{className:"w-full sm:w-auto",variant:"default",disabled:o||!t.installable,onClick:()=>{g({source:t.repoSource,subpath:t.repoSubpath,scope:a,skillDir:t.skillDir})},children:o?"Installing…":"Install"})]})]})]})}),e.jsx(T0,{open:l,onOpenChange:d,conflicts:u,onConfirm:w=>{f&&(g({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:w}),d(!1))}})]}):null},R0=async()=>{try{if(os())return await Dn();const s=Zr()?.settings;if(s)return(await s.load())?.settings||{};const r=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});return r.ok?await r.json().catch(()=>null):null}catch{return null}},_0=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:l,lastCatalogError:d}=so(),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(!1),[h,j]=c.useState(null),[b,x]=c.useState(!1);c.useEffect(()=>{i()},[i]);const v=c.useMemo(()=>o?n[o]||[]:[],[n,o]),N=c.useMemo(()=>{const M=u.trim().toLowerCase();return M?v.filter(C=>{const k=C.skillName.toLowerCase(),A=(C.description||"").toLowerCase(),E=(C.frontmatterName||"").toLowerCase();return k.includes(M)||A.includes(M)||E.includes(M)}):v},[v,u]),y=c.useMemo(()=>t.find(M=>M.id===o)||null,[t,o]),S=!!(o&&o.startsWith("custom:")),D=async()=>{if(!(!o||!S)&&window.confirm("Remove this catalog?")){x(!0);try{const M=await R0(),k=(Array.isArray(M?.skillCatalogs)?M?.skillCatalogs:[]).filter(A=>A.id!==o);await ns({skillCatalogs:k}),await i({refresh:!0})}finally{x(!1)}}};return e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(rf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:s,onValueChange:r,animate:!1}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Skills Catalog"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Browse curated repositories and install skills into your OpenCode configuration."})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Source"}),e.jsxs(vs,{value:o||"",onValueChange:M=>a(M),children:[e.jsx(js,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:y?.label||"Select source"})}),e.jsx(Ss,{align:"start",children:t.map(M=>e.jsx(Lt,{value:M.id,className:"pr-2 [&>span:first-child]:hidden",children:M.label},M.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ne,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:l,className:"gap-2",children:[e.jsx(Dr,{className:"h-4 w-4"}),"Refresh"]}),S?e.jsxs(Ne,{type:"button",variant:"outline",onClick:()=>{D()},disabled:b,className:"gap-2",children:[e.jsx(Ks,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ne,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Kt,{className:"h-4 w-4"}),"Add catalog"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(pt,{value:u,onChange:M=>m(M.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:l?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(M=>{const C=M.installed?.isInstalled,k=M.installed?.scope;return e.jsx("div",{className:"rounded-lg border bg-muted/10 px-3 py-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label truncate",children:M.skillName}),C?e.jsxs("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:["installed (",k||"unknown",")"]}):null,M.installable?null:e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"not installable"})]}),M.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:M.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),M.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:M.warnings.join(" · ")}):null]}),e.jsx(Ne,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!M.installable,onClick:()=>{j(M),w(!0)},children:"Install"})]})},`${M.sourceId}:${M.skillDir}`)})}),e.jsx(P0,{open:f,onOpenChange:p}),e.jsx(F0,{open:g,onOpenChange:w,item:h})]})})},O0=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:l,setSelectedSkill:d}=Hs(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,g]=c.useState("manual");c.useEffect(()=>{!m&&p!=="manual"&&g("manual")},[m,p]),c.useEffect(()=>{f&&d(null)},[f,d]);const w=m?e.jsx(rf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:g,animate:!1}):null,[h,j]=c.useState(""),[b,x]=c.useState("user"),[v,N]=c.useState(""),[y,S]=c.useState(""),[D,M]=c.useState([]),[C,k]=c.useState([]),[A,E]=c.useState(!1),[R,V]=c.useState(!1),[T,B]=c.useState(""),[re,Y]=c.useState(""),[_,q]=c.useState(!1),[O,z]=c.useState(""),[U,ne]=c.useState(""),[oe,Q]=c.useState(null),[de,I]=c.useState(!1),[W,F]=c.useState(""),$=m?h.trim()!==""||v.trim()!==""||y.trim()!==""||C.length>0:v!==T||y!==re,L=oe?U!==W:O.trim()!=="";c.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)j(i.name||""),x(i.scope||"user"),N(i.description||""),S(i.instructions||""),B(""),Y(""),M([]),k(i.pendingFiles||[]);else if(s&&u){V(!0);try{const Te=await t(s);if(Te){const K=Te.sources.md;N(K.description||""),S(K.instructions||""),B(K.description||""),Y(K.instructions||""),M(K.supportingFiles||[])}}catch(Te){console.error("Failed to load skill details:",Te)}finally{V(!1)}}})()},[u,m,s,a,i,t,p]);const J=async()=>{const je=m?h.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!je){se.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(je)||je.length>64){se.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!v.trim()){se.error("Description is required");return}if(m&&a.some(Te=>Te.name===je)){se.error("A skill with this name already exists");return}E(!0);try{const Te={name:je,description:v.trim(),instructions:y.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&C.length>0?C:void 0};let K;m?(K=await n(Te),K&&(l(null),k([]),d(je))):(K=await o(je,Te),K&&(B(v.trim()),Y(y.trim()))),K?se.success(m?"Skill created successfully":"Skill updated successfully"):se.error(m?"Failed to create skill":"Failed to update skill")}catch(Te){console.error("Error saving skill:",Te),se.error("An error occurred while saving")}finally{E(!1)}},pe=()=>{Q(null),z(""),ne(""),F(""),q(!0)},be=async je=>{if(Q(je),z(je),m){const K=C.find(X=>X.path===je)?.content||"";ne(K),F(K),q(!0);return}if(s){I(!0),q(!0);try{const{readSupportingFile:Te}=Hs.getState(),K=await Te(s,je);ne(K||""),F(K||"")}catch{se.error("Failed to load file content"),ne(""),F("")}finally{I(!1)}}},he=async()=>{if(!O.trim()){se.error("File name is required");return}const je=O.trim(),Te=oe!==null;if(m){if(Te)k(te=>te.map(fe=>fe.path===oe?{path:je,content:U}:fe)),se.success(`File "${je}" updated`);else{if(C.some(te=>te.path===je)){se.error("A file with this name already exists");return}k(te=>[...te,{path:je,content:U}]),se.success(`File "${je}" added`)}q(!1),Q(null);return}if(!s){se.error("No skill selected");return}const{writeSupportingFile:K}=Hs.getState();if(await K(s,je,U)){se.success(Te?`File "${je}" updated`:`File "${je}" created`),q(!1),Q(null);const te=await t(s);te&&M(te.sources.md.supportingFiles||[])}else se.error(Te?"Failed to update file":"Failed to create file")},Ae=async je=>{if(m){k(Te=>Te.filter(K=>K.path!==je)),se.success(`File "${je}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${je}"?`)){const{deleteSupportingFile:Te}=Hs.getState();if(await Te(s,je)){se.success(`File "${je}" deleted`);const X=await t(s);X&&M(X.sources.md.supportingFiles||[])}else se.error("Failed to delete file")}};return m&&p==="external"?e.jsx(_0,{mode:p,onModeChange:g}):!s&&!i||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(fu,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a skill from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})}):R?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsx("div",{className:"text-center text-muted-foreground",children:e.jsx("p",{className:"typography-body",children:"Loading skill details..."})})}):e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?w:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":s}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pt,{value:h,onChange:je=>j(je.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(vs,{value:b,onValueChange:je=>x(je),children:[e.jsxs(js,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(Ps,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(Ss,{align:"end",children:[e.jsx(Lt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ps,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Available in all projects"})]})}),e.jsx(Lt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Is,{value:v,onChange:je=>N(je.target.value),placeholder:"Brief description of what this skill does...",rows:2,className:"max-h-32 resize-none"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"The agent uses this to decide when to load the skill"})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Instructions"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Detailed instructions for the agent when this skill is loaded"})]}),e.jsx(Is,{value:y,onChange:je=>S(je.target.value),placeholder:"Step-by-step instructions, guidelines, or reference content...",rows:12,className:"font-mono typography-meta max-h-80 resize-y"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Supporting Files"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Reference documentation, scripts, or templates"})]}),e.jsxs(Ne,{variant:"outline",size:"sm",onClick:pe,className:"gap-1.5",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const je=m?C:D;return je.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-2",children:m?'No files yet. Use "Add File" to include reference materials.':'No supporting files. Use "Add File" to include reference materials.'}):e.jsx("div",{className:"space-y-2",children:je.map(Te=>e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 rounded-lg border bg-muted/30 hover:bg-muted/50 cursor-pointer transition-colors",onClick:()=>be(Te.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(tr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Te.path}),m&&e.jsx("span",{className:"typography-micro text-muted-foreground bg-muted px-1 rounded flex-shrink-0 leading-none pb-px border border-border/50",children:"pending"})]}),e.jsx(Ne,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:K=>{K.stopPropagation(),Ae(Te.path)},children:e.jsx(Ks,{className:"h-3.5 w-3.5"})})]},Te.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:J,disabled:A||!$,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(ca,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ms,{open:_,onOpenChange:je=>{q(je),je||Q(null)},children:e.jsxs(fs,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(xs,{className:"flex-shrink-0",children:[e.jsx(ys,{children:oe?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ns,{children:oe?"Modify the file content":"Create a new file in the skill directory"})]}),de?e.jsx("div",{className:"flex-1 flex items-center justify-center py-8",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Loading file content..."})}):e.jsxs("div",{className:"space-y-4 flex-1 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"File Path"}),e.jsx(pt,{value:O,onChange:je=>z(je.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:oe!==null}),!oe&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Relative path within the skill directory. Subdirectories will be created automatically."})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-h-0 flex flex-col",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground flex-shrink-0",children:"Content"}),e.jsx(Is,{value:U,onChange:je=>ne(je.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"ghost",onClick:()=>{q(!1),Q(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Xr,{onClick:he,disabled:de||!L,children:oe?"Save Changes":"Create File"})]})]})})]})})},$0="__add_provider__",L0=({onItemSelect:s})=>{const r=et(u=>u.providers),t=et(u=>u.selectedProviderId),n=et(u=>u.setSelectedProvider),{isMobile:o}=Ft(),[a,i]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:P("flex h-full flex-col",d),children:[e.jsx("div",{className:P("border-b px-3",o?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",r.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n($0),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:r.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(qn,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No providers found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]}):r.map(u=>{const m=Array.isArray(u.models)?u.models.length:0,f=u.id===t;return e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",f?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{type:"button",onClick:()=>{n(u.id),s?.()},className:"flex min-w-0 flex-1 items-center gap-2 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsx(rs,{providerId:u.id,className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 min-w-0 text-foreground",children:u.name||u.id}),e.jsx("span",{className:"typography-micro text-muted-foreground/60 flex-shrink-0",children:m})]})},u.id)})})]})},B0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Dd=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=B0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Ad="__add_provider__",Nn=s=>typeof s=="object"&&s!==null,Ed=s=>{const r=typeof s.type=="string"?s.type:"",t=`${s.name??""} ${s.label??""}`.toLowerCase(),n=`${r} ${t}`.toLowerCase();return n.includes("oauth")?"oauth":n.includes("api")?"api":r.toLowerCase()},z0=s=>{if(!Nn(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Nn(o)));return r},W0=s=>{if(typeof s=="string")return{id:s};if(!Nn(s))return null;const r=typeof s.id=="string"&&s.id||typeof s.providerID=="string"&&s.providerID||typeof s.slug=="string"&&s.slug||typeof s.name=="string"&&s.name;if(!r)return null;const t=typeof s.name=="string"?s.name:void 0;return{id:r,name:t}},H0=s=>{let r=[];Array.isArray(s)?r=s:Nn(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>W0(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},U0=()=>{const s=et(F=>F.providers),r=et(F=>F.selectedProviderId),t=et(F=>F.setSelectedProvider),n=et(F=>F.getModelMetadata),[o,a]=c.useState({}),[i,l]=c.useState(!1),[d,u]=c.useState({}),[m,f]=c.useState(null),[p,g]=c.useState(""),[w,h]=c.useState(null),[j,b]=c.useState({}),[x,v]=c.useState({}),[N,y]=c.useState([]),[S,D]=c.useState(!1),[M,C]=c.useState(null),[k,A]=c.useState(""),[E,R]=c.useState(""),[V,T]=c.useState(!1);c.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),c.useEffect(()=>{let F=!0;return(async()=>{l(!0);try{const L=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!L.ok)throw new Error(`Auth methods request failed (${L.status})`);const J=await L.json().catch(()=>({}));if(!F)return;a(z0(J))}catch(L){if(!F)return;console.error("Failed to load provider auth methods:",L),se.error("Failed to load provider authentication methods")}finally{F&&l(!1)}})(),()=>{F=!1}},[]),c.useEffect(()=>{let F=!0;return(async()=>{D(!0),C(null);try{const L=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!L.ok)throw new Error(`Provider list request failed (${L.status})`);const J=await L.json().catch(()=>({}));if(!F)return;y(H0(J))}catch(L){if(!F)return;console.error("Failed to load available providers:",L),C("Unable to load provider list")}finally{F&&D(!1)}})(),()=>{F=!1}},[]);const B=c.useMemo(()=>new Set(s.map(F=>F.id)),[s]),re=c.useMemo(()=>N.filter(F=>!B.has(F.id)),[N,B]);c.useEffect(()=>{if(r===Ad){if(!k&&re.length>0){A(re[0].id);return}k&&!re.some(F=>F.id===k)&&A(re[0]?.id??"")}},[r,k,re]);const Y=s.find(F=>F.id===r),_=async F=>{const $=d[F]?.trim()??"";if(!$){se.error("API key is required");return}const L=`api:${F}`;f(L);try{const J=await fetch(`/api/auth/${encodeURIComponent(F)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:$})}),pe=await J.json().catch(()=>null);if(!J.ok){const be=pe?.error||"Failed to save API key";throw new Error(be)}se.success("API key saved"),u(be=>({...be,[F]:""})),await Hn({scopes:["providers"],mode:"active"}),t(F)}catch(J){console.error("Failed to save API key:",J),se.error("Failed to save API key")}finally{f(null)}},q=async(F,$)=>{const L=`oauth:${F}:${$}`;f(L);try{const J=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:$})}),pe=await J.json().catch(()=>null);if(!J.ok){const X=pe?.error||"Failed to start OAuth flow";throw new Error(X)}const be=Nn(pe)?pe:{},he=Nn(be.data)?be.data:be,Ae=typeof he.url=="string"&&he.url||typeof he.verification_uri_complete=="string"&&he.verification_uri_complete||typeof he.verification_uri=="string"&&he.verification_uri||void 0,je=typeof he.instructions=="string"&&he.instructions||typeof he.message=="string"&&he.message||void 0,Te=typeof he.user_code=="string"&&he.user_code||typeof he.code=="string"&&he.code||typeof he.userCode=="string"&&he.userCode||void 0;if(!Ae&&!je&&!Te)throw new Error("No OAuth details returned");const K=`${F}:${$}`;v(X=>({...X,[K]:{url:Ae,instructions:je,userCode:Te}})),Ae&&window.open(Ae,"_blank","noopener,noreferrer"),h({providerId:F,methodIndex:$}),se.message("Complete the OAuth flow in your browser")}catch(J){console.error("Failed to start OAuth flow:",J),se.error("Failed to start OAuth flow")}finally{f(null)}},O=async(F,$)=>{const L=`${F}:${$}`,J=j[L]?.trim(),pe=`oauth-complete:${F}:${$}`;f(pe);try{const be={method:$};J&&(be.code=J);const he=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(be)}),Ae=await he.json().catch(()=>null);if(!he.ok){const je=Ae?.error||"Failed to complete OAuth flow";throw new Error(je)}se.success("OAuth connection completed"),b(je=>({...je,[L]:""})),h(null),await Hn({scopes:["providers"],mode:"active"}),t(F)}catch(be){console.error("Failed to complete OAuth flow:",be),se.error("Failed to complete OAuth flow")}finally{f(null)}},z=async F=>{try{await navigator.clipboard.writeText(F),se.success("OAuth link copied")}catch($){console.error("Failed to copy OAuth link:",$),se.error("Failed to copy OAuth link")}},U=async F=>{try{await navigator.clipboard.writeText(F),se.success("Device code copied")}catch($){console.error("Failed to copy device code:",$),se.error("Failed to copy device code")}},ne=async F=>{const $=`disconnect:${F}`;f($);try{const L=await fetch(`/api/provider/${encodeURIComponent(F)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),J=await L.json().catch(()=>null);if(!L.ok){const pe=J?.error||"Failed to disconnect provider";throw new Error(pe)}se.success("Provider disconnected"),await Hn({scopes:["providers"],mode:"active"})}catch(L){console.error("Failed to disconnect provider:",L),se.error("Failed to disconnect provider")}finally{f(null)}},oe=r===Ad;if(!oe&&s.length===0)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(qn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"No providers detected"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Check your OpenCode configuration"})]})});if(oe)return e.jsx(dt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:"Connect provider"}),e.jsx("p",{className:"typography-body text-muted-foreground",children:"Choose a provider to connect and set up its authentication."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Provider"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Select a provider that is not connected yet."})]}),S?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M}):re.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Ut,{open:V,onOpenChange:F=>{T(F),F||R("")},children:[e.jsx(Vt,{asChild:!0,children:e.jsxs("button",{type:"button",className:P("flex w-fit items-center justify-between gap-2 rounded-lg border border-input bg-transparent px-3 py-2 typography-ui-label","hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),children:[e.jsx("span",{className:k?"text-foreground":"text-muted-foreground",children:k?re.find(F=>F.id===k)?.name||k:"Select provider"}),e.jsx(Mt,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Gt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:F=>F.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:F=>F.stopPropagation(),children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:F=>R(F.target.value),onKeyDown:F=>F.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(dt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const F=re.filter($=>{const L=E.toLowerCase();return($.name||$.id).toLowerCase().includes(L)||$.id.toLowerCase().includes(L)});return F.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):F.map($=>e.jsxs(vt,{onSelect:()=>{A($.id),T(!1),R("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:$.name||$.id}),k===$.id&&e.jsx(At,{className:"h-4 w-4 text-primary"})]},$.id))})()})]})]})]}),k&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{type:"password",value:d[k]??"",onChange:F=>u($=>({...$,[k]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ne,{size:"sm",onClick:()=>_(k),disabled:m===`api:${k}`,className:"h-8",children:m===`api:${k}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),(()=>{const $=(o[k]??[]).filter(L=>Ed(L)==="oauth");return $.length===0?null:e.jsx("div",{className:"space-y-3",children:$.map((L,J)=>{const pe=L.label||L.name||`OAuth method ${J+1}`,be=`${k}:${J}`,he=w?.providerId===k&&w?.methodIndex===J;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:pe}),(L.description||L.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(L.description||L.help)})]}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>q(k,J),disabled:m===`oauth:${k}:${J}`,className:"h-8",children:"Connect"})]}),x[be]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:x[be]?.instructions}),x[be]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:x[be]?.userCode,readOnly:!0}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>U(x[be]?.userCode??""),className:"h-8",children:"Copy code"})]}),x[be]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:x[be]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:x[be]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>z(x[be]?.url??""),className:"h-8",children:"Copy link"})]})]}),he&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:j[be]??"",onChange:Ae=>b(je=>({...je,[be]:Ae.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ne,{size:"sm",onClick:()=>O(k,J),disabled:m===`oauth-complete:${k}:${J}`,className:"h-8",children:m===`oauth-complete:${k}:${J}`?"Saving…":"Complete"})]})]},`${k}-${pe}`)})})})()]})]})]})});if(!Y)return e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(qn,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a provider from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Review details and configure auth"})]})});const Q=Array.isArray(Y.models)?Y.models:[],I=(o[Y.id]??[]).filter(F=>Ed(F)==="oauth"),W=Q.filter(F=>{const $=typeof F?.name=="string"?F.name:"",L=typeof F?.id=="string"?F.id:"",J=p.trim().toLowerCase();return J?$.toLowerCase().includes(J)||L.toLowerCase().includes(J):!0});return e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{providerId:Y.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:Y.name||Y.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",Y.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{type:"password",value:d[Y.id]??"",onChange:F=>u($=>({...$,[Y.id]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ne,{size:"sm",onClick:()=>_(Y.id),disabled:m===`api:${Y.id}`,className:"h-8",children:m===`api:${Y.id}`?"Saving…":"Save key"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Keys are sent directly to OpenCode and never stored by OpenChamber."})]}),e.jsx("div",{className:"pt-2 border-t border-border/40",children:e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>ne(Y.id),disabled:m===`disconnect:${Y.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${Y.id}`?"Disconnecting…":"Disconnect provider"})}),I.length>0&&e.jsx("div",{className:"space-y-3",children:I.map((F,$)=>{const L=F.label||F.name||`OAuth method ${$+1}`,J=`${Y.id}:${$}`,pe=w?.providerId===Y.id&&w?.methodIndex===$;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:L}),(F.description||F.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(F.description||F.help)})]}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>q(Y.id,$),disabled:m===`oauth:${Y.id}:${$}`,className:"h-8",children:"Connect"})]}),x[J]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:x[J]?.instructions}),x[J]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:x[J]?.userCode,readOnly:!0}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>U(x[J]?.userCode??""),className:"h-8",children:"Copy code"})]}),x[J]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:x[J]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ne,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:x[J]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ne,{size:"sm",variant:"outline",onClick:()=>z(x[J]?.url??""),className:"h-8",children:"Copy link"})]})]}),pe&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(pt,{value:j[J]??"",onChange:be=>b(he=>({...he,[J]:be.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ne,{size:"sm",onClick:()=>O(Y.id,$),disabled:m===`oauth-complete:${Y.id}:${$}`,className:"h-8",children:m===`oauth-complete:${Y.id}:${$}`?"Saving…":"Complete"})]})]},`${Y.id}-${L}`)})})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Models"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Browse and filter models exposed by this provider."})]}),e.jsx(pt,{value:p,onChange:F=>g(F.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:W.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):W.map(F=>{const $=typeof F?.id=="string"?F.id:"",L=typeof F?.name=="string"?F.name:$,J=$?n(Y.id,$):void 0,pe=Dd(J?.limit?.context),be=Dd(J?.limit?.output),he=[];return J?.tool_call&&he.push({key:"tools",icon:ia,label:"Tool calling"}),J?.reasoning&&he.push({key:"reasoning",icon:ar,label:"Reasoning"}),J?.attachment&&he.push({key:"image",icon:br,label:"Image input"}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:L}),(pe||be)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[pe?`${pe} ctx`:"",pe&&be?" · ":"",be?`${be} out`:""]}),he.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:he.map(({key:Ae,icon:je,label:Te})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Te,"aria-label":Te,children:e.jsx(je,{className:"h-3 w-3"})},Ae))})]},$)})})]})]})})},V0={branch:Ot,briefcase:Ki,house:Gi,graduation:Vi,code:nr,heart:cu},G0={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},K0=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:l}=ya(),{setSidebarOpen:d}=_e(),{isMobile:u}=Ft(),[m,f]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),p=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||f(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{i(),l()},[i,l]);const g=m?"bg-transparent":p?"bg-background":"bg-sidebar",w=()=>{o("new"),s?.(),u&&d(!1)},h=async j=>{window.confirm(`Are you sure you want to delete profile "${j.name}"?`)&&(await a(j.id)?se.success(`Profile "${j.name}" deleted successfully`):se.error("Failed to delete profile"))};return e.jsxs("div",{className:P("flex h-full flex-col",g),children:[e.jsx("div",{className:P("border-b px-3",u?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",t.length]}),e.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsxs(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(Id,{profile:n,isSelected:r==="global",onSelect:()=>{o("global"),s?.(),u&&d(!1)},onDelete:void 0,isReadOnly:!0})]}),t.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),t.length===0&&!n?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Ot,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:t.map(j=>e.jsx(Id,{profile:j,isSelected:r===j.id,onSelect:()=>{o(j.id),s?.(),u&&d(!1)},onDelete:()=>h(j)},j.id))})]})]})},Id=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=V0[s.icon||"branch"]||Ot,i=G0[s.color||""];return e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),e.jsx("span",{className:"typography-ui-label font-normal truncate flex-1 text-foreground",children:s.name})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.userEmail})]}),!o&&n&&e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6 flex-shrink-0 -mr-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsx(Gt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(vt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Ks,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},Pd=[{key:"keyword",label:"Green",cssVar:"var(--syntax-keyword)"},{key:"error",label:"Red",cssVar:"var(--status-error)"},{key:"string",label:"Cyan",cssVar:"var(--syntax-string)"},{key:"function",label:"Orange",cssVar:"var(--syntax-function)"},{key:"type",label:"Yellow",cssVar:"var(--syntax-type)"}],q0=[{key:"branch",Icon:Ot,label:"Branch"},{key:"briefcase",Icon:Ki,label:"Work"},{key:"house",Icon:Gi,label:"Personal"},{key:"graduation",Icon:Vi,label:"School"},{key:"code",Icon:nr,label:"Code"}],Y0=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=ya(),a=c.useMemo(()=>s&&s!=="new"?r(s):null,[s,r]),i=s==="new",l=s==="global",[d,u]=c.useState(""),[m,f]=c.useState(""),[p,g]=c.useState(""),[w,h]=c.useState(""),[j,b]=c.useState("keyword"),[x,v]=c.useState("branch"),[N,y]=c.useState(!1);c.useEffect(()=>{i?(u(""),f(""),g(""),h(""),b("keyword"),v("branch")):a&&(u(a.name),f(a.userName),g(a.userEmail),h(a.sshKey||""),b(a.color||"keyword"),v(a.icon||"branch"))},[a,i,s]);const S=async()=>{if(!m.trim()||!p.trim()){se.error("User name and email are required");return}y(!0);try{const C={name:d.trim()||m.trim(),userName:m.trim(),userEmail:p.trim(),sshKey:w.trim()||null,color:j,icon:x};let k;if(i)k=await t(C);else if(s)k=await n(s,C);else return;k?se.success(i?"Profile created successfully":"Profile updated successfully"):se.error(i?"Failed to create profile":"Failed to update profile")}catch(C){console.error("Error saving profile:",C),se.error("An error occurred while saving")}finally{y(!1)}},D=async()=>{if(!(!s||i)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?se.success("Profile deleted successfully"):se.error("Failed to delete profile")}catch(C){console.error("Error deleting profile:",C),se.error("An error occurred while deleting")}},M=c.useMemo(()=>Pd.find(k=>k.key===j)?.cssVar||"var(--syntax-keyword)",[j]);return s?e.jsx(dt,{outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:i?"New Git Profile":l?"Global Identity":d||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:i?"Create a new Git identity profile for your repositories":l?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!l&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Profile Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Basic profile settings and display name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Display Name"}),e.jsx(pt,{value:d,onChange:C=>u(C.target.value),placeholder:"Work Profile, Personal, etc."}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Friendly name to identify this profile (optional, defaults to user name)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Color"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:Pd.map(C=>e.jsx("button",{onClick:()=>b(C.key),className:P("w-8 h-8 rounded-lg border-2 transition-all",j===C.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:C.cssVar},title:C.label},C.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Icon"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:q0.map(C=>{const k=C.Icon;return e.jsx("button",{onClick:()=>v(C.key),className:P("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",x===C.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:C.label,children:e.jsx(k,{className:"w-4 h-4",style:{color:M}})},C.key)})})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"Git Configuration"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Git user settings that will be applied to repositories"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Name ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["The name that will appear in Git commit messages.",e.jsx("br",{}),"This is the author name shown in git log and GitHub/GitLab interfaces."]})]})]}),e.jsx(pt,{value:m,onChange:C=>f(C.target.value),placeholder:"John Doe",required:!l,readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.name configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["User Email ",!l&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["The email address for Git commits.",e.jsx("br",{}),"This should match your email in GitHub/GitLab",e.jsx("br",{}),"to ensure proper attribution of commits."]})]})]}),e.jsx(pt,{type:"email",value:p,onChange:C=>g(C.target.value),placeholder:"john@example.com",required:!l,readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["SSH Key Path",e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Path to SSH private key used for Git authentication.",e.jsx("br",{}),"This key will be used for HTTPS and SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(pt,{value:w,onChange:C=>h(C.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:l,disabled:l}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),!l&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!i&&e.jsxs(Ne,{size:"sm",variant:"destructive",onClick:D,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Ks,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:P("flex gap-2",i&&"ml-auto"),children:e.jsxs(Ne,{size:"sm",variant:"default",onClick:S,disabled:N,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(ca,{className:"h-3 w-3"}),N?"Saving...":"Save Profile"]})})]})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ps,{className:"mx-auto mb-3 h-12 w-12 opacity-50"}),e.jsx("p",{className:"typography-body",children:"Select a profile from the sidebar"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"or create a new one"})]})})};function ri(s,r,t){return Math.min(t,Math.max(r,s))}const ta=Ce.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=Ce.useRef(null);Ce.useImperativeHandle(f,()=>p.current);const[g,w]=Ce.useState(()=>String(s));Ce.useEffect(()=>{document.activeElement!==p.current&&w(String(s))},[s]);const h=Ce.useCallback(()=>{p.current?.focus()},[]),j=Ce.useCallback(k=>{const A=ri(k,t,n);r(A),w(String(A))},[n,t,r]),b=Ce.useCallback(()=>{const k=Number(g);return Number.isFinite(k)?k:s},[g,s]),x=Ce.useCallback(()=>{j(b()+o),h()},[j,b,h,o]),v=Ce.useCallback(()=>{j(b()-o),h()},[j,b,h,o]),N=k=>{const A=k.target.value;w(A);const E=Number(A);Number.isFinite(E)&&r(ri(E,t,n))},y=k=>{const A=Number(g);if(!Number.isFinite(A))w(String(s));else{const E=ri(A,t,n);E!==A&&r(E),w(String(E))}l?.(k)},S=k=>{if(k.key==="ArrowUp"){k.preventDefault(),x();return}if(k.key==="ArrowDown"){k.preventDefault(),v();return}d?.(k)},D=b(),M=u||D<=t,C=u||D>=n;return e.jsxs("div",{className:P("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:g,onChange:N,onBlur:y,onKeyDown:S,disabled:u,className:P("h-full w-14 bg-transparent px-1.5 text-center typography-ui-label text-foreground","placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground","border-0 outline-none","disabled:pointer-events-none disabled:cursor-not-allowed","[appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none",a)}),e.jsxs("div",{className:"flex w-6 flex-col border-l border-border",children:[e.jsx("button",{type:"button","aria-label":"Increase value",disabled:C,onClick:x,className:P("flex flex-1 items-center justify-center","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(oa,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:M,onClick:v,className:P("flex flex-1 items-center justify-center border-t border-border","text-muted-foreground hover:bg-accent hover:text-foreground","disabled:pointer-events-none disabled:opacity-50"),children:e.jsx(Mt,{className:"h-3.5 w-3.5"})})]})]})});ta.displayName="NumberInput";const X0=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Td=[{value:"collapsed",label:"Collapsed",description:"Activity and tools start collapsed"},{value:"activity",label:"Summary",description:"Activity expanded, tools collapsed"},{value:"detailed",label:"Detailed",description:"Activity expanded, key tools expanded"}],Fd=[{id:"dynamic",label:"Dynamic",description:"New files inline, modified files side-by-side. Responsive inline fallback only in Dynamic mode."},{id:"inline",label:"Always inline",description:"Show all file diffs as a single unified view."},{id:"side-by-side",label:"Always side-by-side",description:"Compare original and modified files next to each other."}],kl=({visibleSettings:s})=>{const{isMobile:r}=Ft(),t=_e(v=>v.showReasoningTraces),n=_e(v=>v.setShowReasoningTraces),o=_e(v=>v.toolCallExpansion),a=_e(v=>v.setToolCallExpansion),i=_e(v=>v.fontSize),l=_e(v=>v.setFontSize),d=_e(v=>v.padding),u=_e(v=>v.setPadding),m=_e(v=>v.inputBarOffset),f=_e(v=>v.setInputBarOffset),p=_e(v=>v.diffLayoutPreference),g=_e(v=>v.setDiffLayoutPreference),w=Zs(v=>v.queueModeEnabled),h=Zs(v=>v.setQueueMode),{themeMode:j,setThemeMode:b}=sn(),x=v=>s?s.includes(v):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[x("theme")&&!Wt()&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Theme Mode"})}),e.jsx("div",{className:"flex gap-1 w-fit",children:X0.map(v=>e.jsx(Bs,{variant:j===v.value?"default":"outline",className:P(j===v.value?void 0:"text-foreground"),onClick:()=>b(v.value),children:v.label},v.value))})]}),x("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:i,onChange:v=>l(Number(v.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(ta,{value:i,onValueChange:l,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>l(100),disabled:i===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]})]}),x("spacing")&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Spacing"})}),r?e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:v=>u(Number(v.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:d}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:d,onChange:v=>u(Number(v.target.value)),className:"flex-1 min-w-0 h-2 bg-muted rounded-lg appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-4 [&::-webkit-slider-thumb]:h-4 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-4 [&::-moz-range-thumb]:h-4 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0"}),e.jsx(ta,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]})]}),x("inputBarOffset")&&r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Input Bar Offset"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Raise the input bar for phones with curved screen edges."})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("input",{type:"range",min:"0",max:"100",step:"5",value:m,onChange:v=>f(Number(v.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[m,"px"]}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Es,{className:"h-3.5 w-3.5"})})]})]}),x("toolOutput")&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Default Tool Output"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:Td.find(v=>v.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Td.map(v=>e.jsx(Bs,{variant:o===v.value?"default":"outline",className:P(o===v.value?void 0:"text-foreground"),onClick:()=>a(v.value),children:v.label},v.value))})]}),x("diffLayout")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Fd.map(v=>e.jsx(Bs,{variant:p===v.id?"default":"outline",className:P(p===v.id?void 0:"text-foreground"),onClick:()=>g(v.id),children:v.label},v.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Fd.find(v=>v.id===p)?.description})]})]}),x("reasoning")&&e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:t,onChange:v=>n(v.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),x("queueMode")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:w,onChange:v=>h(v.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:w?`Enter queues messages, ${Zt()}+Enter sends immediately.`:`Enter sends immediately, ${Zt()}+Enter queues messages.`})]})]})},Rd="https://github.com/btriapitsyn/openchamber",Q0=800,nf=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=da(),{isMobile:a}=Ft(),i=o.info?.currentVersion||"unknown",l=c.useRef(!1);c.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(t){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(se.success("You are on the latest version"),l.current=!1)},Q0);return()=>clearTimeout(u)}},[o.checking,t,o.available,o.error]);const d=o.checking||t;return a?e.jsxs("div",{className:"w-full space-y-2",children:[e.jsxs("button",{onClick:()=>Hn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Es,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",i]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:P("typography-meta text-muted-foreground/60 hover:text-muted-foreground disabled:cursor-default",d&&"animate-pulse [animation-duration:1s]"),children:"Check updates"}),!d&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:"flex items-center gap-1 typography-meta text-primary hover:underline",children:[e.jsx(bn,{className:"h-3.5 w-3.5"}),"Update"]})]}),o.error&&e.jsx("p",{className:"typography-micro text-destructive truncate",children:o.error}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("a",{href:Rd,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(xi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(pu,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Discord"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(yi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ci,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:i})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Co,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"typography-meta",children:"Checking..."})]}),!o.checking&&o.available&&e.jsxs("button",{onClick:()=>r(!0),className:P("flex items-center gap-2 px-3 py-1.5 rounded-md","text-sm font-medium","bg-primary text-primary-foreground","hover:bg-primary/90","transition-colors"),children:[e.jsx(bn,{className:"h-4 w-4"}),"Update to ",o.info?.version]}),!o.checking&&!o.available&&!o.error&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Up to date"})]}),o.error&&e.jsx("p",{className:"typography-meta text-destructive",children:o.error}),e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:o.checking,className:P("typography-meta text-muted-foreground hover:text-foreground","underline-offset-2 hover:underline","disabled:opacity-50 disabled:cursor-not-allowed"),children:"Check for updates"})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("a",{href:Rd,target:"_blank",rel:"noopener noreferrer",className:P("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(xi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:P("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(yi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Ci,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]})},J0=1440*60*1e3,of=5,_d=1440*60*1e3,ni=s=>s.time?.updated??s.time?.created??0,Od=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=of,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*J0,i=[...s].sort((d,u)=>ni(u)-ni(d)),l=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=ni(d);return u?u<a:!1}).map(d=>d.id)},af=s=>{const r=s?.autoRun!==!1,t=me(h=>h.sessions),n=me(h=>h.currentSessionId),o=me(h=>h.isLoading),a=me(h=>h.deleteSessions),i=_e(h=>h.autoDeleteEnabled),l=_e(h=>h.autoDeleteAfterDays),d=_e(h=>h.autoDeleteLastRunAt),u=_e(h=>h.setAutoDeleteLastRunAt),[m,f]=c.useState(!1),p=c.useRef(!1),g=c.useMemo(()=>l<=0?[]:Od({sessions:t,currentSessionId:n,cutoffDays:l}),[l,n,t]),w=c.useCallback(async({force:h=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||l<=0)&&!h)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const j=Date.now();if(!h&&d&&j-d<_d)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=Od({sessions:t,currentSessionId:n,cutoffDays:l,now:j});if(b.length===0)return u(j),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(b,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[l,i,d,n,a,o,t,u]);return c.useEffect(()=>{if(!r||!i||l<=0||o||t.length===0)return;const h=Date.now();d&&h-d<_d||w()},[l,i,d,r,o,t.length,w]),{candidates:g,isRunning:m,runCleanup:w,keepRecentCount:of}},oi=1,ai=365,lf=()=>{const{isMobile:s}=Ft(),r=_e(p=>p.autoDeleteEnabled),t=_e(p=>p.autoDeleteAfterDays),n=_e(p=>p.setAutoDeleteEnabled),o=_e(p=>p.setAutoDeleteAfterDays),[a,i]=c.useState(String(t));c.useEffect(()=>{i(String(t))},[t]);const{candidates:l,isRunning:d,runCleanup:u}=af({autoRun:!1}),m=l.length,f=c.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){se.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&se.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&se.error(`Failed to delete ${p.failedIds.length} session${p.failedIds.length===1?"":"s"}`)},[u]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session retention"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const g=p.target.value;if(i(g),g.trim()==="")return;const w=Number(g);if(!Number.isFinite(w))return;const h=Math.min(ai,Math.max(oi,Math.round(w)));o(h)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const g=Math.min(ai,Math.max(oi,Math.round(p)));o(g),i(String(g))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(ta,{value:t,onValueChange:o,min:oi,max:ai,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Bs,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},cf=()=>{const s=et(k=>k.setProvider),r=et(k=>k.setModel),t=et(k=>k.setAgent),n=et(k=>k.setCurrentVariant),o=et(k=>k.setSettingsDefaultModel),a=et(k=>k.setSettingsDefaultVariant),i=et(k=>k.setSettingsDefaultAgent),l=et(k=>k.settingsAutoCreateWorktree),d=et(k=>k.setSettingsAutoCreateWorktree),u=et(k=>k.providers),[m,f]=c.useState(),[p,g]=c.useState(),[w,h]=c.useState(),[j,b]=c.useState(!0),x=c.useMemo(()=>{if(!m)return{providerId:"",modelId:""};const k=m.split("/");return k.length!==2?{providerId:"",modelId:""}:{providerId:k[0]||"",modelId:k[1]||""}},[m]);c.useEffect(()=>{(async()=>{try{let A=null;if(os())A=await Dn();else{const E=Zr()?.settings;if(E)try{const V=(await E.load())?.settings;V&&(A={defaultModel:typeof V.defaultModel=="string"?V.defaultModel:void 0,defaultVariant:typeof V.defaultVariant=="string"?V.defaultVariant:void 0,defaultAgent:typeof V.defaultAgent=="string"?V.defaultAgent:void 0})}catch{}if(!A){const R=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});R.ok&&(A=await R.json())}}if(A){const E=typeof A.defaultModel=="string"&&A.defaultModel.trim().length>0?A.defaultModel.trim():void 0,R=typeof A.defaultVariant=="string"&&A.defaultVariant.trim().length>0?A.defaultVariant.trim():void 0,V=typeof A.defaultAgent=="string"&&A.defaultAgent.trim().length>0?A.defaultAgent.trim():void 0;f(E),g(R),h(V)}}catch(A){console.warn("Failed to load defaults settings:",A)}finally{b(!1)}})()},[]);const v=c.useCallback(async(k,A)=>{const E=k&&A?`${k}/${A}`:void 0;f(E),g(void 0),a(void 0),n(void 0),o(E),k&&A&&u.find(V=>V.id===k)&&(s(k),r(A));try{await ns({defaultModel:E??"",defaultVariant:""})}catch(R){console.warn("Failed to save default model:",R)}},[u,n,s,r,o,a]),N="__default__",y=c.useCallback(async k=>{const A=k===N?void 0:k||void 0;g(A),a(A),n(A);try{await ns({defaultVariant:A??""})}catch(E){console.warn("Failed to save default variant:",E)}},[n,a]),S=c.useCallback(async k=>{const A=k||void 0;h(A),i(A),k&&t(k);try{await ns({defaultAgent:A??""})}catch(E){console.warn("Failed to save default agent:",E)}},[t,i]),D=c.useMemo(()=>{const E=u.find(R=>R.id===x.providerId)?.models.find(R=>R.id===x.modelId)?.variants;return E?Object.keys(E):[]},[x.modelId,x.providerId,u]),M=D.length>0;c.useEffect(()=>{!M&&p&&(g(void 0),a(void 0),n(void 0),ns({defaultVariant:""}).catch(()=>{}))},[p,n,a,M]);const C=c.useCallback(async k=>{const A=k.target.checked;d(A);try{await ns({autoCreateWorktree:A})}catch(E){console.warn("Failed to save auto create worktree setting:",E)}},[d]);return j?null:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Session Defaults"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:"Configure default behaviors for new sessions."})]})]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default model"}),e.jsx(Sl,{providerId:x.providerId,modelId:x.modelId,onChange:v})]}),M&&e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default thinking"}),e.jsxs(vs,{value:p??N,onValueChange:y,children:[e.jsx(js,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Yr,{placeholder:"Thinking"})}),e.jsxs(Ss,{children:[e.jsx(Lt,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),D.map(k=>e.jsx(Lt,{value:k,className:"pr-2 [&>span:first-child]:hidden",children:k},k))]})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("label",{className:"typography-ui-label text-muted-foreground",children:"Default agent"}),e.jsx(sf,{agentName:w||"",onChange:S})]})]}),(m||w)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",m&&e.jsxs("span",{className:"text-foreground",children:[m,M?` (${p??"default"})`:""]}),m&&w&&" / ",w&&e.jsx("span",{className:"text-foreground",children:w})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:l,onChange:C}),e.jsx("span",{className:"typography-ui-label text-foreground",children:"Always create worktree for new sessions"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5.5 mt-1",children:l?`New session (Worktree): ${Zt()} + N • New session (Standard): Shift + ${Zt()} + N`:`New session (Standard): ${Zt()} + N • New session (Worktree): Shift + ${Zt()} + N`})]})]})},Z0=()=>{const s=Pt(I=>I.getActiveProject()),r=Pt(I=>I.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=al(t),a=Qu(t),{sessions:i,getWorktreeMetadata:l}=me(),[d,u]=c.useState(n?.branchPrefix??""),[m,f]=c.useState(n?.baseBranch??"HEAD"),[p,g]=c.useState([]),[w,h]=c.useState(!1),[j,b]=c.useState(!1),[x,v]=c.useState(null),[N,y]=c.useState(null),[S,D]=c.useState([]),[M,C]=c.useState(!1),k=".openchamber",A=c.useCallback((I,W)=>{const F=I.replace(/\\/g,"/").replace(/\/+$/,""),$=!F||F==="/"?`/${k}`:`${F}/${k}`;return W?`${$}/${W}`:$},[]),E=c.useCallback(async()=>{if(!(!t||x===!1))try{const W=(await vn(t)).map(J=>jn(t,J)),$=`${A(t,"")}/`,L=W.filter(J=>J.path.startsWith($));D(L)}catch{}},[t,x,A]);c.useEffect(()=>{if(!t)return;let I=!1;return b(!0),C(!0),v(null),y(null),D([]),(async()=>{try{const W=await en(t);if(I)return;if(v(W),W){const[F,$]=await Promise.all([tl(t),vn(t).catch(()=>[])]);if(!I){F&&y({all:F.all,current:F.current});const L=$.map(he=>jn(t,he)),pe=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${k}`}/`,be=L.filter(he=>he.path.startsWith(pe));D(be)}}}catch{}finally{I||(b(!1),C(!1))}})(),()=>{I=!0}},[t]),c.useEffect(()=>{if(!t)return;let I=!1;return h(!0),(async()=>{try{const W=await ro(t);I||g(W.length>0?W:[""])}catch{I||g([""])}finally{I||h(!1)}})(),()=>{I=!0}},[t]),c.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const R=N??a,V=x??o,T=c.useMemo(()=>{const I=[],W=R?.current?`Current (HEAD: ${R.current})`:"Current (HEAD)";return I.push({value:"HEAD",label:W,group:"special"}),R&&(R.all.filter(L=>!L.startsWith("remotes/")).sort((L,J)=>L.localeCompare(J)).forEach(L=>{I.push({value:L,label:L,group:"local"})}),R.all.filter(L=>L.startsWith("remotes/")).map(L=>L.replace(/^remotes\//,"")).sort((L,J)=>L.localeCompare(J)).forEach(L=>{I.push({value:L,label:L,group:"remote"})})),I},[R]),B=c.useRef(null),re=c.useCallback(I=>{u(I),B.current=I},[]),Y=c.useCallback(I=>{s?.id&&(r(s.id,{branchPrefix:I}),B.current=null)},[s?.id,r]),_=c.useCallback(()=>{Y(d)},[d,Y]);c.useEffect(()=>()=>{B.current!==null&&s?.id&&r(s.id,{branchPrefix:B.current})},[s?.id,r]);const q=c.useCallback(I=>{f(I),s?.id&&r(s.id,{baseBranch:I})},[s?.id,r]),O=c.useCallback((I,W)=>{g(F=>{const $=[...F];return $[I]=W,$})},[]),z=c.useCallback(()=>{g(I=>[...I,""])},[]),U=c.useCallback(I=>{g(W=>W.filter((F,$)=>$!==I))},[]),ne=c.useCallback(async()=>{if(!t)return;const I=p.filter(W=>W.trim().length>0);await Ou(t,I)},[t,p]),oe=c.useCallback(()=>{ne()},[ne]),Q=c.useCallback(I=>{const W=I.path.replace(/\\/g,"/").replace(/\/+$/,""),F=i.filter(he=>{if(l(he.id)?.path===I.path)return!0;const je=he.directory;return!!(je&&je.replace(/\\/g,"/").replace(/\/+$/,"")===W)}),$=new Set(F.map(he=>he.id)),L=he=>{const Ae=i.filter(Te=>{const K=Te.parentID;return K&&he.has(K)});if(Ae.length===0)return[];const je=new Set(Ae.map(Te=>Te.id));return[...Ae,...L(je)]},J=L($),pe=new Set,be=[...F,...J].filter(he=>pe.has(he.id)?!1:(pe.add(he.id),!0));kn.requestDelete({sessions:be,mode:"worktree",worktree:I})},[i,l]),de=c.useMemo(()=>i.map(I=>I.id).join(","),[i]);return c.useEffect(()=>{x&&t&&E()},[de,x,t,E]),t?j?e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."})]})}):V===!1?e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Worktree settings are only available for Git repositories."})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Branch prefix"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:"Prefix for auto-generated branch names when creating new worktrees."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"e.g. feature, bugfix, wip (no trailing slash)"})]}),e.jsx(pt,{value:d,onChange:I=>re(I.target.value),onBlur:_,placeholder:"feature",className:"max-w-xs"})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(tt,{sideOffset:8,className:"max-w-xs",children:"Default branch to create new worktrees from."})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default branch for new worktree branches"})]}),e.jsxs(vs,{value:m,onValueChange:q,children:[e.jsx(js,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Yr,{placeholder:"Select a branch"})}),e.jsxs(Ss,{children:[e.jsxs(Vr,{children:[e.jsx(xn,{children:"Default"}),T.filter(I=>I.group==="special").map(I=>e.jsx(Lt,{value:I.value,children:I.label},I.value))]}),T.some(I=>I.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(Jo,{}),e.jsxs(Vr,{children:[e.jsx(xn,{children:"Local branches"}),T.filter(I=>I.group==="local").map(I=>e.jsx(Lt,{value:I.value,children:I.label},I.value))]})]}),T.some(I=>I.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(Jo,{}),e.jsxs(Vr,{children:[e.jsx(xn,{children:"Remote branches"}),T.filter(I=>I.group==="remote").map(I=>e.jsx(Lt,{value:I.value,children:I.label},I.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically when a new worktree is created. Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_WORKTREE_PATH"})," for the project root."]})]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((I,W)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pt,{value:I,onChange:F=>O(W,F.target.value),onBlur:oe,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{U(W),setTimeout(ne,0)},className:"flex-shrink-0 flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Ht,{className:"h-4 w-4"})})]},W)),e.jsxs("button",{type:"button",onClick:z,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(ls,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(tt,{sideOffset:8,className:"max-w-xs",children:["Worktrees created under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})," directory. Deleting a worktree will also remove any linked sessions."]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Manage worktrees for this project"})]}),M?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):S.length===0?e.jsxs("p",{className:"typography-meta text-muted-foreground/70",children:["No worktrees found under ",e.jsx("code",{className:"font-mono text-xs",children:".openchamber"})]}):e.jsx("div",{className:"space-y-1",children:S.map(I=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-sidebar-accent/30 transition-colors group",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"typography-meta text-foreground truncate",children:I.label||I.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:I.relativePath||I.path})]}),e.jsx("button",{type:"button",onClick:()=>Q(I),className:"flex-shrink-0 flex h-7 w-7 items-center justify-center rounded text-muted-foreground/50 hover:text-destructive hover:bg-destructive/10 opacity-0 group-hover:opacity-100 transition-opacity focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete worktree ${I.branch||I.label}`,children:e.jsx(Ks,{className:"h-4 w-4"})})]},I.path))})]})]}):e.jsx("div",{className:"space-y-4",children:e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree settings"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})]})})},ej=({section:s})=>{const{isMobile:r}=Ft(),t=r&&qi();if(!s)return e.jsxs(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-3 p-3 sm:space-y-6 sm:p-6",children:[e.jsx(kl,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(cf,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(lf,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(nf,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(tj,{});case"chat":return e.jsx(sj,{});case"sessions":return e.jsx(rj,{});case"worktree":return e.jsx(Z0,{});default:return null}};return e.jsx(dt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},tj=()=>e.jsx(kl,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),sj=()=>e.jsx(kl,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),rj=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(cf,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(lf,{})})]}),nj=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"worktree",label:"Worktree",items:["Branch","Setup"]}],oj=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=Ft(),n=t&&qi(),[o,a]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const l=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:P("flex h-full flex-col",l),children:[e.jsx(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:nj.map(d=>{const u=s===d.id;return e.jsx("div",{className:P("group relative rounded-md px-1.5 py-1 transition-all duration-200",u?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("button",{onClick:()=>r(d.id),className:"w-full text-left flex flex-col gap-0 rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"typography-ui-label font-normal text-foreground",children:d.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:d.items.join(" · ")})]})},d.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(nf,{})})]})},aj=(()=>{const s=ef.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),ii=200,li=500,ij=264,lj=700,Oi=({onClose:s,forceMobile:r})=>{const t=Ft(),n=r??t.isMobile,[o,a]=c.useState("settings"),[i,l]=c.useState("visual"),[d,u]=c.useState(!1),[m,f]=c.useState(()=>typeof window<"u"?Math.min(li,Math.max(ii,Math.floor(window.innerWidth*.2))):ij),[p,g]=c.useState(!1),[w,h]=c.useState(!1),[j,b]=c.useState(0),x=c.useRef(null),v=c.useRef(0),N=c.useRef(m),[y,S]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=c.useMemo(()=>Wt(),[]);c.useEffect(()=>{typeof window>"u"||S(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{const I=x.current;if(!I)return;const W=new ResizeObserver(F=>{for(const $ of F)b($.contentRect.width)});return W.observe(I),b(I.clientWidth),()=>W.disconnect()},[]);const C=Pt(I=>I.projects),k=Pt(I=>I.activeProjectId),A=Pt(I=>I.setActiveProject),E=c.useMemo(()=>[...C].sort((I,W)=>(I.label||I.path).localeCompare(W.label||W.path)),[C]),R=c.useMemo(()=>E.length===0?null:E.find(I=>I.id===k)??E[0],[k,E]),V=c.useCallback(I=>I.replace(/[-_]/g," ").replace(/\b\w/g,W=>W.toUpperCase()),[]),T=c.useMemo(()=>{if(!R)return"Project";const I=R.label&&R.label.trim().length>0?R.label:R.path.split("/").filter(Boolean).pop()||R.path;return V(I)},[R,V]),B=E.length>0,re=j===0||j>=lj;c.useEffect(()=>{if(o==="agents"){setTimeout(()=>{Fr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Tr.getState().loadCommands()},0);return}o==="skills"&&(Hs.getState().loadSkills(),so.getState().loadCatalog())},[k,o]),c.useEffect(()=>{if(typeof window>"u")return;const I=()=>{if(!p){const W=Math.min(li,Math.max(ii,Math.floor(window.innerWidth*.2)));f(W)}};return window.addEventListener("resize",I),()=>window.removeEventListener("resize",I)},[p]),c.useEffect(()=>{if(!w)return;const I=F=>{const $=F.clientX-v.current,L=Math.min(li,Math.max(ii,N.current+$));f(L),g(!0)},W=()=>h(!1);return window.addEventListener("pointermove",I),window.addEventListener("pointerup",W,{once:!0}),()=>{window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",W)}},[w]);const Y=I=>{h(!0),v.current=I.clientX,N.current=m,I.preventDefault()},_=c.useCallback(async I=>{if(!I.target.closest("button, a, input, select, textarea")&&I.button===0&&y)try{const{getCurrentWindow:W}=await is(async()=>{const{getCurrentWindow:$}=await import("./vendor-.bun-B2HtLj-d.js").then(L=>L.cr);return{getCurrentWindow:$}},__vite__mapDeps([0,1]));await W().startDragging()}catch(W){console.error("Failed to start window dragging:",W)}},[y]),q=c.useCallback(async I=>{if(I.button===0&&y)try{const{getCurrentWindow:W}=await is(async()=>{const{getCurrentWindow:$}=await import("./vendor-.bun-B2HtLj-d.js").then(L=>L.cr);return{getCurrentWindow:$}},__vite__mapDeps([0,1]));await W().startDragging()}catch(W){console.error("Failed to start window dragging:",W)}},[y]),O=c.useCallback(I=>{a(I),u(!1)},[]),z=c.useCallback(()=>{n&&u(!0)},[n]),U=()=>{switch(o){case"settings":return e.jsx(oj,{selectedSection:i,onSelectSection:I=>{l(I),z()}});case"agents":return e.jsx(x0,{onItemSelect:z});case"commands":return e.jsx(C0,{onItemSelect:z});case"skills":return e.jsx(D0,{onItemSelect:z});case"providers":return e.jsx(L0,{onItemSelect:z});case"git-identities":return e.jsx(K0,{onItemSelect:z});default:return null}},ne=()=>{switch(o){case"agents":return e.jsx(N0,{});case"commands":return e.jsx(M0,{});case"skills":return e.jsx(O0,{});case"providers":return e.jsx(U0,{});case"git-identities":return e.jsx(Y0,{});case"settings":return e.jsx(ej,{section:i});default:return null}},oe=Zt(),Q=c.useMemo(()=>y&&D?"pl-[5.75rem]":"",[y,D]),de=y&&D;return e.jsxs("div",{ref:x,className:P("flex h-full flex-col overflow-hidden",y?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:_,className:P("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&Q,y?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80"),style:{borderColor:"var(--interactive-border)"},children:[n&&d&&e.jsx("button",{type:"button",onClick:()=>u(!1),"aria-label":"Back",className:"inline-flex h-9 w-9 flex-shrink-0 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(hh,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:P("flex items-center",n?"gap-1":"h-full"),children:[!n&&de&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),aj.map(({id:I,label:W,icon:F})=>{const $=o===I,L=F;return n?e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{onClick:()=>O(I),className:P("relative flex h-9 w-9 items-center justify-center rounded-md transition-colors","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",$?"text-foreground":"text-muted-foreground"),"aria-pressed":$,"aria-label":W,children:e.jsx(L,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(tt,{children:e.jsx("p",{children:W})})]},I):e.jsxs(c.Fragment,{children:[e.jsxs("button",{onClick:()=>O(I),onMouseDown:$?q:void 0,className:P("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",$?"app-region-drag":"app-region-no-drag","hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",$?"text-foreground":"text-muted-foreground"),"aria-pressed":$,"aria-label":W,children:[e.jsx(L,{className:"h-4 w-4",weight:"regular"}),re&&e.jsx("span",{children:W})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},I)})]}),(s||B)&&e.jsxs("div",{className:P("flex items-center gap-2",n?"":"pr-3"),children:[B&&e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:T,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(ir,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:T,className:P("flex h-9 max-w-[18rem] items-center gap-1.5 bg-transparent px-2 text-foreground outline-none hover:text-foreground/80 focus-visible:ring-2 focus-visible:ring-ring",!n&&"app-region-no-drag"),children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label font-medium",children:T}),e.jsx(Mt,{className:"size-4 opacity-50"})]})}),e.jsx(Gt,{align:"end",className:"w-auto",children:e.jsx(Ju,{value:R?.id??"",onValueChange:I=>{I&&A(I)},children:E.map(I=>{const W=I.label?.trim()?I.label.trim():I.path.split("/").filter(Boolean).pop()||I.path,F=V(W);return e.jsx(Zu,{value:I.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:F})},I.id)})})})]}),s&&e.jsxs(rt,{delayDuration:500,children:[e.jsx(nt,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:P("inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",!n&&"app-region-no-drag"),children:e.jsx(Ht,{className:"h-5 w-5"})})}),e.jsx(tt,{children:e.jsxs("p",{children:["Close Settings (",oe,"+,)"]})})]})]})]}),e.jsx("div",{className:"flex flex-1 overflow-hidden",children:n?d?e.jsx("div",{className:"flex-1 overflow-hidden bg-background","data-keyboard-avoid":"true",children:e.jsx(as,{children:ne()})}):e.jsx("div",{className:P("flex-1 overflow-hidden",M?"bg-background":"bg-sidebar"),children:e.jsx(as,{children:U()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:P("relative overflow-hidden border-r",y?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":M?"bg-background":"bg-sidebar",w?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:P("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",w?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:Y,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(as,{children:U()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(as,{children:ne()})})]})})]})},cj=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=_e(),{isMobile:m}=Ft(),[f,p]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");c.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),jb({enabled:!0});const g=da(b=>b.checkForUpdates);c.useEffect(()=>{const b=setTimeout(()=>{g()},3e3);return()=>clearTimeout(b)},[g]),c.useEffect(()=>{_e.getState().isMobile!==m&&t(m)},[m,t]),c.useEffect(()=>{if(typeof window>"u")return;let b;const x=()=>{b!==void 0&&window.clearTimeout(b),b=window.setTimeout(()=>{_e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",x),()=>{window.removeEventListener("resize",x),b!==void 0&&window.clearTimeout(b)}},[]),c.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const b=document.documentElement;let x=0,v=!1,N=0,y=null;const S=_e.getState().setKeyboardOpen,D=()=>{y&&(y.style.setProperty("--oc-keyboard-avoid-offset","0px"),y.removeAttribute("data-keyboard-avoid-active"),y=null)},M=V=>{if(!V)return null;const T=V.closest("[data-keyboard-avoid]");if(T)return T;if(V.classList.contains("overlay-scrollbar-container")){const B=V.parentElement;if(B instanceof HTMLElement)return B}return V},C=()=>{x=0,v=!0,b.style.setProperty("--oc-keyboard-inset","0px"),S(!1)},k=()=>{const V=window.visualViewport,T=V?Math.round(V.height):window.innerHeight,B=V?Math.max(0,Math.round(V.offsetTop)):0;b.style.setProperty("--oc-visual-viewport-offset-top",`${B}px`);const re=document.activeElement,Y=re?.tagName,q=Y==="INPUT"||Y==="TEXTAREA"||Y==="SELECT"||!!re?.isContentEditable,O=Math.round(b.clientHeight||window.innerHeight),z=T+B,U=Math.max(0,O-z),oe=U>=(q?120:180)?U:0;if(v)oe===0&&(v=!1),x=0;else if(x===0)oe>0&&q&&(x=oe);else{const de=!q&&T>N+6;oe===0?(x=0,S(!1)):de?C():(oe>0&&q||oe>x)&&(x=oe,S(!0))}b.style.setProperty("--oc-keyboard-inset",`${x}px`),N=T;const Q=q?M(re):null;if(!m||!Q||!re)D();else{Q!==y&&(D(),y=Q);const de=B+T,W=re.getBoundingClientRect().bottom-de,F=8,$=Math.max(x,oe),L=W>F&&$>0?Math.min(W,$):0,J=y;J&&(J.style.setProperty("--oc-keyboard-avoid-offset",`${L}px`),J.setAttribute("data-keyboard-avoid-active","true"))}if(m&&q){const de=document.scrollingElement;de&&de.scrollTop!==0&&(de.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};k();const A=window.visualViewport;A?.addEventListener("resize",k),A?.addEventListener("scroll",k),window.addEventListener("resize",k),window.addEventListener("orientationchange",k);const E=V=>{const T=V.target;if(!T)return;const B=T.tagName;(B==="INPUT"||B==="TEXTAREA"||B==="SELECT"||T.isContentEditable)&&(v=!1),k()};document.addEventListener("focusin",E,!0);const R=V=>{const T=V.target;if(!T)return;const B=T.tagName;if(B==="INPUT"||B==="TEXTAREA"||B==="SELECT"||T.isContentEditable){const Y=V.relatedTarget,_=Y?.tagName;if(_==="INPUT"||_==="TEXTAREA"||_==="SELECT"||Y?.isContentEditable)return;C()}};return document.addEventListener("focusout",R,!0),()=>{A?.removeEventListener("resize",k),A?.removeEventListener("scroll",k),window.removeEventListener("resize",k),window.removeEventListener("orientationchange",k),document.removeEventListener("focusin",E,!0),document.removeEventListener("focusout",R,!0),D()}},[m]);const w=c.useMemo(()=>{switch(r){case"git":return e.jsx(Zv,{});case"diff":return e.jsx(_y,{});case"terminal":return e.jsx(u0,{});default:return null}},[r]),h=r==="chat",j=a&&!m;return e.jsx(mb,{children:e.jsxs("div",{className:P("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Zy,{}),e.jsx(sb,{}),e.jsx(ib,{}),m?e.jsxs(e.Fragment,{children:[!(a||l)&&e.jsx(Sc,{}),e.jsx("div",{className:P("flex flex-1 overflow-hidden bg-background",(a||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:P("absolute inset-0",!h&&"invisible"),children:e.jsx(as,{children:e.jsx(Ri,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(as,{children:w})})]})}),e.jsx(ws,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Mi,{mobileVariant:!0})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(as,{children:e.jsx(zc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})}),a&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(as,{children:e.jsx(Oi,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!j&&e.jsx(qy,{isOpen:s,isMobile:m,children:e.jsx(Mi,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:P("absolute inset-0 flex flex-col",(j||l)&&"invisible"),children:[e.jsx(Sc,{}),e.jsx("div",{className:"flex flex-1 overflow-hidden bg-background",children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:P("absolute inset-0",!h&&"invisible"),children:e.jsx(as,{children:e.jsx(Ri,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(as,{children:w})})]})})]}),l&&e.jsx("div",{className:P("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(as,{children:e.jsx(zc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),j&&e.jsx("div",{className:P("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(as,{children:e.jsx(Oi,{onClose:()=>i(!1)})})})]}),!j&&e.jsx(Hy,{})]})})},dj=550,uj=()=>{const[s,r]=c.useState("chat"),[t,n]=c.useState(0),o=c.useRef(null),a=me(D=>D.currentSessionId),i=me(D=>D.sessions),l=me(D=>!!D.newSessionDraft?.open),d=me(D=>D.openNewSessionDraft),[u,m]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=et(D=>D.isInitialized),p=et(D=>D.initializeApp),g=me(D=>D.loadSessions),w=me(D=>D.loadMessages),h=me(D=>D.messages),[j,b]=c.useState(()=>f),[x,v]=c.useState(!1),N=c.useRef(0);c.useEffect(()=>{a&&r("chat")},[a]),c.useEffect(()=>{!a&&!l&&d()},[a,l,d]);const y=c.useCallback(()=>{r("sessions")},[]);c.useEffect(()=>{const D=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&m(D);const M=C=>{const A=C.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&m(A)};return window.addEventListener("openchamber:connection-status",M),()=>window.removeEventListener("openchamber:connection-status",M)},[]),c.useEffect(()=>{const D=M=>{const k=M.detail?.view;k==="settings"?r("settings"):k==="chat"?r("chat"):k==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",D),()=>window.removeEventListener("openchamber:navigate",D)},[]),c.useEffect(()=>{(async()=>{if(x||j||u!=="connected")return;const M=Date.now();if(!(M-N.current<750)){N.current=M,v(!0);try{const C=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();C&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:f}),f||await p();const k=et.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await g();const A=me.getState().error;if(C&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:k.providers.length,agents:k.agents.length,sessions:me.getState().sessions.length,sessionsError:A}),typeof A=="string"&&A.length>0)return;b(!0)}catch{}finally{v(!1)}}})()},[u,f,j,p,x,g]),c.useEffect(()=>{(async()=>{if(!j||u!=="connected"||s!=="chat"||l||!a)return;if(!(h.has(a)&&(h.get(a)?.length||0)>0))try{await w(a)}catch{}})()},[u,a,s,j,w,h,l]),c.useEffect(()=>{const D=o.current;if(!D)return;const M=new ResizeObserver(C=>{for(const k of C)n(k.contentRect.width)});return M.observe(D),n(D.clientWidth),()=>M.disconnect()},[]);const S=t>0&&t<dj;return e.jsx("div",{ref:o,className:"h-full w-full bg-background text-foreground flex flex-col",children:s==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx($d,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Mi,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(Oi,{onClose:()=>r("sessions"),forceMobile:S}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx($d,{title:l&&!a?"New session":i.find(D=>D.id===a)?.title||"Chat",showBack:!0,onBack:y,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(as,{children:e.jsx(Ri,{})})})]})})},$d=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:i,showContextUsage:l})=>{const{getCurrentModel:d}=et(),u=me(h=>h.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,g=typeof f?.output=="number"?f.output:0,w=u(p,g);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(du,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1 h-9 w-9 items-center justify-center p-2",title:s,children:s}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(Kt,{className:"h-5 w-5"})}),a&&e.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:e.jsx(Yn,{className:"h-5 w-5"})}),i&&e.jsx(Ni,{headerIconButtonClass:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"}),o&&e.jsx("button",{onClick:o,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Settings",children:e.jsx(Kr,{className:"h-5 w-5"})}),l&&w&&w.totalTokens>0&&e.jsx(ki,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit??0,size:"compact"})]})},$i=".openchamber",ko=s=>{const r=Pt.getState(),t=r.activeProjectId,n=t?r.projects.find(l=>l.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?St(s):"",a=`/${$i}/`,i=o.indexOf(a);return i>0?o.slice(0,i):s?St(s):null},St=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ld=s=>{const r=St(s);return!r||r==="/"?`/${$i}`:`${r}/${$i}`},mj=(s,r)=>{const t=St(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const i=St(o);if(i)return i}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},fj=async s=>{const r=St(s);if(!r)return[];try{const n=(await ke.listLocalDirectory(r)).filter(o=>o.isDirectory);return mj(r,n)}catch{return[]}},Nr=(s,r)=>{const t=St(s),n=St(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},df=async(s,r)=>{const t=St(r);if(!t)return t;try{const n=await s.path.get({directory:t});return St(n.data?.directory??"")||t}catch{return t}},uf=async(s,r)=>{const t=St(r);if(!t)return[];const n=await df(s,t),o=i=>i.filter(l=>{const d=St(l.directory??"");return d?Nr(d,t)||n!==t&&Nr(d,n):!1}),a=async i=>{const l=await s.session.list({directory:i});return Array.isArray(l.data)?l.data:[]};try{const i=o(await a(t));if(i.length>0)return i}catch{}if(n&&n!==t)try{const i=o(await a(n));if(i.length>0)return i}catch{}try{const i=await s.session.list(void 0),l=Array.isArray(i.data)?i.data:[];return o(l)}catch{return[]}},pj=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(St(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>St(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await vn(r),a=new Map(o.map(i=>[St(i.worktree),i]));n.forEach(i=>{const l=a.get(i);l&&t.set(i,jn(r,l))})}catch{}return t},ci=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await pj(t,n),i=me.getState(),l=Array.from(new Set(o.map(p=>St(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const g=t.sessions.filter(x=>St(x.path)===p).map(x=>x.id),w=i.getSessionsByDirectory(p),h=Array.isArray(w)?w.map(x=>x.id):[];let j=[];if(h.length===0)try{j=(await uf(r,p)).map(v=>v.id)}catch{j=[]}const b=Array.from(new Set([...h,...j,...g].filter(Boolean)));m.push({worktreePath:p,sessionIds:b,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,l.length)},f)),m};function hj(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),i=r.length>=4&&!isNaN(a)&&String(a)===o,l=i?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:t,provider:n,model:d,index:i?a:1}}const Mr=Bt()(Xt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=ct.getState().currentDirectory,n=ko(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=St(n),a=Ld(o),i=r().groups;s({isLoading:!0,error:null});try{const l=ke.getApiClient(),d=await df(l,o),u=Ld(d);let m=new Map,f=[];try{f=await vn(o),m=new Map(f.map(v=>[St(v.worktree),v]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await l.session.list({directory:o}),y=Array.isArray(N.data)?N.data:[];if(y.some(S=>{const D=St(S.directory??"");return Nr(D,a)||Nr(D,u)}))return y}catch{}const v=await l.session.list(void 0);return Array.isArray(v.data)?v.data:[]},g=async v=>{const N=new Map,y=5;let S=0;const D=async()=>{for(;S<v.length;){const M=v[S];S+=1;const C=St(M);if(C)try{(await uf(l,C)).forEach(A=>N.set(A.id,A))}catch(k){console.debug("Failed to fetch sessions from worktree:",C,k)}}};return await Promise.all(Array.from({length:Math.min(y,v.length)},D)),Array.from(N.values())};let h=(await p()).filter(v=>{const N=St(v.directory??"");return N?Nr(N,a)||Nr(N,u):!1});if(h.length===0){const v=new Set;f.map(y=>St(y.worktree)).filter(y=>Nr(y,a)||Nr(y,u)).forEach(y=>v.add(y));const N=Array.from(new Set([a,u].map(y=>St(y)).filter(Boolean)));await Promise.all(N.map(async y=>{(await fj(y)).forEach(D=>v.add(D))})),v.size>0&&(h=await g(Array.from(v)))}const j=new Map;for(const v of h){const N=v.time?.updated??0;j.set(v.id,typeof N=="number"?N:0)}const b=new Map;for(const v of h){const N=hj(v.title);if(!N)continue;const y=St(v.directory),S=m.get(y),D={id:v.id,path:y,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:S?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:S?jn(o,S):void 0},M=b.get(N.groupSlug);M?M.push(D):b.set(N.groupSlug,[D])}const x=Array.from(b.entries()).map(([v,N])=>{const y=N.reduce((S,D)=>{const M=j.get(D.id)??0;return Math.max(S,M)},0);return{name:v,sessions:N.sort((S,D)=>{const M=S.providerId.localeCompare(D.providerId);if(M!==0)return M;const C=S.modelId.localeCompare(D.modelId);return C!==0?C:S.instanceNumber-D.instanceNumber}),lastActive:y||Date.now(),sessionCount:N.length}});x.sort((v,N)=>v.name.localeCompare(N.name)),s({groups:x,isLoading:!1,error:null})}catch(l){console.error("Failed to load agent groups:",l),s({groups:i.length>0?i:[],isLoading:!1,error:l instanceof Error?l.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},deleteGroup:async t=>{const n=r().groups.find(i=>i.name===t);if(!n)return!1;const o=ct.getState().currentDirectory,a=ko(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const i=ke.getApiClient(),l=await ci({apiClient:i,group:n,projectDirectory:St(a),worktreePaths:n.sessions.map(f=>f.path)}),d=me.getState(),u=new Set;l.forEach(({worktreePath:f,sessionIds:p,metadata:g})=>{p.forEach(w=>{u.add(w),g&&(d.setWorktreeMetadata(w,g),d.setSessionDirectory(w,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&s({error:"Failed to delete some sessions"}),r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(i){return s({error:i instanceof Error?i.message:"Failed to delete group"}),!1}finally{s({isLoading:!1})}},deleteGroupWorktree:async(t,n)=>{const o=r().groups.find(d=>d.name===t);if(!o)return!1;const a=St(n);if(!a)return!1;const i=ct.getState().currentDirectory,l=ko(i);if(!l)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=ke.getApiClient(),u=await ci({apiClient:d,group:o,projectDirectory:St(l),worktreePaths:[a]}),m=me.getState(),f=new Set;u.forEach(({worktreePath:w,sessionIds:h,metadata:j})=>{h.forEach(b=>{f.add(b),j&&(m.setWorktreeMetadata(b,j),m.setSessionDirectory(b,w))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups();const g=r().groups.find(w=>w.name===t);if(!g)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const w=r().selectedSessionId,h=new Set(g.sessions.map(j=>j.id));(!w||!h.has(w))&&s({selectedSessionId:g.sessions[0]?.id??null})}return p.length===0}catch(d){return s({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{s({isLoading:!1})}},keepOnlyGroupWorktree:async(t,n)=>{const o=r().groups.find(m=>m.name===t);if(!o)return!1;const a=St(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>St(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=ct.getState().currentDirectory,u=ko(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=ke.getApiClient(),f=await ci({apiClient:m,group:o,projectDirectory:St(u),worktreePaths:l}),p=me.getState(),g=new Set;f.forEach(({worktreePath:h,sessionIds:j,metadata:b})=>{j.forEach(x=>{g.add(x),b&&(p.setWorktreeMetadata(x,b),p.setSessionDirectory(x,h))})});const{failedIds:w}=await p.deleteSessions(Array.from(g),{archiveWorktree:!0,silent:!0});if(w.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const h=r().groups.find(b=>b.name===t),j=h?.sessions.find(b=>St(b.path)===a)??h?.sessions[0]??null;s({selectedSessionId:j?.id??null})}return w.length===0}catch(m){return s({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{s({isLoading:!1})}},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),gj=s=>{const t=Date.now()-s,n=Math.floor(t/(60*1e3)),o=Math.floor(t/(3600*1e3)),a=Math.floor(t/(1440*60*1e3));return n<1?"now":n<60?`${n}m`:o<24?`${o}h`:`${a}d`},xj=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),u=Mr(f=>f.deleteGroup),m=c.useCallback(async()=>{if(l)return;if(d(!0),se.info(`Deleting "${s.name}"...`),await u(s.name))se.success(`Deleted "${s.name}"`);else{const p=Mr.getState().error;se.error(p||`Failed to delete "${s.name}"`)}d(!1),i(!1)},[u,s.name,l]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:P("group relative flex items-center rounded-md px-1.5 py-1.5 cursor-pointer",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),onClick:t,children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col gap-0.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-micro text-muted-foreground/60 flex items-center gap-1",children:[e.jsx(Ot,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:gj(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(Ut,{open:n,onOpenChange:o,children:[e.jsx(Vt,{asChild:!0,children:e.jsx("button",{type:"button",className:P("inline-flex h-3.5 w-[18px] items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","opacity-0 group-hover:opacity-100",n&&"opacity-100"),"aria-label":"Group menu",onClick:f=>f.stopPropagation(),children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsx(Gt,{align:"end",className:"min-w-[140px]",children:e.jsx(vt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),i(!0)},children:"Delete"})})]})})]})}),e.jsx(ms,{open:a,onOpenChange:i,children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"outline",onClick:()=>i(!1),disabled:l,children:"Cancel"}),e.jsx(Ne,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},yj=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=c.useState(""),[i,l]=c.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Mr(),f=ct(j=>j.currentDirectory);c.useEffect(()=>{f&&m()},[f,m]);const p=5,g=c.useMemo(()=>{if(!o.trim())return d;const j=o.toLowerCase();return d.filter(b=>b.name.toLowerCase().includes(j))},[o,d]),w=i?g:g.slice(0,p),h=g.length-p;return e.jsxs("div",{className:P("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(pt,{value:o,onChange:j=>a(j.target.value),placeholder:"Search Agent Groups...",className:"pl-8 h-8 rounded-lg border-border/40 bg-background/50 typography-meta"})]})}),e.jsx("div",{className:"px-2.5 pb-2",children:e.jsxs(Ne,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(Mt,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium text-muted-foreground uppercase tracking-wider",children:"Agent Groups"}),u&&e.jsx("span",{className:"typography-micro text-muted-foreground/50 ml-auto",children:"Loading..."})]}),e.jsxs(dt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[w.map(j=>e.jsx(xj,{group:j,isSelected:r===j.name,onSelect:()=>t?.(j.name)},j.name)),!i&&h>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",h,")"]}),i&&g.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&g.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},bj=10*1024*1024,wj=5,vj=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=c.useState(""),[a,i]=c.useState(""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState("HEAD"),[g,w]=c.useState([]),[h,j]=c.useState(!1),[b,x]=c.useState([]),[v,N]=c.useState(!1),[y,S]=c.useState(!1),D=c.useRef(null),M=c.useRef(null),C=ct(Q=>Q.currentDirectory??null),{isGitRepository:k,isLoading:A}=bl(C),E=c.useMemo(()=>{if(typeof window>"u")return null;const Q=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof Q=="string"&&Q.trim().length>0?Q.trim():null},[]),R=c.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),V=Pt(Q=>Q.activeProjectId),T=Pt(Q=>Q.projects),B=c.useMemo(()=>{if(R&&E)return E;if(V){const F=T.find($=>$.id===V);if(F?.path)return F.path}const Q=C??E;if(!Q)return null;const de=Q.replace(/\\/g,"/").replace(/\/+$/,"")||Q,W=de.indexOf("/.openchamber/");return W>0?de.slice(0,W):de.endsWith("/.openchamber")?de.slice(0,de.length-13):de},[V,T,C,E,R]);c.useEffect(()=>{if(!B)return;let Q=!1;return S(!0),(async()=>{try{const de=await ro(B);Q||x(de)}catch{}finally{Q||S(!1)}})(),()=>{Q=!0}},[B]);const re=c.useCallback(Q=>{l.length>=wj||d(de=>[...de,Q])},[l.length]),Y=c.useCallback(Q=>{d(de=>de.filter((I,W)=>W!==Q))},[]),_=c.useCallback((Q,de)=>{d(I=>I.map((W,F)=>F===Q?de:W))},[]),q=async Q=>{const de=Q.target.files;if(!de)return;let I=0;for(let W=0;W<de.length;W++){const F=de[W];if(F.size>bj){se.error(`File "${F.name}" is too large (max 10MB)`);continue}try{const $=await new Promise((J,pe)=>{const be=new FileReader;be.onload=()=>J(be.result),be.onerror=pe,be.readAsDataURL(F)}),L={id:Zo(),filename:F.name,mimeType:F.type||"application/octet-stream",size:F.size,dataUrl:$};w(J=>[...J,L]),I++}catch($){console.error("File attach failed",$),se.error(`Failed to attach "${F.name}"`)}}I>0&&se.success(`Attached ${I} file${I>1?"s":""}`),D.current&&(D.current.value="")},O=Q=>{w(de=>de.filter(I=>I.id!==Q))},z=h||t,U=!!(n.trim()&&a.trim()&&l.length>=1&&k&&!A),ne=async Q=>{if(Q.preventDefault(),!(!U||z)){j(!0);try{const de=l.map(({providerID:F,modelID:$,displayName:L,variant:J})=>({providerID:F,modelID:$,displayName:L,variant:J})),I=g.length>0?g.map(F=>({mime:F.mimeType,filename:F.filename,url:F.dataUrl})):void 0,W=b.filter(F=>F.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:de,agent:u||void 0,worktreeBaseBranch:f,files:I,setupCommands:W.length>0?W:void 0}),o(""),i(""),d([]),m(""),w([]),p("HEAD")}catch(de){console.error("Failed to create agent group:",de),se.error("Failed to create agent group")}finally{j(!1)}}},oe=Q=>{xl(Q)||Q.key==="Enter"&&!Q.shiftKey&&(Q.preventDefault(),U&&!z&&ne(Q))};return e.jsx("div",{className:P("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:ne,className:"w-full max-w-2xl space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"group-name",className:"typography-ui-label font-medium text-foreground",children:"Group Name"}),e.jsx(pt,{id:"group-name",value:n,onChange:Q=>o(Q.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch naming"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-1.5",children:[e.jsx(Ot,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(wm,{directory:C,value:f,onChange:p}),e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Creates new branches from ",e.jsx("code",{className:"font-mono text-xs",children:f})]})]}),e.jsxs(ga,{open:v,onOpenChange:N,children:[e.jsxs(gl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",b.filter(Q=>Q.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(Q=>Q.trim()).length," configured)"]})]}),e.jsx(Mt,{className:P("h-4 w-4 text-muted-foreground transition-transform duration-200",v&&"rotate-180")})]}),e.jsx(xa,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),y?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[b.map((Q,de)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(pt,{value:Q,onChange:I=>{const W=[...b];W[de]=I.target.value,x(W)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const I=b.filter((W,F)=>F!==de);x(I)},className:"flex-shrink-0 flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Remove command",children:e.jsx(Ht,{className:"h-4 w-4"})})]},de)),e.jsxs("button",{type:"button",onClick:()=>x([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(vm,{value:u,onChange:m}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Defaults to your configured default agent"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Models"}),e.jsx(bm,{selectedModels:l,onAdd:re,onRemove:Y,onUpdate:_,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Is,{ref:M,id:"prompt",value:a,onChange:Q=>i(Q.target.value),onKeyDown:oe,placeholder:"Ask anything...",className:"min-h-[100px] max-h-[300px] resize-none border-0 bg-transparent px-4 py-3 typography-markdown focus-visible:ring-0 focus-visible:ring-offset-0"}),g.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 px-3 pb-2",children:g.map(Q=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[Q.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:Q.filename,children:Q.filename}),e.jsx("button",{type:"button",onClick:()=>O(Q.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},Q.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",onChange:q,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>D.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(ou,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!U||z,className:P("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",U?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:z?e.jsx(gh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(nu,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},jj=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Mr(),{setCurrentSession:i,currentSessionId:l}=me(),[d,u]=c.useState(null),[m,f]=c.useState(!1),p=c.useMemo(()=>t?s.sessions.find(v=>v.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),g=c.useCallback(v=>{n(v.id),i(v.id)},[n,i]);c.useEffect(()=>{if(s.sessions.length>0){const v=t?s.sessions.find(N=>N.id===t)??s.sessions[0]:s.sessions[0];v&&(v.id!==l&&i(v.id),t||n(v.id))}},[s.name,s.sessions,t,l,n,i]);const w=p?.id===l,h=c.useCallback(()=>{if(!p?.path){se.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{se.success("Worktree path copied")}).catch(()=>{se.error("Failed to copy path")})},[p?.path]),j=c.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),b=c.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),x=c.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(se.info("Removing worktree..."),await o(s.name,d.path))se.success("Worktree removed");else{const N=Mr.getState().error;se.error(N||"Failed to remove worktree");return}else if(se.info("Removing other worktrees..."),await a(s.name,d.path))se.success("Removed other worktrees");else{const N=Mr.getState().error;se.error(N||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:P("flex h-full flex-col bg-background",r),children:[e.jsxs("div",{className:"flex-shrink-0 border-b border-border/30 px-4 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-4",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h1",{className:"typography-heading-lg text-foreground truncate",children:s.name}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 typography-meta text-muted-foreground",children:[e.jsxs("span",{children:[s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{children:"·"}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ot,{className:"h-3.5 w-3.5"}),p?.worktreeMetadata?.label||p?.branch||"No branch"]})]})]})}),s.sessions.length>0&&e.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsxs(Ne,{variant:"outline",className:"w-full justify-between h-10 px-3",children:[e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:p&&e.jsxs(e.Fragment,{children:[e.jsx(rs,{providerId:p.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsx("span",{className:"truncate typography-body",children:p.modelId}),p.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",p.instanceNumber]})]})}),e.jsx(Mt,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Gt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(v=>e.jsxs(vt,{onClick:()=>g(v),className:"flex items-center gap-2 py-2",children:[e.jsx(rs,{providerId:v.providerId,className:"h-5 w-5 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate typography-body",children:v.modelId}),v.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",v.instanceNumber]})]}),v.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(Ot,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:v.worktreeMetadata?.label||v.branch})]})]}),p?.id===v.id&&e.jsx(At,{className:"h-4 w-4 text-primary flex-shrink-0"})]},v.id))})]})}),e.jsxs(Ut,{children:[e.jsx(Vt,{asChild:!0,children:e.jsx(Ne,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsxs(Gt,{align:"end",className:"min-w-[220px]",children:[e.jsx(vt,{onSelect:v=>{v.preventDefault(),j()},variant:"destructive",children:"Remove this worktree"}),e.jsx(vt,{onSelect:v=>{v.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(vt,{onClick:v=>{v.stopPropagation(),h()},disabled:!p?.path,children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ms,{open:!!d,onOpenChange:v=>{v||u(null)},children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(xs,{children:[e.jsx(ys,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ns,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"."]})})]}),e.jsxs(qs,{children:[e.jsx(Ne,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ne,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{x()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?w?e.jsx(qm,{sessionId:p.id,children:e.jsx(Km,{})}):e.jsxs("div",{className:"h-full flex flex-col",children:[e.jsx("div",{className:"px-4 py-2 bg-muted/30 border-b border-border/30",children:e.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[e.jsx(rs,{providerId:p.providerId,className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel}),e.jsx("span",{children:"·"}),e.jsx("span",{className:"font-mono text-xs truncate",children:p.path})]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center p-8",children:[e.jsxs("p",{className:"typography-body text-muted-foreground mb-2",children:["Loading session for ",e.jsx("span",{className:"font-medium text-foreground",children:p.displayLabel})]}),e.jsxs("p",{className:"typography-micro text-muted-foreground/60",children:["Session ID: ",p.id]})]})})]}):e.jsx("div",{className:"h-full flex items-center justify-center",children:e.jsx("p",{className:"typography-body text-muted-foreground",children:"No sessions in this group"})})})]})},Sj=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=et(v=>v.isInitialized),a=et(v=>v.initializeApp),i=me(v=>v.loadSessions),l=ct(v=>v.setDirectory),d=c.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Mr(),{createMultiRun:g,isLoading:w}=Gn();c.useEffect(()=>{if(!r)return;const v=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(v==="connected"||v==="connecting"||v==="error"||v==="disconnected")&&n(v);const N=y=>{const D=y.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),c.useEffect(()=>{if(!r||t!=="connected")return;const v=Date.now();if(v-d.current<750)return;d.current=v;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{l(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const S=et.getState();if(!S.isInitialized||!S.isConnected||S.providers.length===0||S.agents.length===0)return;await i(),qt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:S.providers.length,agents:S.agents.length,sessions:me.getState().sessions.length})}catch{}})()},[t,o,a,r,i,l]);const h=c.useCallback(v=>{m(v)},[m]),j=c.useCallback(()=>{m(null)},[m]),b=c.useCallback(async v=>{se.info(`Creating agent group "${v.name}" with ${v.models.length} model(s)...`);const N=await g(v);if(N){se.success(`Agent group "${v.name}" created with ${N.sessionIds.length} session(s)`);const y=N.groupSlug,S=async(D=6)=>{for(let M=0;M<D;M+=1){if(await p(),Mr.getState().groups.some(k=>k.name===y))return!0;await new Promise(k=>setTimeout(k,500))}return!1};try{await me.getState().loadSessions()}catch{}await S(),m(y)}else{const y=Gn.getState().error;se.error(y||"Failed to create agent group")}},[g,p,m]),x=f();return e.jsxs("div",{className:P("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(yj,{selectedGroupName:u,onGroupSelect:h,onNewAgent:j})}),e.jsx("div",{className:"flex-1 min-w-0",children:x?e.jsx(jj,{group:x}):e.jsx(vj,{onCreateGroup:b,isCreating:w})})]})},di=({...s})=>{const{theme:r="system"}=xh();return e.jsx(yh,{theme:r,className:"toaster group",closeButton:!0,style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--error-bg":"var(--popover)","--error-text":"var(--popover-foreground)","--error-border":"var(--border)","--success-bg":"var(--popover)","--success-text":"var(--popover-foreground)","--success-border":"var(--border)","--warning-bg":"var(--popover)","--warning-text":"var(--popover-foreground)","--warning-border":"var(--border)","--info-bg":"var(--popover)","--info-text":"var(--popover-foreground)","--info-border":"var(--border)"},...s})},kj=(s=5e3)=>{const[r,t]=Ce.useState(null);return Ce.useEffect(()=>{if(!os())return;let n=!1,o=null;const a=async()=>{const i=await $h();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Nj=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=me(),l=kj(4e3),d=c.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=c.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,g=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:g?.isStreaming||!1,isZombie:g?.isZombie||!1,backgroundCount:g?.backgroundMessageCount||0,lastAccessed:g?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,t,n,o]),m=t.size;return e.jsxs(pl,{className:"fixed bottom-4 right-4 w-96 p-4 shadow-none z-50 bg-background/95 backdrop-blur bottom-safe-area",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(Ne,{size:"icon",variant:"ghost",className:"h-6 w-6",onClick:s,children:e.jsx(Ht,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Total Messages"}),e.jsx("div",{className:"typography-markdown font-semibold",children:d})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Cached Sessions"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[m," / ",ds.MAX_SESSIONS]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[ds.VIEWPORT_MESSAGES," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Background Stream Limit:"}),e.jsxs("span",{children:[ds.BACKGROUND_STREAMING_BUFFER," messages"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Zombie Timeout:"}),e.jsxs("span",{children:[ds.ZOMBIE_TIMEOUT/1e3/60," minutes"]})]})]}),e.jsxs("div",{className:"border-t pt-2",children:[e.jsx("div",{className:"typography-meta font-semibold mb-1",children:"Sessions in Memory:"}),e.jsx(dt,{outerClassName:"max-h-48",className:"space-y-1 pr-1",children:u.map(f=>e.jsxs("div",{className:`typography-meta p-1.5 rounded flex items-center justify-between ${f.isCurrent?"bg-primary/10":"bg-muted/30"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("span",{className:"truncate",children:f.title}),f.isStreaming&&e.jsx(wh,{className:"h-3 w-3 text-primary animate-pulse"}),f.isZombie&&e.jsx("span",{className:"text-warning",children:"!"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:`font-mono ${f.messageCount>ds.VIEWPORT_MESSAGES?"text-warning":""}`,children:[f.messageCount," msgs"]}),f.backgroundCount>0&&e.jsxs("span",{className:"text-primary",children:["+",f.backgroundCount]})]})]},f.id))})]}),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsxs(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Ks,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(tt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(tt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(rt,{delayDuration:1e3,children:[e.jsx(nt,{asChild:!0,children:e.jsx(Ne,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{console.log("[MemoryDebug] Session store state:",{sessions:r.map(f=>({id:f.id,title:f.title})),currentSessionId:o,cachedSessions:Array.from(t.keys()),memoryStates:Object.fromEntries(n)})},children:"Log State"})}),e.jsx(tt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Cj="openchamber-message-cursors",Cn="cursors",Mj=1,mf="openchamber.messageCursors",Nl=()=>typeof window<"u",Cl=()=>Nl()&&typeof indexedDB<"u",ff=()=>Cl()?new Promise((s,r)=>{const t=indexedDB.open(Cj,Mj);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Cn)||n.createObjectStore(Cn)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),pf=()=>{if(!Nl())return{};try{const s=window.localStorage.getItem(mf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},Dj=s=>{if(Nl())try{window.localStorage.setItem(mf,JSON.stringify(s))}catch{}},Aj=async(s,r,t)=>{if(!s||!r)return;if(Cl())try{const o=await ff();await new Promise((a,i)=>{const l=o.transaction(Cn,"readwrite");l.objectStore(Cn).put({messageId:r,completedAt:t},s),l.oncomplete=()=>a(),l.onerror=()=>i(l.error??new Error("Cursor write failed")),l.onabort=()=>i(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=pf();n[s]={messageId:r,completedAt:t},Dj(n)},Ej=async s=>{if(!s)return null;if(Cl())try{const t=await ff(),n=await new Promise((o,a)=>{const i=t.transaction(Cn,"readonly"),d=i.objectStore(Cn).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),i.onerror=()=>a(i.error??new Error("Cursor read failed")),i.onabort=()=>a(i.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return pf()[s]??null},Ij=50,Pj=750,Bd=new WeakMap,zd=s=>{if(!s||!Array.isArray(s))return 0;const r=Bd.get(s);if(r!==void 0)return r;let t=0;for(let n=0;n<s.length;n++){const o=s[n];if(o?.type==="text"){const a=o.text??o.content;typeof a=="string"&&(t+=a.length)}}return Bd.set(s,t),t},Tj=10,Wd=s=>{if(typeof s!="string")return null;const r=s.trim();if(!r)return null;const t=r.indexOf("_"),n=t>=0?r.slice(t+1):r;return!n||n.length<Tj?null:n},Hd=(s,r)=>{const t=Wd(s),n=Wd(r);return!t||!n||t.length!==n.length?!0:t>n},Li=new Map,Ud=(s,r)=>{const t=`${s}:${r}`,n=Li.get(t);if(n&&n.sessionId===s)return n.message;const i=(me.getState().messages.get(s)||[]).find(l=>l.info.id===r)||null;return Li.set(t,{sessionId:s,message:i}),i},Fj=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,currentSessionId:a,applySessionMetadata:i,sessions:l,getWorktreeMetadata:d,loadMessages:u,loadSessions:m,updateSession:f,removeSessionFromStore:p}=me(),{checkConnection:g}=et(),w=ct(ae=>ae.currentDirectory),h=c.useMemo(()=>{if(!a)return;try{const H=d?.(a);if(H?.path)return H.path}catch(H){console.warn("Failed to inspect worktree metadata for session directory:",H)}const ae=l.find(H=>H.id===a);if(ae&&typeof ae.directory=="string"&&ae.directory.trim().length>0)return ae.directory.trim()},[a,d,l]),j=c.useMemo(()=>{if(h&&h.length>0)return h;if(typeof w=="string"&&w.trim().length>0)return w.trim()},[h,w]);c.useEffect(()=>{let ae=!1;return(async()=>{try{const xe=await ke.listPendingPermissions();if(ae||xe.length===0)return;xe.forEach(G=>{o(G)})}catch{}})(),()=>{ae=!0}},[o]);const b=c.useCallback(ae=>{if(typeof ae!="string")return null;const H=ae.trim();if(!H)return null;const xe=H.replace(/\\/g,"/");return xe.length>1?xe.replace(/\/+$/,""):xe},[]),x=c.useCallback(ae=>{if(!ae)return null;try{const xe=d?.(ae),G=b(xe?.path??null);if(G)return G}catch{}const H=l.find(xe=>xe.id===ae);return b(H?.directory??null)},[d,b,l]),v=_e(ae=>ae.setEventStreamStatus),N=c.useRef(null),y=c.useCallback((ae,H)=>{const xe=H??null,G=N.current;if(!(G&&G.status===ae&&G.hint===xe)){if(N.current={status:ae,hint:xe},qt()){const Fe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[ae]??"[INFO]",qe=xe?`${Fe} SSE ${ae}: ${xe}`:`${Fe} SSE ${ae}`;console.info(qe)}v(ae,xe)}},[v]),S=c.useCallback((ae,H)=>{if(!ae)return Promise.resolve();const xe=Date.now();if(B.current)return B.current;if(xe-re.current<Pj)return Promise.resolve();const G=u(ae).catch(ye=>{console.warn(`[useEventStream] Failed to resync messages (${H}):`,ye)}).finally(()=>{B.current=null,re.current=Date.now()});return B.current=G,G},[u]),D=c.useCallback(async ae=>{qt()&&console.info("[useEventStream] Bootstrapping state:",ae);try{await Promise.all([m(),a?S(a,ae):Promise.resolve()])}catch(H){console.warn("[useEventStream] Bootstrap failed:",ae,H)}},[a,m,S]),M=c.useCallback((ae,H,xe)=>{qt()&&console.debug(`[MessageTracker] ${ae}: ${H}`,xe)},[]),C=c.useCallback(ae=>{qt()&&console.debug(`[MessageTracker] ${ae}: reported`)},[]),k=c.useRef(null),A=c.useRef(null),E=c.useRef(0);c.useRef(new Set);const R=c.useRef(new Map),V=c.useRef(null),T=c.useRef(!1),B=c.useRef(null),re=c.useRef(0),Y=c.useRef(new Set),_=c.useCallback(()=>{if(typeof document>"u")return"visible";const ae=document.visibilityState;return ae==="hidden"&&document.hasFocus()?"visible":ae},[]),q=c.useRef(_()),O=c.useRef(typeof navigator>"u"?!0:navigator.onLine),z=c.useRef(!1),U=c.useRef(null),ne=c.useRef(null),oe=c.useRef(Date.now()),Q=c.useRef(!1),de=c.useCallback(ae=>{const H=Date.now();H-oe.current>25e3&&(D(ae),oe.current=H)},[D]);c.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(Q.current=!0)},[]);const I=c.useRef(new Map),W=c.useRef(new Map),F=c.useRef(0),$=c.useRef(null),L=c.useRef(a),J=c.useRef(null),pe=c.useRef(null);c.useEffect(()=>{L.current=a},[a]);const be=c.useCallback((ae,H)=>{if(!ae)return;const xe=Date.now(),G=R.current,ye=G.get(ae);if(ye&&xe-ye<3e3)return;G.set(ae,xe);const Fe=qe=>{if(typeof H=="string"&&H.trim().length>0)return H.trim();try{const Ee=d?.(qe);if(Ee?.path)return Ee.path}catch{}const Re=l.find(Ee=>Ee.id===qe);return Re&&typeof Re.directory=="string"&&Re.directory.trim().length>0?Re.directory.trim():null};setTimeout(async()=>{try{const qe=Fe(ae),Re=qe?await ke.withDirectory(qe,()=>ke.getSession(ae)):await ke.getSession(ae);if(Re){const Ee={};typeof Re.title=="string"&&Re.title.length>0&&(Ee.title=Re.title),Re.summary!==void 0&&(Ee.summary=Re.summary),Object.keys(Ee).length>0&&i(ae,Ee)}}catch(qe){console.warn("Failed to refresh session metadata:",qe)}},100)},[i,d,l]),he=c.useCallback((ae,H)=>{if(me.getState().sessionActivityPhase?.get(ae)===H){W.current=new Map(me.getState().sessionActivityPhase??new Map);return}const G=I.current.get(ae);G&&(clearTimeout(G),I.current.delete(ae));const ye=new Map(me.getState().sessionActivityPhase??new Map);if(ye.set(ae,H),W.current=ye,me.setState({sessionActivityPhase:ye}),H==="cooldown"){const Fe=setTimeout(()=>{if(I.current.delete(ae),me.getState().sessionActivityPhase?.get(ae)==="cooldown"){const Re=new Map(me.getState().sessionActivityPhase??new Map);Re.set(ae,"idle"),W.current=Re,me.setState({sessionActivityPhase:Re})}},2e3);I.current.set(ae,Fe)}},[]),Ae=c.useCallback(async()=>{const ae=Date.now();if($.current)return $.current;if(ae-F.current<1500)return;F.current=ae;const H=G=>{const ye=new Set,Fe=new Set(l.map(Re=>Re.id));Object.entries(G).forEach(([Re,Ee])=>{if(!Re||!Ee)return;ye.add(Re);const Ye=Ee.type==="busy"||Ee.type==="retry"?"busy":"idle";he(Re,Ye)});const qe=me.getState().sessionActivityPhase;if(qe)for(const[Re,Ee]of qe.entries())Fe.has(Re)&&(Ee==="busy"||Ee==="cooldown")&&!ye.has(Re)&&he(Re,"idle")},xe=(async()=>{try{const G=await ke.getGlobalSessionStatus();if(G&&Object.keys(G).length>0){H(G);return}const ye=new Set;l.forEach(Ye=>{const ot=x(Ye.id);ot&&ye.add(ot)});const Fe=b(j??null);Fe&&ye.add(Fe);const qe=Array.from(ye);if(qe.length===0){const Ye=await ke.getSessionStatus();Ye&&H(Ye);return}const Re=await Promise.allSettled(qe.map(Ye=>ke.getSessionStatusForDirectory(Ye))),Ee={};if(Re.forEach(Ye=>{Ye.status!=="fulfilled"||!Ye.value||Object.assign(Ee,Ye.value)}),Object.keys(Ee).length===0&&Array.from(me.getState().sessionActivityPhase?.values?.()??[]).some(ot=>ot==="busy"||ot==="cooldown")&&!await ke.checkHealth().catch(()=>!1))return;H(Ee)}catch{}})().finally(()=>{$.current=null});return $.current=xe,xe},[j,b,x,l,he]);c.useEffect(()=>{const ae=a??null,H=J.current,xe=x(ae),G=pe.current;H&&ae&&H!==ae&&G&&xe&&G!==xe&&Ae(),J.current=ae,pe.current=xe},[a,Ae,x]);const je=c.useCallback(ae=>{if(oe.current=Date.now(),qt()&&console.debug("[useEventStream] Received event:",ae.type,ae.properties),!ae.properties)return;const H=ae.properties;if(!new Set(["session.abort","session.error"]).has(ae.type)){const G=(typeof H.session=="object"&&H.session!==null?H.session:null)||(typeof H.sessionInfo=="object"&&H.sessionInfo!==null?H.sessionInfo:null);if(G){const ye=G,Fe=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof H.sessionID=="string"&&H.sessionID.length>0?H.sessionID:typeof H.id=="string"&&H.id.length>0?H.id:void 0;if(Fe){const qe=typeof ye.title=="string"?ye.title:typeof H.title=="string"?H.title:void 0,Re=typeof ye.summary=="object"&&ye.summary!==null?ye.summary:typeof H.summary=="object"&&H.summary!==null?H.summary:void 0;if(qe!==void 0||Re!==void 0){const Ee={};qe!==void 0&&(Ee.title=qe),Re!==void 0&&(Ee.summary=Re),i(Fe,Ee)}}}}switch(ae.type){case"server.connected":g();break;case"global.disposed":case"server.instance.disposed":{D("server_disposed_event");break}case"openchamber:session-activity":{const G=typeof H.sessionId=="string"?H.sessionId:null,ye=typeof H.phase=="string"?H.phase:null;G&&(ye==="idle"||ye==="busy"||ye==="cooldown")&&(he(G,ye),be(G,typeof H.directory=="string"?H.directory:null));break}case"mcp.tools.changed":{const G=typeof H.directory=="string"?H.directory:j;$n.getState().refresh({directory:G??null,silent:!0});break}case"session.status":if(Q.current)break;{const G=typeof H.sessionID=="string"?H.sessionID:null,ye=typeof H.status=="object"&&H.status!==null?H.status:null,Fe=typeof ye?.type=="string"?ye.type:null;G&&Fe&&(he(G,Fe==="busy"||Fe==="retry"?"busy":"idle"),be(G,typeof H.directory=="string"?H.directory:null))}break;case"message.part.updated":{const G=typeof H.part=="object"&&H.part!==null?H.part:null;if(!G)break;const ye=G,Fe=typeof H.info=="object"&&H.info!==null?H.info:H,qe=typeof Fe.sessionID=="string"?Fe.sessionID:null,Re=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof qe=="string"&&qe.length>0?qe:typeof H.sessionID=="string"&&H.sessionID.length>0?H.sessionID:null,Ee=typeof Fe.id=="string"?Fe.id:null,Ye=typeof ye.messageID=="string"&&ye.messageID.length>0?ye.messageID:typeof Ee=="string"&&Ee.length>0?Ee:typeof H.messageID=="string"&&H.messageID.length>0?H.messageID:null;if(!Re||!Ye){qt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ye.sessionID??qe??H.sessionID,messageID:ye.messageID??Ee??H.messageID});break}const ot=Re,ut=Ye,kt=me.getState().sessionMemoryState.get(ot)?.trimmedHeadMaxId;if(kt&&!Hd(ut,kt)){qt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:ot,messageId:ut,trimmedHeadMaxId:kt});break}let Rt="assistant";if(Fe&&typeof Fe.role=="string")Rt=Fe.role;else{const Nt=Ud(ot,ut);if(Nt){const Qt=Nt.info.role;typeof Qt=="string"&&(Rt=Qt)}}if(M(ut,"part_received",{role:Rt}),Rt==="user"&&ye.synthetic===!0){M(ut,"skipped_synthetic_user_part");break}const Et={...G,type:G.type||"text"};M(ut,"addStreamingPart_called"),s(ot,ut,Et,Rt);break}case"message.updated":{const G=typeof H.info=="object"&&H.info!==null?H.info:H,ye=G,Fe=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof H.sessionID=="string"&&H.sessionID.length>0?H.sessionID:null,qe=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof H.messageID=="string"&&H.messageID.length>0?H.messageID:null;if(!Fe||!qe){qt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ye.sessionID??H.sessionID,messageID:ye.id??H.messageID});break}const Re=Fe,Ee=qe,Ye=me.getState().sessionMemoryState.get(Re)?.trimmedHeadMaxId;if(Ye&&!Hd(Ee,Ye)){qt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:Re,messageId:Ee,trimmedHeadMaxId:Ye});break}if(Q.current&&qt())try{const Ge=H.parts||ye.parts||[],Ke=(Array.isArray(Ge)?Ge.filter(lt=>lt?.type==="text"):[]).map(lt=>{const Ze=lt;return typeof Ze?.text=="string"?Ze.text:typeof Ze?.content=="string"?Ze.content:""}).join(`
107
+ `);console.info("[STREAM-TRACE] message.updated",{messageId:Ee,role:ye.role,status:ye.status,textLen:Ke.length,textPreview:Ke.slice(0,120),partsCount:Array.isArray(Ge)?Ge.length:0})}catch{}if(M(Ee,"message_updated",{role:ye.role}),ye.role==="user"){const Ge=H.parts||ye.parts,st=Array.isArray(Ge)?Ge:[],Ke={...G,userMessageMarker:!0,clientRole:"user"};if(t(Re,Ee,Ke),st.length>0)for(let lt=0;lt<st.length;lt++){const Ze=st[lt];if(Ze.synthetic===!0)continue;const mt={...Ze,type:Ze?.type||"text",sessionID:Ze?.sessionID||Re,messageID:Ze?.messageID||Ee};s(Re,Ee,mt,"user")}M(Ee,"user_message_created_from_event",{partsCount:st.length});break}const ot=Ud(Re,Ee),ut=zd(ot?.parts||[]),kt=ot?.info?.finish==="stop",Rt=H.parts||ye.parts,Et=Array.isArray(Rt)?Rt:[],Nt=Et.length>0,Tt=typeof(ye.time||{})?.completed=="number";if(!Nt&&!Tt)break;const Se=G.finish,Pe=typeof Se=="string"?Se:null,We=Pe==="stop";if(ye.role==="assistant"&&Nt){const Ge=zd(Et);if(ut>0&&Ge+Ij<ut&&!We){M(Ee,"skipped_shrinking_update",{incomingLen:Ge,existingLen:ut});break}if(Q.current){const Ke=ut>0&&Ge<ut,lt=Et.some(mt=>{if(!mt||mt.type!=="text")return!1;const ee=mt;return typeof ee.text=="string"&&ee.text.length>0});if(Ke&&!(We&&lt)){M(Ee,"desktop_shrinking_update_suppressed",{incomingLen:Ge,existingLen:ut});break}}}if(t(Re,Ee,G),Nt&&ye.role!=="user"){const Ke=(me.getState().messages.get(Re)||[]).find(mt=>mt.info.id===Ee),lt=!Ke||Ke.parts.length===0;M(Ee,lt?"server_parts_injected":"server_parts_refreshed",{count:Et.length});const Ze=Q.current&&ye.role==="assistant"?Et.filter(mt=>mt?.type!=="text"):Et;for(let mt=0;mt<Ze.length;mt++){const ee=Ze[mt],we={...ee,type:ee?.type||"text",sessionID:ee?.sessionID||Re,messageID:ee?.messageID||Ee};s(Re,Ee,we,ye.role),M(Ee,`server_part_${mt}`)}}const at=G.time,jt=at?.completed,zt=typeof jt=="number"&&Number.isFinite(jt),Jt=Pe==="stop"||kt;if(G.role==="assistant"&&(zt||Jt)&&G.role==="assistant"){const st=me.getState().messages.get(Re)||[];let Ke=null,lt="";for(let Oe=0;Oe<st.length;Oe++){const Be=st[Oe];Be.info.role==="assistant"&&Be.info.id>lt&&(lt=Be.info.id,Ke=Be.info.id)}if(a===Re&&Ee!==Ke)break;if(!Jt&&Q.current){M(Ee,"desktop_completion_without_stop");break}const mt=zt?jt:Date.now();zt||t(Re,Ee,{...G,time:{...at??{},completed:mt}}),M(Ee,"completed",{timeCompleted:mt}),C(Ee),Aj(Re,Ee,mt),r(Re,Ee),Q.current||Pe==="stop"&&me.getState().sessionActivityPhase?.get(Re)==="busy"&&he(Re,"cooldown");const ee=G.sessionID,we=typeof ee=="string"&&ee.length>0?ee:Re;be(we,typeof H.directory=="string"?H.directory:null),G.summary&&typeof we=="string"&&n(we,null)}break}case"session.created":case"session.updated":{const G=typeof H.info=="object"&&H.info!==null?H.info:typeof H.sessionInfo=="object"&&H.sessionInfo!==null?H.sessionInfo:typeof H.session=="object"&&H.session!==null?H.session:H,ye=typeof G.id=="string"&&G.id.length>0?G.id:typeof G.sessionID=="string"&&G.sessionID.length>0?G.sessionID:typeof H.sessionID=="string"&&H.sessionID.length>0?H.sessionID:typeof H.id=="string"&&H.id.length>0?H.id:void 0;if(ye){const Fe=typeof G.time=="object"&&G.time!==null?G.time:typeof H.time=="object"&&H.time!==null?H.time:null,qe=Fe&&typeof Fe.compacting=="number"?Fe.compacting:null;n(ye,qe);const Re=typeof G.directory=="string"?G.directory:typeof H.directory=="string"?H.directory:null,Ee={...G,id:ye,...Re?{directory:Re}:{}};f(Ee)}break}case"session.deleted":{const G=typeof H.sessionID=="string"?H.sessionID:typeof H.id=="string"?H.id:null;G&&p(G);break}case"session.abort":{const G=typeof H.sessionID=="string"&&H.sessionID.length>0?H.sessionID:null,ye=typeof H.messageID=="string"&&H.messageID.length>0?H.messageID:null;G&&ye&&r(G,ye);break}case"permission.asked":{if(!("sessionID"in H)||typeof H.sessionID!="string")break;const G=H;o(G);const ye=`${G.sessionID}:${G.id}`;Y.current.has(ye)||setTimeout(()=>{if(L.current===G.sessionID||!me.getState().permissions.get(G.sessionID)?.some(Ee=>Ee.id===G.id))return;Y.current.add(ye);const Re=me.getState().sessions.find(Ee=>Ee.id===G.sessionID)?.title||"Session";is(async()=>{const{toast:Ee}=await import("./vendor-.bun-B2HtLj-d.js").then(Ye=>Ye.cq);return{toast:Ee}},__vite__mapDeps([0,1])).then(({toast:Ee})=>{Ee.warning("Permission required",{description:Re,action:{label:"Open",onClick:()=>{_e.getState().setActiveMainTab("chat"),me.getState().setCurrentSession(G.sessionID)}}})})},0);break}case"permission.replied":break;case"todo.updated":{const G=typeof H.sessionID=="string"?H.sessionID:null,ye=Array.isArray(H.todos)?H.todos:null;G&&ye&&Bb(G,ye);break}}},[a,s,r,t,o,g,be,n,i,M,C,he,f,p,D,j]),Te=c.useCallback(()=>{const ae=_();return q.current=ae,ae==="visible"&&O.current},[_]),K=c.useCallback(()=>{qt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:Q.current,hasUnsubscribe:!!k.current,currentSessionId:L.current,effectiveDirectory:j,onlineStatus:O.current,visibilityState:q.current,lastEventTimestamp:oe.current,reconnectAttempts:E.current})},[j]),X=c.useCallback(async()=>!0,[]),te=c.useCallback(()=>{if(T.current){qt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(T.current=!0,A.current&&(clearTimeout(A.current),A.current=null),k.current){const ae=k.current;k.current=null;try{ae()}catch(H){console.warn("[useEventStream] Error during unsubscribe:",H)}}T.current=!1},[]),fe=c.useCallback(async ae=>{if(K(),!Te()){z.current=!0,O.current?y("paused","Paused while hidden"):y("offline","Waiting for network");return}Q.current&&(await X()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),ae?.resetAttempts&&(E.current=0),te(),oe.current=Date.now(),y("connecting",null),qt()&&console.info("[useEventStream] Starting event stream...");const H=G=>{console.warn("Event stream error:",G)},xe=()=>{const G=z.current;if(E.current=0,z.current=!1,oe.current=Date.now(),y("connected",null),g(),Array.from(me.getState().sessionActivityPhase?.values?.()??[]).some(Fe=>Fe==="busy"||Fe==="cooldown")&&Ae(),G)D("sse_reconnected");else{const Fe=L.current;Fe&&setTimeout(()=>{S(Fe,"sse_reconnected").then(()=>be(Fe)).catch(qe=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",qe)})},0)}};if(qt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:j,isCleaningUp:T.current}),T.current){qt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const G=ke.subscribeToGlobalEvents(Fe=>{const qe=Fe.payload,Re=Fe.payload,Ee=typeof Re.properties=="object"&&Re.properties!==null?Re.properties:{},Ye=Fe.directory&&Fe.directory!=="global"?{...Ee,directory:Fe.directory}:Ee;je({type:typeof qe.type=="string"?qe.type:"",properties:Ye})},H,xe),ye=()=>{try{G()}catch(Fe){console.warn("[useEventStream] Error during unsubscribe:",Fe)}};T.current?ye():k.current=ye}catch(G){console.error("[useEventStream] Error during subscription:",G),H(G)}},[Te,te,y,g,S,be,je,j,Ae,X,K,D]),ue=c.useCallback(ae=>{if(!Te()){z.current=!0,te(),O.current?y("paused","Paused while hidden"):y("offline","Waiting for network");return}const H=E.current+1;E.current=H;const xe=ae??`Retrying (${H})`;y("reconnecting",xe);const G=H<=3?Math.min(1e3*Math.pow(2,H-1),8e3):Math.min(2e3*Math.pow(2,H-3),32e3),ye=Math.floor(Math.random()*250),Fe=G+ye;A.current&&clearTimeout(A.current),A.current=setTimeout(()=>{fe({resetAttempts:!1})},Fe)},[Te,te,y,fe]);c.useEffect(()=>{const ae=I.current;typeof window<"u"&&(window.__messageTracker=M);let H=null;Q.current&&typeof window<"u"&&(H=Ye=>{const ot=typeof Ye.detail?.sessionId=="string"?Ye.detail.sessionId:null,ut=typeof Ye.detail?.phase=="string"?Ye.detail.phase:null;ot&&(ut==="idle"||ut==="busy"||ut==="cooldown")&&(he(ot,ut),be(ot))},window.addEventListener("openchamber:session-activity",H));const xe=()=>{U.current&&(clearTimeout(U.current),U.current=null)},G=()=>{U.current||(U.current=setTimeout(()=>{const Ye=_();q.current=Ye,Ye!=="visible"?(te(),z.current=!0,y("paused","Paused while hidden")):xe()},5e3))},ye=()=>{if(q.current=_(),q.current==="visible"){if(xe(),de("visibility_restore"),z.current||!k.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Ye=L.current;Ye&&(S(Ye,"visibility_restore").catch(()=>{}),be(Ye)),Ae(),y("connecting","Resuming stream"),fe({resetAttempts:!0})}}else y("paused","Paused while hidden"),G()},Fe=()=>{if(q.current=_(),q.current==="visible"&&(xe(),de("window_focus"),z.current||!k.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Ye=L.current;Ye&&(be(Ye),S(Ye,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(ot=>console.warn("[useEventStream] Failed to refresh messages:",ot))),Ae(),y("connecting","Resuming stream"),fe({resetAttempts:!0})}},qe=()=>{O.current=!0,de("network_restored"),(z.current||!k.current)&&(y("connecting","Network restored"),fe({resetAttempts:!0}))},Re=()=>{O.current=!1,z.current=!0,y("offline","Waiting for network"),te()};typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",qe),window.addEventListener("offline",Re),window.addEventListener("focus",Fe));const Ee=setTimeout(()=>{fe({resetAttempts:!0})},100);return ne.current&&clearInterval(ne.current),ne.current=setInterval(()=>{if(!Te())return;const Ye=Date.now();Array.from(me.getState().sessionActivityPhase?.values?.()??[]).some(ut=>ut==="busy"||ut==="cooldown")&&Ae(),Ye-oe.current>25e3&&Promise.resolve().then(async()=>{try{await ke.checkHealth()?oe.current=Date.now():ue("Refreshing stalled stream")}catch(ut){console.warn("Health check after stale stream failed:",ut),ue("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Ee),H&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",H),typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",qe),window.removeEventListener("offline",Re),window.removeEventListener("focus",Fe)),xe(),ne.current&&(clearInterval(ne.current),ne.current=null),ae.forEach(Ye=>clearTimeout(Ye)),ae.clear(),Li.clear(),z.current=!1,q.current=_(),O.current=typeof navigator>"u"?!0:navigator.onLine,te(),V.current&&(clearTimeout(V.current),V.current=null),y("idle",null)}},[j,M,_,te,y,fe,ue,u,be,he,Ae,Te,m,de,S])},Rj=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=me(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=_e(),{themeMode:p,setThemeMode:g}=sn(),{working:w}=Pm(),h=c.useRef(null),j=c.useRef(null),b=c.useRef(!1),x=c.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);c.useEffect(()=>{const v=N=>{if(Cs(N)&&N.key==="k"&&(N.preventDefault(),a()),Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const S=Zr()?.diagnostics;if(!S||(N.preventDefault(),b.current))return;b.current=!0,S.downloadLogs().then(({fileName:D,content:M})=>{const C=D||"openchamber.log",k=new Blob([M],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(k),E=document.createElement("a");E.href=A,E.download=C,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(A)}).finally(()=>{b.current=!1});return}if(Cs(N)&&N.key==="."&&(N.preventDefault(),i()),Cs(N)&&N.key.toLowerCase()==="n"){if(N.preventDefault(),et.getState().settingsAutoCreateWorktree?!N.shiftKey:N.shiftKey){u("chat"),d(!1),pa();return}u("chat"),d(!1),s()}if(Cs(N)&&N.key==="/"){N.preventDefault();const y=["light","dark","system"],D=(y.indexOf(p)+1)%y.length;g(y[D])}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:y,setTimelineDialogOpen:S}=_e.getState();S(!y);return}if(Cs(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:y}=_e.getState();m(!y);return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:y,isSessionSwitcherOpen:S}=_e.getState();y?d(!S):l();return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:y,isCommandPaletteOpen:S,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:k,isModelSelectorOpen:A}=_e.getState();if(y||S||D||M||C||!(k==="chat"))return;N.preventDefault(),f(!A);return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:y,isCommandPaletteOpen:S,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:k}=_e.getState();if(y||S||D||M||C||!(k==="chat"))return;const R=et.getState();if(R.getCurrentModelVariants().length===0)return;N.preventDefault(),R.cycleCurrentVariant();const T=et.getState().currentVariant,B=me.getState(),re=B.currentSessionId,Y=et.getState().currentAgentName,_=et.getState().currentProviderId,q=et.getState().currentModelId;re&&Y&&_&&q&&B.saveAgentModelVariantForSession(re,Y,_,q,T);return}if(N.key==="Escape"){const{isSettingsDialogOpen:y,isCommandPaletteOpen:S,isHelpDialogOpen:D,isSessionSwitcherOpen:M,isAboutDialogOpen:C,activeMainTab:k}=_e.getState();if(y){N.preventDefault(),m(!1),x();return}if(S||D||M||C||!(k==="chat")){x();return}const R=o;if(!(w.canAbort&&!!R)){x();return}const T=Date.now(),B=h.current;if(B&&T<B){N.preventDefault(),x(),r();return}N.preventDefault();const re=t(3e3)??T+3e3;h.current=re,j.current&&clearTimeout(j.current);const Y=Math.max(re-T,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&x()},Y||0);return}};return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[s,r,a,i,l,d,u,m,f,g,p,w,t,x,o]),c.useEffect(()=>()=>{x()},[x])},Vd="openchamber:menu-action",_j=s=>{const{openNewSessionDraft:r}=me(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:d}=_e(),{addProject:u}=Pt(),{requestAccess:m,startAccessing:f}=ha(),{setThemeMode:p}=sn(),g=c.useRef(!1),w=c.useCallback(()=>{os()?m("").then(async h=>{if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&se.error("Failed to select directory",{description:h.error});return}const j=await f(h.path);if(!j.success){se.error("Failed to open directory",{description:j.error||"Desktop could not grant file access."});return}u(h.path,{id:h.projectId})||se.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(h=>{console.error("Desktop: Error selecting directory:",h),se.error("Failed to select directory")}):kn.requestDirectoryDialog()},[u,m,f]);c.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":t();break;case"new-session":i("chat"),a(!1),r();break;case"new-worktree-session":i("chat"),a(!1),pa();break;case"change-workspace":w();break;case"open-git-tab":{const{activeMainTab:x}=_e.getState();i(x==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:x}=_e.getState();i(x==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:x}=_e.getState();i(x==="terminal"?"chat":"terminal");break}case"theme-light":p("light");break;case"theme-dark":p("dark");break;case"theme-system":p("system");break;case"toggle-sidebar":o();break;case"toggle-memory-debug":s?.();break;case"help-dialog":n();break;case"download-logs":{const v=Zr()?.diagnostics;if(!v||g.current)break;g.current=!0,v.downloadLogs().then(({fileName:N,content:y})=>{const S=N||"openchamber.log",D=new Blob([y],{type:"text/plain;charset=utf-8"}),M=URL.createObjectURL(D),C=document.createElement("a");C.href=M,C.download=S,document.body.appendChild(C),C.click(),document.body.removeChild(C),URL.revokeObjectURL(M),se.success("Logs saved",{description:`Downloaded to ~/Downloads/${S}`})}).catch(()=>{se.error("Failed to download logs")}).finally(()=>{g.current=!1});break}}};return window.addEventListener(Vd,h),()=>window.removeEventListener(Vd,h)},[r,t,n,o,a,i,l,d,p,s,w])},Oj=s=>s.role==="assistant",Gd=s=>{const r=s.info;if(!Oj(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},Bo=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},Kd=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Un(n)).join(" ").replace(/\s+/g," ").trim(),$j=(s,r)=>{if(!s||!Bo(s.info))return-1;const t=Kd(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((i,l)=>{if(!Bo(i.info))return;const d=Kd(i),u=!!(t&&d&&d===t),m=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=l,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=l,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(i=>{if(!Bo(i.info))return!1;const l=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof l!="number"?!1:Math.abs(l-n)<1e3}):-1},Lj=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=me(),n=c.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=c.useRef(void 0),a=c.useRef(0),i=c.useCallback(async()=>{if(!s||n)return;const l=Date.now();if(!(l-a.current<2e3)){a.current=l;try{const d=r.get(s)||[],u=await ke.getSessionMessages(s),m=await Ej(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(h=>h.info.id===f.info.id),w=p===-1?$j(f,u):p;if(w!==-1)if(w<u.length-1){const h=u.slice(w+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:b}=me.getState();b(s,j)}else{const h=u[w],j=d[d.length-1],b=Gd(h),x=Gd(j);if(b&&!x){console.log("[SYNC] Last message completed on server");const v=[...d.slice(0,-1),h],{syncMessages:N}=me.getState();N(s,v)}}else if(Bo(f.info)){const h=u.slice(-ds.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=me.getState();j(s,h)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(g=>g.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const w=u.slice(p+1).slice(-ds.VIEWPORT_MESSAGES);if(w.length>0){console.log(`[SYNC] Restoring ${w.length} messages after cursor`);const{syncMessages:h}=me.getState();h(s,w)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-ds.VIEWPORT_MESSAGES),{syncMessages:w}=me.getState();w(s,g)}}else if(u.length>0){const p=u.slice(-ds.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:g}=me.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);c.useEffect(()=>{const l=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",l),()=>window.removeEventListener("focus",l)},[i]),c.useEffect(()=>{if(!s||n)return;const l=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(l,3e4)};return o.current=setTimeout(l,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),c.useEffect(()=>{const l=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[i])},Bj=()=>{c.useEffect(()=>{let s=!1;return(async()=>{try{const t=await ke.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,l=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&me.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function zj(){const{git:s}=An(),r=ct(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=me(),{setActiveDirectory:a,startPolling:i,stopPolling:l,fetchAll:d}=Yt(),u=c.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(g=>g.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);c.useEffect(()=>{if(!u||!s){l();return}return a(u),d(u,s),i(s),()=>{l()}},[u,s,a,i,l,d])}function Wj({children:s}){return zj(),e.jsx(e.Fragment,{children:s})}const Hj=()=>{const[{isUpdating:s,message:r},t]=c.useState(()=>og());return c.useEffect(()=>ng(t),[]),s?e.jsxs("div",{className:"fixed inset-0 z-[9999] flex flex-col items-center justify-center gap-6 backdrop-blur-md",children:[e.jsx(vl,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},Uj=({open:s,onOpenChange:r})=>{const[t,n]=c.useState(null);c.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:l}=await is(async()=>{const{getVersion:u}=await import("./vendor-.bun-B2HtLj-d.js").then(m=>m.cs);return{getVersion:u}},__vite__mapDeps([0,1])),d=await l();n(d)}catch{n("1.4.5")}})():n("1.4.5")},[s]);const o=t;return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsx(fs,{className:"max-w-xs p-6",children:e.jsxs("div",{className:"flex flex-col items-center text-center space-y-4",children:[e.jsx(vl,{width:64,height:64}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"OpenChamber"}),o&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Version ",o]})]}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["A fan-made interface for"," ",e.jsx("a",{href:"https://opencode.ai/",target:"_blank",rel:"noopener noreferrer",className:"hover:text-foreground transition-colors",children:"OpenCode"})," ","agent"]}),e.jsxs("div",{className:"flex items-center gap-4 pt-2",children:[e.jsxs("a",{href:"https://github.com/btriapitsyn/openchamber",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(xi,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://discord.gg/ZYRSdnwwKA",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(pu,{className:"h-4 w-4"}),e.jsx("span",{children:"Discord"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(yi,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground/60 pt-2",children:"Made with love to comunity"})]})})})};function ui({apis:s,children:r}){return e.jsx(ll.Provider,{value:s,children:r})}const Vj="curl -fsSL https://opencode.ai/install | bash",Gj=3e3;function Kj({onCopy:s}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Gs,{className:"h-4 w-4"})})]})}const qj=3e4;function Yj({onCliAvailable:s}){const[r,t]=c.useState(!1),[n,o]=c.useState(!1),[a,i]=c.useState(!1);c.useEffect(()=>{const m=setTimeout(()=>o(!0),qj);return()=>clearTimeout(m)},[]),c.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const l=c.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await is(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-B2HtLj-d.js").then(w=>w.cr);return{getCurrentWindow:g}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=c.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=c.useCallback(async()=>{try{await navigator.clipboard.writeText(Vj),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return c.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,Gj);return m(),()=>clearInterval(f)},[d,s]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(zo,{className:"h-4 w-4"})]})," ","is required to continue."]})]}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"bg-background/60 backdrop-blur-sm border border-border rounded-lg px-5 py-3 font-mono text-sm w-fit",children:r?e.jsxs("div",{className:"flex items-center justify-center gap-2",style:{color:"var(--status-success)"},children:[e.jsx(At,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(Kj,{onCopy:u})})}),e.jsxs("a",{href:"https://opencode.ai/docs",target:"_blank",rel:"noopener noreferrer",className:"text-sm text-muted-foreground hover:text-foreground transition-colors inline-flex items-center gap-1 justify-center",children:["View documentation",e.jsx(zo,{className:"h-3 w-3"})]}),e.jsx("p",{className:"text-sm text-muted-foreground animate-pulse",children:"Waiting for OpenCode installation..."})]}),n&&e.jsxs("div",{className:"absolute bottom-8 left-0 right-0 text-center space-y-1",children:[e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["Already installed? Make sure ",e.jsx("code",{className:"text-foreground/70",children:"opencode"})," is in your PATH"]}),e.jsxs("p",{className:"text-sm text-muted-foreground/70",children:["or set ",e.jsx("code",{className:"text-foreground/70",children:"OPENCODE_BINARY"})," environment variable."]})]})]})}const Xj=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=_e();return e.jsx(Uj,{open:s,onOpenChange:r})};function Qj({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=et(),{error:o,clearError:a,loadSessions:i}=me(),l=ct(y=>y.currentDirectory),d=ct(y=>y.isSwitchingDirectory),[u,m]=c.useState(!1),{uiFont:f,monoFont:p}=Jm(),[g,w]=c.useState(()=>s.runtime.isDesktop),[h,j]=c.useState(()=>s.runtime.isVSCode),[b,x]=c.useState(()=>s.runtime.isDesktop?Lh():!0);c.useEffect(()=>{w(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),c.useEffect(()=>(zl(s),()=>zl(null)),[s]),c.useEffect(()=>{if(typeof document>"u")return;const y=document.documentElement,S=vd[f]?.stack??vd[r0].stack,D=Br[p]?.stack??Br[$o].stack;y.style.setProperty("--font-sans",S),y.style.setProperty("--font-heading",S),y.style.setProperty("--font-family-sans",S),y.style.setProperty("--font-mono",D),y.style.setProperty("--font-family-mono",D),y.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=S)},[f,p]),c.useEffect(()=>{if(t){const S=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},150);return()=>clearTimeout(S)}},[t]),c.useEffect(()=>{const y=setTimeout(()=>{const S=document.getElementById("initial-loading");S&&!t&&(S.classList.add("fade-out"),setTimeout(()=>{S.remove()},300))},5e3);return()=>clearTimeout(y)},[t]),c.useEffect(()=>{(async()=>h||await r())()},[r,h]),c.useEffect(()=>{if(d)return;(async()=>h||n&&(ke.setDirectory(l),await i()))()},[l,d,i,n,h]),Fj(),Rj();const v=c.useCallback(()=>{m(y=>!y)},[]);_j(v),Lj(),Bj(),af(),c.useEffect(()=>{const y=S=>{Cs(S)&&S.shiftKey&&S.key==="D"&&(S.preventDefault(),m(D=>!D))};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[]),c.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=c.useCallback(()=>{x(!0),window.location.reload()},[]);return g&&!b?e.jsx(as,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(Yj,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(as,{children:e.jsx(ui,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Sj,{}),e.jsx(di,{})]})})}):e.jsx(as,{children:e.jsx(ui,{apis:s,children:e.jsx(gd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(uj,{}),e.jsx(di,{})]})})})}):e.jsx(as,{children:e.jsx(ui,{apis:s,children:e.jsx(Wj,{children:e.jsx(gd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(cj,{}),e.jsx(di,{}),e.jsx(Hj,{}),e.jsx(Xj,{}),u&&e.jsx(Nj,{onClose:()=>m(!1)})]})})})})})}const hf=async()=>{if(typeof window>"u")return;let s=null,r=null;try{s=window.localStorage.getItem("homeDirectory"),r=window.localStorage.getItem("lastDirectory")}catch(n){console.warn("Failed to read saved directory preferences:",n)}const t=ct.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},gf="/auth/session",Jj=async()=>fetch(gf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),qd=async s=>fetch(gf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Ml=({children:s})=>e.jsxs("div",{className:"relative flex min-h-screen items-center justify-center overflow-hidden bg-background text-foreground",style:{fontFamily:'"Inter", "SF Pro Text", -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif'},children:[e.jsx("div",{className:"pointer-events-none absolute inset-0 opacity-55",style:{background:"radial-gradient(120% 140% at 50% -20%, var(--surface-overlay) 0%, transparent 68%)"}}),e.jsx("div",{className:"pointer-events-none absolute inset-0",style:{backgroundColor:"var(--surface-subtle)",opacity:.22}}),e.jsx("div",{className:"relative z-10 flex w-full justify-center px-4 py-12 sm:px-6",children:s})]}),Zj=({message:s="Preparing workspace…"})=>e.jsx(Ml,{children:e.jsx("div",{className:"w-full max-w-sm rounded-3xl border border-border/40 bg-card/90 px-6 py-5 text-center shadow-none backdrop-blur",children:e.jsx("p",{className:"typography-ui-label text-muted-foreground",children:s})})}),eS=({onRetry:s})=>e.jsx(Ml,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 text-center",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-destructive",children:"Unable to reach server"}),e.jsx("p",{className:"typography-meta text-muted-foreground max-w-xs",children:"We couldn't verify the UI session. Check that the service is running and try again."})]}),e.jsx(Ne,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),tS=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},sS=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},rS=({children:s})=>{const r=c.useMemo(()=>os(),[]),t=c.useMemo(()=>Wt(),[]),n=r||t,[o,a]=c.useState(()=>n?"authenticated":"pending"),[i,l]=c.useState(""),[d,u]=c.useState(!1),[m,f]=c.useState(""),p=c.useRef(null),g=c.useRef(n),w=c.useRef(!1),h=c.useCallback(async()=>{if(n){a("authenticated");return}a(b=>b==="authenticated"?b:"pending");try{const b=await Jj();if(b.ok){a("authenticated"),f("");return}if(b.status===401){a("locked");return}a("error")}catch(b){console.warn("Failed to check session status:",b),a("error")}},[n]);c.useEffect(()=>{n||h()},[h,n]),c.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),c.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),c.useEffect(()=>{if(n||o!=="locked"||w.current||d)return;const b=tS();b&&(w.current=!0,sS(),u(!0),f(""),qd(b).then(x=>{if(x.ok){l(""),a("authenticated");return}if(x.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(x=>{console.warn("Failed to submit URL token:",x),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),c.useEffect(()=>{n||o==="authenticated"&&!g.current&&(g.current=!0,(async()=>(await ju(),await Su(),await hf()))())},[n,o]);const j=async b=>{if(b.preventDefault(),!(!i||d)){u(!0),f("");try{const x=await qd(i);if(x.ok){l(""),a("authenticated");return}if(x.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(x){console.warn("Failed to submit UI password:",x),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(Zj,{}):o==="error"?e.jsx(eS,{onRetry:()=>{h()}}):o==="locked"?e.jsx(Ml,{children:e.jsxs("div",{className:"flex flex-col items-center gap-6 w-full max-w-xs",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold text-foreground",children:"Unlock OpenChamber"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"This session is password-protected."})]}),e.jsxs("form",{onSubmit:j,className:"w-full space-y-2","data-keyboard-avoid":"true",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(vh,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(pt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:b=>{l(b.target.value),m&&f("")},className:"pl-10","aria-invalid":!!m||void 0,"aria-describedby":m?"oc-ui-auth-error":void 0,disabled:d})]}),e.jsx(Ne,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx(jh,{className:"h-4 w-4"})})]}),m&&e.jsx("p",{id:"oc-ui-auth-error",className:"typography-meta text-destructive",children:m})]})]})}):e.jsx(e.Fragment,{children:s})},mi=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(l=>l+l).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class nS{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
108
+ `)}generateTailwindVariables(r){const t=[];t.push(` --background: ${r.colors.surface.background} !important;`),t.push(` --foreground: ${r.colors.surface.foreground} !important;`),t.push(` --muted: ${r.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --card: ${r.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${r.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${r.colors.interactive.border} !important;`),t.push(` --input: ${r.colors.interactive.border} !important;`),t.push(` --primary: ${r.colors.primary.base} !important;`),t.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --secondary: ${r.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${r.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --destructive: ${r.colors.status.error} !important;`),t.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),t.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&t.push(` --radius: ${r.config.radius.md} !important;`);const n=mi(r.colors.surface.muted),o=mi(r.colors.surface.subtle),a=mi(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const i=r.metadata.variant==="dark",l=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,l)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
109
+ ${t}
110
+ }
111
+
112
+ .dark {
113
+ ${t}
114
+ }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
115
+ ${t}
116
+ }
117
+
118
+ :root:not(.dark) {
119
+ ${t}
120
+ }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const t=[];return t.push(` --primary-base: ${r.base};`),t.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),t.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),t.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),t.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),t.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),t}generateSurfaceColors(r){const t=[];return t.push(` --surface-background: ${r.background};`),t.push(` --surface-foreground: ${r.foreground};`),t.push(` --surface-muted: ${r.muted};`),t.push(` --surface-muted-foreground: ${r.mutedForeground};`),t.push(` --surface-elevated: ${r.elevated};`),t.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),t.push(` --surface-overlay: ${r.overlay};`),t.push(` --surface-subtle: ${r.subtle};`),t}generateInteractiveColors(r){const t=[];return t.push(` --interactive-border: ${r.border};`),t.push(` --interactive-border-hover: ${r.borderHover};`),t.push(` --interactive-border-focus: ${r.borderFocus};`),t.push(` --interactive-selection: ${r.selection};`),t.push(` --interactive-selection-foreground: ${r.selectionForeground};`),t.push(` --interactive-focus: ${r.focus};`),t.push(` --interactive-focus-ring: ${r.focusRing};`),t.push(` --interactive-cursor: ${r.cursor};`),t.push(` --interactive-hover: ${r.hover};`),t.push(` --interactive-active: ${r.active};`),t}generateStatusColors(r){const t=[];return t.push(` --status-error: ${r.error};`),t.push(` --status-error-foreground: ${r.errorForeground};`),t.push(` --status-error-background: ${r.errorBackground};`),t.push(` --status-error-border: ${r.errorBorder};`),t.push(` --status-warning: ${r.warning};`),t.push(` --status-warning-foreground: ${r.warningForeground};`),t.push(` --status-warning-background: ${r.warningBackground};`),t.push(` --status-warning-border: ${r.warningBorder};`),t.push(` --status-success: ${r.success};`),t.push(` --status-success-foreground: ${r.successForeground};`),t.push(` --status-success-background: ${r.successBackground};`),t.push(` --status-success-border: ${r.successBorder};`),t.push(` --status-info: ${r.info};`),t.push(` --status-info-foreground: ${r.infoForeground};`),t.push(` --status-info-background: ${r.infoBackground};`),t.push(` --status-info-border: ${r.infoBorder};`),t}generateSyntaxColors(r){const t=[];t.push(` --syntax-background: ${r.base.background};`),t.push(` --syntax-foreground: ${r.base.foreground};`),t.push(` --syntax-comment: ${r.base.comment};`),t.push(` --syntax-keyword: ${r.base.keyword};`),t.push(` --syntax-string: ${r.base.string};`),t.push(` --syntax-number: ${r.base.number};`),t.push(` --syntax-function: ${r.base.function};`),t.push(` --syntax-variable: ${r.base.variable};`),t.push(` --syntax-type: ${r.base.type};`),t.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(r){const t=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(r,t){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),r.chat?n.push(...this.generateChatColors(r.chat,t)):n.push(...this.generateDefaultChatColors(t)),r.tools?n.push(...this.generateToolColors(r.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(r,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const t=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${r.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${r.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${r.colors.interactive.border};`),t}generateChatColors(r,t){const n=[],o=r.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const t=[];return t.push(` --chat-background: ${r.colors.surface.background};`),t.push(` --chat-user-message: ${r.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),t.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${r.colors.interactive.border};`),t.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),t}generateToolColors(r,t){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const t=[];return t.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),t.push(` --tools-title: ${r.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${r.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${r.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${r.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(r){const t=[];return r&&(r.fonts&&(r.fonts.sans&&(t.push(` --font-sans: ${r.fonts.sans};`),t.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(t.push(` --font-mono: ${r.fonts.mono};`),t.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&t.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&t.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&t.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&t.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&t.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&t.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&t.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&t.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&t.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&t.push(` --transition-slow: ${r.transitions.slow};`))),t}generateTypographyVariables(){const r=[],t=Wt()?Yh:Yi;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}lighten(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}adjustHue(r,t){return this.lighten(r,t/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Dl={metadata:{id:"flexoki-light",name:"Flexoki Light",description:"An inky color scheme for prose and code - light variant",author:"Steph Ango",version:"1.0.0",variant:"light",tags:["light","warm","natural","paper"]},colors:{primary:{base:"#EC8B49",hover:"#F9AE77",active:"#DA702C",foreground:"#FFFCF0",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#FFFCF0",foreground:"#100F0F",muted:"#F2F0E5",mutedForeground:"#6F6E69",elevated:"#E6E4D9",elevatedForeground:"#100F0F",overlay:"#100F0F20",subtle:"#DAD8CE"},interactive:{border:"#DAD8CE",borderHover:"#CECDC3",borderFocus:"#EC8B49",selection:"#100F0F44",selectionForeground:"#100F0F",focus:"#EC8B49",focusRing:"#EC8B4940",cursor:"#100F0F",hover:"#DAD8CE",active:"#CECDC3"},status:{error:"#AF3029",errorForeground:"#FFFCF0",errorBackground:"#D14D4120",errorBorder:"#D14D4150",warning:"#BC5215",warningForeground:"#FFFCF0",warningBackground:"#DA702C20",warningBorder:"#DA702C50",success:"#66800B",successForeground:"#FFFCF0",successBackground:"#879A3920",successBorder:"#879A3950",info:"#205EA6",infoForeground:"#FFFCF0",infoBackground:"#4385BE20",infoBorder:"#4385BE50"},syntax:{base:{background:"#F2F0E5",foreground:"#100F0F",comment:"#6F6E69",keyword:"#205EA6",string:"#24837B",number:"#5E409D",function:"#BC5215",variable:"#100F0F",type:"#AD8301",operator:"#AF3029"},tokens:{commentDoc:"#B7B5AC",stringEscape:"#100F0F",keywordImport:"#AF3029",storageModifier:"#205EA6",functionCall:"#BC5215",method:"#66800B",variableProperty:"#205EA6",variableOther:"#66800B",variableGlobal:"#A02F6F",variableLocal:"#E6E4D9",parameter:"#100F0F",constant:"#100F0F",class:"#BC5215",className:"#BC5215",interface:"#AD8301",struct:"#BC5215",enum:"#BC5215",typeParameter:"#BC5215",namespace:"#AD8301",module:"#AF3029",tag:"#205EA6",jsxTag:"#A02F6F",tagAttribute:"#AD8301",tagAttributeValue:"#24837B",boolean:"#AD8301",decorator:"#AD8301",label:"#A02F6F",punctuation:"#6F6E69",macro:"#205EA6",preprocessor:"#A02F6F",regex:"#24837B",url:"#205EA6",key:"#BC5215",exception:"#A02F6F"},highlights:{diffAdded:"#66800B",diffAddedBackground:"#879A3920",diffRemoved:"#AF3029",diffRemovedBackground:"#D14D4120",diffModified:"#205EA6",diffModifiedBackground:"#4385BE20",lineNumber:"#CECDC3",lineNumberActive:"#100F0F"}},markdown:{heading1:"#AD8301",heading2:"#BC5215",heading3:"#205EA6",heading4:"#100F0F",link:"#205EA6",linkHover:"#4385BE",inlineCode:"#24837B",inlineCodeBackground:"#F2F0E5",blockquote:"#6F6E69",blockquoteBorder:"#DAD8CE",listMarker:"#AD830199"},chat:{userMessage:"#100F0F",userMessageBackground:"#F2F0E5",assistantMessage:"#100F0F",assistantMessageBackground:"#FFFCF0",timestamp:"#6F6E69",divider:"#DAD8CE"},tools:{background:"#F2F0E550",border:"#DAD8CE80",headerHover:"#DAD8CE",icon:"#6F6E69",title:"#100F0F",description:"#6F6E69",edit:{added:"#66800B",addedBackground:"#66800B25",removed:"#AF3029",removedBackground:"#AF302925",lineNumber:"#CECDC3"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},Al={metadata:{id:"flexoki-dark",name:"Flexoki Dark",description:"An inky color scheme for prose and code - dark variant",author:"Steph Ango",version:"1.0.0",variant:"dark",tags:["dark","warm","natural","ink"]},colors:{primary:{base:"#EC8B49",hover:"#DA702C",active:"#F9AE77",foreground:"#100F0F",muted:"#EC8B4980",emphasis:"#F9AE77"},surface:{background:"#100F0F",foreground:"#CECDC3",muted:"#1C1B1A",mutedForeground:"#878580",elevated:"#282726",elevatedForeground:"#CECDC3",overlay:"#00000080",subtle:"#343331"},interactive:{border:"#343331",borderHover:"#403E3C",borderFocus:"#EC8B49",selection:"#CECDC330",selectionForeground:"#CECDC3",focus:"#EC8B49",focusRing:"#EC8B4950",cursor:"#CECDC3",hover:"#343331",active:"#403E3C"},status:{error:"#D14D41",errorForeground:"#100F0F",errorBackground:"#AF302920",errorBorder:"#AF302950",warning:"#DA702C",warningForeground:"#100F0F",warningBackground:"#BC521520",warningBorder:"#BC521550",success:"#A0AF54",successForeground:"#100F0F",successBackground:"#66800B20",successBorder:"#66800B50",info:"#4385BE",infoForeground:"#100F0F",infoBackground:"#205EA620",infoBorder:"#205EA650"},syntax:{base:{background:"#1C1B1A",foreground:"#CECDC3",comment:"#878580",keyword:"#4385BE",string:"#3AA99F",number:"#8B7EC8",function:"#DA702C",variable:"#CECDC3",type:"#D0A215",operator:"#D14D41"},tokens:{commentDoc:"#575653",stringEscape:"#CECDC3",keywordImport:"#D14D41",storageModifier:"#4385BE",functionCall:"#DA702C",method:"#879A39",variableProperty:"#4385BE",variableOther:"#879A39",variableGlobal:"#CE5D97",variableLocal:"#282726",parameter:"#CECDC3",constant:"#CECDC3",class:"#DA702C",className:"#DA702C",interface:"#D0A215",struct:"#DA702C",enum:"#DA702C",typeParameter:"#DA702C",namespace:"#D0A215",module:"#D14D41",tag:"#4385BE",jsxTag:"#CE5D97",tagAttribute:"#D0A215",tagAttributeValue:"#3AA99F",boolean:"#D0A215",decorator:"#D0A215",label:"#CE5D97",punctuation:"#878580",macro:"#4385BE",preprocessor:"#CE5D97",regex:"#3AA99F",url:"#4385BE",key:"#DA702C",exception:"#CE5D97"},highlights:{diffAdded:"#879A39",diffAddedBackground:"#66800B20",diffRemoved:"#D14D41",diffRemovedBackground:"#AF302920",diffModified:"#4385BE",diffModifiedBackground:"#205EA620",lineNumber:"#403E3C",lineNumberActive:"#CECDC3"}},markdown:{heading1:"#D0A215",heading2:"#DA702C",heading3:"#4385BE",heading4:"#CECDC3",link:"#4385BE",linkHover:"#205EA6",inlineCode:"#A0AF54",inlineCodeBackground:"#1C1B1A",blockquote:"#878580",blockquoteBorder:"#343331",listMarker:"#D0A21599"},chat:{userMessage:"#CECDC3",userMessageBackground:"#282726",assistantMessage:"#CECDC3",assistantMessageBackground:"#100F0F",timestamp:"#878580",divider:"#343331"},tools:{background:"#1C1B1A50",border:"#34333180",headerHover:"#34333150",icon:"#878580",title:"#CECDC3",description:"#878580",edit:{added:"#879A39",addedBackground:"#66800B25",removed:"#D14D41",removedBackground:"#AF302925",lineNumber:"#403E3C"}}},config:{fonts:{sans:'"IBM Plex Mono", monospace',mono:'"IBM Plex Mono", monospace',heading:'"IBM Plex Mono", monospace'},radius:{none:"0",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem",full:"9999px"},transitions:{fast:"150ms ease",normal:"250ms ease",slow:"350ms ease"}}},eo=[Dl,Al];function sa(s){return eo.find(r=>r.metadata.id===s)}const xf=Dl.metadata.id,yf=Al.metadata.id,oS=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,bf=s=>s==="dark"?Al:Dl,aS=s=>(eo.find(t=>t.metadata.variant===s)??bf(s)).metadata.id,No=(s,r)=>{const t=sa(s);return t&&t.metadata.variant===r?t:eo.find(o=>o.metadata.variant===r)??bf(r)},iS=typeof window<"u"?c.useLayoutEffect:c.useEffect,ra=(s,r)=>{if(!s)return r==="light"?xf:yf;const t=sa(s);return t&&t.metadata.variant===r?t.metadata.id:aS(r)},lS=s=>{let r=xf,t=yf,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=sa(d);f&&(n=f.metadata.variant==="dark"?"dark":"light",f.metadata.variant==="dark"?t=f.metadata.id:r=f.metadata.id)}}else(u==="light"||u==="dark")&&(n=u);r=ra(a,"light"),t=ra(i,"dark")}if(s){const o=sa(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function cS({children:s,defaultThemeId:r}){const t=Ce.useMemo(()=>new nS,[]),[n,o]=Ce.useState(()=>lS(r)),[a,i]=Ce.useState(()=>oS()),[l,d]=Ce.useState(()=>typeof window>"u"||!Wt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ce.useMemo(()=>Wt(),[]),m=Ce.useMemo(()=>u&&l?l:n.themeMode==="light"?No(n.lightThemeId,"light"):n.themeMode==="dark"||a?No(n.darkThemeId,"dark"):No(n.lightThemeId,"light"),[u,n,a,l]),f=Ce.useMemo(()=>u&&l?[l,...eo]:eo,[u,l]);Ce.useEffect(()=>{if(!u)return;const N=D=>{d(D);const M=D.metadata.variant==="dark"?"dark":"light",C=_e.getState();C.theme!==M&&C.setTheme(M)},y=D=>{const M=D.detail;M?.theme&&N(M.theme)},S=window.__OPENCHAMBER_VSCODE_THEME__;return S&&N(S),window.addEventListener("openchamber:vscode-theme",y),()=>window.removeEventListener("openchamber:vscode-theme",y)},[u]);const p=Ce.useCallback(N=>{if(typeof document>"u")return;const y=N.colors.surface.background;os()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=y;let S=document.querySelector('meta[name="theme-color"]');S||(S=document.createElement("meta"),S.setAttribute("name","theme-color"),document.head.appendChild(S)),S.setAttribute("content",y);const D=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let M=document.querySelector(`meta[name="theme-color"][media="${D}"]`);M||(M=document.createElement("meta"),M.setAttribute("name","theme-color"),M.setAttribute("media",D),document.head.appendChild(M)),M.setAttribute("content",y)},[]),g=Ce.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);iS(()=>{if(typeof window>"u")return;t.apply(m),g(u),p(m);const N=document.documentElement;N.classList.remove("light","dark"),N.classList.add(m.metadata.variant)},[g,t,m,u,p]),Ce.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),y=S=>{i(S.matches)};return i(N.matches),N.addEventListener("change",y),()=>N.removeEventListener("change",y)},[n.themeMode]),Ce.useEffect(()=>{typeof window>"u"||(localStorage.setItem("themeMode",n.themeMode),localStorage.setItem("lightThemeId",n.lightThemeId),localStorage.setItem("darkThemeId",n.darkThemeId),localStorage.setItem("useSystemTheme",String(n.themeMode==="system")),localStorage.setItem("selectedThemeId",m.metadata.id),localStorage.setItem("selectedThemeVariant",m.metadata.variant==="light"?"light":"dark"))},[n,m]),Ce.useEffect(()=>{ns({themeId:m.metadata.id,themeVariant:m.metadata.variant==="light"?"light":"dark",useSystemTheme:n.themeMode==="system",lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId})},[m.metadata.id,m.metadata.variant,n.themeMode,n.lightThemeId,n.darkThemeId]),Ce.useEffect(()=>{if(typeof window>"u")return;const N=y=>{const S=y.detail;S&&o(D=>{let M=D.themeMode;S.useSystemTheme===!0?M="system":S.useSystemTheme===!1&&(S.themeVariant==="dark"||S.themeVariant==="light")&&(M=S.themeVariant);let C=D.lightThemeId;typeof S.lightThemeId=="string"&&S.lightThemeId.length>0&&(C=ra(S.lightThemeId,"light"));let k=D.darkThemeId;return typeof S.darkThemeId=="string"&&S.darkThemeId.length>0&&(k=ra(S.darkThemeId,"dark")),M===D.themeMode&&C===D.lightThemeId&&k===D.darkThemeId?D:{themeMode:M,lightThemeId:C,darkThemeId:k}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const w=Ce.useCallback(N=>{const y=f.find(S=>S.metadata.id===N);y&&o(S=>y.metadata.variant==="dark"?S.darkThemeId===y.metadata.id&&S.themeMode==="dark"?S:{...S,darkThemeId:y.metadata.id,themeMode:"dark"}:S.lightThemeId===y.metadata.id&&S.themeMode==="light"?S:{...S,lightThemeId:y.metadata.id,themeMode:"light"})},[f]),h=Ce.useCallback(N=>{o(y=>y.themeMode===N?y:{...y,themeMode:N})},[]),j=Ce.useCallback(N=>{if(N){o(S=>S.themeMode==="system"?S:{...S,themeMode:"system"});return}const y=m.metadata.variant==="dark"?"dark":"light";o(S=>S.themeMode===y?S:{...S,themeMode:y})},[m.metadata.variant]),b=Ce.useCallback(N=>{const y=f.find(S=>S.metadata.id===N&&S.metadata.variant==="light");y&&o(S=>S.lightThemeId===y.metadata.id?S:{...S,lightThemeId:y.metadata.id})},[f]),x=Ce.useCallback(N=>{const y=f.find(S=>S.metadata.id===N&&S.metadata.variant==="dark");y&&o(S=>S.darkThemeId===y.metadata.id?S:{...S,darkThemeId:y.metadata.id})},[f]),v={currentTheme:m,availableThemes:f,setTheme:w,isSystemPreference:n.themeMode==="system",setSystemPreference:j,themeMode:n.themeMode,setThemeMode:h,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:b,setDarkThemePreference:x};return e.jsx(cl.Provider,{value:v,children:s})}const dS=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=_e();return c.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),c.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},uS={getLastAssistantMessage(){const s=me.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const t=s.messages.get(r);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const g={id:p.id,type:p.type};return p.type==="text"?(g.text=p.text,g.textLength=p.text?.length||0):p.type==="tool"?(g.tool=p.tool,g.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(g.isStepMarker=!0),g}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!i&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(s,r=80){return!s||typeof s!="string"||s.length<=r?s:s.substring(0,r)+"…"},truncateMessages(s){return s.map(r=>({...r,parts:(r.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(s=!1){const r=me.getState(),t=r.currentSessionId;if(!t)return console.log("[ERROR] No active session"),[];const n=r.messages.get(t)||[];return console.log(`[MESSAGES] Total messages in session: ${n.length}`),n.forEach((o,a)=>{console.log(`[${a}] ${o.info.role} - ${o.info.id} - ${o.parts.length} parts`)}),s?this.truncateMessages(n):n},async getAppStatus(){const s=ct.getState(),r=me.getState(),t=s.currentDirectory||null,n=ke.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(S=>{const D=S.directory;typeof D=="string"&&D.trim().length>0?(a.add(D),i[D]=(i[D]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const l=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(S){return{available:!1,error:S instanceof Error?S.message:String(S)}}})(),d=typeof window<"u"?window.__OPENCHAMBER_RUNTIME_APIS__:null,u=typeof window<"u"?window.__OPENCHAMBER_DESKTOP_SERVER__:null,m=!!(d?.runtime?.isDesktop||typeof window<"u"&&window.opencodeDesktop),f=async S=>{try{return await S.json()}catch{return null}},p=async S=>{try{return await S.text()}catch{return null}},g=async S=>{try{const D=await fetch(S);return D.ok?await f(D):{status:D.status}}catch(D){return{error:D instanceof Error?D.message:String(D)}}};let w=null,h=null,j=null,b=null;const x=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";w=await g(x);const v=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";h=await g(v),j=await g("/api/config/settings");try{const S=await fetch("/api/health"),D=S.headers.get("content-type")||"",M=await p(S);b={status:S.status,ok:S.ok,contentType:D,type:D.includes("application/json")?"json":"html",preview:M?M.slice(0,120):null}}catch(S){b={error:S instanceof Error?S.message:String(S)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await en(t)}catch(S){N={isGitRepo:null,error:S instanceof Error?S.message:String(S)}}const y={runtime:{isDesktop:m,hasRuntimeApis:!!d,desktopServerOrigin:u?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:t,opencodeDirectory:w?.directory||w?.worktree||n,homeDirectory:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},sessions:{total:o.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:a.size,directorySamples:Array.from(a).slice(0,5),directoryCounts:i},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:l,opencode:{pathInfo:w,projectInfo:h,health:b},openchamber:{settingsInfo:j}};return console.log("[DEBUG] App status snapshot:",y),y},checkLastMessage(){const s=this.getLastAssistantMessage();if(!s)return!1;const r=s.isEmpty||s.isEmptyResponse;return r?(console.error("[ALERT] PROBLEMATIC MESSAGE DETECTED!"),console.log("Details:",{messageId:s.messageId,isEmpty:s.isEmpty,isEmptyResponse:s.isEmptyResponse,partsCount:s.partsCount}),s.parts.length>0&&console.log("Parts:",s.parts)):console.log("[OK] Last message looks good!"),r},getStreamingState(){const s=me.getState(),r=s.currentSessionId?s.streamingMessageIds.get(s.currentSessionId)??null:null;return console.log("[STREAM] Streaming State:",{streamingMessageId:r,streamingMessageIds:Array.from(s.streamingMessageIds.entries()),messageStreamStates:Array.from(s.messageStreamStates.entries())}),{streamingMessageId:r,streamingMessageIds:s.streamingMessageIds,streamStates:s.messageStreamStates}},findEmptyMessages(){const s=me.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!i&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
121
+ `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
122
+ `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
123
+ `),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
124
+ `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(s={}){const{includeNonAssistant:r=!1,verbose:t=!0,maxTableRows:n=25}=s,o=me.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const g=p.filter(w=>typeof w=="number");return g.length>0?Math.max(...g):null},f=l.map((p,g)=>{const w=p.info??{},h=Array.isArray(p.parts)?p.parts:[],j=w.time??{},b=u(j.completed),x=b!==null,v=h.filter(E=>E.type==="tool"),N=h.filter(E=>E.type==="reasoning"),y=m(v.map(E=>u(E.state?.time?.end??E.state?.time?.start))),S=m(N.map(E=>u(E.time?.end??E.time?.start))),D=m([y,S].filter(E=>E!==null)),M=v.some(E=>["pending","running","started"].includes(E.state?.status)),C=N.some(E=>typeof E.time?.end!="number");v.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),x||(d.completedMissing+=1);const k=!!(x&&typeof y=="number"&&b<y);k&&(d.completedBeforeTool+=1);const A=!!(x&&typeof S=="number"&&b<S);return A&&(d.completedBeforeReasoning+=1),x&&M&&(d.runningToolsWhenCompleted+=1),x&&C&&(d.reasoningOpenWhenCompleted+=1),{index:g,messageId:w.id,role:w.role,completedAt:b,latestToolTimestamp:y,latestReasoningTimestamp:S,latestPartTimestamp:D,completed_missing:!x,completed_before_tool:k,completed_before_reasoning:A,running_tools_when_completed:!!(x&&M),reasoning_open_when_completed:!!(x&&C),has_tools:v.length>0,has_reasoning:N.length>0}});return t&&(console.table(f.slice(0,n)),f.length>n&&console.log(`Displayed first ${n} rows out of ${f.length}.`),console.log("[SUMMARY] Message completion timing:",d)),{summary:d,rows:f}},checkCompletionStatus(){const s=me.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(j=>j.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(j=>j.type==="step-finish"),i=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&i),p=s.messageStreamStates,g=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,w=p.get(o.info.id),h=o.info.id===g;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",i),console.log("messageIsComplete:",f),console.log("lifecycle phase:",w?.phase),console.log("isStreamingCandidate:",h),console.log("streamingMessageId:",g),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:i,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=uS,qt()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));let Yd=!1;const mS=()=>{if(Yd||typeof window>"u")return;Yd=!0;let s={showReasoningTraces:_e.getState().showReasoningTraces,autoDeleteEnabled:_e.getState().autoDeleteEnabled,autoDeleteAfterDays:_e.getState().autoDeleteAfterDays},r=null,t=null;const n=()=>{const a=r;r=null,t=null,a&&Object.keys(a).length>0&&ns(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};_e.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},l={};i.showReasoningTraces!==s.showReasoningTraces&&(l.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(l.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(l.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(l).length>0&&o(l)})};let Xd=!1;const Qd="openchamber-typography-base",fS=()=>{if(typeof document>"u")return;const r=`:root {
125
+ ${Object.entries(Yi).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
126
+ `)}
127
+ }
128
+ `,t=document.getElementById(Qd);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=Qd,n.textContent=r,document.head.appendChild(n)},pS=()=>{Xd||typeof window>"u"||(Xd=!0,fS())},hS=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await ju();await Su();mS();pS();await hf();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),r.sessionContextUsage.get(t);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const wf=document.getElementById("root");if(!wf)throw new Error("Root element not found");Sh.createRoot(wf).render(e.jsx(Ce.StrictMode,{children:e.jsx(cS,{children:e.jsx(dS,{children:e.jsx(rS,{children:e.jsx(Qj,{apis:hS})})})})}));if(typeof window<"u"){const s=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};s(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&s()})}const yS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ms as D,Gr as S,fs as a,py as b,P as c,kw as d,Nw as e,ad as f,tn as g,Cw as h,Dw as i,yS as m,Wm as p,Mw as r,Do as t};