@openchamber/web 1.5.0 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,156 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-CqCnPJev.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-D8JjsNSh.js","assets/index-B5OwFsqC.js","assets/index-DXflA-iU.css"])))=>i.map(i=>d[i]);
2
- import{t as Vf,c as Gf,F as qf,j as e,R as Kf,T as Qf,P as Yf,C as Xf,A as Jf,a as Zf,b as Vt,d as Jt,p as Es,e as Is,f as ep,_ as as,g as i,r as bu,i as Ht,I as tp,k as sp,l as rp,m as np,n as op,L as ap,o as ip,q as lp,s as cp,u as _t,S as dp,v as up,w as vu,x as mp,y as fp,z as pp,B as hp,D as gp,E as xp,G as Ae,H as Ql,J as te,K as Fi,M as Yl,N as Sa,O as Ft,Q as Rs,U as rs,V as il,W as wu,X as ju,Y as yp,Z as jr,$ as bp,a0 as _s,a1 as Hs,a2 as _r,a3 as zt,a4 as ka,a5 as vp,a6 as en,a7 as an,a8 as tn,a9 as Ri,aa as Fs,ab as Su,ac as wp,ad as jp,ae as Sp,af as kp,ag as Np,ah as Cp,ai as Mp,aj as Lo,ak as Dp,al as ku,am as ta,an as Fr,ao as is,ap as lr,aq as ln,ar as co,as as Xt,at as cr,au as Ap,av as Ep,aw as Nu,ax as ll,ay as sn,az as Cu,aA as dr,aB as Mu,aC as Cn,aD as Ip,aE as Na,aF as Va,aG as Pp,aH as Or,aI as xr,aJ as Ys,aK as Tp,aL as Xs,aM as Fp,aN as Xl,aO as Rp,aP as _p,aQ as Op,aR as $p,aS as Lp,aT as Bp,aU as zp,aV as Wp,aW as Hp,aX as Up,aY as Ga,aZ as Vp,a_ as ur,a$ as cl,b0 as dl,b1 as Gp,b2 as qp,b3 as Kp,b4 as Qp,b5 as Yp,b6 as Xp,b7 as Jp,b8 as Zp,b9 as eh,ba as th,bb as sh,bc as rh,bd as nh,be as oh,bf as ah,bg as ih,bh as yr,bi as sa,bj as mr,bk as nr,bl as lh,bm as ch,bn as Ca,bo as dh,bp as ul,bq as uh,br as mh,bs as fh,bt as Zn,bu as ph,bv as hh,bw as gh,bx as xh,by as yh,bz as eo,bA as Bo,bB as Ma,bC as bh,bD as vh,bE as wn,bF as xn,bG as Du,bH as wh,bI as jh,bJ as Os,bK as Au,bL as Sh,bM as Eu,bN as kh,bO as Nh,bP as _i,bQ as Iu,bR as Pu,bS as Ch,bT as or,bU as to,bV as Mh,bW as Jl,bX as Dh,bY as Oi,bZ as uo,b_ as Fn,b$ as Ah,c0 as Tu,c1 as ml,c2 as fl,c3 as pl,c4 as Eh,c5 as Ih,c6 as Ph,c7 as Zl,c8 as Fu,c9 as Th,ca as Fh,cb as Rh,cc as _h,cd as Ru,ce as so,cf as _u,cg as Ou,ch as qa,ci as Da,cj as $u,ck as Oh,cl as $h,cm as Lh,cn as $i,co as Lu,cp as Li,cq as Bh,cr as zh,cs as Wh,ct as Hh,cu as Uh,cv as Vh,cw as Gh,cx as qh}from"./vendor-.bun-CqCnPJev.js";import{c as Kh,l as Qh,g as Yh,r as Xh,d as Jh,a as Zh,b as eg,e as tg,u as sg,f as rg,h as ng,i as og,j as ag,k as ig,m as lg}from"./index-B5OwFsqC.js";const es=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Wt=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,rn=()=>typeof window>"u"?!1:!es()&&!Wt(),$r=()=>es()?window.opencodeDesktop??null:null,Bu=()=>{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},zu=async()=>{const s=$r();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},cg=async()=>{const s=$r();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},dg=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,Lr=async()=>{const s=Bu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},ug=async s=>{const r=Bu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},mg=async s=>{const r=$r();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)}}},fg=async s=>{const r=$r();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)}}},pg=async s=>{const r=$r();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)}}},hg=async()=>{const s=$r();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},gg=async s=>{const r=$r();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},xg=async()=>{const s=$r();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 _(...s){return Vf(Gf(s))}const Wu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Ds=s=>Wu()&&es()?s.metaKey:s.ctrlKey,Yt=()=>Wu()&&es()?"⌘":"Ctrl",Hu=(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 l=Math.max(0,n-(a.length+2));if(l<=0)return`…/${a}`;let c="";for(const d of o){if(!d)continue;const u=c?`${c}/${d}`:d;if(u.length>l)break;c=u}if(!c){const d=o[0]??"";c=d?d.slice(0,l):""}return c?`${c}…/${a}`:`…/${a}`},ra=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Yr(s,r){if(!s)return"";const t=ra(s);if(t==="/")return"/";const n=r?ra(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 ec(s,r){if(!s)return"/";const t=ra(s);if(!t||t==="/")return"/";const n=r?ra(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Ts(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new qf([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function yg({delayDuration:s=0,...r}){return e.jsx(Zf,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function dt({delayDuration:s=0,...r}){return e.jsx(yg,{delayDuration:s,children:e.jsx(Kf,{"data-slot":"tooltip",...r})})}function ut({...s}){return e.jsx(Qf,{"data-slot":"tooltip-trigger",...s})}function lt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Yf,{children:e.jsxs(Xf,{"data-slot":"tooltip-content",sideOffset:r,className:_("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(Jf,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Ka=null;const tc=()=>{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}}},bg=()=>{if(typeof window>"u"||!window.localStorage)return tc();const s=window.localStorage,r=tc();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}}},ds=()=>(Ka||(Ka=bg()),Ka),hl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},vg={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function sc(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const br={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)"}}},zo={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...br.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...br.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:zo.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...br.tool.inline})},$e=Vt()(Jt(Es((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,diffViewMode:"single",isTimelineDialogOpen:!1,nativeNotificationsEnabled:!1,notificationMode:"hidden-only",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(hl);if(o===1){for(const[l]of a)n.style.removeProperty(sc(l));return}for(const[l,c]of a){const d=parseFloat(c);Number.isFinite(d)&&n.style.setProperty(sc(l),`${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 l=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*l).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*l).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*l).toFixed(3)),n.style.setProperty("--line-height-loose",(2*l).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setDiffViewMode:t=>{s({diffViewMode:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(l=>l.providerID===t&&l.modelID===n)?{favoriteModels:o.favoriteModels.filter(l=>!(l.providerID===t&&l.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(l=>!(l.providerID===t&&l.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})},setNativeNotificationsEnabled:t=>{s({nativeNotificationsEnabled:t})},setNotificationMode:t=>{s({notificationMode:t})}}),{name:"ui-store",storage:Is(()=>ds()),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,diffViewMode:s.diffViewMode,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode})}),{name:"ui-store"}));async function wg(){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 jg(){return es()?"desktop":rn()?"web":null}const rc={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},Aa=Vt()((s,r)=>({...rc,checkForUpdates:async()=>{const t=jg();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await hg():t==="web"&&(n=await wg()),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 gg(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 xg()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(rc)}})),Sg="/api",kg=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,Ng=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(kg.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}},Cg=()=>{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},xo=s=>s.replace(/\\/g,"/"),Qa=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class Mg{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=Sg){const n=Cg()||r;this.baseUrl=Ng(n),this.client=ep({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],c=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return c.length>=2?{homeDirectory:`${a}/${c[0]}/${c[1]}`,username:c[1]}:c.length===1?{homeDirectory:`${a}/${c[0]}`,username:c[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 compressImage(r,t,n=.8,o=2048){return typeof document>"u"?r:new Promise(a=>{const l=new Image;l.onload=()=>{let c=l.width,d=l.height;(c>o||d>o)&&(c>d?(d=Math.round(d*(o/c)),c=o):(c=Math.round(c*(o/d)),d=o));const u=document.createElement("canvas");u.width=c,u.height=d;const m=u.getContext("2d");if(!m){a(r);return}m.drawImage(l,0,0,c,d);let f=t;t==="image/png"&&r.length>2.5*1024*1024&&(f="image/jpeg");try{a(u.toDataURL(f,n))}catch{a(r)}},l.onerror=()=>a(r),l.src=r})}async convertHeicToJpeg(r){try{const t=(await as(async()=>{const{default:f}=await import("./vendor-.bun-CqCnPJev.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),l=new Uint8Array(a.length);for(let f=0;f<a.length;f++)l[f]=a.charCodeAt(f);const c=new Blob([l],{type:r.mime}),d=await t({blob:c,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(r.mime.startsWith("image/")&&(r.mime==="image/jpeg"||r.mime==="image/png"||r.mime==="image/webp")&&r.url.length>1.33*1024*1024){const n=await this.compressImage(r.url,r.mime),o=n.startsWith("data:image/jpeg")?"image/jpeg":r.mime;return{...r,mime:o,url:n}}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 l=await this.normalizeFilePart(a),c={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(c)}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 l of a.files){const c=await this.normalizeFilePart(l),d={type:"file",mime:c.mime,filename:c.filename,url:c.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 l=await a.json().catch(()=>null);return!l||typeof l!="object"?{}:l}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 replyToQuestion(r,t){const n=!Array.isArray(t)||t.length===0?[]:Array.isArray(t[0])?t:[t];return(await this.client.question.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},answers:n})).data||!1}async rejectQuestion(r){return(await this.client.question.reject({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async listPendingQuestions(r){const t=[],n=async d=>{try{const u=typeof d=="string"?d.trim():"";return(await this.client.question.list(u?{directory:u}:void 0)).data||[]}catch{return[]}};t.push(n(null));const o=new Set;for(const d of r?.directories??[]){const u=this.normalizeCandidatePath(d??null);u&&o.add(u)}for(const d of o)t.push(n(d));const a=await Promise.all(t),l=[],c=new Set;for(const d of a)for(const u of d){if(!u||typeof u!="object")continue;const m=u.id;typeof m!="string"||m.length===0||c.has(m)||(c.add(m),l.push(u))}return l}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 l of t)if(l.startsWith("data:"))n.push(l.slice(5).replace(/^\s/,""));else if(l.startsWith("id:")){const c=l.slice(3).trim();c&&(o=c)}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 l=a;if(typeof l.type=="string")return{directory:o&&o.length>0?o:"global",payload:l}}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 l=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!l.ok||!l.body)throw new Error(`Global SSE connect failed with status ${l.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const c=l.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await c.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 y of g){const h=this.parseSseBlock(y);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),l=c=>{a&&c.directory!==a||r(c)};return this.globalSseListeners.add(l),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(c){console.warn("[OpencodeClient] Global SSE open handler error:",c)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(l),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const l=a?.key??"default",c=a?.scope??"directory",d=this.sseAbortControllers.get(l);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(l,u);let m;if(c==="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}}},y=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)};return u.signal.addEventListener("abort",y,{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),()=>{y(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const g=p;if(typeof g.type=="string")return g;const y=g.payload;if(y&&typeof y=="object"){const h=y;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 y=>{try{const h=p?{directory:p}:void 0,j={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:v=>{v instanceof Error&&v.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",v),t&&!u.signal.aborted&&t(v))},onSseEvent:v=>{if(u.signal.aborted)return;v.id&&typeof v.id=="string"&&(m=v.id);const w=v.data,N=f(w);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 v 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,y),3e4);await new Promise(b=>setTimeout(b,j)),u.signal.aborted||await g(y+1);return}if(!u.signal.aborted){const h=Math.min(3e3*Math.pow(2,y),3e4);await new Promise(j=>setTimeout(j,h)),await g(y+1)}};try{await g(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l)}})(),()=>{this.sseAbortControllers.get(l)===u&&this.sseAbortControllers.delete(l),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=Qa();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const l=a instanceof Error?a.message:String(a);throw new Error(l||"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,t){const n=Qa();if(n)try{const o=await n.listDirectory(r||"");return!o||!Array.isArray(o.entries)?[]:o.entries.map(a=>({name:a.name,path:xo(a.path),isDirectory:!!a.isDirectory,isFile:!a.isDirectory,isSymbolicLink:!1}))}catch(o){throw console.error("Failed to list directory contents:",o),o}try{const o=new URLSearchParams;r&&r.trim().length>0&&o.set("path",r),t?.respectGitignore&&o.set("respectGitignore","true");const a=o.toString(),l=await fetch(`${this.baseUrl}/fs/list${a?`?${a}`:""}`);if(!l.ok){const d=await l.json().catch(()=>({})),u=typeof d.error=="string"?d.error:"Failed to list directory";throw new Error(u)}const c=await l.json();return!c||!Array.isArray(c.entries)?[]:c.entries}catch(o){throw console.error("Failed to list directory contents:",o),o}}async searchFiles(r,t){const n=Qa(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?xo(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=xo(f.path),g=p.split("/").filter(Boolean).pop()||p,y=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?xo(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||g;return{name:g,path:p,relativePath:y,extension:g.includes(".")?g.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const l=new URLSearchParams;o&&o.length>0&&l.set("directory",o),typeof r=="string"&&l.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&l.set("limit",String(t.limit));const c=`${this.baseUrl}/fs/search${l.toString()?`?${l.toString()}`:""}`,d=await fetch(c,{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 zu();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??{},l=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(l)}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 Ee=new Mg,Dg=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:Ee},Symbol.toStringTag,{value:"Module"})),Bi=new Set;function Ea(s){return Bi.add(s),()=>{Bi.delete(s)}}function ar(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 l=a(o);l instanceof Promise&&l.catch(c=>{console.error("[ConfigSync] Async listener failed:",c)})}catch(l){console.error("[ConfigSync] Listener threw:",l)}}function ro(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const gl="Updating OpenCode configuration...";let ir=0,Rr=gl;const zi=new Set;function na(){const s={isUpdating:ir>0,message:Rr};zi.forEach(r=>r(s))}function Ks(s){ir+=1,ir===1?(Rr=s||gl,na()):s&&(Rr=s,na())}function As(){ir!==0&&(ir-=1,ir===0&&(Rr=gl,na()))}function vr(s){Rr===s&&ir>0||(Rr=s,ir>0&&na())}function Ag(s){return zi.add(s),s({isUpdating:ir>0,message:Rr}),()=>{zi.delete(s)}}function Eg(){return{isUpdating:ir>0,message:Rr}}const rr=Vt()(Jt(Es((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(l=>{const c=l.queuedMessages[t]??[];return{queuedMessages:{...l.queuedMessages,[t]:[...c,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const l=(o.queuedMessages[t]??[]).filter(c=>c.id!==n);if(l.length===0){const{[t]:c,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:l}}})},popToInput:(t,n)=>{const l=(r().queuedMessages[t]??[]).find(c=>c.id===n);return l?(s(c=>{const u=(c.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=c.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...c.queuedMessages,[t]:u}}}),l):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),ss({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Is(()=>ds()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),nc=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},Ig=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},Pg=s=>{const r=$e.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},Tg=async()=>{if(typeof window>"u")return null;if(es()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return nc(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=Ig(r);return nc(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Uu=null;const oc=s=>{Uu=s},Qs=()=>Uu,Wo=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"),s.commitMessageModel?localStorage.setItem("commitMessageModel",s.commitMessageModel):localStorage.removeItem("commitMessageModel"))},Fg=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():"",l=typeof o.label=="string"?o.label.trim():"",c=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!l||!c||t.has(a)||(t.add(a),r.push({id:a,label:l,source:c,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},Rg=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,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=c==="/"?c:c.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(l)||n.has(d))continue;t.add(l),n.add(d);const u={id:l,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},Vu=()=>{const s=$e.persist;if(s&&typeof s=="object")return s},Gu=()=>Qs()?.settings??null,Ho=s=>{const r=$e.getState(),t=rr.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)},ac=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=Rg(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.commitMessageModel=="string"&&r.commitMessageModel.length>0&&(t.commitMessageModel=r.commitMessageModel),typeof r.queueModeEnabled=="boolean"&&(t.queueModeEnabled=r.queueModeEnabled);const o=Fg(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},_g=async()=>{const s=Gu();if(s)try{const r=await s.load();return ac(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 ac(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},qu=async()=>{if(typeof window>"u")return;const s=Vu(),r=t=>{Wo(t);const n=()=>Ho(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=es()?await Lr():await _g();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},ss=async s=>{if(typeof window>"u")return;if(es()){try{const t=await ug(s);t&&(Wo(t),Ho(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=Gu();if(r)try{const t=await r.save(s);t&&(Wo(t),Ho(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&&(Wo(n),Ho(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Ku=async()=>{if(typeof window>"u")return;const s=Vu();try{const r=await Tg();if(!r)return;const t=()=>Pg(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)}},Og=3e4,$g=40,Lg=60,Bg=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},Ia=Vt()(Jt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Lg){if(!t||t.trim().length===0)return[];const a=t.trim(),l=typeof n=="string"?n.trim():"",c=Bg(a,l,o),d=Date.now(),u=r().cache[c];if(u&&d-u.timestamp<Og)return u.files;const m=r().inFlight[c];if(m)return m;const f=Ee.searchFiles(l,{directory:a,limit:o}).then(p=>(s(g=>{const y={...g.cache,[c]:{files:p,timestamp:Date.now()}},h=g.cacheKeys.filter(j=>j!==c);for(h.push(c);h.length>$g;){const j=h.shift();j&&delete y[j]}return{cache:y,cacheKeys:h}}),p)).finally(()=>{s(p=>{const g={...p.inFlight};return delete g[c],{inFlight:g}})});return s(p=>({inFlight:{...p.inFlight,[c]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const l={...a.cache},c=a.cacheKeys.filter(m=>m.startsWith(o)?(delete l[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:l,cacheKeys:c,inFlight:u}})}}),{name:"file-search-store"})),Zt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var zg={};let Vs=null;const Us=ds(),ic=Us.getItem("lastDirectory"),Wg=typeof ic=="string"&&ic.length>0,yo=s=>{try{Ia.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Hg=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Ug=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},Uo=(s,r)=>{const t=Ug(s,r);return Hg(t)},oa=()=>{if(typeof window<"u"){const r=Us.getItem("homeDirectory")||Vs||null,t=Us.getItem("lastDirectory");if(t)return Uo(t,r);if(Vs)return Vs;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 Vs=n,Us.setItem("homeDirectory",n),n;if(r)return Vs=r,r}const s=typeof process<"u"&&zg?.HOME;return s||process?.cwd?.()||"/"},Vg=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},Gg=s=>(Vs=s,typeof window<"u"&&Us.setItem("homeDirectory",s),ss({homeDirectory:s}),s),Qu=async()=>{const s=n=>{const o=Vg(n);return o?Gg(o):null};try{const n=await Ee.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await Ee.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 zu(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=oa(),t=s(r);return t||r},Xr=oa();Xr&&Ee.setDirectory(Xr);const qg=!!(Xr&&Xr!=="/"),vt=Vt()(Jt((s,r)=>({currentDirectory:Xr,directoryHistory:[Xr],historyIndex:0,homeDirectory:Xr,hasPersistedDirectory:Wg,isHomeReady:qg,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Vs||r().homeDirectory||Us.getItem("homeDirectory"),a=Uo(t,o);Zt()&&console.log("[DirectoryStore] setDirectory called with path:",a),Ee.setDirectory(a),yo(),s(l=>{const c=[...l.directoryHistory.slice(0,l.historyIndex+1),a];return Us.setItem("lastDirectory",a),ss({lastDirectory:a}),{currentDirectory:a,directoryHistory:c,historyIndex:c.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];Ee.setDirectory(o),yo(),Us.setItem("lastDirectory",o),ss({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];Ee.setDirectory(o),yo(),Us.setItem("lastDirectory",o),ss({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Vs||r().homeDirectory||oa();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,l=a.lastIndexOf("/");if(l===-1){const c=Vs||oa();n(c)}else n(l===0?"/":a.substring(0,l))},goHome:async()=>{const t=Vs||r().homeDirectory||await Qu();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Vs=o;const a=n.homeDirectory!==o,l=Us.getItem("lastDirectory"),c=typeof l=="string"&&l.length>0,d=!c&&(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?Uo(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(h=>Uo(h,o)),p=f.some((h,j)=>h!==n.directoryHistory[j]),g=!!(m&&m!==n.currentDirectory),y={homeDirectory:o,hasPersistedDirectory:c,isHomeReady:u};if(d?(y.currentDirectory=o,y.directoryHistory=[o],y.historyIndex=0,y.isSwitchingDirectory=!1):(g||p)&&(y.currentDirectory=m,y.directoryHistory=f,y.historyIndex=Math.min(n.historyIndex,f.length-1),y.isSwitchingDirectory=!1),s(()=>y),(d||g)&&u){const h=d?o:m;Ee.setDirectory(h),yo(),Us.setItem("lastDirectory",h),ss({lastDirectory:h})}ss({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Qu().then(s=>{vt.getState().synchronizeHomeDirectory(s)});const jn=ds(),Yu="projects",Wi="activeProjectId",Kg=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},Pa=s=>{const r=s.trim();if(!r)return"";const t=jn.getItem("homeDirectory")||vt.getState().homeDirectory||"",o=Kg(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},Xu=s=>{const r=Pa(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},Qg=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Ju=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,l=typeof a.id=="string"?a.id.trim():"",c=typeof a.path=="string"?a.path.trim():"";if(!l||!c)continue;const d=Pa(c);if(!d||t.has(l)||n.has(d))continue;t.add(l),n.add(d);const u={id:l,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},Yg=()=>{try{const s=jn.getItem(Yu);return s?Ju(JSON.parse(s)):[]}catch{return[]}},Xg=()=>{try{const s=jn.getItem(Wi);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},xl=(s,r)=>{try{jn.setItem(Yu,JSON.stringify(s))}catch{}try{r?jn.setItem(Wi,r):jn.removeItem(Wi)}catch{}},un=(s,r)=>{xl(s,r),ss({projects:s,activeProjectId:r??void 0})},Jg=Yg(),Zg=()=>{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=Pa(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:Xu(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return Zt()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Ws=Zg(),yl=Ws?.projects??Jg,Zu=Ws?.activeProjectId??Xg()??yl[0]?.id??null;Ws&&xl(yl,Zu);const Ot=Vt()(Jt((s,r)=>({projects:yl,activeProjectId:Zu,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=Pa(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Ws)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const l=a.normalizedPath,c=r().projects.find(y=>y.path===l);if(c)return r().setActiveProject(c.id),c;const d=Date.now(),u=n?.label?.trim()||Xu(l),m=n?.id?.trim(),p={id:m&&!r().projects.some(y=>y.id===m)?m:Qg(),path:l,label:u,addedAt:d,lastOpenedAt:d},g=[...r().projects,p];return s({projects:g}),Zt()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Ws)return;const n=r(),o=n.projects.filter(l=>l.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),un(o,a),a){const l=o.find(c=>c.id===a);l&&(Ee.setDirectory(l.path),vt.getState().setDirectory(l.path,{showOverlay:!1}))}else vt.getState().goHome()},setActiveProject:t=>{if(Ws)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const l=Date.now(),c=n.map(d=>d.id===t?{...d,lastOpenedAt:l}:d);s({projects:c,activeProjectId:t}),un(c,t),Ee.setDirectory(a.path),vt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Ws)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const l=Date.now(),c=n.map(d=>d.id===t?{...d,lastOpenedAt:l}:d);s({projects:c,activeProjectId:t}),un(c,t)},renameProject:(t,n)=>{if(Ws)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:l}=r(),c=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:c}),un(c,l)},reorderProjects:(t,n)=>{if(Ws)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const l=[...o],[c]=l.splice(t,1);l.splice(n,0,c),s({projects:l}),un(l,a)},synchronizeFromSettings:t=>{if(Ws)return;const n=Ju(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),l=JSON.stringify(a.projects)!==JSON.stringify(n),c=a.activeProjectId!==o;if(!(!l&&!c)&&(s({projects:n,activeProjectId:o}),xl(n,o),o)){const d=n.find(u=>u.id===o);d&&(Ee.setDirectory(d.path),vt.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(Ws)return;const{projects:o,activeProjectId:a}=r(),l=o.find(u=>u.id===t);if(!l)return;const c={...l.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?c.branchPrefix=n.branchPrefix.trim():delete c.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?c.baseBranch=n.baseBranch.trim():delete c.baseBranch),n.autoCreateWorktree!==void 0&&(c.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(c).length>0?c:void 0}:u);s({projects:d}),un(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&Ot.getState().synchronizeFromSettings(r)});const ex=new Set(["init","review"]),yn=s=>ex.has(s.name),Vn="useCommandsStore",Hi=s=>new Promise(r=>setTimeout(r,s)),bo=()=>{try{const r=Ot.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=Ee.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},tx=2e4,lc=300,cc=4,sx=800,rx=200,nx=2e3,Br=Vt()(Jt(Es((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=bo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await Ee.withDirectory(a,()=>Ee.listCommandsWithDetails()),d=await Promise.all(c.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${l}`,{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 l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{Ks("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=bo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.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 Ya({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&ar("commands",{source:Vn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||As()}},updateCommand:async(t,n)=>{Ks("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 l=bo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},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 Ya({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&ar("commands",{source:Vn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||As()}},deleteCommand:async t=>{Ks("Deleting command configuration…");let n=!1;try{const o=bo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),c?.requiresReload??!0)return n=!0,await Ya({message:c?.message,delayMs:c?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&ar("commands",{source:Vn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||As()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Is(()=>ds()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Br);async function ox(s){const r=typeof s=="number"&&s>0?Math.min(s,lc):0;r>0&&await Hi(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<tx;){n+=1,vr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ee.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,l=n<=cc&&a<1200?lc:Math.min(sx+Math.max(0,n-cc)*rx,nx);await Hi(l)}throw o||new Error("OpenCode did not become ready in time")}async function Ya(s={}){const{message:r,delayMs:t}=s;try{vr(r||"Refreshing commands…")}catch{}try{await ox(t),vr("Refreshing commands…"),await Br.getState().loadCommands(),ar("commands",{source:Vn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),vr("OpenCode refresh failed. Please retry refreshing configuration manually."),await Hi(1500)}finally{As()}}let dc=null;dc||(dc=Ea(s=>{if(s.source!==Vn&&ro(s,"commands")){const{loadCommands:r}=Br.getState();r()}}));const Cr=()=>{const s=Ee.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},Vo="useSkillsStore",Gs=Vt()(Jt(Es((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=Cr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills${l}`);if(!c.ok)throw new Error(`Failed to list skills: ${c.status}`);const m=((await c.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 l=200*(o+1);await new Promise(c=>setTimeout(c,l))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=Cr(),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=>{Ks("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=Cr(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),c=await l.json().catch(()=>null);if(!l.ok){const u=c?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&ar("skills",{source:Vo}),d}catch{return!1}finally{As()}},updateSkill:async(t,n)=>{Ks("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=Cr(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/skills/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&ar("skills",{source:Vo}),u}catch{return!1}finally{As()}},deleteSkill:async t=>{Ks("Deleting skill...");try{const n=Cr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),l=await a.json().catch(()=>null);if(!a.ok){const d=l?.error||"Failed to delete skill";throw new Error(d)}const c=await r().loadSkills();return c&&ar("skills",{source:Vo}),r().selectedSkillName===t&&s({selectedSkillName:null}),c}catch{return!1}finally{As()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=Cr(),a=o?`&directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return l.ok?(await l.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=Cr(),l=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${l}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=Cr(),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:Is(()=>ds()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Gs);let uc=null;uc||(uc=Ea(s=>{if(s.source!==Vo&&ro(s,"skills")){const{loadSkills:r}=Gs.getState();r()}}));const Xa=()=>{const s=Ee.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},mo=Vt()(Jt((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 l=Xa(),c=t?.refresh?"&refresh=true":"",d=l?`?directory=${encodeURIComponent(l)}${c}`:c?"?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,y=g&&f.some(h=>h.id===g)?g:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:y}),!0}catch(l){o={kind:"unknown",message:l instanceof Error?l.message:String(l)};const c=200*(a+1);await new Promise(d=>setTimeout(d,c))}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=Xa(),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)}),l=await a.json().catch(()=>null);if(!a.ok||!l){const c=l?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:c}),{ok:!1,error:c}}return l.ok?(s({scanResults:l.items||[]}),l):(s({lastScanError:l.error||{kind:"unknown",message:"Failed to scan repository"}}),l)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=Xa(),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)}),l=await a.json().catch(()=>null);if(!l){const c={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}if(!a.ok||!l.ok){const c=l.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:c}),{ok:!1,error:c}}return Gs.getState().loadSkills(),l}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"})),ax=()=>{const s=Ee.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},vo=()=>{try{const r=Ot.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=Ee.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},Qr=s=>{const r=s;return r.native===!0||r.builtIn===!0},em=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},tm=s=>s.filter(r=>!em(r)),Go="useAgentsStore",aa=s=>new Promise(r=>setTimeout(r,s)),ix=2e4,mc=300,fc=4,lx=800,cx=200,dx=2e3,zr=Vt()(Jt(Es((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=vo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await Ee.withDirectory(o,()=>Ee.listAgents()),c=await Promise.all(l.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(c)?s({agents:c,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{Ks("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=vo(),l=a?`?directory=${encodeURIComponent(a)}`:"",c=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${l}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await c.json().catch(()=>null);if(!c.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Gn({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&ar("agents",{source:Go}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||As()}},updateAgent:async(t,n)=>{Ks("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 l=vo(),c=l?`?directory=${encodeURIComponent(l)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${c}`,{method:"PATCH",headers:{"Content-Type":"application/json",...l?{"x-opencode-directory":l}:{}},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 Gn({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&ar("agents",{source:Go}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||As()}},deleteAgent:async t=>{Ks("Deleting agent configuration…");let n=!1;try{const o=vo(),a=o?`?directory=${encodeURIComponent(o)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),c=await l.json().catch(()=>null);if(!l.ok){const m=c?.error||"Failed to delete agent";throw new Error(m)}if(c?.requiresReload??!0)return n=!0,await Gn({message:c?.message,delayMs:c?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&ar("agents",{source:Go}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||As()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return tm(t)}}),{name:"agents-store",storage:Is(()=>ds()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=zr);async function ux(s){const r=typeof s=="number"&&s>0?Math.min(s,mc):0;r>0&&await aa(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<ix;){n+=1,vr(`Waiting for OpenCode… (attempt ${n})`);try{if(await Ee.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(c){o=c}const a=Date.now()-t,l=n<=fc&&a<1200?mc:Math.min(lx+Math.max(0,n-fc)*cx,dx);await aa(l)}throw o||new Error("OpenCode did not become ready in time")}const mx=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function fx(s={}){const{message:r,delayMs:t}=s,n=mx(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{vr(r||"Refreshing configuration…")}catch{}try{await ux(t);const a=at.getState(),l=zr.getState(),c=Br.getState(),d=Gs.getState(),u=mo.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"),y=n.includes("all")||n.includes("skills"),h=ax(),j=o==="projects"?Ot.getState().projects:[],b=Array.from(new Set([...h?[h]:[],...j.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&at.setState({directoryScoped:{}});const v=[];for(const N of b)m&&v.push(a.loadProviders({directory:N}).then(()=>{})),f&&v.push(a.loadAgents({directory:N}).then(()=>{}));const w=[];p&&w.push(l.loadAgents().then(()=>{})),g&&w.push(c.loadCommands().then(()=>{})),y&&(w.push(d.loadSkills().then(()=>{})),w.push(u.loadCatalog().then(()=>{}))),vr("Refreshing configuration…"),await Promise.all([...v,...w])}catch{vr("OpenCode refresh failed. Please retry."),await aa(1500)}finally{As()}}async function Gn(s){await fx(s)}async function qn(s){Ks(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 Gn({...n,message:t.message,delayMs:t.reloadDelayMs}):await Gn(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),vr("Failed to reload configuration. Please try again."),await aa(2e3),As(),r}}let pc=null;pc||(pc=Ea(s=>{if(s.source!==Go&&ro(s,"agents")){const{loadAgents:r}=zr.getState();r()}}));const px="https://models.dev/api.json",hx="/api/openchamber/models-metadata",hc="opencode",gc="big-pickle",gx=async()=>{try{if(es()){const c=await Lr();return{defaultModel:c?.defaultModel,defaultVariant:c?.defaultVariant,defaultAgent:c?.defaultAgent,autoCreateWorktree:c?.autoCreateWorktree,commitMessageModel:c?.commitMessageModel}}const s=Qs()?.settings;if(s)try{const d=(await s.load())?.settings;if(d){const u=typeof d?.defaultModel=="string"?d.defaultModel.trim():"",m=typeof d?.defaultVariant=="string"?d.defaultVariant.trim():"",f=typeof d?.defaultAgent=="string"?d.defaultAgent.trim():"",p=typeof d?.commitMessageModel=="string"?d.commitMessageModel.trim():"";return{defaultModel:u.length>0?u:void 0,defaultVariant:m.length>0?m:void 0,defaultAgent:f.length>0?f:void 0,autoCreateWorktree:typeof d?.autoCreateWorktree=="boolean"?d.autoCreateWorktree:void 0,commitMessageModel:p.length>0?p: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():"",l=typeof t?.commitMessageModel=="string"?t.commitMessageModel.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,commitMessageModel:l.length>0?l:void 0}}catch{return{}}},wo=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]}},xx=s=>s?.toLowerCase?.()??"",yx=s=>s==="primary"||s==="all"||s===void 0||s===null,no=s=>typeof s=="object"&&s!==null,ia=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),bx=s=>{if(!no(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!ia(t)||n&&!ia(n))return!1}return!0},vx=s=>{if(!no(s))return!1;const r=s;return r.models===void 0||no(r.models)},sm=(s,r)=>{const t=xx(s);return!t||!r?"":`${t}/${r}`},wx=s=>{const r=new Map;if(!no(s))return r;for(const[t,n]of Object.entries(s)){if(!vx(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!no(a)))for(const[l,c]of Object.entries(a)){if(!bx(c))continue;const d=typeof l=="string"&&l.length>0?l:c.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof c.id=="string"&&c.id.length>0?c.id:d,providerId:o,name:typeof c.name=="string"?c.name:void 0,tool_call:typeof c.tool_call=="boolean"?c.tool_call:void 0,reasoning:typeof c.reasoning=="boolean"?c.reasoning:void 0,temperature:typeof c.temperature=="boolean"?c.temperature:void 0,attachment:typeof c.attachment=="boolean"?c.attachment:void 0,modalities:c.modalities?{input:ia(c.modalities.input)?c.modalities.input:void 0,output:ia(c.modalities.output)?c.modalities.output:void 0}:void 0,cost:c.cost,limit:c.limit,knowledge:typeof c.knowledge=="string"?c.knowledge:void 0,release_date:typeof c.release_date=="string"?c.release_date:void 0,last_updated:typeof c.last_updated=="string"?c.last_updated:void 0},m=sm(o,d);m&&r.set(m,u)}}return r},jx=async()=>{if(typeof fetch!="function")return new Map;const s=[hx,px];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 l=await fetch(r,a);if(!l.ok)throw new Error(`Metadata request to ${r} returned status ${l.status}`);const c=await l.json();return wx(c)}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 Ja=null;const Sx=(s,r)=>{s().size>0||Ja||(Ja=jx().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{Ja=null}))},kx=s=>new Promise(r=>setTimeout(r,s)),bl="__global__",Sn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:bl},mn=s=>s===bl?null:s,Nx=()=>{if(typeof window>"u")return bl;const s=Ee.getDirectory()??vt.getState().currentDirectory;return Sn(s)},at=Vt()(Jt(Es((s,r)=>({activeDirectoryKey:Nx(),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,settingsCommitMessageModel:void 0,activateDirectory:async t=>{const n=Sn(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:mn(n)}),await r().loadAgents({directory:mn(n)}))},loadProviders:async t=>{const n=Sn(t?.directory??mn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),l=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let c=null;for(let d=0;d<3;d++)try{Sx(()=>r().modelsMetadata,g=>s({modelsMetadata:g}));const u=await Ee.withDirectory(mn(n),()=>Ee.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(g=>{const y=g.models??{},h=Object.keys(y).map(j=>y[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}};if(g.activeDirectoryKey===n&&(j.providers=p,j.defaultProviders=f,!g.currentProviderId&&!g.currentModelId&&g.settingsDefaultModel)){const b=wo(g.settingsDefaultModel);if(b){const v=p.find(w=>w.id===b.providerId);if(v?.models.some(w=>w.id===b.modelId)){const w=v.models.find(x=>x.id===b.modelId),N=g.settingsDefaultVariant&&w?.variants?.[g.settingsDefaultVariant]?g.settingsDefaultVariant:void 0;j.currentProviderId=b.providerId,j.currentModelId=b.modelId,j.currentVariant=N,j.selectedProviderId=b.providerId,h.currentProviderId=b.providerId,h.currentModelId=b.modelId,h.currentVariant=N,h.selectedProviderId=b.providerId}}}return j});return}catch(u){c=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",c),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:l},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=l,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=wo(d.settingsDefaultModel);if(p){const g=a.find(y=>y.id===p.providerId);if(g?.models.some(y=>y.id===p.modelId)){const y=g.models.find(j=>j.id===p.modelId),h=d.settingsDefaultVariant&&y?.variants?.[d.settingsDefaultVariant]?d.settingsDefaultVariant:void 0;f.currentProviderId=p.providerId,f.currentModelId=p.modelId,f.currentVariant=h,f.selectedProviderId=p.providerId,m.currentProviderId=p.providerId,m.currentModelId=p.modelId,m.currentVariant=h,m.selectedProviderId=p.providerId}}}return f})},setProvider:t=>{const{providers:n}=r(),o=n.find(c=>c.id===t);if(!o)return;const l=o.models[0]?.id||"";s(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentVariant:c.currentVariant,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentProviderId:t,currentModelId:l,selectedProviderId:t};return{currentProviderId:t,currentModelId:l,selectedProviderId:t,directoryScoped:{...c.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,l={...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]:l}}})},setCurrentVariant:t=>{s(n=>{if(n.currentVariant===t)return n;const o=n.activeDirectoryKey,l={...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]:l}}})},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,l={...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]:l}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const l=a.activeDirectoryKey,c={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[l]??{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:c};return{agentModelSelections:c,directoryScoped:{...a.directoryScoped,[l]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=Sn(t?.directory??mn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let l=null;for(let c=0;c<3;c++)try{const[d,u]=await Promise.all([Ee.withDirectory(mn(n),()=>Ee.listAgents()),gx()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(x=>{const A={...x.directoryScoped[n]??{providers:f,agents:a,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:m},C={settingsDefaultModel:u.defaultModel,settingsDefaultVariant:u.defaultVariant,settingsDefaultAgent:u.defaultAgent,settingsAutoCreateWorktree:u.autoCreateWorktree??!1,settingsCommitMessageModel:u.commitMessageModel,directoryScoped:{...x.directoryScoped,[n]:A}};return x.activeDirectoryKey===n&&(C.agents=m),C}),m.length===0)return s(x=>{const A={...x.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},C={directoryScoped:{...x.directoryScoped,[n]:A}};return x.activeDirectoryKey===n&&(C.currentAgentName=void 0),C}),!0;const p=(x,k)=>{const A=f.find(C=>C.id===x);return A?A.models.some(C=>C.id===k):!1},g=m.filter(x=>yx(x.mode));let j=g.find(x=>x.name==="build")||g[0]||m[0];const b={};if(u.defaultAgent){const x=m.find(k=>k.name===u.defaultAgent);x?j=x:b.defaultAgent=""}let v,w,N;if(u.defaultModel){const x=wo(u.defaultModel);if(x&&p(x.providerId,x.modelId)){if(v=x.providerId,w=x.modelId,u.defaultVariant){const C=f.find(M=>M.id===x.providerId)?.models.find(M=>M.id===x.modelId)?.variants;C&&Object.prototype.hasOwnProperty.call(C,u.defaultVariant)?N=u.defaultVariant:b.defaultVariant=""}}else b.defaultModel=""}if(!v&&j?.model?.providerID&&j?.model?.modelID&&p(j.model.providerID,j.model.modelID)&&(v=j.model.providerID,w=j.model.modelID),!v)if(p(hc,gc))v=hc,w=gc;else{const x=f[0];x&&x.models[0]&&(v=x.id,w=x.models[0].id)}return s(x=>{const k=x.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},A={...k,providers:f,agents:m,currentAgentName:j.name,currentProviderId:v??k.currentProviderId,currentModelId:w??k.currentModelId,currentVariant:N},C={directoryScoped:{...x.directoryScoped,[n]:A}};return x.activeDirectoryKey===n&&(C.currentAgentName=j.name,v&&w&&(C.currentProviderId=v,C.currentModelId=w,C.currentVariant=N)),C}),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}),ss(b).catch(()=>{})),!0}catch(d){l=d;const u=200*(c+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",l),s(c=>{const d=c.activeDirectoryKey===n?c.providers:c.directoryScoped[n]?.providers??[],m={...c.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...c.directoryScoped,[n]:m}};return c.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:l}=r();if(s(c=>{const d=c.activeDirectoryKey,m={...c.directoryScoped[d]??{providers:c.providers,agents:c.agents,currentProviderId:c.currentProviderId,currentModelId:c.currentModelId,currentAgentName:c.currentAgentName,selectedProviderId:c.selectedProviderId,agentModelSelections:c.agentModelSelections,defaultProviders:c.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...c.directoryScoped,[d]:m}}}),t&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const d=c.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&c.setState(g=>{const y=new Map(g.currentAgentContext);return y.set(u,t),{currentAgentContext:y}}),u&&m(u)&&(p(u,t)||f(u,n))}}if(t&&typeof window<"u"){const c=window.__zustand_session_store__;if(c){const{currentSessionId:u,getAgentModelForSession:m}=c.getState();if(u&&m(u,t))return}if(a){const u=wo(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 y;if(l){const v=o.find(w=>w.id===u.providerId)?.models.find(w=>w.id===u.modelId)?.variants;v&&Object.prototype.hasOwnProperty.call(v,l)&&(y=l)}const h={...g,currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:y};return{currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:y,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,y={...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]:y}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultVariant:t=>{s({settingsDefaultVariant:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},setSettingsCommitMessageModel:t=>{s({settingsCommitMessageModel:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await Ee.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const l=400*n;await kx(l)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=Zt();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 Ee.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=sm(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return tm(t)}}),{name:"config-store",storage:Is(()=>ds()),partialize:s=>({activeDirectoryKey:s.activeDirectoryKey,directoryScoped:s.directoryScoped,currentProviderId:s.currentProviderId,currentModelId:s.currentModelId,currentVariant:s.currentVariant,currentAgentName:s.currentAgentName,selectedProviderId:s.selectedProviderId,agentModelSelections:s.agentModelSelections,defaultProviders:s.defaultProviders,settingsDefaultModel:s.settingsDefaultModel,settingsDefaultVariant:s.settingsDefaultVariant,settingsDefaultAgent:s.settingsDefaultAgent,settingsAutoCreateWorktree:s.settingsAutoCreateWorktree})})));typeof window<"u"&&(window.__zustand_config_store__=at);let xc=null;xc||(xc=Ea(async s=>{const r=[];if(ro(s,"agents")){const{loadAgents:t}=at.getState();r.push(t().then(()=>{}))}if(ro(s,"providers")){const{loadProviders:t}=at.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let yc=null;typeof window<"u"&&!yc&&(yc=vt.subscribe((s,r)=>{const t=Sn(s.currentDirectory),n=Sn(r.currentDirectory);t!==n&&at.getState().activateDirectory(s.currentDirectory)}));const us={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},Cx=180,xs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function cn(s){const r=xs();return r?r.checkIsGitRepository(s):Kh(s)}async function Mx(s){const r=xs();return r?r.getGitStatus(s):Yh(s)}async function vl(s){const r=xs();return r?r.getGitBranches(s):lg(s)}async function Dx(s,r){const t=xs();return t?t.deleteGitBranch(s,r):Jh(s,r)}async function Ax(s,r){const t=xs();return t?t.deleteRemoteBranch(s,r):Zh(s,r)}async function Ex(s){const r=xs();return r?r.listGitWorktrees(s):Qh(s)}async function Ix(s,r){const t=xs();return t?t.addGitWorktree(s,r):eg(s,r)}async function rm(s,r){const t=xs();return t?t.removeGitWorktree(s,r):Xh(s,r)}async function Px(s){const r=xs();return r?r.ensureOpenChamberIgnored(s):ig(s)}async function Tx(){const s=xs();return s?s.getGitIdentities():ag()}async function Fx(s){const r=xs();return r?r.createGitIdentity(s):rg(s)}async function Rx(s,r){const t=xs();return t?t.updateGitIdentity(s,r):sg(s,r)}async function _x(s){const r=xs();return r?r.deleteGitIdentity(s):tg(s)}async function Ox(){const s=xs();return s?.discoverGitCredentials?s.discoverGitCredentials():ng()}async function $x(){const s=xs();return s?.getGlobalGitIdentity?s.getGlobalGitIdentity():og()}const Lx="openchamber.json",nm=".openchamber";function om(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const Bx=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ui=(s,r)=>{const t=Bx(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},am=s=>Ui(Ui(s,nm),Lx);async function im(s){const r=am(s);try{const t=om();if(t?.readFile)try{const l=await t.readFile(r);if(!l.content.trim())return null;const c=JSON.parse(l.content);return!c||typeof c!="object"?null:c}catch{return null}const n=await fetch(`${cm()}/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 zx(s,r){const t=am(s),n=Ui(s,nm);try{await Ee.createDirectory(n);const o=om();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(l){return console.error("Failed to write openchamber config via runtime API:",l),!1}return(await fetch(`${cm()}/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 Wx(s,r){const n={...await im(s)||{},...r};return zx(s,n)}async function fo(s){return(await im(s))?.["setup-worktree"]??[]}async function lm(s,r){const t=r.filter(n=>n.trim().length>0);return Wx(s,{"setup-worktree":t})}function Hx(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function cm(){const s="/api";return s.startsWith("/"),s}const Ux=".openchamber",bc="/api";function Vx(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const Sr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},vc=(s,r)=>{const t=Sr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},dm=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",Gx=async s=>{try{await Ee.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function qx(s,r){const t=Sr(s),n=vc(t,Ux);return await Gx(n),vc(n,r)}async function um(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,l=Sr(r),c=await qx(l,t),d={path:c,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await Ix(l,d),{path:c,branch:n,label:dm(n),projectDirectory:l,relativePath:c.startsWith(`${l}/`)?c.slice(l.length+1):c}}async function Kx(s){const{projectDirectory:r,path:t,force:n}=s,o=Sr(r);await rm(o,{path:t,force:n})}async function mm(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:l}=s,c=Sr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await rm(c,{path:t,force:o}),d&&(await Dx(c,{branch:d,force:!0}),a))try{await Ax(c,{branch:d,remote:l})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Mn(s){const r=Sr(s);return Ex(r)}async function wl(s){const r=Sr(s),t=await Mx(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Dn(s,r){const t=Sr(s),n=Sr(r.worktree);return{path:n,branch:r.branch??"",label:dm(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function fm(s,r,t){const n=t??await fo(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Hx(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=Vx();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 l=await fetch(`${bc}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),c=await l.json().catch(()=>null);if(l.status===202&&c&&typeof c.jobId=="string"){const d=c.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(`${bc}/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(!l.ok){const d=c&&c.error||"Request failed";return console.error("[worktreeService] Web exec failed:",c),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",c),c}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(l=>({command:l,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const pm=ds(),hm="oc.sessionSelectionByDirectory",Za=".openchamber",Qx=()=>{try{const s=pm.getItem(hm);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 qo=null;const jl=()=>(qo||(qo=Qx()),qo),gm=s=>{qo=s;try{pm.setItem(hm,JSON.stringify(s))}catch{}},xm=s=>{if(!s)return null;const t=jl()[s];return typeof t=="string"?t:null},hr=(s,r)=>{if(!s)return;const t={...jl()};r?t[s]=r:delete t[s],gm(t)},Yx=(s,r)=>{if(!s)return;const t=xm(s);if(!t)return;if(!new Set(r).has(t)){const o={...jl()};delete o[s],gm(o)}},wc=async(s,r)=>{const t=s.status??await wl(s.path).catch(()=>{});await mm({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},Ct=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},jc=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return Ct(r)},Xx=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,jo=(...s)=>{Zt()&&Xx()&&console.log("[OpenChamber][VSCode][sessions]",...s)},Mr=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())},Ls=s=>{const r=new Map;s.forEach(t=>{const n=Ct(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,Mr(n));return r},fn=(s,r)=>{const t=s.find(n=>n.id===r);return t?Ct(t.directory??null):null},Jx=async(s,r,t)=>{const n=Ct(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:Ct(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Mn(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 l=new Map;a.forEach(u=>{const m=Dn(n,u),f=Ct(m.path)??m.path;f!==n&&l.set(f,m)});let c=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=l.get(m);if(!f){d.delete(u)&&(c=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),c=!0)}),c?d:null},ht=Vt()(Jt(Es((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=vt.getState(),n=Ot.getState(),o=Ee.getApiClient(),a=jc(),l=!!a;jo("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:Ee.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const c=new Map,d=async O=>{const U=Ct(O)??O,Q=U,W=c.get(Q);if(W)return W;try{const L=await o.path.get({directory:O}),q=Ct(L.data?.directory??null)??U;return c.set(Q,q),q}catch{return c.set(Q,U),U}},u=(O,U,Q)=>{const W=Ct(U);if(!W)return O;const H=Q?.includeDescendants===!0?`${W}/`:null,q=Q?.includeMissingDirectory===!0;return O.filter(X=>{const Y=Ct(X.directory??null);return Y?!!(Y===W||H&&Y.startsWith(H)):q})},m=(O,U,Q)=>{const W=Ct(U);if(!W)return O;const L=Ct(Q??null);if(!L||L===W)return O.map(X=>Ct(X.directory??null)?X:{...X,directory:W});const H=L==="/"?"/":`${L}/`,q=W==="/"?"/":`${W}/`;return O.map(X=>{const Y=Ct(X.directory??null);if(!Y)return{...X,directory:W};if(Y===L)return{...X,directory:W};if(H!=="/"&&Y.startsWith(H)){const re=Y.slice(H.length);return{...X,directory:`${q}${re}`}}return X})},f=async O=>{const U=Ct(O);if(!U)try{const Y=await o.session.list(void 0);return Array.isArray(Y.data)?Y.data:[]}catch(Y){throw console.debug("Failed to list sessions (global):",Y),Y}const Q=await d(U),W=async()=>{const Y=await o.session.list({directory:U});return Array.isArray(Y.data)?Y.data:[]};let L=[],H=null,q=!1;try{L=await W()}catch(Y){console.debug("Failed to list sessions for directory:",U,Y),H=Y,L=[]}if(L.length===0){q=!0;try{const Y=await o.session.list(void 0),re=Array.isArray(Y.data)?Y.data:[];L=u(re,Q,{includeDescendants:l,includeMissingDirectory:!1})}catch(Y){throw console.debug("Failed to list sessions (global fallback):",Y),H||Y}}const X=u(L,Q,{includeDescendants:l,includeMissingDirectory:!q});return jo("fetchSessionsForDirectory",{requestedDirectory:U,canonicalDirectory:Q,fetched:L.length,filtered:X.length}),m(X,U,Q)},p=Ct(t.currentDirectory??Ee.getDirectory()??null),g=n.projects.find(O=>O.id===n.activeProjectId)??null,y=Ct(g?.path??null),h=y??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 O=>{const U=Ct(O.path);if(!U)return{projectId:O.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const Q=await cn(U).catch(()=>!1),W=await f(U||null);jo("projectSessions",{projectId:O.id,projectPath:U,isGitRepo:Q,parentSessions:W.length});const L=[];let H=[];const q=new Set;if(q.add(U),Q){const Y=`${U}/${Za}`;try{const re=new Set;(await Ee.listLocalDirectory(U)).some($=>$.isDirectory&&$.name===Za)&&(await Ee.listLocalDirectory(Y)).filter(R=>R.isDirectory).forEach(R=>{const z=/^([A-Za-z]:)?\//.test(R.path)?R.path:`${Y}/${R.name}`,G=Ct(z)??z;re.add(G)});const F=await Mn(U);Array.isArray(F)&&(H=F.map($=>Dn(U,$)).filter($=>$.path.includes(`/${Za}/`)),H.forEach($=>re.add($.path))),re.forEach($=>{const R=Ct($)??$;q.add(R)}),re.size>0&&(await Promise.allSettled(Array.from(re).map(R=>f(R)))).forEach(R=>{R.status==="fulfilled"&&Array.isArray(R.value)&&L.push(...R.value)})}catch{H=[]}}const X=Mr([...W,...L]);return{projectId:O.id,projectPath:U,sessions:X,discoveredWorktrees:H,validPaths:q}})),v=new Map;b.forEach(O=>{O.projectPath&&O.validPaths.forEach(U=>{const Q=Ct(U)??U,W=O.sessions.filter(L=>(Ct(L.directory??null)??Q)===Q);v.set(Q,Mr(W))})});const w=Mr(Array.from(v.values()).flat()),N=r();let x=N.worktreeMetadata;for(const O of b)if(O.projectPath)try{const U=await Jx(O.sessions,O.projectPath,x);U&&(x=U)}catch(U){console.debug("Failed to refresh worktree metadata during session load:",U)}const k=new Map;b.forEach(O=>{O.projectPath&&k.set(O.projectPath,O.discoveredWorktrees)});const A=new Set;b.forEach(O=>{O.validPaths.forEach(U=>{const Q=Ct(U)??U;Q&&A.add(Q)})});const C=p??y??null,M=C&&A.has(C)?C:y??C,S=M?v.get(M)??[]:w,D=new Set(w.map(O=>O.id));for(const[O,U]of v.entries())Yx(O,U.map(Q=>Q.id));const E=(M??null)!==(N.lastLoadedDirectory??null);let T=N.currentSessionId;if((!T||!D.has(T)||E)&&(T=S[0]?.id??w[0]?.id??null),M){const O=xm(M);O&&D.has(O)&&(T=O)}const I=(()=>{if(!T)return M??null;const O=x.get(T)?.path;if(O)return Ct(O)??O;const U=fn(w,T);return U||(M??null)})();try{Ee.setDirectory(I??void 0)}catch(O){console.warn("Failed to sync OpenCode directory after session load:",O)}const P=y?b.find(O=>O.projectPath===y)?.discoveredWorktrees??[]:[];s({sessions:w,sessionsByDirectory:v,currentSessionId:T,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:x,availableWorktrees:P,availableWorktreesByProject:k}),M&&hr(M,T),I&&I!==M&&hr(I,T)}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=vt.getState(),l=Ct(a.currentDirectory),c=jc(),d=c??Ct(n??Ee.getDirectory()??l);jo("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:c});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 v=b.get(d)??[];b.set(d,Mr([p,...v]))}return{sessions:j,sessionsByDirectory:b,currentSessionId:u,webUICreatedSessions:new Set([...h.webUICreatedSessions,u]),isLoading:!1}}),d)try{Ee.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(v=>{const w=v.sessions.map(x=>x.id===u?b:x),N=new Map(v.sessionsByDirectory);if(d){const k=(N.get(d)??[]).map(A=>A.id===u?b:A);N.set(d,Mr(k))}return{sessions:w,sessionsByDirectory:Ls(w),currentSessionId:b.id,webUICreatedSessions:new Set([...Array.from(v.webUICreatedSessions).filter(x=>x!==u),b.id])}}),hr(d??null,b.id)},y=async()=>{const h=Ee.getApiClient(),j=20;for(let b=0;b<j;b+=1){try{const v=await h.session.list(d?{directory:d}:void 0),N=(Array.isArray(v.data)?v.data:[]).find(x=>!(f.has(x.id)||t&&x.title&&x.title!==t));if(N)return N}catch(v){console.debug("Session poll attempt failed:",v)}await new Promise(v=>setTimeout(v,2e3))}return null};try{const h=()=>Ee.createSession({title:t,parentID:o??void 0});let j=null;try{j=d?await Ee.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 y()),j?(g(j),j):(s(b=>({sessions:b.sessions.filter(v=>v.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(b.webUICreatedSessions).filter(v=>v!==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=fn(r().sessions,t),l=o?.path??a;let c=null;try{o&&n?.archiveWorktree&&(await wc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),c=o);const d=()=>Ee.deleteSession(t);if(!(l?await Ee.withDirectory(l,d):await d()))return s(p=>{const g={isLoading:!1,error:"Failed to delete session"};if(c){const y=new Map(p.worktreeMetadata);y.delete(t),g.worktreeMetadata=y}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 y=new Map(p.worktreeMetadata);y.delete(t);const h=n?.archiveWorktree&&o?p.availableWorktrees.filter(b=>Ct(b.path)!==Ct(o.path)):p.availableWorktrees,j=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const b=Ct(o.projectDirectory)??o.projectDirectory,v=j.get(b)??[];j.set(b,v.filter(w=>Ct(w.path)!==Ct(o.path)))}return{sessions:g,sessionsByDirectory:Ls(g),currentSessionId:m,isLoading:!1,worktreeMetadata:y,availableWorktrees:h,availableWorktreesByProject:j}});const f=l??Ee.getDirectory()??null;return hr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(c?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 l=[],c=[],d=new Set,u=[],m=new Set;for(const j of o)try{const b=r().worktreeMetadata.get(j),v=fn(r().sessions,j),w=b?.path??v;b&&n?.archiveWorktree&&!m.has(b.path)&&(await wc(b,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(j),u.push({path:b.path,projectDirectory:b.projectDirectory}),m.add(b.path));const N=()=>Ee.deleteSession(j);(w?await Ee.withDirectory(w,N):await N())?(l.push(j),b?.path&&!u.some(k=>k.path===b.path)&&u.push({path:b.path,projectDirectory:b.projectDirectory})):c.push(j)}catch{c.push(j)}const f=vt.getState();u.forEach(({path:j,projectDirectory:b})=>{f.currentDirectory===j&&f.setDirectory(b,{showOverlay:!1})});const p=new Set(l),g=c.length>0?c.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let y=null;s(j=>{const b=j.sessions.filter(k=>!p.has(k.id));j.currentSessionId&&p.has(j.currentSessionId)?y=null:y=j.currentSessionId;const v=new Map(j.worktreeMetadata);for(const k of p)v.delete(k);for(const k of d)v.delete(k);const w=new Set(u.map(k=>Ct(k.path)).filter(k=>!!k)),N=w.size>0?j.availableWorktrees.filter(k=>!w.has(Ct(k.path)??k.path)):j.availableWorktrees,x=new Map(j.availableWorktreesByProject);return u.length>0&&u.reduce((A,C)=>{const M=Ct(C.projectDirectory)??C.projectDirectory,S=Ct(C.path)??C.path;return A.has(M)||A.set(M,new Set),A.get(M)?.add(S),A},new Map).forEach((A,C)=>{const S=(x.get(C)??[]).filter(D=>!A.has(Ct(D.path)??D.path));x.set(C,S)}),{sessions:b,sessionsByDirectory:Ls(b),currentSessionId:y,...a?{}:{isLoading:!1,error:g},worktreeMetadata:v,availableWorktrees:N,availableWorktreesByProject:x}});const h=Ee.getDirectory()??null;return hr(h,y),{deletedIds:l,failedIds:c}},updateSessionTitle:async(t,n)=>{try{const o=fn(r().sessions,t),a=r().worktreeMetadata.get(t),l=()=>Ee.updateSession(t,n),c=a?.path??o,d=c?await Ee.withDirectory(c,l):await l();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:Ls(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=fn(r().sessions,t),o=Ee.getApiClient(),l=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ee.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=l?await Ee.withDirectory(l,c):await c();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Ls(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=fn(r().sessions,t),o=Ee.getApiClient(),l=r().worktreeMetadata.get(t)?.path??n,c=async()=>{const u=n??Ee.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=l?await Ee.withDirectory(l,c):await c();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:Ls(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=Ee.getDirectory()??null;hr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=Ct(t)??t,{sessionsByDirectory:o,sessions:a}=r(),l=o.get(n);return l||a.filter(c=>(Ct(c.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return Ct(n.path)??n.path;const o=r().sessions.find(l=>l.id===t);return Ct(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 l=o.sessions[a],c=n.time?{...l.time,...n.time}:l.time,d=n.summary===void 0?l.summary:n.summary||void 0,u=n.share===void 0?l.share:n.share||void 0,m={...l,...n,time:c,summary:d,share:u},f=m.title!==l.title||m.parentID!==l.parentID||m.directory!==l.directory||m.version!==l.version||m.projectID!==l.projectID||JSON.stringify(m.time)!==JSON.stringify(l.time)||JSON.stringify(m.summary??null)!==JSON.stringify(l.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(l.share??null),p=[...o.sessions];return p[a]=f?m:l,{sessions:p,sessionsByDirectory:Ls(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 c=o[a].directory??null,d=n??void 0;c!==(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:Ls(m)}}),c&&hr(c,null),n&&hr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(c=>c.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(c=>c.id===t.id?t:c),l=Mr(a);return{sessions:l,sessionsByDirectory:Ls(l)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=Ct(o?.directory??null),l=n.sessions.filter(u=>u.id!==t);if(l.length===n.sessions.length)return n;const c=new Map(n.worktreeMetadata);c.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&hr(a,null),{sessions:l,sessionsByDirectory:Ls(l),currentSessionId:d,worktreeMetadata:c}})}}),{name:"session-store",storage:Is(()=>ds()),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:[],l=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],c=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=Mr(n);return{...r,...s,sessions:f,sessionsByDirectory:Ls(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(l),availableWorktrees:c,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),ym="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.",Zx="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: ",ei=s=>typeof s=="string"&&s.trim()===ym.trim(),ti=(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},On=(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},Sc=new Map,bm=s=>{const r=Sc.get(s);r&&(clearTimeout(r),Sc.delete(s))},Vr=s=>{for(const r of s)bm(r)},oo=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>oo(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>oo(r)).join("")}return""},Kn=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:Kn(n)).join("");const t=oo(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||oo(o.delta)||""}return""}).join(""):"")},$n=(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=oo(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},kc=50*1024*1024,ey=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"}},ty=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"}},sy=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},ry=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],l=s[n+2],c=o<<16|(a??0)<<8|(l??0);t+=r[c>>18&63],t+=r[c>>12&63],t+=typeof a=="number"?r[c>>6&63]:"=",t+=typeof l=="number"?r[c&63]:"="}return t},qs=Vt()(Jt(Es((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(y=>y.filename===t.name&&y.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=kc;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 50MB.`);const l=["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"],c=ty(t);!l.some(y=>c.startsWith(y)||c===y||c==="")&&c!==""&&console.warn(`File type "${c}" might not be supported`);const u=new FileReader,m=await new Promise((y,h)=>{u.onload=()=>y(u.result),u.onerror=h,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${c}`):m,p=y=>{const h=y.replace(/\\/g,"/").split("/");return h[h.length-1]||y},g={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:c,filename:p(t.name),size:t.size,source:"local"};s(y=>({attachedFiles:[...y.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 c=o,d,u;if(!c)try{const b=Ee.getApiClient(),v=t.lastIndexOf("/"),w=v>0?t.substring(0,v):"/",N=v>0?t.substring(v+1):t,x=await b.file.read({path:N,directory:w});x.data&&"content"in x.data?(c=x.data.content,d=x.data.encoding??void 0,u=x.data.mimeType??void 0):c=""}catch(b){console.error("Failed to read server file:",b),c=`[File: ${n}]`}const m=u||ey(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return c||"";const v=new TextEncoder().encode(c||"");return ry(v)})(),g=d==="base64"?sy(p):new TextEncoder().encode(c||"").length;if(g>kc)throw new Error(`File "${n}" is too large. Maximum size is 50MB.`);const y=new File([],n,{type:f}),h=`data:${f};base64,${p}`,j={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:y,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:Is(()=>ds()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),ny=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),oy=s=>s?ny.has(s.toLowerCase()):!1,ay=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},iy=s=>{if(s)try{const r=ay();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},ly=(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"},Ko=s=>{const r=iy(s);return r?ly(r.permission,"edit"):"ask"},Nc=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},si=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return Nc(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:Nc(t.tokens)},ri=(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,l=Math.min(o?a:32e3,32e3),c=Math.min(l,n),d=n>0?Math.max(n-c,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:c}},Ln=["ask","allow","full"],wt=Vt()(Jt(Es((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 l=new Map(a.sessionModelSelections);return l.set(t,{providerId:n,modelId:o}),{sessionModelSelections:l}})},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(l=>{const c=new Map(l.sessionAgentModelSelections);let d=c.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),c.set(t,d),{sessionAgentModelSelections:c}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},saveAgentModelVariantForSession:(t,n,o,a,l)=>{s(c=>{const d=new Map(c.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 l===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,l),u.set(n,m),d.set(t,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(t,n,o,a)=>{const{sessionAgentModelVariantSelections:l}=r(),c=l.get(t);if(!c)return;const d=c.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:l}=r(),c=new Map,d=(y,h)=>{if("mode"in y&&y.mode&&typeof y.mode=="string"&&n.find(w=>w.name===y.mode))return y.mode;if(y.providerID&&y.modelID){const v=n.find(w=>w.model?.providerID===y.providerID&&w.model?.modelID===y.modelID);if(v)return v.name}const{currentAgentContext:j}=r(),b=j.get(t);if(b&&n.find(v=>v.name===b))return b;if(h>0&&y.providerID&&y.modelID){const w=(o.get(t)||[]).filter(N=>N.info.role==="assistant").sort((N,x)=>N.info.time.created-x.info.time.created);for(let N=h-1;N>=0;N--){const k=w[N].info;if(k.providerID===y.providerID&&k.modelID===y.modelID){if(k.mode&&typeof k.mode=="string"&&n.find(M=>M.name===k.mode))return k.mode;const A=n.find(C=>C.model?.providerID===k.providerID&&C.model?.modelID===k.modelID);if(A)return A.name}}}return y.providerID&&y.modelID&&n.find(w=>w.name==="build")?"build":null},u=o.get(t)||[],m=u.filter(y=>y.info.role==="assistant"||y.info.role==="user").sort((y,h)=>y.info.time.created-h.info.time.created),f=u.filter(y=>y.info.role==="assistant").sort((y,h)=>y.info.time.created-h.info.time.created);let p,g;for(let y=0;y<m.length;y++){const h=m[y],{info:j}=h,b=j;if(b.role==="user"){p=typeof b.variant=="string"&&b.variant.trim().length>0?b.variant:void 0,g=b.model?.providerID&&b.model?.modelID?{providerID:b.model.providerID,modelID:b.model.modelID}:void 0;continue}if(b.providerID&&b.modelID){const v=d(b,f.indexOf(h));if(v&&n.find(w=>w.name===v)){p&&g&&g.providerID===b.providerID&&g.modelID===b.modelID&&l(t,v,b.providerID,b.modelID,p);const w={providerId:b.providerID,modelId:b.modelID,timestamp:j.time.created},N=c.get(v);(!N||w.timestamp>N.timestamp)&&c.set(v,w)}}p=void 0,g=void 0}for(const[y,h]of c)a(t,y,h.providerId,h.modelId);return c},getContextUsage:(t,n,o,a)=>{if(!t)return null;const l=ri(0,n,o),c=l.contextLimit,d=l.normalizedOutput??0,u=l.thresholdLimit;if(c===0||u===0)return null;const f=(a.get(t)||[]).filter(w=>w.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],g=p.info.id,y=w=>{const N=()=>{s(x=>{const k=x.sessionContextUsage.get(t);if(k&&k.totalTokens===w.totalTokens&&k.percentage===w.percentage&&k.contextLimit===w.contextLimit&&(k.outputLimit??0)===(w.outputLimit??0)&&(k.normalizedOutput??0)===(w.normalizedOutput??0)&&k.thresholdLimit===w.thresholdLimit&&k.lastMessageId===w.lastMessageId)return x;const A=new Map(x.sessionContextUsage);return A.set(t,w),{sessionContextUsage:A}})};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 w=h.normalizedOutput??h.outputLimit??0,N=h.contextLimit!==c||w!==d||h.thresholdLimit!==u;if(N&&h.totalTokens>0){const x=h.totalTokens/u*100,k={totalTokens:h.totalTokens,percentage:Math.min(x,100),contextLimit:c,outputLimit:l.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:g};return y(k),k}if(!N&&h.totalTokens>0)return h}const j=si(p);if(j===0)return h||null;const b=ri(j,n,o),v={totalTokens:j,percentage:b.percentage,contextLimit:b.contextLimit,outputLimit:b.outputLimit,normalizedOutput:b.normalizedOutput,thresholdLimit:b.thresholdLimit,lastMessageId:g};return y(v),v},updateSessionContextUsage:(t,n,o,a)=>{const c=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(c.length===0)return;const d=c[c.length-1],u=si(d);if(u===0)return;const m=ri(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 c=r().sessionContextUsage.get(t);(!c||c.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let l=0;const c=()=>{l++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&si(u)>0){r().updateSessionContextUsage(t,0,0,o);return}l<a&&setTimeout(c,1e3)};setTimeout(c,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Ko(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Ko(n))=>{if(!t||!n)return;const l=a??"ask";l==="deny"||o==="deny"||Ln.includes(o)&&s(c=>{const d=new Map(c.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===l?(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=Ko(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const l=r().getSessionAgentEditMode(t,n,a),c=Ln.indexOf(l),d=Ln.indexOf(a),m=((c>=0?c:d>=0?d:0)+1)%Ln.length,f=Ln[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Is(()=>ds()),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,l])=>{t.set(a,new Map(l))});const n=new Map;s?.sessionAgentModelVariantSelections&&s.sessionAgentModelVariantSelections.forEach(([a,l])=>{const c=new Map;l.forEach(([d,u])=>{c.set(d,new Map(u))}),n.set(a,c)});const o=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([a,l])=>{o.set(a,new Map(l))}),{...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 ni=[],oi=null;const cy=50,dy=3e4,Gr=new Map,So=new Map,pn=new Map,uy=10,la=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<uy?null:n},ko=(s,r)=>{const t=la(s),n=la(r);return!t||!n||t.length!==n.length?!0:t>n},my=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},bn=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),ca=s=>s?.finish==="stop",Mc=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??""}`}}},Dc=new Set,da=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(Mc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=Mc(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},fy=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=bn(t),a=bn(n),l=ca(s.info),c=ca(r.info);let d=n;return l&&o>=a?d=da(t,n):c&&a>=o?d=da(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},ai=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]=fy(r[a],n)}return r},py=(s,r)=>{let t=r,n=r?la(r):null;for(const o of s){const a=o?.info?.id,l=la(a);!a||!l||(!n||l>n)&&(n=l,t=a)}return t},Zs=(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},hn=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},No=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},hy=(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},Ac=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),gy=async s=>{if(s)try{return ht.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},Ec=s=>{if(!s)return null;try{return ht.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},Ic=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},ii=async(s,r)=>{const t=await gy(s);return t?Ee.withDirectory(t,r):r()},St=Vt()(Jt(Es((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=us.VIEWPORT_MESSAGES)=>{const o=await ii(t,()=>Ee.getSessionMessages(t)),a=Ec(t),l=Ic(o,a),c=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(c?l.filter(m=>{const f=m?.info?.id;return f?ko(f,c):!0}):l).slice(-n);s(m=>{const f=new Map(m.messages),p=m.messages.get(t)||[],g=new Map(p.filter(M=>typeof M.info?.id=="string").map(M=>[M.info.id,M])),y=u.map(M=>{const S={...M.info,clientRole:M.info?.clientRole??M.info.role,userMessageMarker:M.info.role==="user"?!0:M.info?.userMessageMarker},D=(Array.isArray(M.parts)?M.parts:[]).map(T=>{if(T?.type==="text"){const I=T.text??T.content??"";if(ei(I))return{...T,synthetic:!0}}return T}),E=S?.id?g.get(S.id):void 0;if(E&&E.info.role==="assistant"){const T=Array.isArray(E.parts)?E.parts:[],I=bn(T),P=bn(D);if(ca(E.info)&&I>P){const U=da(T,D);return{...M,info:S,parts:U}}}return{...M,info:S,parts:D}}),h=ai(y),j=new Set(p.map(M=>M.info.id)),b=new Set(h.map(M=>M.info.id)),v=[];j.forEach(M=>{b.has(M)||v.push(M)}),f.set(t,h);const w=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);w.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 x={messages:f,sessionMemoryState:w};Vr(v);const k=On(m.messageStreamStates,v);if(k!==m.messageStreamStates&&(x.messageStreamStates=k),v.length>0){const M=m.streamingMessageIds.get(t);M&&v.includes(M)&&(x.streamingMessageIds=Zs(x.streamingMessageIds??m.streamingMessageIds,t,null))}if(v.length>0){const M=No(x.messageSessionIndex??m.messageSessionIndex,v);M!==(x.messageSessionIndex??m.messageSessionIndex)&&(x.messageSessionIndex=M)}if(v.length>0){const M=new Map(m.pendingAssistantParts);let S=!1;v.forEach(D=>{M.delete(D)&&(S=!0)}),S&&(x.pendingAssistantParts=M)}const A=x.messageSessionIndex??m.messageSessionIndex;let C=A;return h.forEach(M=>{const S=M?.info?.id;typeof S=="string"&&S.length>0&&(C=hn(C,S,t))}),C!==A&&(x.messageSessionIndex=C),x})},sendMessage:async(t,n,o,a,l,c,d,u,m)=>{if(!l)throw new Error("No session selected");const f=l;r().sessionAbortFlags.has(f)&&s(p=>{const g=new Map(p.sessionAbortFlags);return g.delete(f),{sessionAbortFlags:g}}),await ii(f,async()=>{try{let p=t;if(t.startsWith("/")){const y=t.indexOf(" "),h=y===-1?t.substring(1):t.substring(1,y),j=y===-1?"":t.substring(y+1).trim(),b=Ee.getApiClient(),v=Ee.getDirectory();if(h==="init"){const w=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await b.session.init({sessionID:f,...v?{directory:v}:{},messageID:w,providerID:n,modelID:o});return}if(h==="summarize"){await b.session.summarize({sessionID:f,...v?{directory:v}:{},providerID:n,modelID:o});return}try{const w=await Ee.getCommandDetails(h);w?.template?p=w.template.replace(/\$ARGUMENTS/g,j):p=t}catch(w){console.error("Command template resolution failed:",w),p=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(y=>{const h=y.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},j=pn.get(f);j&&(clearTimeout(j),pn.delete(f));const b=new Map(y.sessionMemoryState);return b.set(f,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:b}});try{const y=new AbortController;s(b=>{const v=new Map(b.abortControllers);return v.set(f,y),{abortControllers:v}});const h=(c??[]).map(b=>({type:"file",mime:b.mimeType,filename:b.filename,url:b.dataUrl}));s(b=>{const v=new Set(b.pendingAssistantHeaderSessions);v.add(f);const w=new Map(b.pendingUserMessageMetaBySession);return w.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:v,pendingUserMessageMetaBySession:w}});const j=u?.map(b=>({text:b.text,files:b.attachments?.map(v=>({type:"file",mime:v.mimeType,filename:v.filename,url:v.dataUrl}))}));if(await Ee.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{qs.getState().clearAttachedFiles()}catch(b){console.error("Failed to clear attached files after send",b)}s(b=>{const v=new Map(b.abortControllers);return v.delete(f),{abortControllers:v}})}catch(y){let h="Network error while sending message. The message may still be processing.";if(y.name==="AbortError")h="Request timed out. The message may still be processing.";else if(y.message?.includes("504")||y.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 y.message&&(h=y.message);throw s(j=>{const b=new Map(j.abortControllers);b.delete(f);const v=new Set(j.pendingAssistantHeaderSessions);v.delete(f);const w=new Map(j.pendingUserMessageMetaBySession);return w.delete(f),{abortControllers:b,pendingAssistantHeaderSessions:v,pendingUserMessageMetaBySession:w}}),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(y=>{const h=new Map(y.abortControllers);h.delete(f);const j=new Set(y.pendingAssistantHeaderSessions);j.delete(f);const b=new Map(y.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 c=hy(n,t);if(c.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(y=>y.type==="reasoning"||y.type==="tool"||y.type==="step-start")){c.add(p.info.id);break}}c.size===0&&m&&c.add(m)}for(const u of c){const m=Gr.get(u);m&&(clearTimeout(m),Gr.delete(u),So.delete(u))}c.size>0&&Vr(c);const d=Date.now();s(u=>{const m=On(u.messageStreamStates,c),f=u.messages.get(t)??[];let p=!1,g=u.messages;if(f.length>0&&c.size>0){const b=f.map(v=>{if(!c.has(v.info.id)&&c.size>0)return v;const w=(v.parts??[]).map(N=>{if(N.type==="reasoning"){const x=N,k={...x.time??{}};return typeof k.end!="number"&&(k.end=d),{...x,time:k}}if(N.type==="tool"){const x=N,k={...x.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...x,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...v,info:{...v.info,abortedAt:d,streaming:!1,status:"aborted"},parts:w}});p&&(g=new Map(u.messages),g.set(t,b))}const y=u.sessionMemoryState.get(t);let h=u.sessionMemoryState;if(y){const b=new Map(u.sessionMemoryState);b.set(t,{...y,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:Zs(u.streamingMessageIds,t,null),...p?{messages:g}:{}}}),Ee.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,l)=>{const c=r();if(Dc.has(n))return;const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!ko(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=c.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>us.ZOMBIE_TIMEOUT){p.isZombie||s(y=>{const h=new Map(y.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=hn(g.messageSessionIndex,n,t);b!==g.messageSessionIndex&&(j.messageSessionIndex=b);const v=M=>{if(!((f==="assistant"||f==="user")&&g.sessionAbortFlags.has(t)))return M;const D=new Map(g.sessionAbortFlags);return D.delete(t),{...M,sessionAbortFlags:D}},w=M=>{const S=M||"",D=So.get(n);if(S&&D===S){const I=r();if(Ac(I,t,n)){const P=Gr.get(n);P&&(clearTimeout(P),Gr.delete(n)),setTimeout(()=>{const O=r();typeof O.forceCompleteMessage=="function"&&O.forceCompleteMessage(t,n,"timeout"),O.completeStreamingMessage(t,n)},100)}}So.set(n,S);const E=Gr.get(n);E&&clearTimeout(E);const T=setTimeout(()=>{const I=r();typeof I.forceCompleteMessage=="function"&&I.forceCompleteMessage(t,n,"timeout"),Ac(I,t,n)&&I.completeStreamingMessage(t,n),Gr.delete(n),So.delete(n)},8e3);Gr.set(n,T)},N=t!==l,x=g.sessionMemoryState.get(t);if(N&&x?.isStreaming){h.length>=us.BACKGROUND_STREAMING_BUFFER&&h.shift();const M=new Map(g.sessionMemoryState);M.set(t,{...x,backgroundMessageCount:(x.backgroundMessageCount||0)+1}),g.sessionMemoryState=M}if(f==="assistant"){const M=g.sessionMemoryState.get(t);if(M){const S=Date.now(),D=new Map(g.sessionMemoryState);D.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??S,lastAccessedAt:S,isZombie:!1}),g.sessionMemoryState=D}}const k=Kn(o);if(ei(k)&&(o.synthetic=!0),my()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const A=j.streamingMessageIds??g.streamingMessageIds;if(f==="assistant"){const M=Zs(A,t,n);M!==A&&(j.streamingMessageIds=M,window.__messageTracker?.(n,"streamingId_set_latest"))}const C=h.findIndex(M=>M.info.id===n);if(C!==-1&&f==="user"){const M=h[C],S=M.parts.findIndex(P=>P.id===o.id);if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_user_part"),g;const D=$n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`user_part_type:${D.type||"unknown"}`);const E={...M};S!==-1?E.parts=E.parts.map((P,O)=>O===S?D:P):E.parts=[...E.parts,D];const T=[...h];T[C]=E;const I=new Map(g.messages);return I.set(t,T),v({messages:I})}if(f==="assistant"&&C!==-1){const M=h[C],S=M.parts.findIndex(O=>O.id===o.id),D=$n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const E={...M};S!==-1?E.parts=E.parts.map((O,U)=>U===S?D:O):E.parts=[...E.parts,D];const T=[...h];T[C]=E;const I=new Map(g.messages);I.set(t,T),j.messageStreamStates=ti(g.messageStreamStates,n);const P=Zs(j.streamingMessageIds??g.streamingMessageIds,t,n);return P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set")),D.type==="text"?w(D.text||""):w(""),v({messages:I,...j})}if(C===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const K=$n(o);window.__messageTracker?.(n,`new_user_part_type:${K.type||"unknown"}`);const ae=g.pendingUserMessageMetaBySession.get(t),F=wt.getState(),$=ae?.mode??F.getSessionAgentSelection(t)??F.getCurrentAgent(t),R=typeof $=="string"&&$.trim().length>0?$.trim():void 0,B=ae?.providerID??(g.lastUsedProvider?.providerID||void 0),z=ae?.modelID??(g.lastUsedProvider?.modelID||void 0);ae&&(j.pendingUserMessageMetaBySession=Cc(g.pendingUserMessageMetaBySession,t));const G={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...R?{mode:R}:{},...B?{providerID:B}:{},...z?{modelID:z}:{},time:{created:Date.now()}},parts:[K]},ge=[...h,G];ge.sort((me,Ne)=>{const Ce=me.info?.time?.created||0,Be=Ne.info?.time?.created||0;return Ce-Be});const oe=new Map(g.messages);return oe.set(t,ge),v({messages:oe})}if(o?.type==="text"){const K=Kn(o).trim();if(K.length>0){const ae=[...h].reverse().find(F=>F.info.role==="user");if(ae){const F=ae.parts.map($=>Kn($)).join("").trim();if(F.length>0&&F===K)return Dc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const M=$n(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?w(M.text||""):w("");const S=g.pendingAssistantParts.get(n),D=S?[...S.parts]:[],E=D.findIndex(K=>K.id===M.id);E!==-1?D[E]=M:D.push(M);const T=new Map(g.pendingAssistantParts);T.set(n,{sessionId:t,parts:D});const I=g.lastUsedProvider?.providerID||"",P=g.lastUsedProvider?.modelID||"",O=Date.now(),U=Ee.getDirectory()??"/",Q=wt.getState(),W=Q.getSessionAgentSelection(t)??Q.getCurrentAgent(t),L=typeof W=="string"&&W.trim().length>0?W.trim():void 0,H=g.pendingAssistantHeaderSessions.has(t);if(H){const K=new Set(g.pendingAssistantHeaderSessions);K.delete(t),j.pendingAssistantHeaderSessions=K}const X={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:O},agent:L||"default",model:{providerID:I,modelID:P},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:O},parentID:n,modelID:P,providerID:I,mode:L||"default",...H?{openchamberHeaderAnchor:!0}:{},path:{cwd:U,root:U},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:D},Y=[...h,X],re=new Map(g.messages);if(re.set(t,Y),f==="assistant"){j.messageStreamStates=ti(g.messageStreamStates,n);const K=Zs(j.streamingMessageIds??g.streamingMessageIds,t,n);K!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=K,window.__messageTracker?.(n,"streamingId_set"))}return v({messages:re,pendingAssistantParts:T,...j})}else{const M=h[C],S=M.parts.findIndex(P=>P.id===o.id),D=$n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${D.type||"unknown"}`);const E={...M};S!==-1?E.parts=E.parts.map((P,O)=>O===S?D:P):E.parts=[...E.parts,D];const T=[...h];T[C]=E;const I=new Map(g.messages);if(I.set(t,T),E.info.role==="assistant"){j.messageStreamStates=ti(g.messageStreamStates,n);const P=Zs(j.streamingMessageIds??g.streamingMessageIds,t,n);P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set"))}return D.type==="text"?w(D.text||""):w(""),v({messages:I,...j})}})},addStreamingPart:(t,n,o,a,l)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,l);return}ni.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:l}),oi||(oi=setTimeout(()=>{const c=[...ni];ni=[],oi=null;const d=r();for(const u of c)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},cy))},forceCompleteMessage:(t,n,o="timeout")=>{const a=l=>{if(t)return t;for(const[c,d]of l.messages.entries())if(d.some(u=>u.info.id===n))return c;return null};s(l=>{const c=a(l);if(!c)return l;const d=l.messages.get(c)??[],u=d.findIndex(x=>x.info.id===n);if(u===-1)return l;const m=d[u];if(!m)return l;const f=Date.now(),p=m.info,g=typeof p?.time?.completed=="number"&&p.time.completed>0;let y=!1;const h={...p};g||(h.time={...p.time??{},completed:f},y=!0),h.status!=="completed"&&(h.status="completed",y=!0),h.streaming&&(h.streaming=!1,y=!0);let j=!1;const b=m.parts.map(x=>{if(!x)return x;if(x.type==="tool"){const k=x.state;if(!k)return x;const A=k.status,C=A==="running"||A==="pending"||A==="started",M=!k.time||typeof k.time?.end!="number";if(C||M){const S={...k};return C&&(S.status="completed"),M&&(S.time={...k.time??{},end:f}),j=!0,{...x,state:S}}return x}if(x.type==="reasoning"){const k=x.time;return!k||typeof k.end!="number"?(j=!0,{...x,time:{...k??{},end:f}}):x}if(x.type==="text"){const k=x.time;return k&&typeof k.end!="number"?(j=!0,{...x,time:{...k,end:f}}):x}return x});if(!y&&!j)return l;window.__messageTracker?.(n,`force_complete:${o}`);const v={...m,info:h,parts:j?b:m.parts},w=[...d];w[u]=v;const N=new Map(l.messages);return N.set(c,w),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{bm(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,l=!1;return n.messages.forEach((d,u)=>{if(l)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 y=new Map(n.messages);y.set(u,g),a=y,l=!0}),{messageStreamStates:o,...l?{messages:a}:{}}}),Vr([t])},updateMessageInfo:(t,n,o)=>{s(c=>{const d=c.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!ko(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),c;const m=[...c.messages.get(t)??[]],f=m.findIndex(C=>C.info.id===n),p=c.pendingAssistantParts.get(n),g=(C=[],M=[])=>{if(!M.length)return C;const S=[...C];return M.forEach(D=>{const E=S.findIndex(T=>T.id===D.id);E===-1?S.push(D):S[E]=D}),S},y=C=>{if(!C)return C;const M=C.clientRole??C.role,S=M==="user"?!0:C.userMessageMarker;return{...C,clientRole:M,...S?{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 U=m[0]?.info,Q=typeof U?.time?.created=="number"?U.time.created:null,W=typeof U?.id=="string"?U.id:null,L=o,H=typeof L?.time?.created=="number"?L.time.created:null,q=typeof L?.id=="string"?L.id:n;let X=!1;if(H!==null&&Q!==null&&(X=H<Q),!X&&q&&W&&(X=q.localeCompare(W)<0),X)return window.__messageTracker?.(n,"skipped_evicted_message_update"),c}const C=y(o);if(C&&C.role==="user"){const O=p?.parts??[],U=c.pendingUserMessageMetaBySession.get(t),Q={info:{...C,userMessageMarker:!0,clientRole:"user",...U?.mode?{mode:U.mode}:{},...U?.providerID?{providerID:U.providerID}:{},...U?.modelID?{modelID:U.modelID}:{}},parts:O.length>0?[...O]:[]},W=new Map(c.messages),L=[...m,Q];L.sort((X,Y)=>{const re=X.info?.time?.created||0,K=Y.info?.time?.created||0;return re-K}),W.set(t,L);const H={messages:W,...U?{pendingUserMessageMetaBySession:Cc(c.pendingUserMessageMetaBySession,t)}:{}},q=hn(H.messageSessionIndex??c.messageSessionIndex,n,t);if(q!==(H.messageSessionIndex??c.messageSessionIndex)&&(H.messageSessionIndex=q),p){const X=new Map(c.pendingAssistantParts);X.delete(n),H.pendingAssistantParts=X}return H}if(!C||C.role!=="assistant")return c;const M=p?.parts??[],S=c.pendingAssistantHeaderSessions.has(t),D={info:{...C,animationSettled:C?.animationSettled??!1,...S?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},E=new Map(c.messages),T=[...m,D];E.set(t,T);const I={messages:E,...S?{pendingAssistantHeaderSessions:(()=>{const O=new Set(c.pendingAssistantHeaderSessions);return O.delete(t),O})()}:{}},P=hn(I.messageSessionIndex??c.messageSessionIndex,n,t);if(P!==(I.messageSessionIndex??c.messageSessionIndex)&&(I.messageSessionIndex=P),p){const O=new Map(c.pendingAssistantParts);O.delete(n),I.pendingAssistantParts=O}return I}const h=m[f],j=h.info;if(j.userMessageMarker===!0||j.clientRole==="user"||j.role==="user"){const C={...h.info,...o,role:"user",clientRole:"user",userMessageMarker:!0,providerID:j.providerID||void 0,modelID:j.modelID||void 0},M=c.pendingUserMessageMetaBySession.get(t);M&&!C.mode&&M.mode&&(C.mode=M.mode);const S={...h,info:C},D=new Map(c.messages),E=[...m];if(E[f]=S,D.set(t,E),M){const T=new Map(c.pendingUserMessageMetaBySession);return T.delete(t),{messages:D,pendingUserMessageMetaBySession:T}}return{messages:D}}const v={...h.info,...o};o.role&&o.role!==h.info.role&&(v.role=h.info.role),v.clientRole=v.clientRole??h.info.clientRole??h.info.role,v.clientRole==="user"&&(v.userMessageMarker=!0);const w=p?.parts?g(h.parts,p.parts):h.parts,N={...h,info:v,parts:w},x=new Map(c.messages),k=[...m];k[f]=N,x.set(t,k);const A={messages:x};if(p){const C=new Map(c.pendingAssistantParts);C.delete(n),A.pendingAssistantParts=C}return A});const a=o?.finish,l=o?.role;typeof a=="string"&&l!=="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 l={};if(a&&(l.streamingMessageIds=Zs(o.streamingMessageIds,t,null),l.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),l.messageStreamStates=d}Object.keys(l).length>0&&s(l),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}}),Vr([n]);let c=!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),c=!0,{sessionMemoryState:m}}),c){const d=pn.get(t);d&&(clearTimeout(d),pn.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,...y}=f;return p.set(t,y),{sessionMemoryState:p}}),pn.delete(t)},2e3);pn.set(t,u)}},syncMessages:(t,n)=>{const o=Ec(t),a=Ic(n,o),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,c=l?a.filter(d=>{const u=d?.info?.id;return u?ko(u,l):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(x=>typeof x.info?.id=="string").map(x=>[x.info.id,x])),p=c.map(x=>{const k={...x.info,clientRole:x.info?.clientRole??x.info.role,userMessageMarker:x.info.role==="user"?!0:x.info?.userMessageMarker,animationSettled:x.info.role==="assistant"?x.info?.animationSettled??!0:x.info?.animationSettled},A=(Array.isArray(x.parts)?x.parts:[]).map(S=>{if(S?.type==="text"){const D=S.text??S.content??"";if(ei(D))return{...S,synthetic:!0}}return S}),C=typeof k?.id=="string"?k.id:void 0,M=C?f.get(C):void 0;if(M&&M.info.role==="assistant"){const S=Array.isArray(M.parts)?M.parts:[],D=bn(S),E=bn(A);if(ca(M.info)&&D>E){const I=da(S,A);return{...x,info:k,parts:I}}}return{...x,info:k,parts:A}}),g=ai(p),y=new Set(m.map(x=>x.info.id)),h=new Set(g.map(x=>x.info.id)),j=[];y.forEach(x=>{h.has(x)||j.push(x)}),u.set(t,g);const b={messages:u,isSyncing:!0};Vr(j);const v=On(d.messageStreamStates,j);if(v!==d.messageStreamStates&&(b.messageStreamStates=v),j.length>0){const x=d.streamingMessageIds.get(t);x&&j.includes(x)&&(b.streamingMessageIds=Zs(b.streamingMessageIds??d.streamingMessageIds,t,null))}if(j.length>0){const x=No(b.messageSessionIndex??d.messageSessionIndex,j);x!==(b.messageSessionIndex??d.messageSessionIndex)&&(b.messageSessionIndex=x)}if(j.length>0){const x=new Map(d.pendingAssistantParts);let k=!1;j.forEach(A=>{x.delete(A)&&(k=!0)}),k&&(b.pendingAssistantParts=x)}const w=b.messageSessionIndex??d.messageSessionIndex;let N=w;return g.forEach(x=>{const k=x?.info?.id;typeof k=="string"&&k.length>0&&(N=hn(N,k,t))}),N!==w&&(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 l=n+dy;return a.get(t)===l?o:(a.set(t,l),{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},l=new Map(o.sessionMemoryState);return l.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:l}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const l=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},c=new Map(a.sessionMemoryState);return c.set(t,{...l,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:c}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=us.VIEWPORT_MESSAGES,o)=>{const a=r(),l=a.messages.get(t);if(!l||l.length<=n)return;const c=a.sessionMemoryState.get(t)||{viewportAnchor:l.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(c.isStreaming&&t===o)return;const d=c.viewportAnchor||l.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(l.length,u+n);m===l.length&&m-u<n&&(u=Math.max(0,m-n));const f=l.slice(u,m),p=l.slice(0,u),g=new Set(f.map(h=>h.info.id)),y=l.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),v={...c,viewportAnchor:d-u,trimmedHeadMaxId:py(p,c.trimmedHeadMaxId)};b.set(t,v);const w={messages:j,sessionMemoryState:b};Vr(y);const N=On(h.messageStreamStates,y);if(N!==h.messageStreamStates&&(w.messageStreamStates=N),y.length>0){const A=h.streamingMessageIds.get(t);A&&y.includes(A)&&(w.streamingMessageIds=Zs(w.streamingMessageIds??h.streamingMessageIds,t,null))}if(y.length>0){const A=No(w.messageSessionIndex??h.messageSessionIndex,y);A!==(w.messageSessionIndex??h.messageSessionIndex)&&(w.messageSessionIndex=A)}const x=w.messageSessionIndex??h.messageSessionIndex;let k=x;return f.forEach(A=>{const C=A?.info?.id;typeof C=="string"&&C.length>0&&(k=hn(k,C,t))}),k!==x&&(w.messageSessionIndex=k),w})},evictLeastRecentlyUsed:t=>{const n=r();if(n.messages.size<=us.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 l=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(l.length===0)return;l.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const c=l[0][0];s(d=>{const m=(d.messages.get(c)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(c),p.delete(c);const g={messages:f,sessionMemoryState:p},y=new Map(d.pendingAssistantParts);let h=!1;y.forEach((N,x)=>{N.sessionId===c&&(y.delete(x),h=!0)}),h&&(g.pendingAssistantParts=y);const j=new Map(d.sessionCompactionUntil);j.delete(c)&&(g.sessionCompactionUntil=j),Vr(m);const b=On(d.messageStreamStates,m);b!==d.messageStreamStates&&(g.messageStreamStates=b);const v=No(g.messageSessionIndex??d.messageSessionIndex,m);v!==(g.messageSessionIndex??d.messageSessionIndex)&&(g.messageSessionIndex=v);const w=Zs(d.streamingMessageIds,c,null);if(w!==d.streamingMessageIds&&(g.streamingMessageIds=w),d.abortControllers.has(c)){const N=new Map(d.abortControllers);N.delete(c),g.abortControllers=N}return g})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),l=o.sessionMemoryState.get(t);if(!a||!l||l.totalAvailableMessages&&a.length>=l.totalAvailableMessages)return;const c=await ii(t,()=>Ee.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=c.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(us.VIEWPORT_MESSAGES,u),f=c.slice(u-m,u);s(p=>{const g=[...f,...a],y=ai(g),h=new Map(p.messages);h.set(t,y);const j=Math.max(0,y.length-a.length),b=new Map(p.sessionMemoryState);return b.set(t,{...l,viewportAnchor:l.viewportAnchor+j,hasMoreAbove:u-m>0,totalAvailableMessages:c.length}),{messages:h,sessionMemoryState:b}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...l,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 l=o[a];if(l.info.role==="assistant"&&"providerID"in l.info&&"modelID"in l.info)return{providerID:l.info.providerID,modelID:l.info.modelID}}return null}}),{name:"message-store",storage:Is(()=>ds()),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"})),xy=s=>typeof s=="object"&&s!==null,yy=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},by=async(s,r)=>{try{const n=ht.getState().getDirectoryForSession(s);if(n)return Ee.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},ao=Vt()(Jt(Es((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 l=t.permission?.toLowerCase?.()??null;let c=n?.currentAgentContext?.get(o);if(c||(c=n?.sessionAgentSelections?.get(o)??void 0),!c&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(c=f.getState().currentAgentName??void 0)}const d=Ko(c),u=n?.getSessionAgentEditMode?.(o,c)??d;if(u==="full"||u==="allow"&&oy(l)){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 by(t,()=>Ee.replyToPermission(n,o)),o==="reject"&&await St.getState().abortCurrentOperation(t),s(a=>{const c=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,c),{permissions:d}})}}),{name:"permission-store",storage:Is(()=>ds()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!xy(s))return r;const t=yy(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),vy=s=>typeof s=="object"&&s!==null,wy=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},Pc=async(s,r)=>{try{const n=ht.getState().getDirectoryForSession(s);if(n)return Ee.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for question handling:",t)}return r()},vn=Vt()(Jt(Es((s,r)=>({questions:new Map,addQuestion:t=>{const n=t.sessionID;!n||r().questions.get(n)?.some(a=>a.id===t.id)||s(a=>{const l=a.questions.get(n)||[],c=new Map(a.questions);return c.set(n,[...l,t]),{questions:c}})},dismissQuestion:(t,n)=>{!t||!n||s(o=>{const l=(o.questions.get(t)||[]).filter(d=>d.id!==n),c=new Map(o.questions);return c.set(t,l),{questions:c}})},respondToQuestion:async(t,n,o)=>{await Pc(t,()=>Ee.replyToQuestion(n,o)),r().dismissQuestion(t,n)},rejectQuestion:async(t,n)=>{await Pc(t,()=>Ee.rejectQuestion(n)),r().dismissQuestion(t,n)}}),{name:"question-store",storage:Is(()=>ds()),partialize:s=>({questions:Array.from(s.questions.entries())}),merge:(s,r)=>{if(!vy(s))return r;const t=wy(s.questions);return{...r,questions:new Map(t)}}}),{name:"question-store"})),Sl=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
- `),Qn=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},Tc=(s,r,t)=>{if(!r)return null;const n=t(r)?.path;if(typeof n=="string"&&n.trim().length>0)return Qn(n);const o=s.find(a=>a.id===r);return o?Qn(o.directory??null):null},he=Vt()(Jt((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,questions: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)=>wt.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>wt.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>wt.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>ht.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=Ot.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=at.getState(),a=o.getVisibleAgents();let l;if(o.settingsDefaultAgent){const c=a.find(d=>d.name===o.settingsDefaultAgent);c&&(l=c.name)}l||(l=a.find(c=>c.name==="build")?.name||a[0]?.name),l&&o.setAgent(l)}catch{}},closeNewSessionDraft:()=>{const t=ht.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 ht.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=St.getState(),{messages:o,lastUsedProvider:a}=n;let l,c;if(o.forEach((b,v)=>{const w=b.find(N=>N.info?.id===t);w&&!l&&(l=w,c=v)}),!l||l.info.role!=="assistant")return;const d=Sl(l.parts);if(!d.trim())return;const u=ht.getState(),m=Tc(u.sessions,c??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:g,currentAgentName:y}=at.getState(),h=p||a?.providerID,j=g||a?.modelID;!h||!j||await Ee.sendMessage({id:f.id,providerID:h,modelID:j,text:d,prefaceText:ym,agent:y??void 0})},deleteSession:(t,n)=>ht.getState().deleteSession(t,n),deleteSessions:(t,n)=>ht.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>ht.getState().updateSessionTitle(t,n),shareSession:t=>ht.getState().shareSession(t),unshareSession:t=>ht.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=ht.getState().currentSessionId,o=Tc(ht.getState().sessions,t,ht.getState().getWorktreeMetadata),a=Ee.getDirectory()??vt.getState().currentDirectory??null,l=o??a;try{Ee.setDirectory(l??void 0)}catch(c){console.warn("Failed to set OpenCode directory for session switch:",c)}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,us.VIEWPORT_MESSAGES)}if(ht.getState().setCurrentSession(t),t){r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,Cx);const d=r().messages.get(t);if(d&&d.length>0){const u=at.getState().agents;if(u.length>0)try{await wt.getState().analyzeAndSaveExternalSessionChoices(t,u,r().messages)}catch(m){console.warn("Failed to analyze session choices:",m)}}}r().evictLeastRecentlyUsed()},loadMessages:t=>St.getState().loadMessages(t),sendMessage:async(t,n,o,a,l,c,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=v=>{s(w=>{const N=new Map(w.sessionActivityPhase??new Map);return N.set(v,"busy"),{sessionActivityPhase:N}})},g=v=>{s(w=>{const N=new Map(w.sessionActivityPhase??new Map);return N.set(v,"idle"),{sessionActivityPhase:N}})};if(m?.open){const v=await ht.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!v?.id)throw new Error("Failed to create session");const w=at.getState(),N=w.currentAgentName,x=f??N,k=w.currentProviderId,A=w.currentModelId;if(k&&A)try{wt.getState().saveSessionModelSelection(v.id,k,A)}catch{}if(x){try{wt.getState().saveSessionAgentSelection(v.id,x)}catch{}if(k&&A){try{wt.getState().saveAgentModelForSession(v.id,x,k,A)}catch{}if(u!==void 0)try{wt.getState().saveAgentModelVariantForSession(v.id,x,k,A,u)}catch{}}}try{ht.getState().initializeNewOpenChamberSession(v.id,w.agents)}catch{}r().closeNewSessionDraft(),p(v.id);try{return await St.getState().sendMessage(t,n,o,x,v.id,l,c,d,u)}catch(C){throw g(v.id),C}}const y=ht.getState().currentSessionId,h=y?wt.getState().getSessionAgentSelection(y):null,j=at.getState().currentAgentName,b=f||h||j||void 0;if(y&&b){try{wt.getState().saveSessionAgentSelection(y,b)}catch{}if(u!==void 0)try{wt.getState().saveAgentModelVariantForSession(y,b,n,o,u)}catch{}}y&&p(y);try{return await St.getState().sendMessage(t,n,o,b,y||void 0,l,c,d,u)}catch(v){throw y&&g(y),v}},abortCurrentOperation:()=>{const t=ht.getState().currentSessionId;return St.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=ht.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&&St.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const c=ht.getState().currentSessionId||t;return St.getState().addStreamingPart(t,n,o,a,c)},completeStreamingMessage:(t,n)=>St.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>St.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>St.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>St.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:wt.getState().currentAgentContext,sessionAgentSelections:wt.getState().sessionAgentSelections,getSessionAgentEditMode:wt.getState().getSessionAgentEditMode};return ao.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>ao.getState().respondToPermission(t,n,o),addQuestion:t=>vn.getState().addQuestion(t),dismissQuestion:(t,n)=>vn.getState().dismissQuestion(t,n),respondToQuestion:(t,n,o)=>vn.getState().respondToQuestion(t,n,o),rejectQuestion:(t,n)=>vn.getState().rejectQuestion(t,n),clearError:()=>ht.getState().clearError(),getSessionsByDirectory:t=>ht.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>ht.getState().getDirectoryForSession(t),getLastMessageModel:t=>St.getState().getLastMessageModel(t),getCurrentAgent:t=>wt.getState().getCurrentAgent(t),syncMessages:(t,n)=>St.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>ht.getState().applySessionMetadata(t,n),addAttachedFile:t=>qs.getState().addAttachedFile(t),addServerFile:(t,n,o)=>qs.getState().addServerFile(t,n,o),removeAttachedFile:t=>qs.getState().removeAttachedFile(t),clearAttachedFiles:()=>qs.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>St.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>St.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>St.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=ht.getState().currentSessionId;return St.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=ht.getState().currentSessionId;return St.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>St.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>wt.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>wt.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>wt.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>wt.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>wt.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>wt.getState().getAgentModelForSession(t,n),saveAgentModelVariantForSession:(t,n,o,a,l)=>wt.getState().saveAgentModelVariantForSession(t,n,o,a,l),getAgentModelVariantForSession:(t,n,o,a)=>wt.getState().getAgentModelVariantForSession(t,n,o,a),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=St.getState().messages;return wt.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>ht.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>ht.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>ht.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>ht.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>ht.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>ht.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=ht.getState().currentSessionId;if(!o)return null;const a=St.getState().messages;return wt.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=St.getState().messages;return wt.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=St.getState().messages;return wt.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=St.getState().messages.get(t)||[],o=ht.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=St.getState().messages;return wt.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>ht.getState().updateSession(t),removeSessionFromStore:t=>ht.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(St.getState().messages.get(t)||[]).find(m=>m.info.id===n);let l="";a&&a.info.role==="user"&&(l=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const c=await Ee.revertSession(t,n);ht.getState().updateSession(c);const d=St.getState().messages.get(t)||[],u=c.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);St.getState().syncMessages(t,f)}}l&&s({pendingInputText:l})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),l=r().sessions.find(p=>p.id===t);if(o.length===0)return;const c=l?.revert?.messageID;let d;if(c){const p=o.findIndex(g=>g.info.id===c);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 as(async()=>{const{toast:p}=await import("./vendor-.bun-CqCnPJev.js").then(g=>g.cy);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 c=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=c.findIndex(m=>m.info.id===a),u=c[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 as(async()=>{const{toast:g}=await import("./vendor-.bun-CqCnPJev.js").then(y=>y.cy);return{toast:g}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await Ee.unrevertSession(t);await ht.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await as(async()=>{const{toast:p}=await import("./vendor-.bun-CqCnPJev.js").then(g=>g.cy);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(l=>l.id===t);if(a)try{const l=await Ee.forkSession(t,n);if(!l||!l.id){const{toast:f}=await as(async()=>{const{toast:p}=await import("./vendor-.bun-CqCnPJev.js").then(g=>g.cy);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 as(async()=>{const{toast:p}=await import("./vendor-.bun-CqCnPJev.js").then(g=>g.cy);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(l.id),u&&s({pendingInputText:u}),await r().loadMessages(l.id);const{toast:m}=await as(async()=>{const{toast:f}=await import("./vendor-.bun-CqCnPJev.js").then(p=>p.cy);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(l){console.error("Failed to fork session:",l);const{toast:c}=await as(async()=>{const{toast:d}=await import("./vendor-.bun-CqCnPJev.js").then(u=>u.cy);return{toast:d}},__vite__mapDeps([0,1]));c.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"}));ht.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=he.getState().newSessionDraft?.open;he.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})});St.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 l=n[a];if(!l||!l.info)continue;const c=l.info;if(c.role==="user"){const d=c.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=c.time&&typeof c.time.created=="number"?c.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),he.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})});qs.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&he.setState({attachedFiles:s.attachedFiles})});wt.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||he.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});ao.subscribe((s,r)=>{s.permissions!==r.permissions&&he.setState({permissions:s.permissions})});vn.subscribe((s,r)=>{s.questions!==r.questions&&he.setState({questions:s.questions})});vt.subscribe((s,r)=>{const t=Qn(s.currentDirectory??null),n=Qn(r.currentDirectory??null);if(t===n)return;const o=he.getState().newSessionDraft;if(!o?.open)return;const a=Qn(o.directoryOverride);a&&a!==n||he.setState(l=>({newSessionDraft:{...l.newSessionDraft,directoryOverride:t,parentID:null}}))});const jy=he.getState().newSessionDraft?.open;he.setState({sessions:ht.getState().sessions,currentSessionId:jy?null:ht.getState().currentSessionId,lastLoadedDirectory:ht.getState().lastLoadedDirectory,isLoading:ht.getState().isLoading,error:ht.getState().error,webUICreatedSessions:ht.getState().webUICreatedSessions,worktreeMetadata:ht.getState().worktreeMetadata,availableWorktrees:ht.getState().availableWorktrees,availableWorktreesByProject:ht.getState().availableWorktreesByProject,messages:St.getState().messages,sessionMemoryState:St.getState().sessionMemoryState,messageStreamStates:St.getState().messageStreamStates,sessionCompactionUntil:St.getState().sessionCompactionUntil,sessionAbortFlags:St.getState().sessionAbortFlags,streamingMessageIds:St.getState().streamingMessageIds,abortControllers:St.getState().abortControllers,lastUsedProvider:St.getState().lastUsedProvider,isSyncing:St.getState().isSyncing,permissions:ao.getState().permissions,questions:vn.getState().questions,attachedFiles:qs.getState().attachedFiles,sessionModelSelections:wt.getState().sessionModelSelections,sessionAgentSelections:wt.getState().sessionAgentSelections,sessionAgentModelSelections:wt.getState().sessionAgentModelSelections,currentAgentContext:wt.getState().currentAgentContext,sessionContextUsage:wt.getState().sessionContextUsage,sessionAgentEditModes:wt.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=he);const kl=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,l]=i.useState(!1),[c,d]=i.useState({length:0,offset:0}),[u,m]=i.useState({length:0,offset:0}),f=i.useRef(null),p=i.useRef(null),g=i.useRef(!1),y=i.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),h=i.useRef(null),j=i.useCallback(()=>{const M=s.current;if(!M)return;const{scrollHeight:S,clientHeight:D,scrollTop:E,scrollWidth:T,clientWidth:I,scrollLeft:P}=M,O=8;if(S>D){const U=Math.max(D-O*2,0),Q=D/S*U,W=Math.max(r,Math.min(U,Q)),L=Math.max(U-W,0),H=Math.max(S-D,1),q=E/H*L;d({length:W,offset:q})}else d({length:0,offset:0});if(!o&&T>I){const U=Math.max(I-O*2,0),Q=I/T*U,W=Math.max(r,Math.min(U,Q)),L=Math.max(U-W,0),H=Math.max(T-I,1),q=P/H*L;m({length:W,offset:q})}else m({length:0,offset:0})},[s,r,o]),b=i.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>l(!1),t)},[t]),v=i.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{j(),l(!0),b()})},[b,j]);i.useEffect(()=>{const M=s.current;if(!M)return;j(),l(!0),b(),M.addEventListener("scroll",v,{passive:!0});const S=typeof ResizeObserver<"u"?new ResizeObserver(()=>j()):null;S?.observe(M);const D=typeof MutationObserver<"u"?new MutationObserver(()=>j()):null;return D?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",v),S?.disconnect(),D?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,v,b,j]);const w=(M,S)=>{const D=s.current;D&&(g.current=!0,y.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:D.scrollTop,scrollLeft:D.scrollLeft},h.current=S,l(!0),f.current&&clearTimeout(f.current),M.currentTarget.setPointerCapture(M.pointerId))},N=M=>{if(!g.current)return;const S=s.current;if(!S)return;const D=h.current;if(D==="vertical"){const{pointerY:E,scrollTop:T}=y.current,I=M.clientY-E,P=S.clientHeight,O=Math.max(P-c.length,1),U=Math.max(S.scrollHeight-S.clientHeight,1),Q=I/O*U;S.scrollTop=T+Q}else if(D==="horizontal"){const{pointerX:E,scrollLeft:T}=y.current,I=M.clientX-E,P=S.clientWidth,O=Math.max(P-u.length,1),U=Math.max(S.scrollWidth-S.clientWidth,1),Q=I/O*U;S.scrollLeft=T+Q}},x=M=>{g.current&&(g.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),b())},k=c.length>0,A=u.length>0;if(!k&&!A)return null;const C=8;return e.jsxs("div",{className:_("overlay-scrollbar",n),"aria-hidden":"true",style:{opacity:a?1:0},children:[k&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--vertical",style:{height:`${c.length}px`,top:`${C+c.offset}px`,right:`${C/2}px`},onPointerDown:M=>w(M,"vertical"),onPointerMove:N,onPointerUp:x,onPointerCancel:x}),A&&e.jsx("div",{className:"overlay-scrollbar__thumb overlay-scrollbar__thumb--horizontal",style:{width:`${u.length}px`,left:`${C+u.offset}px`,bottom:`${C/2}px`},onPointerDown:M=>w(M,"horizontal"),onPointerMove:N,onPointerUp:x,onPointerCancel:x})]})},gt=i.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:l="div",scrollbarClassName:c,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const g=i.useRef(null);return i.useImperativeHandle(p,()=>g.current,[]),e.jsxs("div",{className:_("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(l,{ref:g,className:_("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(kl,{containerRef:g,minThumbSize:o,hideDelayMs:a,className:c,disableHorizontal:d})]})});gt.displayName="ScrollableOverlay";const Fc="mobile-overlay-root",Sy=()=>{if(typeof document>"u")return null;let s=document.getElementById(Fc);return s||(s=document.createElement("div"),s.id=Fc,document.body.appendChild(s)),s},ws=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:l,renderHeader:c})=>{const d=i.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=Sy()),i.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=l??"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:_("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 c?c(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(gt,{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 bu.createPortal(m,d.current)},Vi=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[l,c]=i.useState(!1),d=i.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=i.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{c(!0)},500)},[]),y=i.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);i.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const h=e.jsxs("div",{className:_("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?y:void 0,children:[e.jsx(tp,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:_(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[h,e.jsx(ws,{open:l,onClose:()=>c(!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:_("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:h}),e.jsx(lt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(j=>e.jsx("p",{className:"typography-micro leading-tight",children:j},j))})})]})},Bn={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},vm=(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 li(){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,l=typeof navigator<"u"?navigator.maxTouchPoints??0:0,c=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||l>0,u=s>Bn.md&&s<=Bn.lg,m=s<=Bn.md;let f=d&&m,p=d&&!f&&u,g=!d||s>Bn.lg,y="desktop";c?(f=!1,p=!1,g=!0,y="desktop"):f?y="mobile":p?y="tablet":(g=!0,y="desktop"),vm(c,y,d);let h="xs";for(const[j,b]of Object.entries(Bn))s>=b&&(h=j);return{isMobile:f,isTablet:p,isDesktop:g,deviceType:y,screenWidth:s,breakpoint:h,hasTouchInput:d}}function $t(){const[s,r]=i.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:li());return i.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(li())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),i.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(li())},a=[],l=c=>{c&&(typeof c.addEventListener=="function"?(c.addEventListener("change",o),a.push(()=>c.removeEventListener("change",o))):typeof c.addListener=="function"&&(c.addListener(o),a.push(()=>c.removeListener(o))))};return l(t),l(n),()=>{a.forEach(c=>c())}},[]),i.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,l=o?.matches??!1,c=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=l||c||d>0;vm(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const Co=5e3,ky=1e4,Ny=5e3,Cy=1e4,My=25,Dy=4,Rc=15e3,er=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),Ay=(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},Ey=(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!!Ay(s.diffStats,r.diffStats)},Iy=(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])),l=new Map(o.map(f=>[f.path,f])),c=new Set([...a.keys(),...l.keys()]);for(const f of c){const p=a.get(f),g=l.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},Gt=Vt()(Jt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:Co,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,er()),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:l}=r();let c=l.get(t);c||(c=er()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(l);return f.set(t,{...c,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(Ey(c.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??er(),g=Iy(p.status,m),y=new Set((p.status?.files??[]).map(v=>v.path)),h=new Set((m.files??[]).map(v=>v.path)),j=new Map(p.diffCache);for(const v of y)h.has(v)||j.delete(v);for(const v of g)j.delete(v);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)??er();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),l=a.get(t)??er();a.set(t,{...l,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(),l=a.get(t),c=o??l?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:c}),u=new Map(r().directories),m=u.get(t)??er();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:c}),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),l=a.get(t)??er();a.set(t,{...l,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 l=a.get(t);if(!l){l=er();const f=new Map(a);f.set(t,l),s({directories:f})}const{force:c=!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);(c||m>Cy||!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),l=a.get(t)??er(),c=new Map(l.diffCache);c.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...l,diffCache:c}),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 c=o.status.files.filter(v=>!o.diffCache.has(v.path)).slice(0,My);if(c.length===0)return;let d=0;const u=[],m=()=>{const v=d;return d+=1,v<c.length?c[v]:null},f=async v=>{const w=n.getGitFileDiff(t,{path:v}),N=new Promise((k,A)=>{setTimeout(()=>A(new Error(`Timed out after ${Rc}ms`)),Rc)}),x=await Promise.race([w,N]);return{path:v,diff:{original:x.original??"",modified:x.modified??""}}},p=async()=>{for(;;){const v=m();if(!v)return;try{u.push(await f(v.path))}catch{}}},g=Math.min(Dy,c.length);await Promise.allSettled(Array.from({length:g},()=>p()));const y=new Map(r().directories),h=y.get(t);if(!h)return;const j=new Map(h.diffCache),b=Date.now();u.forEach(v=>{j.set(v.path,{...v.diff,fetchedAt:b})}),y.set(t,{...h,diffCache:j}),s({directories:y})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??er();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:c}=r();if(!c){s({pollIntervalId:o()});return}if(await r().fetchStatus(c,t,{silent:!0}))await r().fetchLog(c,t),r().fetchAllDiffs(c,t),s({currentPollInterval:Co});else{const m=Math.min(a+Ny,ky);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:Co})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:Co}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),wm=s=>Gt(r=>s?r.directories.get(s)?.status??null:null),jm=s=>Gt(r=>s?r.directories.get(s)?.branches??null:null),Py=s=>Gt(r=>s?r.directories.get(s)?.log??null:null),Ty=s=>Gt(r=>s?r.directories.get(s)?.identity??null:null),Nl=s=>Gt(r=>s?r.directories.get(s)?.isGitRepo??null:null),Fy=s=>Gt(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function qt({...s}){return e.jsx(sp,{"data-slot":"dropdown-menu",...s})}function Kt({...s}){return e.jsx(rp,{"data-slot":"dropdown-menu-trigger",...s})}function Qt({className:s,sideOffset:r=4,...t}){return e.jsx(np,{children:e.jsx(op,{"data-slot":"dropdown-menu-content",sideOffset:r,className:_("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 Et({className:s,inset:r,variant:t="default",...n}){return e.jsx(up,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:_("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 ua({...s}){return e.jsx(ip,{"data-slot":"dropdown-menu-radio-group",...s})}function ma({className:s,children:r,...t}){return e.jsxs(lp,{"data-slot":"dropdown-menu-radio-item",className:_("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(cp,{children:e.jsx(_t,{className:"size-3"})})}),r]})}function Ir({className:s,inset:r,...t}){return e.jsx(ap,{"data-slot":"dropdown-menu-label","data-inset":r,className:_("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function js({className:s,...r}){return e.jsx(dp,{"data-slot":"dropdown-menu-separator",className:_("bg-border -mx-1 my-0.5 h-px",s),...r})}const Ry=mp("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 Ie({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?vu:"button";return e.jsx(a,{"data-slot":"button",className:_(Ry({variant:r,size:t,className:s})),...o})}const po=fp,Ta=({className:s,...r})=>e.jsx(pp,{className:_("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}),ho=({className:s,...r})=>e.jsx(hp,{className:_("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),_y={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"}]},question:{displayName:"Question",category:"ai",outputLanguage:"text",inputFields:[{key:"questions",label:"Questions",type:"code",language:"json"}]}};function Cl(s){return _y[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Oy(s,r,t){const n=Cl(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=fr(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 fr(s){const r=s.split(".").pop()?.toLowerCase(),t=s.split("/").pop()?.toLowerCase()||"",n={dockerfile:"dockerfile",makefile:"makefile",gnumakefile:"makefile","cmakelists.txt":"cmake",gemfile:"ruby",rakefile:"ruby",podfile:"ruby",vagrantfile:"ruby",guardfile:"ruby",brewfile:"ruby",fastfile:"ruby",appfile:"ruby",matchfile:"ruby",pluginfile:"ruby",scanfile:"ruby",snapfile:"ruby",".gitignore":"text",".gitattributes":"text",".gitmodules":"ini",".editorconfig":"ini",".npmrc":"ini",".yarnrc":"yaml",".prettierrc":"json",".eslintrc":"json",".babelrc":"json",".browserslistrc":"text","tsconfig.json":"jsonc","jsconfig.json":"jsonc",".env":"bash",".env.local":"bash",".env.development":"bash",".env.production":"bash",".env.test":"bash",procfile:"yaml",codeowners:"text","package-lock.json":"json","composer.lock":"json","yarn.lock":"yaml","pnpm-lock.yaml":"yaml","cargo.lock":"toml","poetry.lock":"toml","gemfile.lock":"ruby","pubspec.lock":"yaml","packages.lock.json":"json","bun.lockb":"text","bun.lock":"json"};return n[t]?n[t]:{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",mts:"typescript",cts:"typescript",html:"html",htm:"html",xhtml:"html",vue:"html",svelte:"html",astro:"html",ejs:"html",hbs:"handlebars",handlebars:"handlebars",mustache:"handlebars",njk:"twig",nunjucks:"twig",twig:"twig",liquid:"liquid",css:"css",scss:"scss",sass:"sass",less:"less",styl:"stylus",stylus:"stylus",pcss:"css",postcss:"css",json:"json",jsonc:"json",json5:"json",jsonl:"json",ndjson:"json",geojson:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",xsl:"xml",xslt:"xml",xsd:"xml",dtd:"xml",plist:"xml",svg:"xml",rss:"xml",atom:"xml",xaml:"xml",csproj:"xml",vbproj:"xml",fsproj:"xml",props:"xml",targets:"xml",nuspec:"xml",resx:"xml",ini:"ini",cfg:"ini",conf:"ini",config:"ini",properties:"properties",env:"bash",csv:"text",tsv:"text",py:"python",pyw:"python",pyx:"python",pxd:"python",pxi:"python",pyi:"python",gyp:"python",gypi:"python",bzl:"python",rb:"ruby",erb:"erb",rake:"ruby",gemspec:"ruby",ru:"ruby",podspec:"ruby",thor:"ruby",jbuilder:"ruby",rabl:"ruby",builder:"ruby",php:"php",phtml:"php",php3:"php",php4:"php",php5:"php",php7:"php",phps:"php",inc:"php","blade.php":"php",java:"java",kt:"kotlin",kts:"kotlin",scala:"scala",sc:"scala",groovy:"groovy",gradle:"groovy",gvy:"groovy",gy:"groovy",gsh:"groovy",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp","c++":"cpp",hpp:"cpp",hxx:"cpp",hh:"cpp","h++":"cpp",ino:"cpp",m:"objectivec",mm:"objectivec",cs:"csharp",csx:"csharp",cake:"csharp",fs:"fsharp",fsx:"fsharp",fsi:"fsharp",vb:"vbnet",go:"go",mod:"go",sum:"text",rs:"rust",swift:"swift",dart:"dart",lua:"lua",pl:"perl",pm:"perl",pod:"perl",t:"perl",r:"r",R:"r",rmd:"markdown",rnw:"r",jl:"julia",hs:"haskell",lhs:"haskell",ex:"elixir",exs:"elixir",eex:"elixir",heex:"elixir",leex:"elixir",erl:"erlang",hrl:"erlang",clj:"clojure",cljs:"clojure",cljc:"clojure",edn:"clojure",lisp:"lisp",cl:"lisp",el:"lisp",scm:"scheme",ss:"scheme",rkt:"scheme",ml:"ocaml",mli:"ocaml",re:"reason",rei:"reason",nim:"nim",nims:"nim",nimble:"nim",zig:"zig",v:"v",vsh:"v",cr:"crystal",d:"d",di:"d",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ksh:"bash",csh:"bash",tcsh:"bash",ps1:"powershell",psm1:"powershell",psd1:"powershell",bat:"batch",cmd:"batch",sql:"sql",psql:"sql",plsql:"sql",mysql:"sql",pgsql:"sql",sqlite:"sql",graphql:"graphql",gql:"graphql",sol:"solidity",asm:"nasm",s:"nasm",S:"nasm",nix:"nix",tf:"hcl",tfvars:"hcl",hcl:"hcl",dockerignore:"text",pp:"puppet",tex:"latex",latex:"latex",sty:"latex",cls:"latex",bib:"bibtex",bst:"bibtex",md:"markdown",mdx:"markdown",markdown:"markdown",mdown:"markdown",mkd:"markdown",rst:"text",adoc:"asciidoc",asciidoc:"asciidoc",org:"text",txt:"text",text:"text",rtf:"text",vim:"vim",vimrc:"vim",mk:"makefile",cmake:"cmake",diff:"diff",patch:"diff",prisma:"prisma",proto:"protobuf",thrift:"thrift",wat:"wasm",wast:"wasm",glsl:"glsl",vert:"glsl",frag:"glsl",geom:"glsl",comp:"glsl",hlsl:"hlsl",fx:"hlsl",cg:"cg",shader:"glsl",htaccess:"apacheconf",nginx:"nginx",kubeconfig:"yaml",ansible:"yaml"}[r||""]||null}const $y=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function io(s){const r=s.split(".").pop()?.toLowerCase();return $y.includes(r||"")}function Gi(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 Ly(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 l=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let c=a;return typeof a=="object"?c=JSON.stringify(a,null,2):typeof a=="boolean"&&(c=a?"Yes":"No"),`${l}: ${c}`}).join(`
12
- `):String(s)}const Ml=i.createContext(null),kr=()=>{const s=i.useContext(Ml);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},Sm=s=>{const r=kr();return s(r)},By=()=>Sm(s=>s.runtime.isDesktop),km=()=>Sm(s=>s.runtime.isVSCode),Nm=({mode:s,onModeChange:r,className:t})=>{const n=i.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(Ie,{size:"sm",variant:"ghost",className:_("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(gp,{className:"h-3 w-3"}):e.jsx(xp,{className:"h-3 w-3"})})},Dl=Ae.createContext(void 0);function Wr(){const s=Ae.useContext(Dl);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function Fa(){return Ae.useContext(Dl)}const zy="Flexoki",Wy="dark",Hy={"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"},Uy=[{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"}}],Vy={name:zy,type:Wy,colors:Hy,tokenColors:Uy},Gy="Flexoki",qy="light",Ky={"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"},Qy=[{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"}}],Yy={name:Gy,type:qy,colors:Ky,tokenColors:Qy},Al="flexoki-dark",El="flexoki-light",Xy=Vy,Jy=Yy;function Cm(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 Mm(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 Il=Mm(Xy,Al,"dark"),Pl=Mm(Jy,El,"light");Cm(Il,Al);Cm(Pl,El);const An={dark:Al,light:El},_c=[Pl,Il];let Oc=!1;function Dm(){Oc||(Ql(An.dark,async()=>Il),Ql(An.light,async()=>Pl),Oc=!0)}const Ss=Ae.forwardRef(({className:s,...r},t)=>e.jsx(gt,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:_("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),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...r}));Ss.displayName="Textarea";const Zy=`
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
-
34
- /* Mobile touch selection support */
35
- [data-line-number] {
36
- touch-action: manipulation;
37
- -webkit-tap-highlight-color: transparent;
38
- cursor: pointer;
39
- }
40
-
41
- /* Ensure interactive line numbers work on touch */
42
- pre[data-interactive-line-numbers] [data-line-number] {
43
- touch-action: manipulation;
44
- }
45
- /* Reduce hunk separator height */
46
- [data-separator-content] {
47
- height: 24px !important;
48
- }
49
- [data-expand-button] {
50
- height: 24px !important;
51
- width: 24px !important;
52
- }
53
- [data-separator-multi-button] {
54
- row-gap: 0 !important;
55
- }
56
- [data-expand-up] {
57
- height: 12px !important;
58
- min-height: 12px !important;
59
- max-height: 12px !important;
60
- margin: 0 !important;
61
- margin-top: 3px !important;
62
- padding: 0 !important;
63
- border-radius: 4px 4px 0 0 !important;
64
- }
65
- [data-expand-down] {
66
- height: 12px !important;
67
- min-height: 12px !important;
68
- max-height: 12px !important;
69
- margin: 0 !important;
70
- margin-top: -3px !important;
71
- padding: 0 !important;
72
- border-radius: 0 0 4px 4px !important;
73
- }
74
- `;function eb(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 tb=(s,r,t)=>{const a=(t.side==="deletions"?s:r).split(`
75
- `),l=Math.max(1,t.start),c=Math.min(a.length,t.end);return l>c?"":a.slice(l-1,c).join(`
76
- `)},qi=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1,layout:l="fill"})=>{const{isMobile:c}=$t(),{inputBarOffset:d,isKeyboardOpen:u}=$e(),f=Fa()?.currentTheme?.metadata?.variant==="dark",p=$e(L=>L.setActiveMainTab),[g,y]=Ae.useState(null),[h,j]=Ae.useState(""),b=Ae.useCallback(()=>{if(c)return"50%";const L=document.querySelector("main.flex-1");if(L){const H=L.getBoundingClientRect();return`${H.left+H.width/2}px`}return"50%"},[c]),[v,w]=Ae.useState(b),N=he(L=>L.sendMessage),x=he(L=>L.currentSessionId),{currentProviderId:k,currentModelId:A,currentAgentName:C,currentVariant:M}=at(),S=wt(L=>L.getSessionAgentSelection),D=wt(L=>L.getAgentModelForSession),E=wt(L=>L.getAgentModelVariantForSession);Ae.useEffect(()=>{if(c)return;const L=()=>{w(b())};return window.addEventListener("resize",L),()=>window.removeEventListener("resize",L)},[c,b]);const T=Ae.useCallback(L=>{if(c&&L&&g&&L.start===L.end){const H=L.start,q=g.start,X=g.end,Y=Math.min(q,X,H),re=Math.max(q,X,H);if(H<q||H>X){y({...L,start:Y,end:re});return}}y(L),L||j("")},[c,g]);Ae.useEffect(()=>{if(!g)return;const L=q=>{const X=q.target;if(document.querySelector("[data-comment-ui]")?.contains(X)||X.closest("[data-sonner-toast]")||X.closest("[data-sonner-toaster]"))return;q.composedPath().some(ae=>ae instanceof HTMLElement?ae.hasAttribute("data-line-number")||ae.closest?.("[data-line-number]"):!1)||(y(null),j(""))},H=setTimeout(()=>{document.addEventListener("click",L)},100);return()=>{clearTimeout(H),document.removeEventListener("click",L)}},[g]);const I=Ae.useCallback(async()=>{if(!g||!h.trim())return;if(!x){te.error("Select a session to send comment");return}const L=S(x)||C,H=L?D(x,L):null,q=H?.providerId||k,X=H?.modelId||A;if(!q||!X){te.error("Select a model to send comment");return}const Y=L&&q&&X?E(x,L,q,X)??M:M,re=tb(s,r,g),K=g.start,ae=g.end,F=g.side==="deletions"?"original":"modified",$=`Comment on \`${n}\` lines ${K}-${ae} (${F}):
77
- \`\`\`${t}
78
- ${re}
79
- \`\`\`
80
-
81
- ${h}`;j(""),y(null),p("chat");try{await N($,q,X,L,void 0,void 0,void 0,Y)}catch(R){console.error("Failed to send comment",R)}},[g,h,s,r,n,t,N,x,k,A,C,M,p,S,D,E]);Dm();const P=Ae.useRef(null),O=Ae.useMemo(()=>{const L=eb(n,s,r);if(P.current?.key===L)return P.current.fileDiff;const H={name:n,contents:s,cacheKey:`old-${L}`},q={name:n,contents:r,cacheKey:`new-${L}`},X=Fi(H,q);return P.current={key:L,fileDiff:X},X},[n,s,r,t]),U=Ae.useMemo(()=>({theme:{dark:An.dark,light:An.light},themeType:f?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!0,enableHoverUtility:!1,onLineSelected:T,unsafeCSS:Zy}),[f,o,a,T]);if(typeof window>"u")return null;const W=g?e.jsx("div",{className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-sidebar flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Ss,{value:h,onChange:L=>{j(L.target.value);const H=L.target;H.style.height="auto";const X=20*5+8;H.style.height=`${Math.min(H.scrollHeight,X)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-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 dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!c,rows:1,onKeyDown:L=>{L.key==="Enter"&&(L.metaKey||L.ctrlKey)&&(L.preventDefault(),I()),L.key==="Escape"&&(L.preventDefault(),y(null),j(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.split("/").pop(),":",g.start,"-",g.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!c&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Yt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:L=>{h.trim()&&(L.preventDefault(),I())},onClick:()=>{c||I()},disabled:!h.trim(),className:_("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",h.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Sa,{className:"h-[18px] w-[18px]"})})]})]})]})}):null;return l==="fill"?e.jsxs("div",{className:_("flex flex-col relative","size-full"),style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":void 0},children:[e.jsx("div",{className:"flex-1 relative min-h-0",children:e.jsx(gt,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,fillContainer:!0,children:e.jsx(Yl,{fileDiff:O,options:U,selectedLines:g})})}),g&&e.jsx("div",{className:_("pointer-events-auto relative pb-2 transition-none z-50 flex justify-center",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true",children:W})]}):e.jsxs("div",{className:_("relative","w-full"),children:[e.jsx(gt,{outerClassName:"pierre-diff-wrapper w-full",disableHorizontal:!1,fillContainer:!1,children:e.jsx(Yl,{fileDiff:O,options:U,selectedLines:g})}),g&&bu.createPortal(e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col justify-end items-start pointer-events-none transition-none transform-gpu",style:{paddingBottom:c?"var(--oc-keyboard-inset, 0px)":"0px",isolation:"isolate"},children:e.jsx("div",{className:_("pointer-events-auto relative pb-2 transition-none",c&&u?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginLeft:v,transform:"translateX(-50%)",marginBottom:c&&!u&&d>0?`${d}px`:"16px"},"data-keyboard-avoid":"true","data-comment-ui":"true",children:W})}),document.body)]})},sb=1100,Am=15e3,Em={"?":{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"}},rb=Em.M,Qo=[{value:"single",label:"Single file",description:"Show one file at a time"},{value:"stacked",label:"All files",description:"Stack all modified files together"}],nb=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"},Im=s=>{const r=nb(s);return Em[r]??rb},ob=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},fa=(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]})},ab=i.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o,showModeSelector:a=!1,mode:l,onModeChange:c})=>{const d=i.useCallback(u=>{if(!o)return u;const m=u.lastIndexOf("/");return m>=0?u.slice(m+1):u},[o]);return s.length===0?null:e.jsxs(qt,{children:[e.jsx(Kt,{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:d(t.path)}),fa(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsxs(Qt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:[a&&l&&c?e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"typography-meta text-muted-foreground",children:"View mode"}),e.jsx(ua,{value:l,onValueChange:u=>c(u),children:Qo.map(u=>e.jsx(ma,{value:u.value,className:"items-center",children:e.jsx("span",{className:"typography-meta text-foreground",children:u.label})},u.value))}),e.jsx(js,{})]}):null,e.jsx(ua,{value:r??"",onValueChange:n,children:s.map(u=>e.jsx(ma,{value:u.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:d(u.path)}),e.jsx("span",{className:"ml-auto",children:fa(u.insertions,u.deletions)})]})},u.path))})]})]})}),ib=i.memo(({mode:s,onModeChange:r})=>{const t=Qo.find(n=>n.value===s)??Qo[0];return e.jsxs(qt,{children:[e.jsx(Kt,{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:[e.jsx("span",{className:"min-w-0 truncate typography-meta",children:t.label}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsx(Qt,{className:"min-w-[220px]",children:e.jsx(ua,{value:s,onValueChange:n=>r(n),children:Qo.map(n=>e.jsx(ma,{value:n.value,children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"typography-meta text-foreground",children:n.label}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:n.description})]})},n.value))})})]})}),lb=i.memo(({changedFiles:s,selectedFile:r,onSelectFile:t})=>s.length===0?null:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"px-2 py-2",children:e.jsx("ul",{className:"flex flex-col gap-1",children:s.map(n=>{const o=Im(n),a=r===n.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>t(n.path),className:_("flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left transition-colors",a?"bg-accent/70 text-foreground":"text-muted-foreground hover:bg-accent/40 hover:text-foreground"),children:[e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:o.color},title:o.description,"aria-label":o.description,children:o.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:n.path,children:n.path}),fa(n.insertions,n.deletions)]})},n.path)})})})),cb=i.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 l=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",c=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:l,children:[o&&e.jsxs("div",{className:c,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:c,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"}})]})]})})}),db=i.memo(({filePath:s,diff:r,renderSideBySide:t})=>{const n=r.original.length>0,o=r.modified.length>0,a=t?"flex flex-row gap-6 items-start justify-center":"flex flex-col gap-4 items-center",l=t?"flex flex-col items-center gap-2 flex-1 min-w-0":"flex flex-col items-center gap-2";return e.jsx("div",{className:"w-full overflow-auto p-4",style:{contain:"layout"},children:e.jsxs("div",{className:a,children:[n&&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:t?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:n?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:t?"max-w-full max-h-[70vh] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),ub=i.memo(({filePath:s,diff:r,renderSideBySide:t,wrapLines:n})=>{const o=i.useMemo(()=>fr(s)||"text",[s]);return io(s)?e.jsx(db,{filePath:s,diff:r,renderSideBySide:t}):e.jsx("div",{className:"w-full",style:{contain:"layout"},children:e.jsx(qi,{original:r.original,modified:r.modified,language:o,fileName:s,renderSideBySide:t,wrapLines:n,layout:"inline"})})}),mb=i.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=i.useMemo(()=>fr(s)||"text",[s]);return io(s)?e.jsx(cb,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(qi,{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(qi,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),fb=i.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Gt(i.useCallback(c=>c.directories.get(s)?.diffCache.get(r)??null,[s,r])),l=i.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return l?e.jsx(mb,{filePath:r,diff:l,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),pb=i.memo(({directory:s,file:r,layout:t,wrapLines:n,scrollRootRef:o,isSelected:a,onSelect:l,registerSectionRef:c})=>{const{git:d}=kr(),u=Gt(i.useCallback(I=>I.directories.get(s)?.diffCache.get(r.path)??null,[s,r.path])),m=Gt(I=>I.setDiff),f=$e(I=>I.setDiffFileLayout),[p,g]=i.useState(!0),[y,h]=i.useState(!1),[j,b]=i.useState(0),[v,w]=i.useState(null),[N,x]=i.useState(!1),k=i.useRef(null),A=i.useRef(null),C=i.useMemo(()=>Im(r),[r]),M=t==="side-by-side",S=i.useMemo(()=>u?{original:u.original,modified:u.modified}:null,[u]),D=i.useCallback(I=>{A.current=I,c(r.path,I)},[r.path,c]),E=i.useCallback(I=>{g(I),I&&h(!0)},[]),T=i.useCallback(()=>{l(r.path)},[r.path,l]);return i.useEffect(()=>{if(!p||y)return;const I=A.current;if(!I)return;if(!o.current||typeof IntersectionObserver>"u"){h(!0);return}const P=new IntersectionObserver(O=>{O.some(U=>U.isIntersecting)&&(h(!0),P.disconnect())},{root:o.current,rootMargin:"200px 0px",threshold:.1});return P.observe(I),()=>P.disconnect()},[y,p,o]),i.useEffect(()=>{if(!p||!y)return;if(!s||S){k.current=null,x(!1);return}const I=`${s}::${r.path}::${j}`;if(k.current===I)return;k.current=I,w(null),x(!0);let P=!1;return(async()=>{try{const O=d.getGitFileDiff(s,{path:r.path}),U=Am,Q=new Promise((L,H)=>{setTimeout(()=>H(new Error(`Timed out after ${U}ms`)),U)}),W=await Promise.race([O,Q]);if(P)return;m(s,r.path,{original:W.original??"",modified:W.modified??""}),x(!1)}catch(O){if(P)return;const U=O instanceof Error?O.message:String(O);w(U),x(!1)}})(),()=>{P=!0,k.current===I&&(k.current=null)}},[s,S,j,r.path,d,y,p,m]),e.jsx("div",{ref:D,className:"scroll-mt-4",children:e.jsxs(po,{open:p,onOpenChange:E,className:"group/collapsible",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-background",children:e.jsxs(Ta,{onClick:T,className:_("relative flex w-full items-center gap-2 px-3 py-1.5 transition-colors rounded-t-xl border border-border/60 overflow-hidden","bg-background hover:bg-background",p?"rounded-b-none":"rounded-b-xl",a?"text-primary":"text-muted-foreground hover:text-foreground"),children:[e.jsx("div",{className:_("absolute inset-0 pointer-events-none transition-colors",a?"bg-primary/10":"group-hover:bg-accent/40")}),e.jsxs("div",{className:"relative flex min-w-0 flex-1 items-center gap-2",children:[e.jsx("span",{className:"flex size-5 items-center justify-center opacity-70 group-hover:opacity-100 transition-opacity",children:p?e.jsx(Ft,{className:"size-4"}):e.jsx(Rs,{className:"size-4"})}),e.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:C.color},title:C.description,"aria-label":C.description,children:C.code}),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label",style:{direction:"rtl",textAlign:"left"},title:r.path,children:r.path})]}),e.jsxs("div",{className:"relative flex items-center gap-2",children:[fa(r.insertions,r.deletions),e.jsx(Nm,{mode:M?"side-by-side":"unified",onModeChange:I=>{const P=I==="side-by-side"?"side-by-side":"inline";f(r.path,P)},className:"opacity-70"})]})]})}),e.jsx(ho,{children:e.jsxs("div",{className:"relative border border-t-0 border-border/60 bg-background rounded-b-xl overflow-hidden",children:[v?e.jsxs("div",{className:"flex flex-col items-center gap-2 px-4 py-8 text-sm text-muted-foreground",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:v}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>b(I=>I+1),children:"Retry"})]}):null,N&&!S&&!v?e.jsxs("div",{className:"flex items-center justify-center gap-2 px-4 py-8 text-sm text-muted-foreground",children:[e.jsx(rs,{size:16,className:"animate-spin"}),"Loading diff…"]}):null,S?e.jsx(ub,{filePath:r.path,diff:S,renderSideBySide:M,wrapLines:n}):null]})})]})})}),hb=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=vt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??void 0},gb=()=>{const{git:s}=kr(),r=hb(),{screenWidth:t,isMobile:n}=$t(),o=Nl(r??null),a=wm(r??null),l=Gt(oe=>oe.isLoadingStatus),{setActiveDirectory:c,fetchStatus:d,setDiff:u}=Gt(),[m,f]=i.useState(null),[p,g]=i.useState(0),[y,h]=i.useState(null),j=i.useRef(null),b=$e(oe=>oe.pendingDiffFile),v=$e(oe=>oe.setPendingDiffFile),w=$e(oe=>oe.diffLayoutPreference),N=$e(oe=>oe.diffFileLayout),x=$e(oe=>oe.setDiffFileLayout),k=$e(oe=>oe.diffWrapLines),A=$e(oe=>oe.setDiffWrapLines),C=$e(oe=>oe.diffViewMode),M=$e(oe=>oe.setDiffViewMode),S=n||k,D=C==="stacked",E=n||t<=768,T=!E&&t>=1024,I=i.useRef(null),P=i.useRef(new Map),O=i.useRef(null),U=i.useMemo(()=>{if(!a?.files)return[];const oe=a.diffStats??{};return a.files.map(me=>({...me,insertions:oe[me.path]?.insertions??0,deletions:oe[me.path]?.deletions??0,isNew:ob(me)})).sort((me,Ne)=>me.path.localeCompare(Ne.path))},[a]),Q=i.useMemo(()=>m?U.find(oe=>oe.path===m)??null:null,[U,m]),W=i.useCallback(oe=>{const me=N[oe.path];if(me)return me;if(w==="inline")return"inline";if(w==="side-by-side")return"side-by-side";const Ne=t<sb;return oe.isNew||Ne?"inline":"side-by-side"},[N,w,t]),L=i.useMemo(()=>Q?W(Q):null,[W,Q]);i.useEffect(()=>{r&&(c(r),Gt.getState().directories.get(r)?.status||d(r,s))},[r,c,d,s]),i.useEffect(()=>{b&&(f(b),v(null),D&&(O.current=b))},[D,b,v]),i.useEffect(()=>{!m&&!b&&U.length>0&&f(U[0].path)},[U,m,b]),i.useEffect(()=>{if(!D){O.current=null;return}const oe=O.current;if(!oe)return;const me=P.current.get(oe);me&&(me.scrollIntoView({behavior:"smooth",block:"start"}),O.current=null)},[U,D]),i.useEffect(()=>{m&&U.length>0&&(U.some(me=>me.path===m)||f(U[0]?.path??null))},[U,m]);const H=i.useCallback((oe,me)=>{const Ne=P.current;me?Ne.set(oe,me):Ne.delete(oe)},[]),q=i.useCallback((oe,me="smooth")=>{const Ne=P.current.get(oe);return Ne?(Ne.scrollIntoView({behavior:me,block:"start"}),!0):!1},[]),X=i.useCallback(oe=>{f(oe)},[]),Y=i.useCallback(oe=>{f(oe),D&&!q(oe)&&(O.current=oe)},[D,q]),re=i.useCallback(oe=>{M(oe),oe==="stacked"&&m&&!q(m,"auto")&&(O.current=m)},[q,m,M]),K=i.useCallback(oe=>{const me=oe==="side-by-side"?"side-by-side":"inline";if(D){U.forEach(Ne=>{x(Ne.path,me)});return}Q&&x(Q.path,me)},[U,D,Q,x]),ae=(L??"side-by-side")==="side-by-side",F=!D||!T,$=Gt(i.useCallback(oe=>!r||!m?null:oe.directories.get(r)?.diffCache.get(m)??null,[r,m])),R=!!$,B=!D&&!!m&&!R;i.useEffect(()=>{if(D)return;if(h(null),!r||!m){j.current=null;return}if($){j.current=null;return}const oe=`${r}::${m}::${p}`;if(j.current===oe)return;j.current=oe;let me=!1;return(async()=>{try{const Ne=s.getGitFileDiff(r,{path:m}),Ce=Am,Be=new Promise((J,ee)=>{setTimeout(()=>ee(new Error(`Timed out after ${Ce}ms`)),Ce)}),V=await Promise.race([Ne,Be]);if(me)return;u(r,m,{original:V.original??"",modified:V.modified??""})}catch(Ne){if(me)return;const Ce=Ne instanceof Error?Ne.message:String(Ne);h(Ce)}})(),()=>{me=!0,j.current===oe&&(j.current=null)}},[r,D,m,$,s,u,p]);const z=()=>!r||U.length===0?null:U.map(oe=>e.jsx(fb,{directory:r,filePath:oe.path,isVisible:oe.path===m,renderSideBySide:ae,wrapLines:S},oe.path)),G=()=>r?e.jsxs("div",{className:"flex flex-1 min-h-0 gap-3 px-3 pb-3 pt-2",children:[T&&e.jsxs("section",{className:"hidden lg:flex w-72 flex-col rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Files"}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:U.length})]}),e.jsx(lb,{changedFiles:U,selectedFile:m,onSelectFile:Y})]}),e.jsx(gt,{ref:I,outerClassName:"flex-1 min-h-0",className:"pr-2",children:e.jsx("div",{className:"flex flex-col gap-3",children:U.map(oe=>e.jsx(pb,{directory:r,file:oe,layout:W(oe),wrapLines:S,scrollRootRef:I,isSelected:oe.path===m,onSelect:X,registerSectionRef:H},oe.path))})})]}):null,ge=()=>r?l&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rs,{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."}):U.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"}):D?G():e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[z(),B&&!R&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:y?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:y}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{h(null),g(oe=>oe+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(rs,{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(il,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:l&&!a?"Loading changes…":`${U.length} ${U.length===1?"file":"files"} changed`})]}),!E&&e.jsx(ib,{mode:C,onModeChange:re}),F&&e.jsx(ab,{changedFiles:U,selectedFile:m,selectedFileEntry:Q,onSelectFile:Y,isMobile:E,showModeSelector:E,mode:C,onModeChange:re}),e.jsx("div",{className:"flex-1"}),Q&&e.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>A(!k),className:_("h-5 w-5 p-0 transition-opacity",S?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:S?"Disable line wrap":"Enable line wrap",children:e.jsx(wu,{className:"size-4"})}),Q&&L&&e.jsx(Nm,{mode:L==="side-by-side"?"side-by-side":"unified",onModeChange:K})]}),ge()]})},xb=()=>{const{git:s}=kr(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=he(),{currentDirectory:o}=vt(),a=r?n.get(r)??void 0:void 0,c=t.find(p=>p.id===r)?.directory,d=a?.path??c??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Gt(),f=Fy(d??null);return i.useEffect(()=>{d&&(u(d),Gt.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},pa=Ae.forwardRef(({className:s,...r},t)=>e.jsx(ju,{className:_("peer inline-flex 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-muted-foreground/30",s),style:{width:"36px",height:"20px",minWidth:"36px",minHeight:"20px"},...r,ref:t,children:e.jsx(yp,{className:_("pointer-events-none block rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"),style:{width:"16px",height:"16px",minWidth:"16px",minHeight:"16px"}})}));pa.displayName=ju.displayName;const yb={},Yo=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},$c=s=>Yo(s)??"__global__",bb=s=>{const r=Object.entries(s??{}),t=r.filter(([,l])=>l?.status==="connected").length,n=r.length,o=r.some(([,l])=>l?.status==="failed"),a=r.some(([,l])=>l?.status==="needs_auth"||l?.status==="needs_client_registration");return{connected:t,total:n,hasFailed:o,hasAuthRequired:a}},Hn=Vt()(Jt((s,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:t=>{const n=$c(t??vt.getState().currentDirectory);return r().byDirectory[n]??yb},refresh:async t=>{const n=Yo(t?.directory??vt.getState().currentDirectory),o=$c(n);t?.silent||s(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const c=(await Ee.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};s(d=>({byDirectory:{...d.byDirectory,[o]:c},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const l=a instanceof Error?a.message:"Failed to load MCP status";s(c=>({loadingKeys:{...c.loadingKeys,[o]:!1},lastErrorKeys:{...c.lastErrorKeys,[o]:l}}))}},connect:async(t,n)=>{const o=Yo(n??vt.getState().currentDirectory);await Ee.getApiClient().mcp.connect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(t,n)=>{const o=Yo(n??vt.getState().currentDirectory);await Ee.getApiClient().mcp.disconnect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function vb(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 wb=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}},jb=s=>{switch(s?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Ki=({headerIconButtonClass:s})=>{const[r,t]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(!1),{isMobile:l}=$t(),d=vt(C=>C.currentDirectory)??null,u=Hn(C=>C.getStatusForDirectory(d)),m=Hn(C=>C.refresh),f=Hn(C=>C.connect),p=Hn(C=>C.disconnect),g=i.useCallback(C=>{C||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),t(C)},[]),y=i.useCallback(C=>{a.current||o(C)},[]),[h,j]=i.useState(!1),[b,v]=i.useState(null);i.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),i.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const w=i.useMemo(()=>bb(u),[u]),N=i.useMemo(()=>Object.keys(u).sort((C,M)=>C.localeCompare(M)),[u]),x=i.useCallback(C=>{if(C?.preventDefault(),h)return;j(!0);const M=new Promise(S=>setTimeout(S,500));Promise.all([m({directory:d}),M]).finally(()=>{j(!1)})},[h,m,d]),k=()=>e.jsxs(e.Fragment,{children:[N.map(C=>{const M=u[C],S=jb(M),D=M?.status==="connected",E=b===C,T=wb(M);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:[l?e.jsx("span",{className:_("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":T}):e.jsxs(dt,{delayDuration:300,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:_("h-2 w-2 rounded-full flex-shrink-0",S==="success"&&"bg-status-success",S==="error"&&"bg-status-error",S==="warning"&&"bg-status-warning",S==="default"&&"bg-muted-foreground/40"),"aria-label":T})}),e.jsx(lt,{side:"left",children:e.jsx("p",{children:T})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:C})]})}),e.jsx(pa,{checked:D,disabled:E,className:"data-[state=checked]:bg-status-info",onCheckedChange:async I=>{v(C);try{I?await f(C,d):await p(C,d)}finally{v(null)}}})]},C)}),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."})]}),A=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:_(s,"relative"),onClick:l?()=>t(!0):void 0,children:[e.jsx(vb,{className:"h-[1.0625rem] w-[1.0625rem]"}),w.total>0&&e.jsx("span",{className:_("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",w.hasFailed?"bg-status-error":w.hasAuthRequired?"bg-status-warning":w.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return l?e.jsxs(e.Fragment,{children:[A,e.jsxs(ws,{open:r,title:"MCP Servers",onClose:()=>t(!1),renderHeader:C=>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:x,"aria-label":"Refresh",children:e.jsx(jr,{className:_("h-4 w-4",h&&"animate-spin")})}),C]})]}),children:[e.jsx("div",{className:"py-1",children:k()}),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(qt,{open:r,onOpenChange:g,children:[e.jsxs(dt,{delayDuration:1e3,open:r?!1:n,onOpenChange:y,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:A})}),e.jsx(lt,{children:e.jsx("p",{children:"MCP Servers"})})]}),e.jsxs(Qt,{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:x,"aria-label":"Refresh",children:e.jsx(jr,{className:_("h-4 w-4",h&&"animate-spin")})})]}),e.jsx(js,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:k()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(js,{}),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})})]})]})]})},Sb=()=>{const s=$e(d=>d.setSessionSwitcherOpen),r=$e(d=>d.toggleSidebar),{isMobile:t}=$t(),[n,o]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const l=i.useCallback(()=>{t?s(!0):r()},[t,s,r]),c="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:l,"aria-label":"Open sessions",className:c,children:e.jsx(ka,{className:"h-5 w-5"})})})},Lc=()=>{const s=$e(H=>H.setSessionSwitcherOpen),r=$e(H=>H.toggleSidebar),t=$e(H=>H.setSettingsDialogOpen),n=$e(H=>H.toggleCommandPalette),o=$e(H=>H.toggleHelpDialog),a=$e(H=>H.isSidebarOpen),l=$e(H=>H.sidebarWidth),c=$e(H=>H.activeMainTab),d=$e(H=>H.setActiveMainTab),{getCurrentModel:u}=at(),m=he(H=>H.getContextUsage),{isMobile:f}=$t(),p=xb(),g=Aa(H=>H.available),y=i.useRef(null),[h,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);Ae.useEffect(()=>{if(typeof window>"u")return;const H=typeof window.opencodeDesktop<"u";j(H)},[]);const v=u(),w=v&&typeof v.limit=="object"&&v.limit!==null?v.limit:null,N=w&&typeof w.context=="number"?w.context:0,x=w&&typeof w.output=="number"?w.output:0,k=m(N,x),A=$e(H=>H.isSessionSwitcherOpen),C=i.useCallback(()=>{if(typeof document>"u")return;const H=document.activeElement;if(!H)return;const q=H.tagName;(q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||H.isContentEditable)&&H.blur()},[]),M=i.useCallback(()=>{if(f){C(),s(!A);return}r()},[C,f,A,s,r]),S=i.useCallback(()=>{f&&C(),s(!1),t(!0)},[C,f,s,t]),D="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=i.useMemo(()=>h&&b?a?"pl-0":"pl-[8.0rem]":"pl-3",[h,b,a]),T=i.useCallback(()=>{if(typeof document>"u")return;const H=y.current?.getBoundingClientRect().height;H&&document.documentElement.style.setProperty("--oc-header-height",`${H}px`)},[]);Ae.useEffect(()=>{if(typeof window>"u")return;T();const H=y.current;if(!H||typeof ResizeObserver>"u")return()=>{};const q=new ResizeObserver(()=>{T()});return q.observe(H),window.addEventListener("resize",T),window.addEventListener("orientationchange",T),()=>{q.disconnect(),window.removeEventListener("resize",T),window.removeEventListener("orientationchange",T)}},[T]),Ae.useEffect(()=>{T()},[T,f]);const I=i.useCallback(async H=>{if(!H.target.closest("button, a, input, select, textarea")&&H.button===0&&h)try{const{getCurrentWindow:q}=await as(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-CqCnPJev.js").then(re=>re.cA);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await q().startDragging()}catch(q){console.error("Failed to start window dragging:",q)}},[h]),P=i.useCallback(async H=>{if(H.button===0&&h)try{const{getCurrentWindow:q}=await as(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-CqCnPJev.js").then(re=>re.cA);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await q().startDragging()}catch(q){console.error("Failed to start window dragging:",q)}},[h]),O=i.useMemo(()=>[{id:"chat",label:"Chat",icon:bp},{id:"diff",label:"Diff",icon:_s,badge:!f&&p>0?p:void 0},{id:"files",label:"Files",icon:Hs},{id:"terminal",label:"Terminal",icon:_r},{id:"git",label:"Git",icon:zt,showDot:f&&p>0}],[p,f]);Ae.useEffect(()=>{const H=q=>{if(Ds(q)&&!q.shiftKey&&!q.altKey){const X=parseInt(q.key,10);X>=1&&X<=O.length&&(q.preventDefault(),d(O[X-1].id))}};return window.addEventListener("keydown",H),()=>window.removeEventListener("keydown",H)},[O,d]);const U=(H,q)=>{const X=c===H.id,Y=H.icon,re=H.id==="chat",K=H.id==="git";return e.jsxs(i.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(H.id),onMouseDown:X?P:void 0,className:_("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",X?"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",X?"text-foreground":"text-muted-foreground",X&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",X&&re&&a&&"before:absolute before:bottom-[-1px] before:right-full before:h-px before:bg-[var(--interactive-border)] before:w-[var(--sidebar-w)]",re&&!(h&&b&&a)&&"border-l",K&&"border-r",re&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...X&&re&&a?{"--sidebar-w":h&&b?`${l}px`:"64px"}:{},...re&&!(h&&b&&a)||K?{borderColor:"var(--interactive-border)"}:{}},"aria-label":H.label,"aria-selected":X,role:"tab",children:[f?e.jsx(Y,{size:20}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{size:16}),e.jsx("span",{className:"header-tab-label",children:H.label})]}),re&&!f&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Vi,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),H.badge!==void 0&&H.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:H.badge})]}),!q&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},H.id)},Q=()=>e.jsxs("div",{onMouseDown:I,className:_("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:M,"aria-label":"Open sessions",className:`${D} mr-2.5`,children:e.jsx(ka,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:O.map((H,q)=>U(H,q===O.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:D,children:e.jsx(an,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Command Palette (",Yt(),"+K)"]})})]}),e.jsx(Ki,{headerIconButtonClass:D}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:D,children:e.jsx(tn,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Yt(),"+.)"]})})]})]})]}),W=()=>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:M,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(vp,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&c==="chat"&&e.jsx(Vi,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.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:O.map(H=>{const q=c===H.id,X=H.icon;return e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&C(),d(H.id)},"aria-label":H.label,"aria-selected":q,role:"tab",className:_(D,"relative",q&&"text-foreground"),children:[e.jsx(X,{className:"h-5 w-5"}),H.badge!==void 0&&H.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:H.badge}),H.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(lt,{children:e.jsx("p",{children:H.label})})]},H.id)})}),e.jsx(Ki,{headerIconButtonClass:D}),e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:S,"aria-label":"Open settings",className:_(D,"relative"),children:[e.jsx(en,{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(lt,{children:e.jsx("p",{children:g?"Settings (Update available)":"Settings"})})]})]})]}),L=_("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:y,className:L,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?W():Q()})};function Tl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:_("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function Pm({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:_("@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 Tm({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:_("leading-none font-semibold",s),...r})}function Fm({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:_("px-6",s),...r})}class os extends i.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(Tl,{className:"w-full max-w-md",children:[e.jsx(Pm,{className:"text-center",children:e.jsxs(Tm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ri,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(Fm,{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(Ie,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Fs,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let Mo=0;function ms({...s}){return e.jsx(wp,{"data-slot":"dialog",...s})}function kb({...s}){return e.jsx(kp,{"data-slot":"dialog-portal",...s})}const Rm=Ae.forwardRef(({className:s,...r},t)=>(Ae.useEffect(()=>(Mo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{Mo=Math.max(0,Mo-1),Mo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(Su,{ref:t,"data-slot":"dialog-overlay",className:_("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));Rm.displayName=Su.displayName;function fs({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(kb,{"data-slot":"dialog-portal",children:[e.jsx(Rm,{className:"rounded-none"}),e.jsxs(jp,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:_("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(Sp,{"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 ys({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-header",className:_("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Js({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:_("flex flex-col-reverse gap-2 bottom-safe-area sm:flex-row sm:justify-end",s),...r})}function bs({className:s,...r}){return e.jsx(Np,{"data-slot":"dialog-title",className:_("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Ms({className:s,...r}){return e.jsx(Cp,{"data-slot":"dialog-description",className:_("text-muted-foreground typography-ui-label",s),...r})}const Bc="https://github.com/btriapitsyn/openchamber/releases";async function Nb(){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 Cb(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 Qi=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=Ae.useState(!1),[p,g]=Ae.useState("idle"),[y,h]=Ae.useState(null),j=t?.version?`${Bc}/tag/v${t.version}`:Bc,b=a?.total?Math.round(a.downloaded/a.total*100):0,v=u==="web",w=t?.updateCommand||"openchamber update";Ae.useEffect(()=>{s||(g("idle"),h(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(w),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},x=Ae.useCallback(async()=>{g("updating"),h(null);const A=await Nb();if(!A.success){g("error"),h(A.error||"Update failed");return}g("restarting"),await new Promise(M=>setTimeout(M,2e3)),g("reconnecting"),await Cb()?window.location.reload():(g("error"),h("Server did not restart. Please refresh manually or run: openchamber restart"))},[]),k=p!=="idle"&&p!=="error";return e.jsx(ms,{open:s,onOpenChange:k?void 0:r,children:e.jsxs(fs,{className:"max-w-md",children:[e.jsx(ys,{children:e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(Mp,{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})]}),v&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Lo,{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&&!k&&e.jsx(gt,{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((A,C)=>/^\d+\.\d+\.\d+$/.test(A.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",A.trim(),`
82
- `]},C):A.replace(/^- /gm,"• ").trim()+`
83
-
84
- `)})}),v&&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(Dp,{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:w}),e.jsx("button",{onClick:N,className:_("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(_t,{className:"h-4 w-4"}):e.jsx(ku,{className:"h-4 w-4"})})]})]}),!v&&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}%`}})})]}),(l||y)&&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:l||y})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:_("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(ta,{className:"h-4 w-4"}),"GitHub"]}),!v&&!o&&!n&&e.jsxs("button",{onClick:c,className:_("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(Fr,{className:"h-4 w-4"}),"Download Update"]}),!v&&n&&e.jsxs("button",{disabled:!0,className:_("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(Lo,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&o&&e.jsxs("button",{onClick:d,className:_("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(Fs,{className:"h-4 w-4"}),"Restart to Update"]}),v&&!k&&e.jsxs("button",{onClick:x,className:_("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(Fr,{className:"h-4 w-4"}),"Update Now"]}),v&&k&&e.jsxs("button",{disabled:!0,className:_("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(Lo,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},zc=264,Wc=200,Hc=500,Mb=40,Uc="openchamber:check-for-updates",Db=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:l}=$e(),[c,d]=i.useState(!1),u=i.useRef(0),m=i.useRef(n||zc),[f,p]=i.useState(!1),g=Aa(),y=i.useRef(!1),h=g.checkForUpdates,{available:j,downloaded:b,checking:v}=g,[w,N]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const S=typeof window.opencodeDesktop<"u";N(S)},[]),i.useEffect(()=>{if(typeof window>"u")return;const S=()=>{typeof window.opencodeDesktop<"u"&&(y.current=!0,h())};return window.addEventListener(Uc,S),()=>{window.removeEventListener(Uc,S)}},[h]),i.useEffect(()=>{y.current&&(v||(j||b?p(!0):te.success("No updates available",{description:"You are running the latest version."}),y.current=!1))},[j,b,v]),i.useEffect(()=>{if(r||!c)return;const S=E=>{const T=E.clientX-u.current,I=Math.min(Hc,Math.max(Wc,m.current+T));o(I)},D=()=>{d(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",D,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",D)}},[r,c,o]),i.useEffect(()=>{r&&c&&d(!1)},[r,c]);const k=i.useCallback(async S=>{if(S.button===0&&w)try{const{getCurrentWindow:D}=await as(async()=>{const{getCurrentWindow:T}=await import("./vendor-.bun-CqCnPJev.js").then(I=>I.cA);return{getCurrentWindow:T}},__vite__mapDeps([0,1]));await D().startDragging()}catch(D){console.error("Failed to start window dragging from sidebar:",D)}},[w]);if(r)return null;const A=s?Math.min(Hc,Math.max(Wc,n||zc)):0,C=w&&x,M=S=>{s&&(d(!0),u.current=S.clientX,m.current=A,S.preventDefault())};return e.jsxs("aside",{className:_("relative flex h-full overflow-hidden border-r",w?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",c?"transition-none":"",!s&&"border-r-0"),style:{width:`${A}px`,minWidth:`${A}px`,maxWidth:`${A}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||A===0,children:[s&&e.jsx("div",{className:_("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",c?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:M,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:_("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:`${A}px`,overflowX:"hidden"},"aria-hidden":!s,children:[C&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${Mb}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{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:_("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(en,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),j||b?e.jsxs("button",{onClick:()=>p(!0),className:_("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(Fr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!w&&e.jsxs(dt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>l(!0),className:_("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(is,{className:"h-4 w-4"})})}),e.jsx(lt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Qi,{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 _m({className:s,...r}){return e.jsx(ln,{"data-slot":"command",className:_("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function Ab({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(ys,{className:"sr-only",children:[e.jsx(bs,{children:s}),e.jsx(Ms,{children:r})]}),e.jsx(fs,{className:_("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(_m,{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 Om({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(lr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(ln.Input,{"data-slot":"command-input",className:_("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 $m({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(gt,{as:ln.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:_("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 Lm({...s}){return e.jsx(ln.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function kn({className:s,...r}){return e.jsx(ln.Group,{"data-slot":"command-group",className:_("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 ha({className:s,...r}){return e.jsx(ln.Separator,{"data-slot":"command-separator",className:_("bg-border -mx-1 h-px",s),...r})}function ls({className:s,...r}){return e.jsx(ln.Item,{"data-slot":"command-item",className:_("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 gr({className:s,...r}){const t=a=>{const l=a.trim().toLowerCase();return l==="ctrl"||l==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):l==="cmd"||l==="⌘"||l==="command"||l==="meta"?e.jsx(an,{className:"size-3.5"}):l==="shift"||l==="⇧"?e.jsx(co,{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:_("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,l)=>e.jsxs(Ae.Fragment,{children:[l>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${l}`)):r.children})}const Vc=["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"],Gc=["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 Eb(){const s=Vc[Math.floor(Math.random()*Vc.length)],r=Gc[Math.floor(Math.random()*Gc.length)];return`${s}-${r}`}function qc(s){const r=Eb();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function Ib(s,r,t=10){let n;try{const o=await vl(s);n=new Set(o?.all??[])}catch{return qc(r)}for(let o=0;o<t;o++){const a=qc(r);if(!n.has(a))return a}return null}const Pb=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let ci=!1;async function Ra(){if(ci)return null;const s=Ot.getState().getActiveProject();if(!s?.path)return te.error("No active project",{description:"Please select a project first."}),null;const r=s.path;let t=!1;try{t=await cn(r)}catch{}if(!t)return te.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;ci=!0,Ks("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,l=await Ib(r,o);if(!l)return te.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const c=Pb(l),u=await um({projectDirectory:r,worktreeSlug:c,branch:l,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await wl(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=he.getState(),g=await p.createSession(void 0,u.path);if(!g)return await Kx({projectDirectory:r,path:u.path,force:!0}).catch(()=>{}),te.error("Failed to create session",{description:"Could not create a session for the worktree."}),null;const y=at.getState(),h=y.agents;p.initializeNewOpenChamberSession(g.id,h),p.setSessionDirectory(g.id,u.path),p.setWorktreeMetadata(g.id,f);try{const v=y.getVisibleAgents();let w;if(y.settingsDefaultAgent){const N=v.find(x=>x.name===y.settingsDefaultAgent);N&&(w=N.name)}if(w||(w=v.find(N=>N.name==="build")?.name||v[0]?.name),w){y.setAgent(w),wt.getState().saveSessionAgentSelection(g.id,w);const N=y.settingsDefaultModel;if(N){const x=N.split("/");if(x.length===2){const[k,A]=x;if(y.getModelMetadata(k,A)){wt.getState().saveSessionModelSelection(g.id,k,A),wt.getState().saveAgentModelForSession(g.id,w,k,A);const M=y.settingsDefaultVariant;if(M){const E=y.providers.find(T=>T.id===k)?.models.find(T=>T.id===A)?.variants;E&&Object.prototype.hasOwnProperty.call(E,M)&&(y.setCurrentVariant(M),wt.getState().saveAgentModelVariantForSession(g.id,w,k,A,M))}}}}}}catch{}vt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const b=(await fo(r)).filter(v=>v.trim().length>0);return b.length>0?(te.success("Worktree created",{description:`Branch: ${l}. Running ${b.length} setup command${b.length===1?"":"s"}...`}),fm(u.path,r,b).then(v=>{if(v.success)te.success("Setup commands completed",{description:`All ${v.results.length} command${v.results.length===1?"":"s"} succeeded.`});else{const w=v.results.filter(x=>!x.success),N=v.results.filter(x=>x.success);te.error("Setup commands failed",{description:`${w.length} of ${v.results.length} command${v.results.length===1?"":"s"} failed.`+(N.length>0?` ${N.length} succeeded.`:"")})}}).catch(()=>{te.error("Setup commands failed",{description:"Could not execute setup commands."})})):te.success("Worktree created",{description:`Branch: ${l}`}),g}catch(n){const o=n instanceof Error?n.message:"Failed to create worktree session";return te.error("Failed to create worktree",{description:o}),null}finally{As(),ci=!1}}const Tb=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:l,toggleSidebar:c}=$e(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=he(),f=at(P=>P.settingsAutoCreateWorktree),{currentDirectory:p}=vt(),{themeMode:g,setThemeMode:y}=Wr(),h=()=>{r(!1)},j=async()=>{n("chat"),a(!1),d(),h()},b=P=>{u(P),h()},v=P=>{y(P),h()},w=()=>{t(!0),h()},N=()=>{h(),Ra()},{isMobile:x}=$t(),k=()=>{if(x){const{isSessionSwitcherOpen:P}=$e.getState();a(!P)}else c();h()},A=()=>{n("diff"),h()},C=()=>{n("git"),h()},M=()=>{n("terminal"),h()},S=()=>{o(!0),h()},D=()=>{qn(),h()},E=()=>{l(!0),h()},T=m(p??""),I=i.useMemo(()=>T.slice(0,5),[T]);return e.jsxs(Ab,{open:s,onOpenChange:r,children:[e.jsx(Om,{placeholder:"Type a command or search..."}),e.jsxs($m,{children:[e.jsx(Lm,{children:"No results found."}),e.jsxs(kn,{heading:"Actions",children:[e.jsxs(ls,{onSelect:k,children:[e.jsx(ka,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(gr,{children:[Yt()," + L"]})]}),e.jsxs(ls,{onSelect:j,children:[e.jsx(Xt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(gr,{children:f?`Shift + ${Yt()} + N`:`${Yt()} + N`})]}),e.jsxs(ls,{onSelect:N,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(gr,{children:f?`${Yt()} + N`:`Shift + ${Yt()} + N`})]}),e.jsxs(ls,{onSelect:w,children:[e.jsx(tn,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(gr,{children:[Yt()," + ."]})]}),e.jsxs(ls,{onSelect:A,children:[e.jsx(_s,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(gr,{children:[Yt()," + 2"]})]}),e.jsxs(ls,{onSelect:M,children:[e.jsx(_r,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(gr,{children:[Yt()," + 3"]})]}),e.jsxs(ls,{onSelect:C,children:[e.jsx(zt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(gr,{children:[Yt()," + 4"]})]}),e.jsxs(ls,{onSelect:E,children:[e.jsx(cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(gr,{children:[Yt()," + T"]})]}),e.jsxs(ls,{onSelect:S,children:[e.jsx(en,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(gr,{children:[Yt()," + ,"]})]}),e.jsxs(ls,{onSelect:D,children:[e.jsx(Fs,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(ha,{}),e.jsxs(kn,{heading:"Theme",children:[e.jsxs(ls,{onSelect:()=>v("light"),children:[e.jsx(Ap,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(_t,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ls,{onSelect:()=>v("dark"),children:[e.jsx(Ep,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(_t,{className:"ml-auto h-4 w-4"})]}),e.jsxs(ls,{onSelect:()=>v("system"),children:[e.jsx(Nu,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(_t,{className:"ml-auto h-4 w-4"})]})]}),I.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ha,{}),e.jsx(kn,{heading:"Recent Sessions",children:I.map(P=>e.jsxs(ls,{onSelect:()=>b(P.id),children:[e.jsx(ll,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},Fb=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(Na,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(an,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},Rb=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(i.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),Fb(t,n)]},`${t}-${n}`))},_b=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=$e(),t=at(a=>a.settingsAutoCreateWorktree),n=Yt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:an},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:tn},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:ka},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:sn},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:Cu},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:dr}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create New Session in Worktree":"Create New Session",icon:t?zt:Xt},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create New Session in Worktree",icon:t?Xt:zt},{keys:[`${n} + I`],description:"Focus Chat Input",icon:Mu},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Cn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:Ip},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:_s},{keys:[`${n} + 3`],description:"Open Files",icon:Hs},{keys:[`${n} + 4`],description:"Open Terminal",icon:_r},{keys:[`${n} + 5`],description:"Open Git Panel",icon:zt},{keys:[`${n} + T`],description:"Open Timeline",icon:cr},{keys:[`${n} + ,`],description:"Open Settings",icon:en}]}];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(ys,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(en,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ms,{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((l,c)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[l.icon&&e.jsx(l.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:l.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l.keys)?l.keys:l.keys.split(" / ")).map((d,u)=>e.jsxs(i.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:Rb(d)})]},`${d}-${u}`))})]},c))})]},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(tn,{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"})]})]})]})})]})]})})},di=new Set,ui=new Set,mi=new Set,En={onDeleteRequest(s){return di.add(s),()=>{di.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||di.forEach(r=>r(s))},onCreateRequest(s){return ui.add(s),()=>{ui.delete(s)}},requestCreate(s){const r=s??{};ui.forEach(t=>t(r))},onDirectoryRequest(s){return mi.add(s),()=>{mi.delete(s)}},requestDirectoryDialog(){mi.forEach(s=>s())}};function Bm(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 Kc="oc.sessions.projectCollapse",Qc="oc.sessions.expandedParents",Yc=s=>{const r=new Date(s),t=new Date,n=(l,c)=>l.getFullYear()===c.getFullYear()&&l.getMonth()===c.getMonth()&&l.getDate()===c.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(",","")},tr=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},Xc=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),Ob=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:l,isDesktopRuntime:c,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:g,onOpenMultiRunLauncher:y,onClose:h,sentinelRef:j,children:b})=>{const{attributes:v,listeners:w,setNodeRef:N,isDragging:x}=Up({id:s});return e.jsxs("div",{ref:N,className:_("relative",x&&"opacity-40"),children:[c&&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:_("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b",!c&&"bg-sidebar"),style:{backgroundColor:c?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:l?"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",...v,children:[e.jsxs(dt,{delayDuration:1500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...w,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:_("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(lt,{side:"right",sideOffset:8,children:t})]}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:_("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:k=>k.stopPropagation(),children:e.jsx(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&e.jsxs(Et,{onClick:y,children:[e.jsx(Bm,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Et,{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:k=>{k.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(Xt,{className:"h-4 w-4"})})]})}),b]})},$b=({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:_("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(Xt,{className:"h-4 w-4"})})]})}),ga=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,l]=i.useState(null),[c,d]=i.useState(""),[u,m]=i.useState(null),f=i.useRef(null),[p,g]=i.useState(new Set),[y,h]=i.useState(()=>new Map),j=i.useRef(new Set),b=i.useMemo(()=>ds(),[]),[v,w]=i.useState(new Set),[N,x]=i.useState(new Map),[k,A]=i.useState(new Set),[C,M]=i.useState(null),[S,D]=i.useState(null),[E,T]=i.useState(new Set),I=i.useRef(new Map),P=i.useRef(0),O=vt(Z=>Z.homeDirectory),U=vt(Z=>Z.currentDirectory),Q=vt(Z=>Z.setDirectory),W=Ot(Z=>Z.projects),L=Ot(Z=>Z.activeProjectId),H=Ot(Z=>Z.addProject),q=Ot(Z=>Z.removeProject),X=Ot(Z=>Z.setActiveProject),Y=Ot(Z=>Z.setActiveProjectIdOnly),re=Ot(Z=>Z.reorderProjects),K=$e(Z=>Z.setActiveMainTab),ae=$e(Z=>Z.setSessionSwitcherOpen),F=$e(Z=>Z.openMultiRunLauncher),$=at(Z=>Z.settingsAutoCreateWorktree),R=he(Z=>Z.sessions),B=he(Z=>Z.sessionsByDirectory),z=he(Z=>Z.currentSessionId),G=he(Z=>Z.setCurrentSession),ge=he(Z=>Z.updateSessionTitle),oe=he(Z=>Z.shareSession),me=he(Z=>Z.unshareSession),Ne=he(Z=>Z.sessionMemoryState),Ce=he(Z=>Z.sessionActivityPhase),Be=he(Z=>Z.permissions),V=he(Z=>Z.worktreeMetadata),J=he(Z=>Z.availableWorktreesByProject),ee=he(Z=>Z.getSessionsByDirectory),xe=he(Z=>Z.openNewSessionDraft),[fe,Oe]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),Se=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{try{const Z=b.getItem(Qc);if(Z){const ve=JSON.parse(Z);Array.isArray(ve)&&g(new Set(ve.filter(Ue=>typeof Ue=="string")))}const we=b.getItem(Kc);if(we){const ve=JSON.parse(we);Array.isArray(ve)&&w(new Set(ve.filter(Ue=>typeof Ue=="string")))}}catch{}},[b]),i.useEffect(()=>{typeof window>"u"||Oe(typeof window.opencodeDesktop<"u")},[]);const Le=i.useMemo(()=>[...R].sort((Z,we)=>(we.time?.updated||0)-(Z.time?.updated||0)),[R]);i.useEffect(()=>{let Z=!1;const we=W.map(ve=>({id:ve.id,path:tr(ve.path)})).filter(ve=>!!ve.path);return x(new Map),we.length===0?()=>{Z=!0}:(we.forEach(ve=>{cn(ve.path).then(Ue=>{Z||x(_e=>{const et=new Map(_e);return et.set(ve.id,Ue),et})}).catch(()=>{Z||x(Ue=>{const _e=new Map(Ue);return _e.set(ve.id,null),_e})})}),()=>{Z=!0})},[W]);const pe=i.useMemo(()=>{const Z=new Map;return Le.forEach(we=>{const ve=we.parentID;ve&&Z.set(we.id,ve)}),Z},[Le]),it=i.useMemo(()=>{const Z=new Map;return Le.forEach(we=>{const ve=we.parentID;if(!ve)return;const Ue=Z.get(ve)??[];Ue.push(we),Z.set(ve,Ue)}),Z.forEach(we=>we.sort((ve,Ue)=>(Ue.time?.updated||0)-(ve.time?.updated||0))),Z},[Le]);i.useEffect(()=>{z&&g(Z=>{const we=new Set(Z);let ve=pe.get(z)||null,Ue=!1;for(;ve;)we.has(ve)||(we.add(ve),Ue=!0),ve=pe.get(ve)||null;return Ue?we:Z})},[z,pe]),i.useEffect(()=>{const Z=new Set;Le.forEach(we=>{const ve=tr(we.directory??null);ve&&Z.add(ve)}),W.forEach(we=>{const ve=tr(we.path);ve&&Z.add(ve)}),Z.forEach(we=>{const ve=y.get(we);ve&&ve!=="unknown"||j.current.has(we)||(j.current.add(we),Ee.listLocalDirectory(we).then(()=>{h(Ue=>{const _e=new Map(Ue);return _e.get(we)==="exists"?Ue:(_e.set(we,"exists"),_e)})}).catch(()=>{h(Ue=>{const _e=new Map(Ue);return _e.get(we)==="missing"?Ue:(_e.set(we,"missing"),_e)})}).finally(()=>{j.current.delete(we)}))})},[Le,W,y]),i.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const xt=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."})]}),Mt=i.useCallback((Z,we,ve,Ue)=>{if(!ve){if(Ue&&Ue!==L&&Y(Ue),we&&we!==U&&Q(we,{showOverlay:!1}),s&&(K("chat"),ae(!1)),!t&&Z===z){r?.(Z);return}G(Z),r?.(Z)}},[L,t,U,z,s,r,K,Y,G,Q,ae]),De=i.useCallback(async()=>{a&&c.trim()&&(await ge(a,c.trim()),l(null),d(""))},[a,c,ge]),ne=i.useCallback(()=>{l(null),d("")},[]),rt=i.useCallback(async Z=>{const we=await oe(Z.id);we&&we.share?.url?te.success("Session shared",{description:"You can copy the link from the menu."}):te.error("Unable to share session")},[oe]),be=i.useCallback((Z,we)=>{navigator.clipboard.writeText(Z).then(()=>{m(we),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{te.error("Failed to copy URL")})},[]),ke=i.useCallback(async Z=>{await me(Z)?te.success("Session unshared"):te.error("Unable to unshare session")},[me]),Qe=i.useCallback(Z=>{const we=[],ve=Ue=>{(it.get(Ue)??[]).forEach(et=>{we.push(et),ve(et.id)})};return ve(Z),we},[it]),tt=he(Z=>Z.deleteSession),He=he(Z=>Z.deleteSessions),Re=i.useCallback(async Z=>{const we=Qe(Z.id),ve=V.get(Z.id);if(ve){const Ue=ve.path,_e=[],et=new Set;R.forEach(pt=>{const ft=V.get(pt.id);ft&&ft.path===Ue&&!et.has(pt.id)&&(_e.push(pt),et.add(pt.id),Qe(pt.id).forEach(At=>{et.has(At.id)||(_e.push(At),et.add(At.id))}))}),En.requestDelete({sessions:_e,mode:"worktree",worktree:ve});return}if(we.length===0)await tt(Z.id)?te.success("Session deleted"):te.error("Failed to delete session");else{const Ue=[Z.id,...we.map(pt=>pt.id)],{deletedIds:_e,failedIds:et}=await He(Ue);_e.length>0&&te.success(`Deleted ${_e.length} session${_e.length===1?"":"s"}`),et.length>0&&te.error(`Failed to delete ${et.length} session${et.length===1?"":"s"}`)}},[Qe,tt,He,V,R]),nt=i.useCallback(()=>{fe&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(Z=>{Z.success&&Z.path?H(Z.path,{id:Z.projectId})||te.error("Failed to add project",{description:"Please select a valid directory."}):Z.error&&Z.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:Z.error})}).catch(Z=>{console.error("Desktop: Error selecting directory:",Z),te.error("Failed to select directory")}):En.requestDirectoryDialog()},[H,fe]),yt=i.useCallback(Z=>{g(we=>{const ve=new Set(we);ve.has(Z)?ve.delete(Z):ve.add(Z);try{b.setItem(Qc,JSON.stringify(Array.from(ve)))}catch{}return ve})},[b]),ct=i.useCallback(Z=>{const we=it.get(Z.id)??[];return{session:Z,children:we.map(ve=>ct(ve)),worktree:V.get(Z.id)??null}},[it,V]),It=i.useCallback((Z,we,ve)=>{const Ue=tr(we??null),_e=[...Z].sort((Ve,Xe)=>(Xe.time?.updated||0)-(Ve.time?.updated||0)),et=new Map(_e.map(Ve=>[Ve.id,Ve])),pt=new Map;_e.forEach(Ve=>{const Xe=Ve.parentID;if(!Xe)return;const kt=pt.get(Xe)??[];kt.push(Ve),pt.set(Xe,kt)}),pt.forEach(Ve=>Ve.sort((Xe,kt)=>(kt.time?.updated||0)-(Xe.time?.updated||0)));const ft=new Map;ve.forEach(Ve=>{if(Ve.path){const Xe=tr(Ve.path)??Ve.path;ft.set(Xe,Ve)}});const Pt=Ve=>{const Xe=tr(Ve.directory??null),kt=V.get(Ve.id)??null;if(kt)return kt;if(Xe){const Lt=ft.get(Xe)??null;if(Lt&&Xe!==Ue)return Lt}return null},At=Ve=>{const Xe=pt.get(Ve.id)??[];return{session:Ve,children:Xe.map(kt=>At(kt)),worktree:Pt(Ve)}},st=_e.filter(Ve=>{const Xe=Ve.parentID;return Xe?!et.has(Xe):!0}).map(Ve=>At(Ve));return[{id:"all",label:"All sessions",description:Ue?Yr(Ue,O):null,isMain:!0,worktree:null,directory:Ue,sessions:st}]},[O,V]),Tt=i.useCallback(Z=>{A(we=>{const ve=new Set(we);return ve.has(Z)?ve.delete(Z):ve.add(Z),ve})},[]),je=i.useCallback(Z=>{P.current=Date.now()+150,w(we=>{const ve=new Set(we);ve.has(Z)?ve.delete(Z):ve.add(Z);try{b.setItem(Kc,JSON.stringify(Array.from(ve)))}catch{}return ve})},[b]),ze=i.useMemo(()=>W.map(Z=>({...Z,normalizedPath:tr(Z.path)})).filter(Z=>!!Z.normalizedPath),[W]),Ze=i.useCallback(Z=>{const we=Se?[]:J.get(Z.normalizedPath)??[],ve=[Z.normalizedPath,...we.map(et=>tr(et.path)??et.path).filter(et=>!!et)],Ue=new Set,_e=[];return ve.forEach(et=>{(B.get(et)??ee(et)).forEach(ft=>{Ue.has(ft.id)||(Ue.add(ft.id),_e.push(ft))})}),_e},[J,ee,B,Se]),Ye=i.useMemo(()=>ze.map(Z=>{const we=Ze(Z),ve=J.get(Z.normalizedPath)??[],Ue=It(we,Z.normalizedPath,ve);return{project:Z,groups:Ue}}),[ze,Ze,It,J]);i.useEffect(()=>{if(!fe)return;const Z=new IntersectionObserver(we=>{we.forEach(ve=>{const Ue=ve.target.dataset.projectId;Ue&&T(_e=>{const et=new Set(_e);return ve.isIntersecting?et.delete(Ue):et.add(Ue),et})})},{threshold:0});return I.current.forEach(we=>{we&&Z.observe(we)}),()=>Z.disconnect()},[fe,Ye]);const mt=i.useCallback((Z,we=0,ve,Ue)=>{const _e=Z.session,et=tr(_e.directory??null)??tr(ve??null),ft=(et?y.get(et):null)==="missing",Pt=Ne.get(_e.id),At=z===_e.id,Te=_e.title||"Untitled Session",st=Z.children.length>0,Ve=p.has(_e.id),Xe=_e.summary?.additions,kt=_e.summary?.deletions,Lt=typeof Xe=="number"||typeof kt=="number";if(a===_e.id)return e.jsx("div",{className:_("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:Bt=>{Bt.preventDefault(),De()},children:[e.jsx("input",{value:c,onChange:Bt=>d(Bt.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:Bt=>{Bt.key==="Escape"&&ne()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(_t,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:ne,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:[st?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:Ve?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Rs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Yc(_e.time?.created||Date.now())}),_e.share?e.jsx(Va,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Lt&&((Xe??0)!==0||(kt??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,Xe??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,kt??0)]})]}):null,st?e.jsxs("span",{className:"truncate",children:[Z.children.length," ",Z.children.length===1?"task":"tasks"]}):null]})]})},_e.id);const ts=Ce?.get(_e.id)??"idle",ns=ts==="busy"||ts==="cooldown",ps=Be.get(_e.id)?.length??0,pr=Pt&&Pt.isZombie?e.jsx(Ri,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(i.Fragment,{children:[e.jsx("div",{className:_("group relative flex items-center rounded-md px-1.5 py-1",At?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",ft?"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:ft,onClick:()=>Mt(_e.id,et,ft,Ue),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 text-foreground"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0 flex-1",children:[e.jsx("span",{className:_("truncate typography-ui-label font-normal text-foreground",ns&&"animate-pulse [animation-duration:1.8s]"),children:Te}),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(Pp,{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:[st?e.jsx("span",{role:"button",tabIndex:0,onClick:Bt=>{Bt.stopPropagation(),yt(_e.id)},onKeyDown:Bt=>{(Bt.key==="Enter"||Bt.key===" ")&&(Bt.preventDefault(),Bt.stopPropagation(),yt(_e.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":Ve?"Collapse subsessions":"Expand subsessions",children:Ve?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Rs,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Yc(_e.time?.created||Date.now())}),_e.share?e.jsx(Va,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Z.worktree?e.jsxs(dt,{delayDuration:700,children:[e.jsx(ut,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx(zt,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(lt,{side:"top",className:"text-xs",children:Z.worktree.branch||Z.worktree.label||"Worktree"})]}):null,Lt&&((Xe??0)!==0||(kt??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,Xe??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,kt??0)]})]}):null,st?e.jsxs("span",{className:"truncate",children:[Z.children.length," ",Z.children.length===1?"task":"tasks"]}):null,ft?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(Ri,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[pr,e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:_("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:Bt=>Bt.stopPropagation(),onKeyDown:Bt=>Bt.stopPropagation(),children:e.jsx(Or,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Et,{onClick:()=>{l(_e.id),d(Te)},className:"[&>svg]:mr-1",children:[e.jsx(xr,{className:"mr-1 h-4 w-4"}),"Rename"]}),_e.share?e.jsxs(e.Fragment,{children:[e.jsx(Et,{onClick:()=>{_e.share?.url&&be(_e.share.url,_e.id)},className:"[&>svg]:mr-1",children:u===_e.id?e.jsxs(e.Fragment,{children:[e.jsx(_t,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ys,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Et,{onClick:()=>ke(_e.id),className:"[&>svg]:mr-1",children:[e.jsx(Tp,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Et,{onClick:()=>rt(_e),className:"[&>svg]:mr-1",children:[e.jsx(Va,{className:"mr-1 h-4 w-4"}),"Share"]}),Z.worktree?e.jsxs(Et,{onClick:()=>{Ue&&Ue!==L&&X(Ue),K("chat"),s&&ae(!1),xe({directoryOverride:Z.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx(zt,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Et,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Re(_e),children:[e.jsx(Xs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),st&&Ve?Z.children.map(Bt=>mt(Bt,we+1,et??ve,Ue)):null]},_e.id)},[y,Ne,Ce,Be,z,p,a,c,De,ne,yt,Mt,rt,be,ke,Re,u,s,L,X,K,ae,xe]),ye=i.useCallback((Z,we,ve)=>{const Ue=k.has(we),_e=n?10:5,et=Z.sessions.length,pt=Ue?Z.sessions:Z.sessions.slice(0,_e),ft=et-pt.length;return e.jsxs(e.Fragment,{children:[pt.map(Pt=>mt(Pt,0,Z.directory,ve)),et===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,ft>0&&!Ue?e.jsxs("button",{type:"button",onClick:()=>Tt(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 ",ft," more ",ft===1?"session":"sessions"]}):null,Ue&&et>_e?e.jsx("button",{type:"button",onClick:()=>Tt(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]})},[k,n,mt,Tt]),ie=Fp(Xl(Hp,{activationConstraint:{distance:8}}),Xl(Wp,{coordinateGetter:zp})),de=i.useCallback(Z=>{D(Z.active.id)},[]),We=i.useCallback(Z=>{const{active:we,over:ve}=Z;if(D(null),!ve||we.id===ve.id)return;const Ue=ze.findIndex(et=>et.id===we.id),_e=ze.findIndex(et=>et.id===ve.id);Ue!==-1&&_e!==-1&&re(Ue,_e)},[ze,re]),Ge=i.useCallback(()=>{D(null)},[]),bt=i.useMemo(()=>{if(!S)return null;const Z=Ye.find(ve=>ve.project.id===S);if(!Z)return null;const we=Z.project;return{id:we.id,label:Xc(we.label?.trim()||ec(we.normalizedPath,O)||we.normalizedPath),isActive:we.id===L}},[S,Ye,O,L]);return e.jsxs("div",{className:_("flex h-full flex-col text-foreground overflow-x-hidden",s?"":fe?"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:W.length})]}),e.jsx("button",{type:"button",onClick:nt,className:_("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",!fe&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(Rp,{className:"h-4.5 w-4.5"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:_("space-y-1 pb-1 pl-2.5 pr-1",""),children:Ye.length===0?xt:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const Z=Ye.find(Ue=>Ue.project.id===L)??Ye[0];if(!Z)return xt;const we=Z.groups.find(Ue=>Ue.isMain&&Ue.sessions.length>0)??Z.groups.find(Ue=>Ue.sessions.length>0)??Z.groups.find(Ue=>Ue.isMain)??Z.groups[0];if(!we)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const ve=`${Z.project.id}:${we.id}`;return ye(we,ve,Z.project.id)})()}):e.jsxs(_p,{sensors:ie,collisionDetection:Op,onDragStart:de,onDragEnd:We,onDragCancel:Ge,children:[e.jsx($p,{items:ze.map(Z=>Z.id),strategy:Lp,children:Ye.map(Z=>{const we=Z.project,ve=we.id,Ue=Xc(we.label?.trim()||ec(we.normalizedPath,O)||we.normalizedPath),_e=Yr(we.normalizedPath,O),et=v.has(ve),pt=ve===L,ft=N.get(ve),Pt=C===ve;return e.jsx(Ob,{id:ve,projectLabel:Ue,projectDescription:_e,isCollapsed:et,isActiveProject:pt,isRepo:!!ft,isHovered:Pt,isDesktopRuntime:fe,isStuck:E.has(ve),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>je(ve),onHoverChange:At=>M(At?ve:null),onNewSession:()=>{ve!==L&&X(ve),K("chat"),s&&ae(!1),$&&ft?Ra():xe({directoryOverride:we.normalizedPath})},onOpenMultiRunLauncher:()=>{ve!==L&&X(ve),F()},onClose:()=>q(ve),sentinelRef:At=>{I.current.set(ve,At)},children:et?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:Z.groups[0]?ye(Z.groups[0],`${ve}:all`,ve):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},ve)})}),e.jsx(Bp,{children:bt?e.jsx($b,{projectLabel:bt.label,isActiveProject:bt.isActive}):null})]})})]})};function jt({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:_("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),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",...t})}const _a=()=>{const[s,r]=Ae.useState(!1);Ae.useEffect(()=>{r(es())},[]);const t=Ae.useCallback(async a=>s?await mg(a):{success:!0,path:a},[s]),n=Ae.useCallback(async a=>s?await fg(a):{success:!0},[s]),o=Ae.useCallback(async a=>s?await pg(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},Jc=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:l,showHidden:c=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=i.useMemo(()=>es(),[]),{isMobile:p}=$t(),[g,y]=i.useState([]),[h,j]=i.useState(new Set),[b,v]=i.useState(!0),[w,N]=i.useState(!1),[x,k]=i.useState(""),[A,C]=i.useState(new Set),[M,S]=i.useState(null),[D,E]=i.useState(""),[T,I]=i.useState(!0),P=i.useRef(null),{requestAccess:O,startAccessing:U,isDesktop:Q}=_a(),W=i.useRef(c),L=i.useCallback(V=>{if(!V)return V;if(V==="/"||V.length===0)return"/";let J=V;for(;J.length>1&&J.endsWith("/");)J=J.slice(0,-1);return J.length===0?"/":J},[]),H=i.useMemo(()=>{if(!x)return null;const V=x.replace(/\\/g,"/");return L(V)},[x,L]),q=i.useMemo(()=>{if(typeof d=="string"&&d.length>0){const V=d.replace(/\\/g,"/"),J=L(V);if(J&&J!=="/")return J}return H&&H!=="/"?H:null},[d,H,L]),X=i.useMemo(()=>typeof u=="boolean"?!!(u&&q):!!q,[u,q]);i.useEffect(()=>{X||(v(!0),y([]))},[X]);const Y=i.useCallback(V=>{if(!V||!X||!q)return!1;const J=V.replace(/\\/g,"/"),ee=L(J)??J;if(ee===q)return!0;const xe=`${q}/`;return ee.startsWith(xe)},[X,q,L]),re=async V=>{if(X){if(a==="deferred"){r(V);return}if(Q){const J=await O(V);J.success&&J.path?(await U(J.path),r(J.path)):(console.error("Failed to get directory access:",J.error),r(V))}else r(V)}};i.useEffect(()=>{let V=!1;const J=fe=>{if(!fe)return!1;const Oe=L(fe.replace(/\\/g,"/"));return!Oe||Oe==="/"?!1:(k(typeof Oe=="string"?Oe:fe.replace(/\\/g,"/")),!0)};return d&&J(d)||(async()=>{try{const fe=await Ee.getFilesystemHome();if(!V&&J(fe))return}catch(fe){console.warn("Failed to resolve filesystem home directory:",fe)}try{const fe=await Ee.getSystemInfo();if(!V&&J(fe?.homeDirectory))return}catch(fe){console.warn("Failed to resolve home directory from system info:",fe)}})(),()=>{V=!0}},[d,L]),i.useEffect(()=>{let V=!1;const J=Oe=>{if(V)return;const Se=Oe.filter(Le=>typeof Le=="string"&&Le.length>0).map(Le=>{const pe=Le.replace(/\\/g,"/");return L(pe)??pe});C(new Set(Se))},ee=()=>{try{const Oe=localStorage.getItem("pinnedDirectories");if(!Oe)return;const Se=JSON.parse(Oe);Array.isArray(Se)&&J(Se)}catch(Oe){console.warn("Failed to load pinned directories from local storage:",Oe)}},xe=async()=>{try{let Oe=[];if(f){const Se=await Lr();Oe=Array.isArray(Se?.pinnedDirectories)?Se.pinnedDirectories:[]}else{const Se=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(Se.ok){const Le=await Se.json();Oe=Array.isArray(Le?.pinnedDirectories)?Le.pinnedDirectories:[]}}if(V)return;J(Oe)}catch(Oe){console.warn("Failed to load pinned directories:",Oe)}};ee();const fe=Oe=>{const Se=Oe.detail;Se&&Array.isArray(Se.pinnedDirectories)&&J(Se.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",fe),xe(),()=>{V=!0,window.removeEventListener("openchamber:settings-synced",fe)}},[f,L]);const K=i.useRef(!0);i.useEffect(()=>{if(K.current){K.current=!1;return}const V={pinnedDirectories:Array.from(A)};ss(V)},[A]),i.useEffect(()=>{q&&C(V=>{const J=Array.from(V).map(ee=>L(ee.replace(/\\/g,"/"))??ee).filter(ee=>Y(ee));return new Set(J)})},[q,Y,L]),i.useEffect(()=>{W.current!==c&&(W.current=c)},[c]);const ae=V=>{C(J=>{if(!Y(V))return J;const ee=L(V.replace(/\\/g,"/"))??V.replace(/\\/g,"/"),xe=new Set(J);return xe.has(ee)?xe.delete(ee):xe.add(ee),xe})},F=i.useMemo(()=>Array.from(A).map(V=>L(V.replace(/\\/g,"/"))??V).filter(V=>Y(V)).map(V=>({path:V,name:V.split("/").pop()||V})).sort((V,J)=>V.name.localeCompare(J.name)),[A,Y,L]),$=i.useCallback(async V=>{const J=Se=>c||!Se.startsWith("."),ee=q;if(!X||!ee)return[];const xe=V&&V.length>0?V:ee,fe=xe?xe.replace(/\\/g,"/"):null,Oe=fe?L(fe)??fe:null;if(Oe){const Se=`${ee}/`;if(!(Oe===ee||Oe.startsWith(Se)))return[]}try{return(await Ee.listLocalDirectory(V)).filter(Le=>{if(!Le.isDirectory||!J(Le.name))return!1;const pe=Le.path.replace(/\\/g,"/"),it=L(pe)??pe,xt=it===ee?ee:`${ee}/`;return it===ee||it.startsWith(xt)}).map(Le=>({name:Le.name,path:Le.path.replace(/\\/g,"/"),isDirectory:!0})).sort((Le,pe)=>Le.name.localeCompare(pe.name))}catch{try{const Le=await Ee.getApiClient().file.list({path:".",directory:V});return Le.data?Le.data.filter(pe=>{if(pe.type!=="directory"||!pe.name||!J(pe.name))return!1;const it=String(pe.absolute||pe.path||pe.name).replace(/\\/g,"/"),xt=L(it)??it,Mt=xt===ee?ee:`${ee}/`;return xt===ee||xt.startsWith(Mt)}).map(pe=>({name:pe.name||"",path:String(pe.absolute||pe.path||pe.name).replace(/\\/g,"/"),isDirectory:!0})).filter(pe=>pe.name!=="").sort((pe,it)=>pe.name.localeCompare(it.name)):[]}catch{return[]}}},[c,q,L,X]),R=i.useRef(!1),B=i.useCallback(async()=>{if(!X||!q){v(!0),y([]);return}R.current||v(!0);try{const V=await $(q);y(V),R.current=!0}catch{}finally{v(!1)}},[X,q,$]);i.useEffect(()=>{X&&(n==="inline"||w)&&B()},[n,w,X,B]);const z=async V=>{if(!X)return;const J=h.has(V.path),ee=new Set(h);if(J){ee.delete(V.path),j(ee);return}ee.add(V.path),j(ee);const xe=await $(V.path),fe=Oe=>Oe.map(Se=>Se.path===V.path?{...Se,children:xe}:Se.children?{...Se,children:fe(Se.children)}:Se);y(Oe=>fe(Oe))};i.useEffect(()=>{M&&P.current&&(P.current.focus(),P.current.select())},[M]);const G=(V,J=[])=>{const ee="new_directory",xe=J.map(Le=>Le.name);if(!xe.includes(ee))return ee;let fe=1;const Oe=new RegExp(`^${ee}(\\d+)$`);for(const Le of xe){const pe=Le.match(Oe);if(pe){const it=parseInt(pe[1],10);it>fe&&(fe=it)}}let Se=2;for(;xe.includes(`${ee}${Se}`);)Se++;return`${ee}${Math.max(Se,fe+1)}`},ge=async V=>{if(X){if(h.has(V.path)){const J=G(V.path,V.children);E(J)}else{const J=new Set(h);if(J.add(V.path),j(J),V.children){const ee=G(V.path,V.children);E(ee)}else{const ee=await $(V.path),xe=Oe=>Oe.map(Se=>Se.path===V.path?{...Se,children:ee}:Se.children?{...Se,children:xe(Se.children)}:Se);y(Oe=>xe(Oe));const fe=G(V.path,ee);E(fe)}}S(V.path)}},oe=async()=>{if(!M||!X)return;const V=D.trim()||"new_directory",J=`${M}/${V}`;try{await Ee.createDirectory(J);const ee=await $(M),xe=fe=>fe.map(Oe=>Oe.path===M?{...Oe,children:ee}:Oe.children?{...Oe,children:xe(Oe.children)}:Oe);y(fe=>xe(fe)),S(null),E("")}catch(ee){console.error("Failed to create directory:",ee)}},me=()=>{S(null),E("")},Ne=(V,J=0)=>{const ee=h.has(V.path),xe=V.isDirectory,fe=A.has(V.path),Oe=s===V.path,Se=n==="inline",Le=e.jsxs(e.Fragment,{children:[xe&&e.jsx("button",{onClick:pe=>{pe.stopPropagation(),z(V)},className:_("hover:bg-accent rounded","p-0.5"),children:ee?e.jsx(Ft,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Rs,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!xe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:pe=>{pe.stopPropagation(),re(V.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:pe=>{pe.stopPropagation(),l&&l(V.path)},className:_("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",Se&&Oe?"text-primary":"text-foreground"),children:[e.jsx(Hs,{className:_("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",Se&&Oe&&"text-primary")}),e.jsx("span",{className:_("font-medium truncate","typography-ui-label",Se&&Oe?"text-primary":"text-foreground"),children:V.name})]}),e.jsx("button",{onClick:pe=>{pe.stopPropagation(),ge(V)},className:_("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(Xt,{className:_("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:pe=>{pe.stopPropagation(),ae(V.path)},className:_("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:fe?"Unpin directory":"Pin directory",children:fe?e.jsx(Ga,{className:_("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Vp,{className:_("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:_("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",Oe?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${J*(p?12:14)+(p?4:6)}px`},children:Le}),ee&&e.jsxs(e.Fragment,{children:[M===V.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Hs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:P,value:D,onChange:pe=>E(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"?(pe.preventDefault(),pe.stopPropagation(),oe()):pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),me())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:pe=>{pe.preventDefault(),pe.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(_t,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:pe=>{pe.preventDefault(),pe.stopPropagation(),me()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),V.children&&V.children.map(pe=>Ne(pe,J+1))]})]},V.path):e.jsxs("div",{children:[e.jsxs(Et,{className:_("flex items-center gap-1 cursor-pointer group",s===V.path&&"bg-accent"),style:{paddingLeft:`${J*12+8}px`},onSelect:pe=>{pe.preventDefault()},children:[xe&&e.jsx("button",{onClick:pe=>{pe.stopPropagation(),z(V)},className:"p-0.5 hover:bg-accent rounded",children:ee?e.jsx(Ft,{className:"h-3 w-3"}):e.jsx(Rs,{className:"h-3 w-3"})}),!xe&&e.jsx("div",{className:"w-4"}),Le]}),ee&&e.jsxs("div",{children:[M===V.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(J+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(Hs,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:P,value:D,onChange:pe=>E(pe.target.value),onKeyDown:pe=>{pe.key==="Enter"?(pe.preventDefault(),pe.stopPropagation(),oe()):pe.key==="Escape"&&(pe.preventDefault(),pe.stopPropagation(),me())},onBlur:oe,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:pe=>{pe.preventDefault(),pe.stopPropagation(),oe()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(_t,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:pe=>{pe.preventDefault(),pe.stopPropagation(),me()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),V.children&&V.children.map(pe=>Ne(pe,J+1))]})]},V.path)},Ce=(V,J)=>{if(n==="inline"){const ee=s===J;return e.jsxs("div",{className:_("group flex items-center gap-2 mx-1 rounded-lg transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",ee?"bg-primary/10":"hover:bg-accent/50"),children:[e.jsxs("button",{onClick:()=>re(J),onDoubleClick:xe=>{xe.stopPropagation(),l&&l(J)},className:_("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",ee?"text-primary":"text-foreground"),children:[e.jsx(Hs,{className:_("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ee?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:_("typography-ui-label font-medium truncate flex-shrink-0",ee?"text-primary":"text-foreground"),children:V}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Yr(J,x)})]}),e.jsx("button",{onClick:()=>ae(J),className:_("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(Ga,{className:_("text-primary","h-3.5 w-3.5")})})]},J)}return e.jsxs(Et,{onSelect:ee=>{ee.preventDefault(),re(J),a==="immediate"&&N(!1)},className:_("flex items-start gap-2 cursor-pointer group py-2",s===J&&"bg-accent"),children:[e.jsx(Hs,{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:V}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Yr(J,x)})]}),e.jsx("button",{onClick:ee=>{ee.stopPropagation(),ee.preventDefault(),ae(J)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Ga,{className:"h-3 w-3 text-primary"})})]},J)},Be=e.jsx(e.Fragment,{children:X?e.jsxs(e.Fragment,{children:[F.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>I(V=>!V),className:_("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:[T?e.jsx(Ft,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Rs,{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:F.length})]}),T&&F.map(({name:V,path:J})=>Ce(V,J)),n==="dropdown"&&e.jsx(js,{}),n==="inline"&&T&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:_("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(V=>Ne(V)),!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:_("overflow-hidden flex flex-col",o),children:e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Be})}):e.jsxs(qt,{open:w,onOpenChange:N,children:[e.jsx(Kt,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",className:_("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(Hs,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Yr(s,x)})]}),e.jsx(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Qt,{align:"start",className:"w-[350px]",children:e.jsx(gt,{outerClassName:"h-full",className:"w-full",children:Be})})]})},Oa=(s,r=200)=>{const[t,n]=Ae.useState(s);return Ae.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},zm=i.forwardRef(({inputValue:s,homeDirectory:r,onSelectSuggestion:t,visible:n,onClose:o,showHidden:a},l)=>{const[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(0),g=i.useRef(null),y=i.useRef([]),h=i.useCallback((x,k)=>{const A=x.trim().toLowerCase();if(!A)return 0;const C=k.toLowerCase();let M=0,S=-1,D=0;for(let E=0;E<A.length;E+=1){const T=A[E];if(!T||T===" ")continue;const I=C.indexOf(T,S+1);if(I===-1)return null;const P=I-S-1;if(P===0?D+=1:D=0,M+=10,M+=Math.max(0,18-I),M-=Math.max(0,P),I===0)M+=12;else{const O=C[I-1];(O==="/"||O==="_"||O==="-"||O==="."||O===" ")&&(M+=10)}M+=D>0?12:0,S=I}return M+=Math.max(0,24-Math.round(C.length/3)),M},[]),j=i.useCallback(x=>x.startsWith("~")&&r?x.replace(/^~/,r):x,[r]),b=i.useCallback(x=>{const k=j(x);if(k.endsWith("/"))return k;const A=k.lastIndexOf("/");return A===-1?"":A===0?"/":k.substring(0,A+1)},[j]),v=i.useCallback(x=>{const k=j(x);if(k.endsWith("/"))return"";const A=k.lastIndexOf("/");return A===-1?k:k.substring(A+1)},[j]),w=Oa(s,150);i.useEffect(()=>{if(!n||!w){d([]);return}const x=b(w),k=v(w).toLowerCase();if(!x){d([]);return}let A=!1;return m(!0),Ee.listLocalDirectory(x).then(C=>{if(A)return;const M=C.filter(D=>!(!D.isDirectory||!a&&D.name.startsWith("."))),S=k?M.map(D=>{const E=h(k,D.name);return E!==null?{entry:D,score:E}:null}).filter(D=>D!==null).sort((D,E)=>E.score-D.score||D.entry.name.localeCompare(E.entry.name)).map(D=>D.entry):M.sort((D,E)=>D.name.localeCompare(E.name));d(S.slice(0,10)),p(0)}).catch(()=>{A||d([])}).finally(()=>{A||m(!1)}),()=>{A=!0}},[n,w,b,v,a,h]),i.useEffect(()=>{y.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),i.useEffect(()=>{if(!n)return;const x=k=>{const A=k.target;!A||!g.current||g.current.contains(A)||o()};return document.addEventListener("pointerdown",x,!0),()=>{document.removeEventListener("pointerdown",x,!0)}},[n,o]);const N=i.useCallback(x=>{const k=x.path.endsWith("/")?x.path:x.path+"/";t(k)},[t]);return i.useImperativeHandle(l,()=>({handleKeyDown:x=>{if(!n||c.length===0)return!1;const k=c.length;if(x.key==="Tab"){if(x.preventDefault(),x.shiftKey)p(A=>(A-1+k)%k);else if(k===1){const A=c[0];A&&N(A)}else p(A=>(A+1)%k);return!0}if(x.key==="ArrowDown")return x.preventDefault(),p(A=>(A+1)%k),!0;if(x.key==="ArrowUp")return x.preventDefault(),p(A=>(A-1+k)%k),!0;if(x.key==="Enter"){x.preventDefault();const A=(f%k+k)%k,C=c[A];return C&&N(C),o(),!0}return x.key==="Escape"?(x.preventDefault(),o(),!0):!1}}),[n,c,f,N,o]),!n||c.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(jr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:c.map((x,k)=>{const A=f===k;return e.jsxs("div",{ref:C=>{y.current[k]=C},className:_("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",A&&"bg-muted"),onClick:()=>{N(x),o()},onMouseEnter:()=>p(k),children:[e.jsx(ur,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:x.name})]},x.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"})]})});zm.displayName="DirectoryAutocomplete";const Zc="directoryTreeShowHidden",Lb=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=vt(),{addProject:a,getActiveProject:l}=Ot(),[c,d]=i.useState(null),[u,m]=i.useState(""),[f,p]=i.useState(!1),[g,y]=i.useState(!1),[h,j]=i.useState(()=>{if(typeof window>"u")return!1;try{const K=window.localStorage.getItem(Zc);if(K==="true")return!0;if(K==="false")return!1}catch{}return!1}),{isDesktop:b,requestAccess:v,startAccessing:w}=_a(),{isMobile:N}=$t(),[x,k]=i.useState(!1),A=i.useRef(null),C=i.useCallback(K=>K?Yr(K,n):"",[n]);i.useEffect(()=>{if(s){p(!1),y(!1),k(!1);const ae=l()?.path||t||n||"";d(ae),m(C(ae))}},[s,t,n,C,l]),i.useEffect(()=>{!s||f||c||n&&o&&(d(n),p(!0),m("~"))},[s,f,c,n,o]),i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Zc,h?"true":"false")}catch{}},[h]);const M=i.useCallback(()=>{r(!1)},[r]),S=i.useCallback(async K=>{if(!(!K||g)){y(!0);try{let ae=K,F;if(b){const R=await v(K);if(!R.success){te.error("Unable to access directory",{description:R.error||"Desktop denied directory access."});return}ae=R.path??K,F=R.projectId;const B=await w(ae);if(!B.success){te.error("Failed to open directory",{description:B.error||"Desktop could not grant file access."});return}}if(!a(ae,{id:F})){te.error("Failed to add project",{description:"Please select a valid directory path."});return}M()}catch(ae){te.error("Failed to select directory",{description:ae instanceof Error?ae.message:"Unknown error occurred."})}finally{y(!1)}}},[a,M,b,v,w,g]),D=i.useCallback(async()=>{const K=u.trim()||c;K&&await S(K)},[S,u,c]),E=i.useCallback(K=>{d(K),p(!0),m(C(K))},[C]),T=i.useCallback(async K=>{d(K),p(!0),m(C(K)),await S(K)},[S,C]),I=i.useCallback(K=>{const ae=K.target.value;if(m(ae),p(!0),k(ae.startsWith("/")||ae.startsWith("~")),ae.startsWith("/")||ae.startsWith("~")){const F=ae.startsWith("~")&&n?ae.replace(/^~/,n):ae;d(F)}},[n]),P=i.useCallback(K=>{A.current?.handleKeyDown(K)||K.key==="Enter"&&(K.preventDefault(),D())},[D]),O=i.useCallback(K=>{d(K),p(!0),m(C(K))},[C]),U=i.useCallback(()=>{k(!1)},[]),Q=i.useCallback(()=>{j(K=>!K)},[]),W=e.jsxs("button",{type:"button",onClick:Q,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(cl,{className:"h-4 w-4 text-primary"}):e.jsx(dl,{className:"h-4 w-4"}),"Show hidden"]}),L=e.jsxs(ys,{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(bs,{children:"Add project directory"}),e.jsxs("div",{className:"hidden sm:flex sm:items-center sm:justify-between sm:gap-4",children:[e.jsx(Ms,{className:"flex-1",children:"Choose a folder to add as a project."}),W]})]}),H=e.jsxs("div",{className:"relative",children:[e.jsx(jt,{value:u,onChange:I,onKeyDown:P,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(zm,{ref:A,inputValue:u,homeDirectory:n,onSelectSuggestion:O,visible:x,onClose:U,showHidden:h})]}),q=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(Jc,{variant:"inline",currentPath:c??t,onSelectPath:E,onDoubleClickPath:T,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o})}),X=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:H}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:W}),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(Jc,{variant:"inline",currentPath:c??t,onSelectPath:E,onDoubleClickPath:T,className:"flex-1 min-h-0",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o,alwaysShowActions:!0})})]}),Y=e.jsxs("div",{className:"flex-1 min-h-0 overflow-hidden flex flex-col gap-3",children:[H,q]}),re=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ie,{variant:"ghost",onClick:M,disabled:g,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Ie,{onClick:D,disabled:g||!f||!c&&!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:re()}),children:X}):e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:_("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:K=>{K.preventDefault()},children:[L,Y,e.jsx(Js,{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:re()})]})})},Do=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,Bb=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},zb=()=>{const[s,r]=i.useState(!1),[t,n]=i.useState(!1),o=i.useRef(new Set),[a,l]=i.useState(null),[c,d]=i.useState([]),[u,m]=i.useState(!1),[f,p]=i.useState(!1),{deleteSession:g,deleteSessions:y,loadSessions:h,getWorktreeMetadata:j}=he(),{currentDirectory:b,homeDirectory:v,isHomeReady:w}=vt(),{projects:N,addProject:x,activeProjectId:k}=Ot(),{requestAccess:A,startAccessing:C}=_a(),{isMobile:M,isTablet:S,hasTouchInput:D}=$t(),E=M||S||D,T=i.useMemo(()=>{const R=(k?N.find(B=>B.id===k)??null:null)?.path??b;return Bb(R)},[k,b,N]),I=i.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||c.some($=>$.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,c]),P=i.useMemo(()=>{const $=a?.worktree;return $&&typeof $.branch=="string"&&$.branch.trim().length>0?!0:c.length>0&&c.every(({metadata:R})=>typeof R.branch=="string"&&R.branch.trim().length>0)},[a?.worktree,c]),O=a?.mode==="worktree",U=O,Q=f||!O||!P;i.useEffect(()=>{T&&(o.current.has(T)||Px(T).then(()=>o.current.add(T)).catch($=>{console.warn("Failed to ensure .openchamber directory is ignored:",$),o.current.delete(T)}))},[T]),i.useEffect(()=>{h()},[h,b]);const W=i.useMemo(()=>N.map($=>`${$.id}:${$.path}`).join("|"),[N]),L=i.useRef(W);i.useEffect(()=>{W!==L.current&&(L.current=W,h())},[h,W]),i.useEffect(()=>{if(!(t||!w||N.length>0)){if(n(!0),es()){A("").then(async $=>{if(!$.success||!$.path){$.error&&$.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:$.error});return}const R=await C($.path);if(!R.success){te.error("Failed to open directory",{description:R.error||"Desktop could not grant file access."});return}x($.path,{id:$.projectId})||te.error("Failed to add project",{description:"Please select a valid directory path."})}).catch($=>{console.error("Desktop: Error selecting directory:",$),te.error("Failed to select directory")});return}r(!0)}},[x,t,w,N.length,A,C]);const H=i.useCallback($=>{l({sessions:$.sessions,dateLabel:$.dateLabel,mode:$.mode??"session",worktree:$.worktree??null})},[]),q=i.useCallback(()=>{l(null),d([]),m(!1),p(!1)},[]);i.useEffect(()=>En.onDeleteRequest($=>{H($)}),[H]),i.useEffect(()=>En.onDirectoryRequest(()=>{r(!0)}),[]),i.useEffect(()=>{if(!a){d([]),m(!1);return}const $=a.sessions.map(B=>{const z=j(B.id);return z?{session:B,metadata:z}:null}).filter(B=>!!B);if(d($),m(!1),$.length===0)return;let R=!1;return(async()=>{const B=await Promise.all($.map(async({metadata:z})=>{if(z.status&&typeof z.status.isDirty=="boolean")return z.status;try{return await wl(z.path)}catch{return z.status}})).catch(z=>(console.warn("Failed to inspect worktree status before deletion:",z),$.map(({metadata:G})=>G.status)));R||!Array.isArray(B)||d(z=>z.map((G,ge)=>({session:G.session,metadata:{...G.metadata,status:B[ge]??G.metadata.status}})))})(),()=>{R=!0}},[a,j]),i.useEffect(()=>{P||m(!1)},[P]);const X=i.useCallback(async()=>{if(a){p(!0);try{const $=U,R=$&&u;if(a.sessions.length===0&&O&&a.worktree){const B=u&&P;await mm({projectDirectory:T,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:B});const z=B?"Worktree and remote branch removed.":"Worktree removed.";te.success("Worktree removed",{description:Do(z)}),q(),h();return}if(a.sessions.length===1){const B=a.sessions[0];if(!await g(B.id,{archiveWorktree:$,deleteRemoteBranch:R})){te.error("Failed to delete session"),p(!1);return}const G=$?R?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;te.success("Session deleted",{description:Do(G)})}else{const B=a.sessions.map(ge=>ge.id),{deletedIds:z,failedIds:G}=await y(B,{archiveWorktree:$,deleteRemoteBranch:R});if(z.length>0){const ge=$?R?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,me=[G.length>0?`${G.length} session${G.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,ge].filter(Boolean).join(" ");te.success(`Deleted ${z.length} session${z.length===1?"":"s"}`,{description:Do(me||void 0)})}if(G.length>0&&(te.error(`Failed to delete ${G.length} session${G.length===1?"":"s"}`,{description:Do("Please try again in a moment.")}),z.length===0)){p(!1);return}}q()}finally{p(!1)}}},[a,u,g,y,q,U,O,P,T,h]),Y=a?.worktree??c[0]?.metadata??null,re=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}`:""}.`:"",K=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:[O&&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($=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:$.title||"Untitled Session"},$.id)),a.sessions.length>5&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",a.sessions.length-5," more"]})]})]}),O?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"}),Y?.label?e.jsx("span",{className:"typography-micro text-muted-foreground/70",children:Y.label}):null]}),e.jsx("p",{className:"typography-micro text-muted-foreground/80 break-all",children:Y?Yr(Y.path,v):"Worktree path unavailable."}),I&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),P?e.jsxs("button",{type:"button",onClick:()=>{Q||m($=>!$)},disabled:Q,className:_("flex w-full items-start gap-3 rounded-xl border border-border/40 bg-sidebar/70 px-3 py-2 text-left",Q?"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(cl,{className:"size-4 text-primary"}):e.jsx(dl,{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,ae=e.jsxs(e.Fragment,{children:[e.jsx(Ie,{variant:"ghost",onClick:q,disabled:f,children:"Cancel"}),e.jsx(Ie,{variant:"destructive",onClick:X,disabled:f,children:f?"Deleting…":O?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),F=O?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[E?e.jsx(ws,{open:!!a,onClose:()=>{f||q()},title:F,footer:e.jsx("div",{className:"flex justify-end gap-2",children:ae}),children:e.jsxs("div",{className:"space-y-2 pb-2",children:[re&&e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:re}),K]})}):e.jsx(ms,{open:!!a,onOpenChange:$=>{if(!$){if(f)return;q()}},children:e.jsxs(fs,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[e.jsxs(ys,{children:[e.jsx(bs,{children:F}),re&&e.jsx(Ms,{children:re})]}),K,e.jsx(Js,{className:"mt-2 gap-2 pt-1 pb-1",children:ae})]})}),e.jsx(Lb,{open:s,onOpenChange:r})]})};function Wb(){return new Worker(Gp,{type:"module"})}const Hb=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Ub(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 ed(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const Vb=({children:s})=>{const r=Kp(),t=Gt(c=>c.activeDirectory),n=Gt(c=>t?c.directories.get(t)?.lastStatusChange??0:0),o=Gt(c=>t?c.directories.get(t)?.diffCache.size??0:0),a=Ae.useRef(!1),l=Ae.useRef(new Map);return Ae.useEffect(()=>{if(!r||a.current)return;a.current=!0;const c={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=Fi(c,{...c,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),Ae.useEffect(()=>{if(!r||!t||!n||o===0)return;const c=Gt.getState().directories.get(t);if(!c||c.diffCache.size===0||(l.current.get(t)??0)>=c.lastStatusChange)return;l.current.set(t,c.lastStatusChange);let u=!1,m=null;const f=Array.from(c.diffCache.entries());let p=0;const g=y=>{if(u)return;const h=Date.now();for(;p<f.length&&!(y&&y.timeRemaining()<8||!y&&Date.now()-h>8);){const[j,b]=f[p];p+=1,fr(j);const v=Ub(j,b.original,b.modified),w={name:j,contents:b.original,cacheKey:`old-${v}`},N={name:j,contents:b.modified,cacheKey:`new-${v}`},x=Fi(w,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,x)}p<f.length&&(m=ed(g))};return g(void 0),p<f.length&&(m=ed(g)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},Gb=({children:s})=>{const t=Fa()?.currentTheme?.metadata?.variant==="dark";Dm();const n=Ae.useMemo(()=>({theme:{dark:An.dark,light:An.light},themeType:t?"dark":"light",langs:Hb}),[t]);return e.jsx(qp,{poolOptions:{workerFactory:Wb,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Vb,{children:s})})},Yi=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),qb=(s,r)=>{const t=Yi(s),n=Yi(r);return`${t}-${n}`.substring(0,60)},td=(s,r)=>`${s}/${r}`,Kb=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Qb=()=>{const s=Ot.getState(),r=s.activeProjectId,t=r?s.projects.find(c=>c.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=vt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,l=o.indexOf("/.openchamber/");return l>0?o.slice(0,l):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},Yn=Vt()(Jt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:l,setupCommands:c}=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=Qb();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await cn(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=Yi(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,g=[],y=c?.filter(x=>x.trim().length>0)??[],h=new Map;for(const x of o){const k=`${x.providerID}:${x.modelID}`;h.set(k,(h.get(k)||0)+1)}const j=new Map;for(const x of o){const k=`${x.providerID}:${x.modelID}`,A=h.get(k)||1,C=(j.get(k)||0)+1;j.set(k,C);const M=qb(x.providerID,x.modelID),S=A>1?td(m,`${M}/${C}`):td(m,M);if(!S)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const D=Kb(S);if(!D)return s({error:`Invalid branch name: ${S}`,isLoading:!1}),null;try{const E=await um({projectDirectory:d,worktreeSlug:D,branch:S,createBranch:!0,startPoint:p}),T=A>1?`${m}/${x.providerID}/${x.modelID}/${C}`:`${m}/${x.providerID}/${x.modelID}`,I=await Ee.withDirectory(E.path,()=>Ee.createSession({title:T}));ht.getState().setWorktreeMetadata(I.id,E),g.push({sessionId:I.id,worktreePath:E.path,providerID:x.providerID,modelID:x.modelID,variant:x.variant})}catch(E){console.warn("[MultiRun] Failed to create session:",E)}}const b=c?.filter(x=>x.trim().length>0)??[];b.length>0&&lm(d,b).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const v=g.map(x=>x.sessionId),w=g[0]?.sessionId??null;if(v.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const N=l?.map(x=>({type:"file",mime:x.mime,filename:x.filename,url:x.url}));try{await ht.getState().loadSessions()}catch{}if(y.length>0)for(const x of g)fm(x.worktreePath,d,y).then(k=>{if(!k.success){const A=k.results.filter(C=>!C.success);console.warn(`[MultiRun] Setup commands failed for ${x.worktreePath}:`,A)}}).catch(k=>{console.warn(`[MultiRun] Setup commands error for ${x.worktreePath}:`,k)});return(async()=>{try{await Promise.allSettled(g.map(async x=>{try{await Ee.withDirectory(x.worktreePath,()=>Ee.sendMessage({id:x.sessionId,providerID:x.providerID,modelID:x.modelID,variant:x.variant,text:n,agent:a,files:N}))}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(x){console.warn("[MultiRun] Failed to start runs:",x)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:v,firstSessionId:w}}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 ks({...s}){return e.jsx(Qp,{"data-slot":"select",...s})}function Jr({...s}){return e.jsx(sh,{"data-slot":"select-group",...s})}function nn({...s}){return e.jsx(Jp,{"data-slot":"select-value",...s})}function Ns({className:s,size:r="default",children:t,...n}){return e.jsxs(Yp,{"data-slot":"select-trigger","data-size":r,className:_("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(Xp,{asChild:!0,children:e.jsx(Ft,{className:"size-4 opacity-50"})})]})}function Cs({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(Zp,{children:e.jsx(eh,{"data-slot":"select-content",className:_("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(gt,{as:th,outerClassName:_("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:_("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 Nn({className:s,...r}){return e.jsx(rh,{"data-slot":"select-label",className:_("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Ut({className:s,children:r,...t}){return e.jsxs(nh,{"data-slot":"select-item",className:_("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(oh,{children:e.jsx(_t,{className:"size-4"})})}),e.jsx(ah,{children:r})]})}function xa({className:s,...r}){return e.jsx(ih,{"data-slot":"select-separator",className:_("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}const Yb="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":Yb}),Xi=new Map;for(const[s,r]of Object.entries(Xb)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Xi.set(t[1].toLowerCase(),r)}function Wm(s){const r=s?.toLowerCase()??null,t=r?Xi.has(r):!1,n=r?Xi.get(r)??null:null,[o,a]=Ae.useState(t?"local":"remote");Ae.useEffect(()=>{a(t?"local":"remote")},[t,r]);const l=Ae.useCallback(()=>{a(c=>c==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:l,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:l,hasLogo:!0}:{src:null,onError:l,hasLogo:!1}:{src:null,onError:l,hasLogo:!1}}const cs=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:l}=Wm(s),c=i.useCallback(()=>{a(),n?.()},[a,n]);return!l||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:_("dark:invert",t),onError:c})},Fl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,Rl=()=>{const{providers:s}=at(),{favoriteModels:r,recentModels:t}=$e(),n=i.useMemo(()=>r.map(({providerID:a,modelID:l})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null),[r,s]),o=i.useMemo(()=>t.map(({providerID:a,modelID:l})=>{const c=s.find(m=>m.id===a);if(!c)return null;const u=(Array.isArray(c.models)?c.models:[]).find(m=>m.id===l);return u?{provider:c,model:u,providerID:a,modelID:l}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:l})=>!r.some(c=>c.providerID===a&&c.modelID===l)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},Hm="h-7",ya=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Jb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Zb=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Jb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},ev=({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:_("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Hm),children:[e.jsx(cs,{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"})})]})},Um=({selectedModels:s,onAdd:r,onRemove:t,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:l=!0,maxModels:c})=>{const{providers:d,modelsMetadata:u}=at(),{favoriteModelsList:m,recentModelsList:f}=Rl(),[p,g]=i.useState(!1),[y,h]=i.useState(""),[j,b]=i.useState(0),[v,w]=i.useState(null),N=i.useRef(null),x=i.useRef(null),k=i.useRef(null),A=i.useRef([]),C=i.useMemo(()=>{const Q=new Map;for(const W of s){const L=`${W.providerID}:${W.modelID}`;Q.set(L,(Q.get(L)||0)+1)}return Q},[s]),M=i.useCallback(Q=>s.filter(L=>L.providerID===Q.providerID&&L.modelID===Q.modelID).findIndex(L=>L.instanceId===Q.instanceId)+1,[s]),S=(Q,W)=>{const L=`${Q}/${W}`;return u.get(L)},D=Q=>{const W=Q?.name||Q?.id||"",L=String(W);return L.length>40?L.substring(0,37)+"...":L},E=i.useCallback((Q,W)=>{if(!y.trim())return!0;const L=y.toLowerCase();return Q.toLowerCase().includes(L)||W.toLowerCase().includes(L)},[y]),T=i.useMemo(()=>m.filter(({model:Q,providerID:W})=>{const H=d.find(X=>X.id===W)?.name||W,q=D(Q);return E(q,H)}),[m,d,E]),I=i.useMemo(()=>f.filter(({model:Q,providerID:W})=>{const H=d.find(X=>X.id===W)?.name||W,q=D(Q);return E(q,H)}),[f,d,E]),P=i.useMemo(()=>d.map(Q=>{const L=(Array.isArray(Q.models)?Q.models:[]).filter(H=>{const q=D(H);return E(q,Q.name||Q.id||"")});return{...Q,models:L}}).filter(Q=>Q.models.length>0),[d,E]),O=T.length>0||I.length>0||P.length>0;i.useEffect(()=>{if(p&&k.current){const W=k.current.getBoundingClientRect().top-100;w(Math.max(150,Math.min(400,W)))}},[p]),i.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),i.useEffect(()=>{if(!p)return;const Q=W=>{x.current&&!x.current.contains(W.target)&&(g(!1),h(""),b(0))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]),i.useEffect(()=>{b(0)},[y]);const U=(Q,W,L,H,q,X)=>{const Y=`${W}:${L}`,re=C.get(Y)||0,K=S(W,L),ae=Zb(K?.limit?.context);return e.jsxs("button",{ref:F=>{A.current[q]=F},type:"button",onClick:()=>{r({providerID:W,modelID:L,displayName:Q.name||L,instanceId:ya()})},onMouseEnter:()=>b(q),className:_("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",X?"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:D(Q)}),ae&&e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:ae})]}),re>0&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:["×",re]})]},`${H}-${Y}`)};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:x,children:[e.jsxs(Ie,{ref:k,type:"button",variant:"outline",size:"sm",className:Hm,onClick:()=>g(!p),children:[e.jsx(Xt,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const Q=[];T.forEach(({model:q,providerID:X,modelID:Y})=>{Q.push({model:q,providerID:X,modelID:Y,section:"fav"})}),I.forEach(({model:q,providerID:X,modelID:Y})=>{Q.push({model:q,providerID:X,modelID:Y,section:"recent"})}),P.forEach(q=>{q.models.forEach(X=>{Q.push({model:X,providerID:q.id,modelID:X.id,section:"provider"})})});const W=Q.length,L=q=>{if(!Fl(q))if(q.key==="ArrowDown"){q.preventDefault(),q.stopPropagation();const X=(j+1)%Math.max(1,W);b(X),setTimeout(()=>{A.current[X]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(q.key==="ArrowUp"){q.preventDefault(),q.stopPropagation();const X=(j-1+Math.max(1,W))%Math.max(1,W);b(X),setTimeout(()=>{A.current[X]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(q.key==="Enter"){q.preventDefault(),q.stopPropagation();const X=Q[j];X&&r({providerID:X.providerID,modelID:X.modelID,displayName:X.model.name||X.modelID,instanceId:ya()})}else q.key==="Escape"&&(q.preventDefault(),q.stopPropagation(),g(!1),h(""),b(0))};let H=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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{ref:N,type:"text",placeholder:"Search models",value:y,onChange:q=>h(q.target.value),onKeyDown:L,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(gt,{outerClassName:"flex-1",style:{maxHeight:v?`${v}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!O&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),T.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(yr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),T.map(({model:q,providerID:X,modelID:Y})=>{const re=H++;return U(q,X,Y,"fav",re,j===re)})]}),I.length>0&&e.jsxs(e.Fragment,{children:[T.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(cr,{className:"h-4 w-4"}),"Recent"]}),I.map(({model:q,providerID:X,modelID:Y})=>{const re=H++;return U(q,X,Y,"recent",re,j===re)})]}),(T.length>0||I.length>0)&&P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),P.map((q,X)=>e.jsxs(i.Fragment,{children:[X>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(cs,{providerId:q.id,className:"h-4 w-4 flex-shrink-0"}),q.name]}),q.models.map(Y=>{const re=H++;return U(Y,q.id,Y.id,"provider",re,j===re)})]},q.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"})]})})()]}),l&&s.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:s.map((Q,W)=>{const L=`${Q.providerID}:${Q.modelID}`,H=C.get(L)||1,q=M(Q),Y=d.find($=>$.id===Q.providerID)?.models.find($=>$.id===Q.modelID),re=Y?.variants?Object.keys(Y.variants):[],K=re.length>0,ae="__default__",F=Q.variant??ae;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(ev,{model:Q,instanceIndex:q,totalSameModel:H,onRemove:()=>t(W)}),K&&e.jsxs(ks,{value:F,onValueChange:$=>{if(!n)return;n(W,{...Q,variant:$===ae?void 0:$})},children:[e.jsxs(Ns,{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(dr,{className:_("h-3.5 w-3.5 flex-shrink-0",F===ae?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(nn,{placeholder:"Thinking"})]}),e.jsxs(Cs,{fitContent:!0,children:[e.jsx(Ut,{value:ae,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),re.map($=>e.jsx(Ut,{value:$,className:"pr-2 [&>span:first-child]:hidden",children:$},$))]})]})]},Q.instanceId)})})]}),o!==void 0&&s.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",c!==void 0?`to ${c} models`:"","."]})]})};function _l(s){const[r,t]=i.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=i.useState(!1),[a,l]=i.useState(null);return i.useEffect(()=>{let c=!1;if(!s){l(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),l(null),(async()=>{try{const d=await cn(s);if(c)return;if(l(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await vl(s).catch(()=>null);if(c)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(y=>!y.startsWith("remotes/")).sort((y,h)=>y.localeCompare(h)).forEach(y=>{m.push({value:y,label:y,group:"local"})}),u.all.filter(y=>y.startsWith("remotes/")).map(y=>y.replace(/^remotes\//,"")).sort((y,h)=>y.localeCompare(h)).forEach(y=>{m.push({value:y,label:y,group:"remote"})})),t(m)}finally{c||o(!1)}})(),()=>{c=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const Vm=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:l,isLoading:c,isGitRepository:d}=_l(s),u=i.useMemo(()=>l.find(f=>f.value===r)?.label??null,[l,r]);i.useEffect(()=>{!l.some(p=>p.value===r)&&l.length>0&&t("HEAD")},[l,r,t]);const m=o||!d||c;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ks,{value:r,onValueChange:t,disabled:m,children:[e.jsx(Ns,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(nn,{children:u}):e.jsx(nn,{placeholder:c?"Loading branches…":"Select a branch"})}),e.jsxs(Cs,{fitContent:!0,children:[e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Default"}),l.filter(f=>f.group==="special").map(f=>e.jsx(Ut,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),l.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Local branches"}),l.filter(f=>f.group==="local").map(f=>e.jsx(Ut,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,l.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Remote branches"}),l.filter(f=>f.group==="remote").map(f=>e.jsx(Ut,{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."})]})},Gm=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=at(f=>f.getVisibleAgents),l=at(f=>f.loadAgents),c=at(f=>f.currentAgentName),d=a(),u=i.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);i.useEffect(()=>{l()},[l]),i.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(y=>y.name===f))return;const p=typeof c=="string"&&c.trim().length>0?c.trim():null;if(p&&u.some(y=>y.name===p)){r(p);return}const g=u[0]?.name;g&&r(g)},[c,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(ks,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Ns,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(nn,{placeholder:"Select an agent"})}),e.jsx(Cs,{fitContent:!0,children:u.length>0&&e.jsx(Jr,{children:u.map(f=>e.jsx(Ut,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},tv=10*1024*1024,sd=5,rd=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=i.useState(""),[a,l]=i.useState(()=>s??""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState([]),[g,y]=i.useState(!1),[h,j]=i.useState([]),[b,v]=i.useState(!1),[w,N]=i.useState(!1),x=i.useRef(null),k=vt(R=>R.currentDirectory??null),A=i.useMemo(()=>{if(typeof window>"u")return null;const R=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof R=="string"&&R.trim().length>0?R.trim():null},[]),C=Ot(R=>R.activeProjectId),M=Ot(R=>R.projects),S=i.useMemo(()=>{if(C){const ge=M.find(oe=>oe.id===C);if(ge?.path)return ge.path}const R=k??A;if(!R)return null;const B=R.replace(/\\/g,"/").replace(/\/+$/,"")||R,G=B.indexOf("/.openchamber/");return G>0?B.slice(0,G):B.endsWith("/.openchamber")?B.slice(0,B.length-13):B},[C,M,k,A]),D=$e(R=>R.isSidebarOpen),[E,T]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),I=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);i.useEffect(()=>{if(typeof window>"u")return;const R=typeof window.opencodeDesktop<"u";T(R)},[]);const P=i.useMemo(()=>E&&I?D?"pl-0":"pl-[8.0rem]":"pl-3",[E,I,D]),[O,U]=i.useState("HEAD"),{isLoading:Q,isGitRepository:W}=_l(k),L=Yn(R=>R.createMultiRun),H=Yn(R=>R.error),q=Yn(R=>R.clearError);i.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&l(R=>R.trim().length>0?R:s)},[s]),i.useEffect(()=>{if(!S)return;let R=!1;return N(!0),(async()=>{try{const B=await fo(S);R||j(B)}catch{}finally{R||N(!1)}})(),()=>{R=!0}},[S]);const X=R=>{c.length>=sd||(d(B=>[...B,R]),q())},Y=R=>{d(B=>B.filter((z,G)=>G!==R)),q()},re=i.useCallback((R,B)=>{d(z=>z.map((G,ge)=>ge===R?B:G))},[]),K=async R=>{const B=R.target.files;if(!B)return;let z=0;for(let G=0;G<B.length;G++){const ge=B[G];if(ge.size>tv){te.error(`File "${ge.name}" is too large (max 10MB)`);continue}try{const oe=await new Promise((Ne,Ce)=>{const Be=new FileReader;Be.onload=()=>Ne(Be.result),Be.onerror=Ce,Be.readAsDataURL(ge)}),me={id:ya(),filename:ge.name,mimeType:ge.type||"application/octet-stream",size:ge.size,dataUrl:oe};p(Ne=>[...Ne,me]),z++}catch(oe){console.error("File attach failed",oe),te.error(`Failed to attach "${ge.name}"`)}}z>0&&te.success(`Attached ${z} file${z>1?"s":""}`),x.current&&(x.current.value="")},ae=R=>{p(B=>B.filter(z=>z.id!==R))},F=async R=>{if(R.preventDefault(),!!a.trim()&&!(c.length<2)){y(!0),q();try{const B=c.map(({instanceId:me,...Ne})=>Ne),z=f.map(me=>({mime:me.mimeType,filename:me.filename,url:me.dataUrl})),G=h.filter(me=>me.trim().length>0),ge={name:n.trim(),prompt:a.trim(),models:B,agent:u||void 0,worktreeBaseBranch:O,files:z.length>0?z:void 0,setupCommands:G.length>0?G:void 0},oe=await L(ge);oe&&(oe.firstSessionId&&he.getState().setCurrentSession(oe.firstSessionId),r?.())}finally{y(!1)}}},$=!!(n.trim()&&a.trim()&&c.length>=2&&W&&!Q);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:_("flex h-12 items-center justify-between border-b app-region-drag",P),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:_("flex items-center gap-3",E&&I&&D&&"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(dt,{delayDuration:500,children:[e.jsx(ut,{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(lt,{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:F,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(jt,{id:"group-name",value:n,onChange:R=>o(R.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(Vm,{directory:k,value:O,onChange:U,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:O||"HEAD"}),"."]})]}),e.jsxs(po,{open:b,onOpenChange:v,children:[e.jsxs(Ta,{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(R=>R.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",h.filter(R=>R.trim()).length," configured)"]})]}),e.jsx(Ft,{className:_("h-4 w-4 text-muted-foreground transition-transform duration-200",b&&"rotate-180")})]}),e.jsx(ho,{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."]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[h.map((R,B)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:R,onChange:z=>{const G=[...h];G[B]=z.target.value,j(G)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const z=h.filter((G,ge)=>ge!==B);j(z)},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"})})]},B)),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(Xt,{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(Gm,{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(Ss,{id:"prompt",value:a,onChange:R=>l(R.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:x,type:"file",multiple:!0,className:"hidden",onChange:K,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Ie,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>x.current?.click(),children:[e.jsx(sa,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(R=>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:[R.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:R.filename,children:R.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",R.size<1024?`${R.size}B`:R.size<1024*1024?`${(R.size/1024).toFixed(1)}KB`:`${(R.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ae(R.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},R.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(Um,{selectedModels:c,onAdd:X,onRemove:Y,onUpdate:re,minModels:2,maxModels:sd})]}),H&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:H}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Ie,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(Ie,{type:"submit",disabled:!$||g,children:g?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(lh,{className:"h-4 w-4 mr-2"}),"Start (",c.length," models)"]})})]})]})})})]})},sv=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:l,isSessionSwitcherOpen:c}=$e(),d=Ae.useRef(null),u=Ae.useRef(null);return Ae.useEffect(()=>{if(!o||!a)return;const m=y=>{const h=y.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=y=>{if(!d.current)return;const h=y.touches[0];if(!h)return;h.clientX-d.current.x>10&&y.preventDefault()},p=y=>{if(!d.current)return;const h=y.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:v}=d.current,{x:w,y:N,time:x}=u.current,k=w-j,A=N-b,C=x-v,M=Math.abs(A)<Math.abs(k),S=C<=n,D=Math.abs(A)<t;k>=t&&M&&S&&D&&!c&&l(!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,l,c]),null},Un=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;Ae.memo(()=>{const s=Ae.useRef(null),{addAttachedFile:r}=he(),{isMobile:t}=$e(),n=km(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",l=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],g=he.getState().attachedFiles.length;try{await r(p),he.getState().attachedFiles.length>g&&m++}catch(y){console.error("File attach failed",y),te.error(y instanceof Error?y.message:"Failed to attach file")}}m>0&&te.success(`Attached ${m} file${m>1?"s":""}`)},c=async u=>{const m=u.target.files;m&&(await l(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 y=p.map(h=>`${h?.name||"file"}: ${h?.reason||"skipped"}`).join(`
85
- `);te.error(`Some files were skipped:
86
- ${y}`)}const g=f.map(y=>{if(!y?.dataUrl)return null;try{const[h,j]=y.dataUrl.split(","),b=y.mimeType||h?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!j)return null;const v=atob(j),w=new Uint8Array(v.length);for(let x=0;x<v.length;x++)w[x]=v.charCodeAt(x);const N=new Blob([w],{type:b});return new File([N],y.name||"file",{type:b})}catch(h){return console.error("Failed to decode VS Code picked file",h),null}}).filter(Boolean);g.length>0&&await l(g)}catch(u){console.error("VS Code file pick failed",u),te.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:c,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:_(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(sa,{className:_(a,"text-current")})})]})});const rv=Ae.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(nr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(Ca,{className:"h-3.5 w-3.5"}):e.jsx(nr,{className:"h-3.5 w-3.5"}),n=l=>l<1024?l+" B":l<1048576?(l/1024).toFixed(1)+" KB":(l/1048576).toFixed(1)+" MB",a=(l=>{const d=l.replace(/\\/g,"/").split("/");return d[d.length-1]||l})(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(ch,{className:"h-3 w-3 text-primary"}):e.jsx(Nu,{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"})})]})}),nv=Ae.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=he();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(rv,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),qm=Ae.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(mr,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(nr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(Ca,{className:"h-3.5 w-3.5"}):e.jsx(nr,{className:"h-3.5 w-3.5"}):e.jsx(nr,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),l=t.filter(d=>!d.mime?.startsWith("image/")),c=i.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:[l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:l.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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>c(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(mr,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(lt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Km=Ae.memo(({message:s,sessionId:r,onEdit:t})=>{const n=rr(l=>l.removeFromQueue),o=i.useMemo(()=>{const l=s.content.split(`
87
- `),c=l[0]||"",d=50;return c.length>d?c.substring(0,d)+"...":c+(l.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(dh,{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"})})]})});Km.displayName="QueuedMessageChip";const nd=[],Qm=Ae.memo(({onEditMessage:s})=>{const r=he(a=>a.currentSessionId),t=rr(i.useCallback(a=>r?a.queuedMessages[r]??nd:nd,[r])),n=rr(a=>a.popToInput),o=i.useCallback(a=>{if(!r)return;const l=n(r,a.id);if(l){if(l.attachments&&l.attachments.length>0){const c=qs.getState().attachedFiles;qs.setState({attachedFiles:[...c,...l.attachments]})}s(l.content,l.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(Km,{message:a,sessionId:r,onEdit:o},a.id))]})})});Qm.displayName="QueuedMessageChips";const ov=i.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=vt(),{addServerFile:a}=he(),l=Ia(D=>D.searchFiles),c=Oa(s,180),[d,u]=i.useState([]),[m,f]=i.useState(!1),[p,g]=i.useState(0),[y,h]=i.useState(360),[j,b]=i.useState({}),[v,w]=i.useState({}),N=i.useRef([]),x=i.useRef([]),k=i.useRef([]),A=i.useRef(null),C=i.useCallback((D,E)=>{const T=D.trim().toLowerCase();if(!T)return 0;const I=E.toLowerCase();let P=0,O=-1,U=0;for(let Q=0;Q<T.length;Q+=1){const W=T[Q];if(!W||W===" ")continue;const L=I.indexOf(W,O+1);if(L===-1)return null;const H=L-O-1;if(H===0?U+=1:U=0,P+=10,P+=Math.max(0,18-L),P-=Math.max(0,H),L===0)P+=12;else{const q=I[L-1];(q==="/"||q==="_"||q==="-"||q==="."||q===" ")&&(P+=10)}P+=U>0?12:0,O=L}return P+=Math.max(0,24-Math.round(I.length/3)),P},[]);i.useEffect(()=>{const D=E=>{const T=E.target;!T||!A.current||A.current.contains(T)||t()};return document.addEventListener("pointerdown",D,!0),()=>{document.removeEventListener("pointerdown",D,!0)}},[t]),i.useEffect(()=>{if(!o){u([]);return}const E=(c??"").trim().toLowerCase();let T=!1;return f(!0),l(o,E,80).then(I=>{if(T)return;const P=E?I.map(O=>{const U=O.relativePath||O.name||O.path,Q=C(E,U);return Q===null?null:{file:O,score:Q,labelLength:U.length}}).filter(Boolean):I.map(O=>({file:O,score:0,labelLength:(O.relativePath||O.name||O.path).length}));P.sort((O,U)=>U.score-O.score||O.labelLength-U.labelLength||O.file.path.localeCompare(U.file.path)),u(P.slice(0,15).map(O=>O.file))}).catch(()=>{T||u([])}).finally(()=>{T||f(!1)}),()=>{T=!0}},[o,c,C,l]),i.useEffect(()=>{g(0),b({}),w({})},[d]),i.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),i.useEffect(()=>{let D=null;const E=()=>{D!==null&&cancelAnimationFrame(D),D=requestAnimationFrame(()=>{const T={},I={};x.current.forEach((P,O)=>{if(!P)return;const Q=k.current[O]?.offsetWidth??P.scrollWidth,W=Math.max(0,Q-P.clientWidth),L=W>8;if(T[O]=L,L){const H=Math.max(.6,W/110);I[O]=H}}),b(T),w(I)})};return E(),window.addEventListener("resize",E),()=>{D!==null&&cancelAnimationFrame(D),window.removeEventListener("resize",E)}},[d]),i.useEffect(()=>{const D=x.current[p];if(!D)return;const E=()=>{const I=D.clientWidth;I>0&&h(I)};if(E(),typeof ResizeObserver>"u")return;const T=new ResizeObserver(E);return T.observe(D),()=>{T.disconnect()}},[p]);const M=i.useCallback(async D=>{await a(D.path,D.name),r(D)},[a,r]);i.useImperativeHandle(n,()=>({handleKeyDown:D=>{if(D==="Escape"){t();return}const E=d.length;if(E!==0){if(D==="ArrowDown"){g(T=>(T+1)%E);return}if(D==="ArrowUp"){g(T=>(T-1+E)%E);return}if(D==="Enter"||D==="Tab"){const T=(p%E+E)%E,I=d[T];I&&M(I)}}}}),[d,p,t,M]);const S=D=>{switch(D.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(_s,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(_s,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(nr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(mr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(Ca,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:A,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(gt,{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(jr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((D,E)=>{const T=D.relativePath||D.name,I=Hu(T,{maxLength:45}),P=p===E,O=j[E]??!1,U=v[E]??2.6,Q=e.jsxs("div",{ref:W=>{N.current[E]=W},className:_("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",P&&"bg-muted"),onClick:()=>M(D),onMouseEnter:()=>g(E),children:[S(D),e.jsxs("span",{ref:W=>{x.current[E]=W},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:P?{"--file-mention-marquee-width":`${y}px`,"--file-mention-marquee-duration":`${U}s`}:void 0,"aria-label":T,children:[e.jsx("span",{ref:W=>{k.current[E]=W},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:T}),O&&P?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:T}):e.jsx("span",{className:"block truncate",children:I})]})]});return e.jsx(i.Fragment,{children:Q},D.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"})]})}),Ym=i.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=he(ul(v=>{const w=v.currentSessionId;return{hasMessagesInCurrentSession:(w?v.messages.get(w)?.length??0:0)>0,currentSessionId:w}})),l=!!a,[c,d]=i.useState([]),[u,m]=i.useState(!1),{commands:f,loadCommands:p}=Br(),[g,y]=i.useState(0),h=i.useRef([]),j=i.useRef(null);i.useEffect(()=>{const v=w=>{const N=w.target;!N||!j.current||j.current.contains(N)||t()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[t]),i.useEffect(()=>{p()},[p]),i.useEffect(()=>{(async()=>{m(!0);try{const w=f.map(M=>({name:M.name,description:M.description,agent:M.agent??void 0,model:M.model??void 0,isBuiltIn:M.name==="init"||M.name==="review",scope:M.scope})),N=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{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}],x=new Map;N.forEach(M=>x.set(M.name,M)),w.forEach(M=>x.set(M.name,M));const k=Array.from(x.values()),A=!o,C=(s?k.filter(M=>Ts(M.name,s)||M.description&&Ts(M.description,s)):k).filter(M=>A||M.name!=="init");C.sort((M,S)=>{const D=M.name.toLowerCase().startsWith(s.toLowerCase()),E=S.name.toLowerCase().startsWith(s.toLowerCase());return D&&!E?-1:!D&&E?1:M.name.localeCompare(S.name)}),d(C)}catch{const w=!o,N=[...l&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...l?[{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}],x=(s?N.filter(k=>Ts(k.name,s)||k.description&&Ts(k.description,s)):N).filter(k=>w||k.name!=="init");d(x)}finally{m(!1)}})()},[s,o,l,f]),i.useEffect(()=>{y(0)},[c]),i.useEffect(()=>{h.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),i.useImperativeHandle(n,()=>({handleKeyDown:v=>{const w=c.length;if(v==="Escape"){t();return}if(w!==0){if(v==="ArrowDown"){y(N=>(N+1)%w);return}if(v==="ArrowUp"){y(N=>(N-1+w)%w);return}if(v==="Enter"||v==="Tab"){const N=(g%w+w)%w,x=c[N];x&&r(x)}}}}),[c,g,t,r]);const b=v=>{switch(v.name){case"init":return e.jsx(nr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Zn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(fh,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(cr,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(mh,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(_r,{className:"h-3.5 w-3.5 text-cyan-500"});default:return v.isBuiltIn?e.jsx(uh,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(an,{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(gt,{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(jr,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[c.map((v,w)=>{const N=v.isBuiltIn,x=v.scope==="project";return e.jsxs("div",{ref:k=>{h.current[w]=k},className:_("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",w===g&&"bg-muted"),onClick:()=>r(v),onMouseEnter:()=>y(w),children:[e.jsx("div",{className:"mt-0.5",children:b(v)}),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:["/",v.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"}):v.scope?e.jsx("span",{className:_("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",x?"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:v.scope}):null,v.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:v.agent})]}),v.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:v.description})]})]},v.name)}),c.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"})]})});Ym.displayName="CommandAutocomplete";const av=s=>s?s!=="primary":!1,Xm=i.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{getVisibleAgents:m}=at(),{agents:f,loadAgents:p}=zr();i.useEffect(()=>{f.length===0&&p()},[p,f.length]),i.useEffect(()=>{const h=m().filter(v=>av(v.mode)).map(v=>{const w=f.find(N=>N.name===v.name);return{name:v.name,description:v.description,mode:v.mode??void 0,scope:w?.scope,isBuiltIn:w?Qr(w):!1}}),j=s.trim(),b=j.length?h.filter(v=>Ts(v.name,j)):h;b.sort((v,w)=>v.name.localeCompare(w.name)),d(b),l(0)},[m,s,f]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const y=h=>{const j=h.target;!j||!o.current||o.current.contains(j)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),i.useImperativeHandle(n,()=>({handleKeyDown:y=>{if(y==="Escape"){t();return}if(c.length){if(y==="ArrowDown"){l(h=>(h+1)%c.length);return}if(y==="ArrowUp"){l(h=>(h-1+c.length)%c.length);return}if(y==="Enter"||y==="Tab"){const h=c[(a+c.length)%c.length];h&&r(h.name)}}}}),[c,r,t,a]);const g=(y,h)=>{const j=y.isBuiltIn,b=y.scope==="project";return e.jsx("div",{ref:v=>{u.current[h]=v},className:_("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",h===a&&"bg-muted"),onClick:()=>r(y.name),onMouseEnter:()=>l(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:["#",y.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"}):y.scope?e.jsx("span",{className:_("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:y.scope}):null]}),y.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:y.description})]})},y.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(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((y,h)=>g(y,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"})]})});Xm.displayName="AgentMentionAutocomplete";const Jm=i.forwardRef(({searchQuery:s,onSkillSelect:r,onClose:t},n)=>{const o=i.useRef(null),[a,l]=i.useState(0),[c,d]=i.useState([]),u=i.useRef([]),{skills:m,loadSkills:f}=Gs();i.useEffect(()=>{f()},[f]),i.useEffect(()=>{const g=s.trim(),h=[...g.length?m.filter(j=>Ts(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),l(0)},[m,s]),i.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),i.useEffect(()=>{const g=y=>{const h=y.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),i.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){t();return}if(c.length){if(g==="ArrowDown"){l(y=>(y+1)%c.length);return}if(g==="ArrowUp"){l(y=>(y-1+c.length)%c.length);return}if(g==="Enter"||g==="Tab"){const y=c[a];y&&r(y.name)}}}}),[c,r,t,a]);const p=(g,y)=>{const h=g.scope==="project";return e.jsx("div",{ref:j=>{u.current[y]=j},className:_("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",y===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>l(y),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:_("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(gt,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:c.length?e.jsx("div",{children:c.map((g,y)=>p(g,y))}):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"})]})});Jm.displayName="SkillAutocomplete";function iv({className:s,children:r,...t}){return e.jsxs(ph,{"data-slot":"scroll-area",className:_("relative",s),...t,children:[e.jsx(hh,{"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(lv,{}),e.jsx(gh,{})]})}function lv({className:s,orientation:r="vertical",...t}){return e.jsx(xh,{"data-slot":"scroll-area-scrollbar",orientation:r,className:_("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(yh,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const cv=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:l}=$t(),c=l,{currentDirectory:d}=vt(),u=Ia(V=>V.searchFiles),[m,f]=i.useState(!1),[p,g]=i.useState(!1),[y,h]=i.useState(""),j=Oa(y,200),[b,v]=i.useState(new Set),[w,N]=i.useState(new Set),[x,k]=i.useState({}),A=i.useRef(new Set),C=i.useRef(new Set),[M,S]=i.useState([]),[D,E]=i.useState(!1),[T,I]=i.useState(!1),[P,O]=i.useState(!1),[U,Q]=i.useState(null),W=n??m,L=o??f,H=i.useCallback(V=>V.slice().sort((J,ee)=>J.type!==ee.type?J.type==="directory"?-1:1:J.name.localeCompare(ee.name)),[]),q=i.useCallback((V,J)=>H(J.filter(ee=>!ee.name.startsWith(".")).map(ee=>{const xe=ee.name,fe=!ee.isDirectory&&xe.includes(".")?xe.split(".").pop()?.toLowerCase():void 0;return{name:xe,path:ee.path||`${V}/${xe}`,type:ee.isDirectory?"directory":"file",size:0,extension:fe}})),[H]),X=i.useCallback(async V=>{I(!0),Q(null);try{const J=await Ee.listLocalDirectory(V),ee=q(V,J.map(xe=>({name:xe.name,path:xe.path,isDirectory:xe.isDirectory})));A.current=new Set([V]),C.current=new Set,k({[V]:ee}),N(new Set)}catch{Q("Failed to load directory contents"),A.current=new Set([V]),C.current=new Set,k({[V]:[]}),N(new Set)}finally{I(!1)}},[q]),Y=i.useCallback(async V=>{const J=V.trim();if(J&&!A.current.has(J)&&!C.current.has(J)){C.current=new Set(C.current),C.current.add(J);try{const ee=await Ee.listLocalDirectory(J),xe=q(J,ee.map(fe=>({name:fe.name,path:fe.path,isDirectory:fe.isDirectory})));A.current=new Set(A.current),A.current.add(J),k(fe=>({...fe,[J]:xe}))}catch{k(ee=>ee[J]?ee:{...ee,[J]:[]})}finally{C.current=new Set(C.current),C.current.delete(J)}}},[q]);i.useEffect(()=>{(W||p)&&d&&X(d)},[W,p,d,X]),i.useEffect(()=>{if(!(W||p)||!d){S([]),E(!1);return}const V=j.trim();if(!V){S([]),E(!1);return}let J=!1;return E(!0),u(d,V,150).then(ee=>{if(J)return;const xe=ee.map(fe=>({name:fe.name,path:fe.path,type:"file",extension:fe.extension,relativePath:fe.relativePath,size:0}));S(xe)}).catch(()=>{J||S([])}).finally(()=>{J||E(!1)}),()=>{J=!0}},[W,p,d,j,u]),i.useEffect(()=>{!W&&!p&&(v(new Set),h(""),S([]),E(!1))},[W,p]);const re=V=>{if(V.type==="directory")return w.has(V.path)?e.jsx(Hs,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(Hs,{className:"h-3.5 w-3.5 text-primary/60"});switch(V.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(_s,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(_s,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(eo,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(mr,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(eo,{className:"h-3.5 w-3.5 text-muted-foreground"})}},K=async V=>{w.has(V)?N(ee=>{const xe=new Set(ee);return xe.delete(V),xe}):(N(ee=>{const xe=new Set(ee);return xe.add(V),xe}),await Y(V))},ae=V=>{v(r?J=>{const ee=new Set(J);return ee.has(V)?ee.delete(V):ee.add(V),ee}:new Set([V]))},F=async()=>{const V=new Map;Object.values(x).forEach(xe=>{xe.forEach(fe=>{fe.type==="file"&&V.set(fe.path,fe)})});const J=new Map(M.map(xe=>[xe.path,xe])),ee=Array.from(b).map(xe=>V.get(xe)??J.get(xe)).filter(xe=>!!xe);O(!0);try{await s(ee),v(new Set),L(!1),g(!1)}finally{O(!1)}},$=i.useMemo(()=>d?x[d]??[]:[],[x,d]),R=y.trim().length>0,B=V=>x[V]??[],z=V=>{if(d&&V.startsWith(d)){const J=V.substring(d.length);return J.startsWith("/")?J.substring(1):J}return V.split("/").pop()||V},G=(V,J)=>{const ee=R?V.relativePath||z(V.path):V.name,xe=R&&ee.includes("/")&&ee.length>45,fe=xe?Hu(ee,{maxLength:c?42:48}):ee,Oe=e.jsxs("div",{className:_("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",V.type==="file"&&b.has(V.path)&&"bg-primary/10"),style:{paddingLeft:`${J*12}px`},onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),V.type==="file"&&ae(V.path)},children:[e.jsxs("div",{className:"flex flex-1 items-center justify-start gap-1",children:[e.jsx("span",{className:"text-muted-foreground",children:re(V)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":ee,children:fe})]}),V.type==="file"&&b.has(V.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return xe?e.jsxs(dt,{delayDuration:120,children:[e.jsx(ut,{asChild:!0,children:Oe}),e.jsx(lt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:ee})})]},V.path):i.cloneElement(Oe,{key:V.path})},ge=(V,J)=>{const ee=V.type==="directory",xe=ee?B(V.path):[],fe=w.has(V.path),Oe=ee&&fe&&C.current.has(V.path)&&xe.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:_("flex w-full items-center justify-start gap-1 px-2 py-1.5 rounded cursor-pointer typography-ui-label text-foreground text-left",!ee&&b.has(V.path)&&"bg-primary/10"),style:{paddingLeft:`${J*12}px`},onClick:Se=>{Se.preventDefault(),Se.stopPropagation(),ee?K(V.path):ae(V.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:re(V)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:V.name}),!ee&&b.has(V.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),ee&&fe&&xe.length>0&&e.jsx("div",{children:xe.map(Se=>ge(Se,J+1))}),ee&&fe&&Oe&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(J+1)*12}px`},children:"Loading…"})]},V.path)},oe=b.size>0?`${b.size} file${b.size!==1?"s":""} selected`:"No files selected",me=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:oe}),e.jsx(Ie,{size:"sm",onClick:F,disabled:b.size===0||P,className:"h-6 typography-meta",children:P?"Attaching...":"Attach Files"})]}),Ne=c?"flex-1 min-h-[240px]":"h-[300px]",Ce=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(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:y,onChange:V=>h(V.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:V=>V.stopPropagation()}),y&&e.jsx("button",{onClick:V=>{V.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(iv,{className:Ne,children:[T&&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..."})}),U&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:U})}),!T&&!U&&e.jsxs("div",{className:"py-1 px-2",children:[R?D?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(V=>G(V,0)):$.map(V=>ge(V,0)),!R&&$.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),R&&!D&&M.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files found"})]})]})]}),Be=e.jsx("span",{className:"inline-flex cursor-pointer",onClick:V=>{V.preventDefault(),V.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:V=>{V.preventDefault(),V.stopPropagation(),L(!0)},children:t}):null,e.jsx(ws,{open:W,onClose:()=>L(!1),title:"Select Project Files",footer:me,children:e.jsx("div",{className:"flex flex-col gap-0",children:Ce})})]}):c?e.jsxs(e.Fragment,{children:[Be,e.jsx(ws,{open:p,onClose:()=>g(!1),title:"Select Project Files",footer:me,children:e.jsx("div",{className:"flex flex-col gap-0",children:Ce})})]}):e.jsxs(qt,{open:W,onOpenChange:L,children:[e.jsx(Kt,{asChild:!0,children:t}),e.jsxs(Qt,{className:_("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[Ce,e.jsx(js,{}),me]})]})},Ao=[{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 Ar(s){if(!s||s==="build")return Ao[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)%(Ao.length-1);return Ao[t]}const dv=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),Zm=s=>dv(s),uv=s=>s?typeof s=="string"?s==="ask":Zm(s)?Object.values(s).some(r=>r==="ask"):!1:!1,mv=s=>s?typeof s=="string"?s==="deny":Zm(s)?Object.values(s).some(r=>r==="deny"):!1:!1,ef=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=uv(t),o=mv(t),a=!n&&!o,l=r==="allow",c=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&l&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&c&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:l,webfetchNotDeny:c}},Eo=s=>s==="primary"||s==="all"||s===void 0||s===null,ba=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},Io=(s,r)=>{const t=ba(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}}},fv=(s,r)=>{const t=ba(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},pv=[{key:"tool_call",icon:Ma,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:dr,label:"Reasoning",isActive:s=>s?.reasoning===!0}],hv={text:{icon:Mu,label:"Text"},image:{icon:mr,label:"Image"},video:{icon:vh,label:"Video"},audio:{icon:bh,label:"Audio"},pdf:{icon:Ca,label:"PDF"}},gv=s=>s.trim().toLowerCase(),zn=(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=>gv(o)))).map(o=>{const a=hv[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},xv=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),yv=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Bs=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=xv.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Po=s=>typeof s!="number"||!Number.isFinite(s)?"—":yv.format(s),fi=s=>pv.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),od=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},ad=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)},id=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:l,setProvider:c,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:g,getCurrentAgent:y,getVisibleAgents:h}=at(),j=h(),{currentSessionId:b,messages:v,saveSessionAgentSelection:w,getSessionAgentSelection:N,saveAgentModelForSession:x,getAgentModelForSession:k,saveAgentModelVariantForSession:A,getAgentModelVariantForSession:C,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:S,setSessionAgentEditMode:D}=he(),E=wt(se=>se.hasHydrated),{toggleFavoriteModel:T,isFavoriteModel:I,addRecentModel:P,isModelSelectorOpen:O,setModelSelectorOpen:U}=$e(),{favoriteModelsList:Q,recentModelsList:W}=Rl(),{isMobile:L}=$t(),H=By(),q=km(),X=L,[Y,re]=i.useState(null),[K,ae]=i.useState(null),[F,$]=i.useState(""),R=i.useCallback(()=>re(null),[]),B=i.useCallback(()=>ae(null),[]),z=i.useRef(void 0),[G,ge]=i.useState(()=>{const se=new Set;return t&&se.add(t),se}),[oe,me]=i.useState(!1),Ne=O,Ce=U,[Be,V]=i.useState(!1),J=i.useId(),[ee,xe]=i.useState(""),[fe,Oe]=i.useState(0),Se=i.useRef([]);i.useEffect(()=>{Y==="model"&&ge(()=>{const se=new Set;return t&&se.add(t),se})},[Y,t]),i.useEffect(()=>{Y!=="agent"&&me(!1),Y!=="model"&&$("")},[Y]);const Le=i.useRef(Ne);i.useEffect(()=>{const se=Le.current;Le.current=Ne,Ne||(V(!1),xe(""),Oe(0),se&&!X&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Ne,X]),i.useEffect(()=>{Oe(0)},[ee]);const pe=y?.(),it=i.useMemo(()=>pe?Io(pe.permission,"edit")??"ask":"deny",[pe]),xt=i.useMemo(()=>{if(pe)return Io(pe.permission,"webfetch")},[pe]),Mt=i.useMemo(()=>{if(!pe)return;const se=fv(pe.permission,"bash");return se||void 0},[pe]),De=i.useMemo(()=>ef({agentDefaultEditMode:it,webfetchPermission:xt,bashPermission:Mt}),[it,xt,Mt]),{cascadeDefaultMode:ne,modeAvailability:rt,autoApproveAvailable:be}=De,ke=!!(b&&a),Qe=ke&&b&&a?S(b,a,ne):ne,tt={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},He=i.useCallback(se=>!rt[se],[rt]),Re=i.useMemo(()=>!ke||He(Qe)&&Qe!==ne?ne:Qe,[ne,He,ke,Qe]),nt=[{mode:"ask",label:tt.ask,disabled:He("ask")},{mode:"allow",label:tt.allow,disabled:He("allow")},{mode:"full",label:tt.full,disabled:He("full")}],yt=i.useMemo(()=>Un(Re),[Re]),ct=!ke||!be;i.useEffect(()=>{ct&&(me(!1),V(!1))},[ct]);const It=L?"mobile":q?"vscode":"default",Tt=It==="mobile"?"h-9":It==="vscode"?"h-6":"h-8",je=It==="mobile"?"h-5 w-5":"h-4 w-4",ze=It==="mobile"?"h-5 w-5":"h-4 w-4",Ze=X?"typography-micro":"typography-meta",Ye=It==="mobile"?"gap-x-2":It==="vscode"?"gap-x-1":"gap-x-3",mt=tt[Re],ye=i.useCallback((se,ce=je)=>{const ue=_(ce,"flex-shrink-0"),Me=Un(se),Ke={color:Me?Me.text:"var(--foreground)"};return se==="full"?e.jsx(xr,{className:ue,style:Ke}):se==="allow"?e.jsx(Bo,{className:ue,style:Ke}):se==="deny"?e.jsx(Cn,{className:ue,style:Ke}):e.jsx(tn,{className:ue,style:Ke})},[je]),ie=i.useCallback(se=>{ct||!b||!a||He(se)||(D(b,a,se,ne),Ce(!1),me(!1),V(!1))},[ne,ct,b,a,D,Ce,V,He]),de=p(),We=Array.isArray(de?.models)?de.models:[],Ge=t&&n?g(t,n):void 0,bt=fi(Ge),Z=zn(Ge,"input"),we=zn(Ge,"output"),ve=i.useMemo(()=>`${t}/${n}`?m():[],[m,t,n]),Ue=ve.length>0,_e=[{label:"Input",value:Po(Ge?.cost?.input)},{label:"Output",value:Po(Ge?.cost?.output)},{label:"Cache read",value:Po(Ge?.cost?.cache_read)},{label:"Cache write",value:Po(Ge?.cost?.cache_write)}],et=[{label:"Context",value:Bs(Ge?.limit?.context)},{label:"Output",value:Bs(Ge?.limit?.output)}],pt=i.useRef(void 0),ft=b?v.get(b)?.length??-1:-1,Pt=i.useRef(null),At=i.useCallback((se,ce,ue)=>{if(!se||!ce)return"model-missing";const Me=r.find(Fe=>Fe.id===se);return Me?(Array.isArray(Me.models)?Me.models:[]).find(Fe=>Fe.id===ce)?(c(se),d(ce),b&&ue&&x(b,ue,se,ce),"applied"):"model-missing":"provider-missing"},[r,c,d,b,x]);i.useEffect(()=>{if(!b){Pt.current=null;return}if(!E||r.length===0||j.length===0)return;(!Pt.current||Pt.current.sessionId!==b)&&(Pt.current={sessionId:b,resolved:!1,inFlight:!1});const se=Pt.current;if(!se||se.resolved||se.inFlight)return;let ce=!1;const ue=()=>{if(ce)return;const Fe=Pt.current;Fe&&Fe.sessionId===b&&(Fe.resolved=!0,Fe.inFlight=!1)},Me=()=>{const Fe=N(b);if(Fe){a!==Fe&&f(Fe);const Je=k(b,Fe);if(Je){const Pe=At(Je.providerId,Je.modelId,Fe);if(Pe==="applied")return"resolved";if(Pe==="provider-missing")return"waiting"}else return"resolved"}for(const Je of j){const Pe=k(b,Je.name);if(!Pe)continue;a!==Je.name&&f(Je.name),w(b,Je.name);const ot=At(Pe.providerId,Pe.modelId,Je.name);if(ot==="applied")return"resolved";if(ot==="provider-missing")return"waiting"}return"continue"},qe=()=>{if(j.length===0)return;const Fe=j.filter(Pe=>Eo(Pe.mode)),Je=j.find(Pe=>Pe.name==="build")||Fe[0]||j[0];Je&&(w(b,Je.name),a!==Je.name&&f(Je.name),Je.model?.providerID&&Je.model?.modelID&&At(Je.model.providerID,Je.model.modelID,Je.name))};return(async()=>{try{const Fe=Me();if(Fe==="resolved"){ue();return}if(Fe==="waiting"||ft===-1)return;if(ft>0){se.inFlight=!0;try{const Je=await M(b,j);if(ce)return;if(Je.size>0){let Pe=null,ot=-1/0;for(const[Dt,Nt]of Je)Nt.timestamp>ot&&(ot=Nt.timestamp,Pe=Dt);if(Pe){w(b,Pe),a!==Pe&&f(Pe);const Dt=Je.get(Pe);if(Dt){const Nt=At(Dt.providerId,Dt.modelId,Pe);if(Nt==="applied"){ue();return}if(Nt==="provider-missing")return}else{ue();return}}}}catch(Je){ce||console.error("[ModelControls] Error resolving session from messages:",Je)}finally{const Je=Pt.current;!ce&&Je&&Je.sessionId===b&&(Je.inFlight=!1)}}qe(),ue()}catch(Fe){ce||console.error("[ModelControls] Error in session switch:",Fe)}})(),()=>{ce=!0}},[b,ft,j,a,N,k,f,At,M,w,E,r]),i.useEffect(()=>{if(!E||!b||r.length===0||j.length===0)return;const ce=N(b)||a;if(!ce)return;const ue=k(b,ce);if(!ue)return;const Me=r.find(Je=>Je.id===ue.providerId);if(!Me||!(Array.isArray(Me.models)?Me.models.some(Je=>Je.id===ue.modelId):!1))return;const Ke=t===ue.providerId,Fe=n===ue.modelId;Ke&&Fe||(ce!==a&&f(ce),At(ue.providerId,ue.modelId,ce))},[E,b,a,t,n,r,j,N,k,At,f]),i.useEffect(()=>{if(!E)return;(async()=>{try{if(a!==pt.current&&(pt.current=a,a&&b)){await new Promise(Me=>setTimeout(Me,50));const ce=k(b,a);if(ce){const Me=At(ce.providerId,ce.modelId,a);if(Me==="applied"||Me==="provider-missing")return}const ue=j.find(Me=>Me.name===a);if(ue?.model?.providerID&&ue?.model?.modelID&&At(ue.model.providerID,ue.model.modelID,a)==="provider-missing")return}}catch(ce){console.error("[ModelControls] Agent change error:",ce)}})()},[a,b,k,At,j,E]),i.useEffect(()=>{if(!E||!a){u(void 0);return}if(!t||!n){u(void 0);return}if(ve.length===0){u(void 0);return}if(o&&!ve.includes(o)){u(void 0);return}if(!b){if(!o){const ue=l&&ve.includes(l)?l:void 0;u(ue)}return}const se=C(b,a,t,n),ce=se&&ve.includes(se)?se:void 0;u(ce)},[ve,E,b,a,t,n,o,C,u,l]);const Te=i.useCallback(se=>{u(se),b&&a&&t&&n&&A(b,a,t,n,se)},[a,n,t,b,A,u]),st=se=>{try{f(se),Ce(!1),b&&w(b,se),X&&R()}catch(ce){console.error("[ModelControls] Handle agent change error:",ce)}},Ve=(se,ce)=>{try{const ue=At(se,ce,a||void 0);if(ue!=="applied"){ue==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",se):ue==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:se,modelId:ce});return}P(se,ce),Ce(!1),X&&R(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(ue){console.error("[ModelControls] Handle model change error:",ue)}},Xe=se=>{const ce=typeof se?.name=="string"?se.name:typeof se?.id=="string"?se.id:"";return ce.length>40?ce.substring(0,37)+"...":ce},kt=()=>r.find(ce=>ce.id===t)?.name||t,Lt=()=>{if(!t||!n||We.length===0)return"Not selected";const se=We.find(ce=>ce.id===n);return Xe(se)},ts=()=>{if(!a){const ce=j.filter(qe=>Eo(qe.mode)),Me=ce.find(qe=>qe.name==="build")||ce[0];return Me?ns(Me.name):"Select Agent"}const se=j.find(ce=>ce.name===a);return ns(se?se.name:a)},ns=se=>se.charAt(0).toUpperCase()+se.slice(1),ps=(se,ce,ue)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ce,"aria-label":ce,role:"img",children:e.jsx(se,{className:"h-3.5 w-3.5"})},ue),pr=i.useCallback(se=>{ge(ce=>{const ue=new Set(ce);return ue.has(se)?ue.delete(se):ue.add(se),ue})},[]),Bt=i.useCallback(se=>{z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{ae(se)},500)},[]),Nr=i.useCallback(()=>{z.current&&clearTimeout(z.current)},[]);i.useEffect(()=>()=>{z.current&&clearTimeout(z.current)},[]);const Rn=()=>!X||K!=="model"?null:e.jsx(ws,{open:!0,onClose:B,title:Ge?.name||Lt(),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:kt()})]}),bt.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:bt.map(({key:se,icon:ce,label:ue})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ps(ce,ue,`cap-${se}`),e.jsx("span",{className:"typography-meta text-foreground",children:ue})]},se))})]}),(Z.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:[Z.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:Z.map(({key:se,icon:ce,label:ue})=>ps(ce,`${ue} input`,`input-${se}`))})]}),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:se,icon:ce,label:ue})=>ps(ce,`${ue} output`,`output-${se}`))})]})]})]}),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:Bs(Ge?.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:Bs(Ge?.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:od(Ge?.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:ad(Ge?.release_date)})]})]})]})]})}),Ba=()=>{if(!X||K!=="agent"||!pe)return null;const se=!!(pe.prompt&&pe.prompt.trim().length>0),ce=pe.model?.providerID&&pe.model?.modelID,ue=pe.temperature!==void 0||pe.topP!==void 0,Me=Je=>{const Pe=ba(pe.permission)??[],ot=Pe.some(Nt=>Nt.permission===Je&&Nt.pattern!=="*"),Dt=Io(Pe,Je)??"ask";return ot?{mode:"ask",label:"Custom"}:Dt==="allow"?{mode:"allow",label:"Allow"}:Dt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},qe=Me("edit"),Ke=Me("bash"),Fe=Me("webfetch");return e.jsx(ws,{open:!0,onClose:B,title:ns(pe.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[pe.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:pe.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:pe.mode==="primary"?"Primary":pe.mode==="subagent"?"Subagent":pe.mode==="all"?"All":"—"})]}),(ce||ue)&&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"}),ce&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[pe.model.providerID," / ",pe.model.modelID]}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[pe.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:pe.temperature})]}),pe.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:pe.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:[ye(qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:qe.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:[ye(Ke.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ke.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:[ye(Fe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Fe.label})]})]})]})]}),se&&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(Bo,{className:"h-4 w-4 text-foreground"})]})})]})})},za=()=>{if(!X)return null;const se=F.trim(),ce=r.map(ue=>{const Me=Array.isArray(ue.models)?ue.models:[],qe=se.length===0?!0:Ts(ue.name,se)||Ts(ue.id,se),Ke=se.length===0?Me:Me.filter(Fe=>{const Je=Xe(Fe),Pe=typeof Fe.id=="string"?Fe.id:"";return Ts(Je,se)||Ts(Pe,se)});return{provider:ue,providerModels:Ke,matchesProvider:qe}}).filter(({matchesProvider:ue,providerModels:Me})=>ue||Me.length>0);return e.jsx(ws,{open:Y==="model",onClose:R,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(lr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{value:F,onChange:ue=>$(ue.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),F&&e.jsx("button",{type:"button",onClick:()=>$(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Cn,{className:"h-4 w-4"})})]})}),ce.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."}),!F&&Q.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(yr,{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:Q.map(({model:ue,providerID:Me,modelID:qe})=>{const Ke=Me===t&&qe===n,Fe=g(Me,qe);return e.jsxs("button",{type:"button",onClick:()=>Ve(Me,qe),className:_("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",Ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(cs,{providerId:Me,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Xe(ue)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Fe?.limit?.context||Fe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Fe?.limit?.context?`${Bs(Fe?.limit?.context)} ctx`:"",Fe?.limit?.context&&Fe?.limit?.output?" • ":"",Fe?.limit?.output?`${Bs(Fe?.limit?.output)} out`:""]})})]},`fav-mobile-${Me}-${qe}`)})})]}),!F&&W.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(cr,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:W.map(({model:ue,providerID:Me,modelID:qe})=>{const Ke=Me===t&&qe===n,Fe=g(Me,qe);return e.jsxs("button",{type:"button",onClick:()=>Ve(Me,qe),className:_("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",Ke?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(cs,{providerId:Me,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Xe(ue)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Fe?.limit?.context||Fe?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Fe?.limit?.context?`${Bs(Fe?.limit?.context)} ctx`:"",Fe?.limit?.context&&Fe?.limit?.output?" • ":"",Fe?.limit?.output?`${Bs(Fe?.limit?.output)} out`:""]})})]},`recent-mobile-${Me}-${qe}`)})})]}),ce.map(({provider:ue,providerModels:Me})=>{if(Me.length===0&&!se.length)return null;const qe=ue.id===t,Ke=G.has(ue.id)||se.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:()=>pr(ue.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Ke,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{providerId:ue.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:ue.name}),qe&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Ke?e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Rs,{className:"h-3 w-3 text-muted-foreground"})]}),Ke&&Me.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:Me.map(Fe=>{const Je=qe&&Fe.id===n,Pe=g(ue.id,Fe.id),ot=fi(Pe).slice(0,3),Dt=zn(Pe,"input");return e.jsxs("div",{className:_("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",!Je&&"hover:bg-muted",Je?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>Ve(ue.id,Fe.id),className:_("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:Xe(Fe)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Pe?.limit?.context||Pe?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Pe?.limit?.context?e.jsxs("span",{children:[Bs(Pe?.limit?.context)," ctx"]}):null,Pe?.limit?.context&&Pe?.limit?.output?e.jsx("span",{children:"•"}):null,Pe?.limit?.output?e.jsxs("span",{children:[Bs(Pe?.limit?.output)," out"]}):null]}),(ot.length>0||Dt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...ot,...Dt].map(({key:Nt,icon:vs,label:$s})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:$s,"aria-label":$s,children:e.jsx(vs,{className:"h-3 w-3"})},`meta-${ue.id}-${Fe.id}-${Nt}`))})]})]}),e.jsx("button",{type:"button",onClick:Nt=>{Nt.preventDefault(),Nt.stopPropagation(),T(ue.id,Fe.id)},className:_("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",I(ue.id,Fe.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":I(ue.id,Fe.id)?"Unfavorite":"Favorite",title:I(ue.id,Fe.id)?"Remove from favorites":"Add to favorites",children:I(ue.id,Fe.id)?e.jsx(yr,{className:"h-4 w-4"}):e.jsx(wn,{className:"h-4 w-4"})})]},Fe.id)})})]},ue.id)})]})})},Hr=()=>{if(!X||!Ue)return null;const se=!o,ce=ue=>{Te(ue),R(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(ws,{open:Y==="variant",onClose:R,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:_("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",se?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ce(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),se&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),ve.map(ue=>{const Me=o===ue,qe=ue.charAt(0).toUpperCase()+ue.slice(1);return e.jsxs("button",{type:"button",className:_("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",Me?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ce(ue),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:qe}),Me&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]},ue)})]})})},Ur=()=>{if(!X)return null;const se=j.filter(ce=>Eo(ce.mode));return e.jsx(ws,{open:Y==="agent",onClose:R,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[se.map(ce=>{const ue=ce.name===a,Me=Ar(ce.name);return e.jsxs("button",{type:"button",className:_("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",Me.class,ue?"active":"border-border/40"),onClick:()=>st(ce.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:_("h-2 w-2 rounded-full",Me.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:ue?{color:`var(${Me.var})`}:void 0,children:ns(ce.name)})]}),ce.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ce.description})]},ce.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:ct,onClick:()=>{ct||me(ce=>!ce)},className:_("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",ct?"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:yt?yt.text:"var(--foreground)",mixBlendMode:"normal"},children:mt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:_("flex items-center justify-center p-1",!yt&&"text-muted-foreground"),style:yt?{color:yt.text}:void 0,children:ye(Re,je)}),e.jsx(Ft,{className:_("h-4 w-4 text-muted-foreground transition-transform",oe?"rotate-180":"")})]})]}),oe&&!ct&&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:nt.map(ce=>{const ue=ce.mode===Re,Me=Un(ce.mode);return e.jsxs("button",{type:"button",disabled:ce.disabled,onClick:()=>ie(ce.mode),className:_("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ce.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",ue?"bg-primary/10":void 0),style:ue&&Me?{backgroundColor:Me.background??void 0}:void 0,children:[ye(ce.mode,je),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:Me?Me.text:"var(--foreground)"},children:ce.label})})]},ce.mode)})})})]})]})})},ql=()=>e.jsx(lt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Ge?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:Ge.name||Lt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:kt()})]}),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:bt.length>0?bt.map(({key:se,icon:ce,label:ue})=>ps(ce,ue,`cap-${se}`)):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:Z.length>0?Z.map(({key:se,icon:ce,label:ue})=>ps(ce,`${ue} input`,`input-${se}`)):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:se,icon:ce,label:ue})=>ps(ce,`${ue} output`,`output-${se}`)):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)"}),_e.map(se=>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:se.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:se.value})]},se.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"}),et.map(se=>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:se.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:se.value})]},se.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:od(Ge.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:ad(Ge.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),dn=(se,ce,ue,Me,qe,Ke)=>{const Fe=g(ce,ue),Je=fi(Fe).map(hs=>({...hs,id:`cap-${hs.key}`})),Pe=[...zn(Fe,"input"),...zn(Fe,"output")],ot=Array.from(new Map(Pe.map(hs=>[hs.key,hs])).values()).map(hs=>({...hs,id:`mod-${hs.key}`})),Dt=[...Je,...ot],Nt=Bs(Fe?.limit?.context),vs=t===ce&&n===ue,$s=I(ce,ue);return e.jsxs("div",{ref:hs=>{Se.current[qe]=hs},className:_("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Ke?"bg-accent":"hover:bg-accent/50"),onClick:()=>Ve(ce,ue),onMouseEnter:()=>Oe(qe),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:Xe(se)}),Fe?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:Nt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Dt.length>0&&e.jsx("div",{className:_("items-center gap-0.5",Ke?"flex":"hidden group-hover:flex"),children:Dt.map(({id:hs,icon:Uf,label:Kl})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Kl,role:"img",title:Kl,children:e.jsx(Uf,{className:"h-2.5 w-2.5"})},hs))}),vs&&e.jsx(_t,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:hs=>{hs.preventDefault(),hs.stopPropagation(),T(ce,ue)},className:_("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",$s?"text-yellow-500":"text-muted-foreground"),"aria-label":$s?"Unfavorite":"Favorite",title:$s?"Remove from favorites":"Add to favorites",children:$s?e.jsx(yr,{className:"h-3.5 w-3.5"}):e.jsx(wn,{className:"h-3.5 w-3.5"})})]})]},`${Me}-${ce}-${ue}`)},_n=(se,ce,ue)=>ue.trim()?Ts(se,ue)||Ts(ce,ue):!0,Wa=()=>{const se=Q.filter(({model:Pe,providerID:ot})=>{const Nt=r.find($s=>$s.id===ot)?.name||ot,vs=Xe(Pe);return _n(vs,Nt,ee)}),ce=W.filter(({model:Pe,providerID:ot})=>{const Nt=r.find($s=>$s.id===ot)?.name||ot,vs=Xe(Pe);return _n(vs,Nt,ee)}),ue=r.map(Pe=>{const Dt=(Array.isArray(Pe.models)?Pe.models:[]).filter(Nt=>{const vs=Xe(Nt);return _n(vs,Pe.name||Pe.id||"",ee)});return{...Pe,models:Dt}}).filter(Pe=>Pe.models.length>0),Me=se.length>0||ce.length>0||ue.length>0,qe=[];se.forEach(({model:Pe,providerID:ot,modelID:Dt})=>{qe.push({model:Pe,providerID:ot,modelID:Dt,section:"fav"})}),ce.forEach(({model:Pe,providerID:ot,modelID:Dt})=>{qe.push({model:Pe,providerID:ot,modelID:Dt,section:"recent"})}),ue.forEach(Pe=>{Pe.models.forEach(ot=>{qe.push({model:ot,providerID:Pe.id,modelID:ot.id,section:"provider"})})});const Ke=qe.length,Fe=Pe=>{if(Pe.key==="ArrowDown")Pe.preventDefault(),Pe.stopPropagation(),Oe(ot=>(ot+1)%Math.max(1,Ke)),setTimeout(()=>{const ot=(fe+1)%Math.max(1,Ke);Se.current[ot]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Pe.key==="ArrowUp")Pe.preventDefault(),Pe.stopPropagation(),Oe(ot=>(ot-1+Math.max(1,Ke))%Math.max(1,Ke)),setTimeout(()=>{const ot=(fe-1+Math.max(1,Ke))%Math.max(1,Ke);Se.current[ot]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Pe.key==="Enter"){Pe.preventDefault(),Pe.stopPropagation();const ot=qe[fe];ot&&Ve(ot.providerID,ot.modelID)}else Pe.key==="Escape"&&(Pe.preventDefault(),Pe.stopPropagation(),Ce(!1))};let Je=0;return e.jsxs(dt,{delayDuration:1e3,children:[X?e.jsxs("button",{type:"button",onClick:()=>re("model"),onTouchStart:()=>Bt("model"),onTouchEnd:Nr,onTouchCancel:Nr,className:_("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",Tt),children:[t?e.jsx(cs,{providerId:t,className:_(ze,"flex-shrink-0")}):e.jsx(xr,{className:_(ze,"text-muted-foreground")}),e.jsx("span",{className:_("model-controls__model-label typography-micro font-medium truncate min-w-0",!L&&"max-w-[220px]"),children:Lt()})]}):e.jsxs(qt,{open:Ne,onOpenChange:Ce,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:_("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",Tt),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(cs,{providerId:t,className:_(ze,"flex-shrink-0")}),e.jsx(xr,{className:_(ze,"text-primary/60 hidden")})]}):e.jsx(xr,{className:_(ze,"text-muted-foreground")}),e.jsx("span",{className:_("model-controls__model-label",Ze,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:Lt()},`${t}-${n}`)]})})}),e.jsxs(Qt,{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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:ee,onChange:Pe=>xe(Pe.target.value),onKeyDown:Fe,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!Me&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),se.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),se.map(({model:Pe,providerID:ot,modelID:Dt})=>{const Nt=Je++;return dn(Pe,ot,Dt,"fav",Nt,fe===Nt)})]}),ce.length>0&&e.jsxs(e.Fragment,{children:[se.length>0&&e.jsx(js,{}),e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(cr,{className:"h-4 w-4"}),"Recent"]}),ce.map(({model:Pe,providerID:ot,modelID:Dt})=>{const Nt=Je++;return dn(Pe,ot,Dt,"recent",Nt,fe===Nt)})]}),(se.length>0||ce.length>0)&&ue.length>0&&e.jsx(js,{}),ue.map((Pe,ot)=>e.jsxs(i.Fragment,{children:[ot>0&&e.jsx(js,{}),e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(cs,{providerId:Pe.id,className:"h-4 w-4 flex-shrink-0"}),Pe.name]}),Pe.models.map(Dt=>{const Nt=Je++;return dn(Dt,Pe.id,Dt.id,"provider",Nt,fe===Nt)})]},Pe.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"})]})]}),ql()]})},go=()=>{if(!pe)return e.jsx(lt,{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 se=!!(pe.prompt&&pe.prompt.trim().length>0),ce=pe.model?.providerID&&pe.model?.modelID,ue=pe.temperature!==void 0||pe.topP!==void 0,Me=Je=>{const Pe=ba(pe.permission)??[],ot=Pe.some(Nt=>Nt.permission===Je&&Nt.pattern!=="*"),Dt=Io(Pe,Je)??"ask";return ot?{mode:"ask",label:"Custom"}:Dt==="allow"?{mode:"allow",label:"Allow"}:Dt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},qe=Me("edit"),Ke=Me("bash"),Fe=Me("webfetch");return e.jsx(lt,{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:ns(pe.name)}),pe.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:pe.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:pe.mode==="primary"?"Primary":pe.mode==="subagent"?"Subagent":pe.mode==="all"?"All":"—"})]}),(ce||ue)&&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"}),ce?e.jsxs("span",{className:"typography-meta text-foreground",children:[pe.model.providerID," / ",pe.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),ue&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[pe.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:pe.temperature})]}),pe.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:pe.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:[ye(qe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:qe.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:[ye(Ke.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ke.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:[ye(Fe.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Fe.label})]})]})]}),se&&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(Bo,{className:"h-4 w-4 text-foreground"})]})]})})},Ha=()=>{if(!Ue)return null;const se=o??"Default",ce=!o,ue=ce?"text-muted-foreground":"text-[color:var(--status-info)]";return X?e.jsxs("button",{type:"button",onClick:()=>re("variant"),className:_("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Tt,"cursor-pointer hover:opacity-70"),children:[e.jsx(dr,{className:_(ze,"flex-shrink-0",ue)}),e.jsx("span",{className:_("model-controls__variant-label",Ze,"font-medium truncate min-w-0",ue),children:se})]}):e.jsxs(dt,{delayDuration:800,children:[e.jsxs(qt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:_("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Tt),children:[e.jsx(dr,{className:_(ze,"flex-shrink-0",ue)}),e.jsx("span",{className:_("model-controls__variant-label",Ze,"font-medium min-w-0 truncate",H?"max-w-[180px]":void 0,ue),children:se})]})})}),e.jsxs(Qt,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Ir,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Et,{className:"typography-meta",onSelect:()=>Te(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"}),ce&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),ve.length>0&&e.jsx(js,{}),ve.map(Me=>{const qe=o===Me,Ke=Me.charAt(0).toUpperCase()+Me.slice(1);return e.jsx(Et,{className:"typography-meta",onSelect:()=>Te(Me),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:Ke}),qe&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},Me)})]})]}),e.jsx(lt,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",se]})})]})},Ua=()=>X?e.jsxs("button",{type:"button",onClick:()=>re("agent"),onTouchStart:()=>Bt("agent"),onTouchEnd:Nr,onTouchCancel:Nr,className:_("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",Tt,"cursor-pointer hover:opacity-70",X&&"ml-1"),children:[e.jsx(sn,{className:_(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Ar(a).var})`}:void 0}),e.jsx("span",{className:_("model-controls__agent-label",Ze,"font-medium truncate min-w-0"),style:a?{color:`var(${Ar(a).var})`}:void 0,children:ts()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(dt,{delayDuration:1e3,children:[e.jsxs(qt,{children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:_("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",Tt),children:[e.jsx(sn,{className:_(ze,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Ar(a).var})`}:void 0}),e.jsx("span",{className:_("model-controls__agent-label",Ze,"font-medium min-w-0 truncate",H?"max-w-[220px]":void 0),style:a?{color:`var(${Ar(a).var})`}:void 0,children:ts()})]})})}),e.jsxs(Qt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[j.filter(se=>Eo(se.mode)).map(se=>e.jsx(Et,{className:"typography-meta",onSelect:()=>st(se.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:_("h-1 w-1 rounded-full agent-dot",Ar(se.name).class)}),e.jsx("span",{className:"font-medium",children:ns(se.name)})]}),se.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:se.description})]})},se.name)),e.jsx(js,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:ct,onClick:()=>{ct||V(se=>!se)},className:_("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",ct?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Be,"aria-controls":J,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:yt?yt.text:"var(--foreground)"},children:mt})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:_("flex items-center justify-center p-1",!yt&&"text-muted-foreground"),style:yt?{color:yt.text}:void 0,children:ye(Re)}),e.jsx(Ft,{className:_("h-3.5 w-3.5 transition-transform text-muted-foreground",Be?"rotate-180":"")})]})]}),Be&&!ct&&e.jsx("div",{id:J,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:nt.map(se=>{const ce=se.mode===Re,ue=Un(se.mode);return e.jsxs("button",{type:"button",disabled:se.disabled,onClick:()=>ie(se.mode),className:_("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",se.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ce?"bg-primary/10":void 0),style:ce&&ue?{backgroundColor:ue.background??void 0}:void 0,children:[ye(se.mode,je),e.jsx("span",{className:"typography-meta font-medium",style:{color:ue?ue.text:"var(--foreground)"},children:se.label})]},se.mode)})})]})]})]}),go()]})}),le=_("@container/model-controls flex items-center min-w-0",L&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:le,children:e.jsxs("div",{className:_("flex items-center min-w-0 flex-1 justify-end",Ye,L&&"overflow-hidden"),children:[Ha(),Wa(),Ua()]})}),za(),Hr(),Ur(),Rn(),Ba()]})},bv=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,ld=(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 l;for(;(l=a.exec(s))!==null;){const c=l.index,d=c+l[0].length,u=c>0?s[c-1]:null;if(!bv(u))continue;const m={name:o.name,source:{value:l[0],start:c,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},tf=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),Ji=Vt()(Jt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=he.getState().getDirectoryForSession(t),a=(n?await Ee.withDirectory(n,()=>Ee.getSessionTodos(t)):await Ee.getSessionTodos(t)).map(tf);s(l=>{const c=new Map(l.sessionTodos);return c.set(t,a),{sessionTodos:c,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"})),vv=(s,r)=>{const t=r.map(tf);Ji.getState().updateTodos(s,t)},cd=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(xn.span,{...t,className:_("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)=>Ae.createElement(xn.span,{...t,key:n+String(o),className:_("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:_("invisible",r),children:s}),e.jsx("span",{...t,className:_("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:_("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(l=>l===" "?" ":l);return e.jsxs(xn.span,{...t,className:_("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((l,c)=>e.jsx(xn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))}),e.jsx("div",{className:_("absolute inset-0"),children:a.map((l,c)=>e.jsx(xn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*c},children:l},String(c)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:_("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:_("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:_("text-primary-muted",r),children:s})})}];function pi({variant:s="shine",className:r,...t}){const a=cd.find(l=>l.variant===s)?.component||cd[0].component;return e.jsx(vu,{children:e.jsx(a,{...t,className:r})})}const dd=1500,wv=2e3;function jv({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:l}){const[c,d]=Ae.useState("idle"),[u,m]=Ae.useState(null),[f,p]=Ae.useState(!1),g=Ae.useRef(0),y=Ae.useRef(null),h=Ae.useRef(null),j=Ae.useRef(null),b=Ae.useRef(null),v=Ae.useRef(!1),w=Ae.useRef(!1),N=Ae.useRef(!1),x=Ae.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),j.current&&(clearTimeout(j.current),j.current=null)},[]),k=Ae.useCallback((T,I)=>{x(),y.current=null,m(T),p(I),d("showing"),g.current=Date.now(),v.current=!0},[x]),A=Ae.useCallback(()=>{if(h.current)return;const T=Date.now()-g.current,I=Math.max(0,dd-T);h.current=setTimeout(()=>{h.current=null;const P=y.current;P&&k(P.text,P.permission)},I)},[k]),C=Ae.useCallback(T=>{if(x(),y.current=null,!v.current){d("idle"),m(null),l?.(!1);return}if(T==="done"&&o&&b.current===o){d("idle"),m(null),v.current=!1,l?.(!1);return}T==="done"&&o&&(b.current=o),d(T),m(null),l?.(!0),j.current=setTimeout(()=>{j.current=null,d("idle"),v.current=!1,l?.(!1)},wv)},[x,o,l]);if(Ae.useEffect(()=>{if(n&&!N.current){N.current=!0,C("aborted");return}if(N.current=!!n,a&&!w.current){w.current=!0,C("done");return}if(!a&&w.current&&(w.current=!1),!(c==="done"||c==="aborted")&&s){const I=Date.now()-g.current;if(c==="idle"||!u)k(s,!!t);else if(s!==u||!!t!==f){if(r)return;I>=dd?k(s,!!t):(y.current={text:s,permission:!!t},A())}}},[s,t,n,a,c,u,f,k,C,A,r]),Ae.useEffect(()=>()=>x(),[x]),Ae.useEffect(()=>{const T=()=>{typeof document>"u"||document.visibilityState==="visible"&&(c==="done"||c==="aborted")&&(x(),d("idle"),m(null),v.current=!1)};return document.addEventListener("visibilitychange",T),()=>document.removeEventListener("visibilitychange",T)},[c,x]),c==="idle"&&!u)return null;let M,S=!0;c==="done"?(M="Done",S=!1):c==="aborted"?(M="Aborted",S=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const D=S?`${M}...`:M,E=c!=="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":M,"data-waiting":f?"true":void 0,children:e.jsx("span",{className:"flex items-center gap-1.5",children:c==="done"?e.jsx(pi,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):c==="aborted"?e.jsx(pi,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(pi,{variant:"shine",className:"typography-ui-header",children:D})})})}const ud={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},Sv=({todo:s})=>{const r=ud[s.status]||ud.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:_("flex-1 typography-ui-label",r.textClassName),children:s.content})})},md=[],kv=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:l,isComplete:c,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=i.useState(!1),g=he(I=>I.currentSessionId),y=Ji(I=>g?I.sessionTodos.get(g)??md:md),h=Ji(I=>I.loadTodos),{isMobile:j}=$e(),b=j||Wt();i.useEffect(()=>{g&&h(g)},[g,h]);const v=i.useMemo(()=>{const I={in_progress:0,pending:1,completed:2,cancelled:3};return[...y].filter(P=>P.status!=="cancelled").sort((P,O)=>I[P.status]-I[O.status])},[y]),w=i.useMemo(()=>v.find(I=>I.status==="in_progress")||v.find(I=>I.status==="pending")||null,[v]),N=i.useMemo(()=>{const I=y.filter(O=>O.status!=="cancelled").length;return{completed:y.filter(O=>O.status==="completed").length,total:I}},[y]),x=v.some(I=>I.status==="in_progress"||I.status==="pending"),k=!m&&(o||!a),[A,C]=i.useState(!1),M=s||c||o||A||x||m,S=i.useRef(null);if(i.useEffect(()=>{if(!f)return;const I=P=>{S.current&&!S.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[f]),!M)return null;const D=()=>p(I=>!I),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(Cn,{size:18,"aria-hidden":"true"})}):null,T=x?e.jsxs("button",{type:"button",onClick:D,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!b&&w?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:w.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(Na,{className:"h-3.5 w-3.5"}):e.jsx(Ft,{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(Cn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(jv,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:l??null,isComplete:c,onResultVisibilityChange:C},g??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:S,children:[E,T,f&&x&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:_("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:v.map(I=>e.jsx(Sv,{todo:I},I.id))})]})]})]})})},Zi=s=>!s||typeof s!="object"?!1:!!s.synthetic,fd=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Zi(r)),Nv=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Zi(t))?s.filter(t=>!Zi(t)):s,Cv={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function Mv(s){const r=he(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return i.useMemo(()=>{if(r==="idle")return Cv;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function Ol(){const s=he(r=>r.currentSessionId);return Mv(s)}const Dv={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},pd=s=>s.role==="assistant",Av=s=>s.type==="reasoning",sf=s=>s.type==="text",hd=s=>{if(sf(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},gd=s=>(sf(s)||Av(s),s.time),Ev=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function rf(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=he(ul(g=>({currentSessionId:g.currentSessionId,messages:g.messages,permissions:g.permissions,sessionAbortFlags:g.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:l}=Ol(),c=i.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=i.useMemo(()=>{if(c.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=c.filter(M=>pd(M.info)&&!fd(M.parts));if(g.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const y=[...g].sort((M,S)=>{const D=typeof M.info.time?.created=="number"?M.info.time.created:null,E=typeof S.info.time?.created=="number"?S.info.time.created:null;return D!==null&&E!==null&&D!==E?D-E:M.info.id.localeCompare(S.info.id)}),h=y[y.length-1];let j,b;const v=new Set(["edit","write"]);for(let M=(h.parts??[]).length-1;M>=0;M-=1){const S=h.parts?.[M];if(S)switch(S.type){case"reasoning":{const D=S.time??gd(S);(!D||typeof D.end>"u")&&!j&&(j="reasoning");break}case"tool":{const D=S.state?.status;if((D==="running"||D==="pending")&&!j){const E=Ev(S);v.has(E)?j="editing":(j="tool",b=E)}break}case"text":{const D=hd(S)??"";if(typeof D=="string"&&D.trim().length>0){const E=gd(S);(!E||typeof E.end>"u")&&!j&&(j="text")}break}}}const w={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",question:"asking question"},N=["working","processing","preparing","warming up","gears turning","computing","calculating","analyzing","wheels spinning","calibrating","synthesizing","connecting dots","inspecting logic","weighing options"],x=M=>w[M]??`using ${M}`,k=()=>N[Math.floor(Math.random()*N.length)],A=j===void 0,C=j==="editing"?"editing file":j==="tool"&&b?x(b):j==="reasoning"?"thinking":j==="text"?"composing":k();return{activePartType:j,activeToolName:b,statusText:C,isGenericStatus:A}},[c]),u=i.useMemo(()=>{const g=s,y=g?n?.get(g)??null:null,h=!!(y&&!y.acknowledged);return{wasAborted:h,abortActive:h}},[s,n]),m=i.useMemo(()=>{if(u.wasAborted)return{...Dv,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const g=a,y=o==="busy",h=l;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:y,isCooldown:h,lifecyclePhase:y?"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,l,d,u]),f=i.useMemo(()=>{const g=a&&d.activePartType==="text";if(!g||c.length===0)return{isActive:g,characterCount:0};const y=c.filter(b=>pd(b.info)&&!fd(b.parts));if(y.length===0)return{isActive:g,characterCount:0};const h=y[y.length-1];let j=0;return(h.parts??[]).forEach(b=>{if(b.type!=="text")return;const v=hd(b)??"";typeof v=="string"&&v.trim().length>0&&(j+=v.length)}),{isActive:g,characterCount:j}},[c,a,d.activePartType]),p=i.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 Iv=8,xd=[],Pv=s=>s==="primary"||s==="all"||s===void 0||s===null,nf=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},yd=(s,r)=>{const t=nf(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}}},Tv=(s,r)=>{const t=nf(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},To=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=i.useState(""),[o,a]=i.useState(!1),[l,c]=i.useState(!1),[d,u]=i.useState(""),[m,f]=i.useState(!1),[p,g]=i.useState(""),[y,h]=i.useState(!1),[j,b]=i.useState(""),[v,w]=i.useState(!1),[N,x]=i.useState(""),[k,A]=i.useState(null),C=i.useRef(null),M=i.useRef(null),S=i.useRef(null),D=i.useRef(null),E=i.useRef(null),T=i.useRef(null),I=he(le=>le.sendMessage),P=he(le=>le.currentSessionId),O=he(le=>le.newSessionDraft?.open),U=he(le=>le.abortCurrentOperation),Q=he(le=>le.acknowledgeSessionAbort),W=he(le=>le.abortPromptSessionId),L=he(le=>le.abortPromptExpiresAt),H=he(le=>le.clearAbortPrompt),q=he(le=>le.sessionAbortFlags),X=he(le=>le.attachedFiles),Y=he(le=>le.addAttachedFile),re=he(le=>le.addServerFile),K=he(le=>le.clearAttachedFiles),ae=he(le=>le.saveSessionAgentSelection),F=he(le=>le.consumePendingInputText),$=he(le=>le.pendingInputText),{currentProviderId:R,currentModelId:B,currentVariant:z,currentAgentName:G,setAgent:ge,getVisibleAgents:oe}=at(),me=oe(),{isMobile:Ne,inputBarOffset:Ce,isKeyboardOpen:Be,setTimelineDialogOpen:V}=$e(),{working:J}=rf(),[ee,xe]=i.useState(!1),fe=i.useRef(null),Oe=i.useRef(!1),Se=i.useRef(!1),Le=rr(le=>le.queueModeEnabled),pe=rr(i.useCallback(le=>P?le.queuedMessages[P]??xd:xd,[P])),it=rr(le=>le.addToQueue),xt=rr(le=>le.clearQueue),{phase:Mt}=Ol(),De=i.useRef(Mt),ne=i.useRef(!1),rt=i.useCallback(le=>{if(!Ne||le.pointerType!=="touch")return;const se=C.current;if(!se||document.activeElement===se)return;le.preventDefault(),le.stopPropagation();const ce=document.scrollingElement;ce&&ce.scrollTop!==0&&(ce.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{se.focus({preventScroll:!0})}catch{se.focus()}const ue=se.value.length;try{se.setSelectionRange(ue,ue)}catch{}},[Ne]);i.useEffect(()=>{if($!==null){const le=F();le&&(n(le),setTimeout(()=>{C.current?.focus()},0))}},[$,F]);const be=i.useMemo(()=>{if(G)return me.find(le=>le.name===G)},[me,G]),ke=i.useMemo(()=>be?yd(be.permission,"edit")??"ask":"deny",[be]),Qe=he(i.useCallback(le=>!P||!G?void 0:le.sessionAgentEditModes.get(P)?.get(G),[P,G])),tt=i.useMemo(()=>{if(be)return yd(be.permission,"webfetch")},[be]),He=i.useMemo(()=>{if(!be)return;const le=Tv(be.permission,"bash");return le||void 0},[be]),Re=i.useMemo(()=>ef({agentDefaultEditMode:ke,webfetchPermission:tt,bashPermission:He}),[ke,tt,He]),nt=!!(P&&G),yt=i.useMemo(()=>nt&&Qe&&Re.modeAvailability[Qe]?Qe:Re.cascadeDefaultMode,[Re,nt,Qe]),ct=i.useMemo(()=>Un(yt),[yt]),It=i.useCallback(le=>Wt()?`color-mix(in srgb, ${le} 55%, transparent)`:le,[]),Tt=i.useMemo(()=>{const le=Wt()?1:2;if(!ct)return{borderWidth:le};const se=ct.border??ct.text;return{borderColor:It(se),borderWidth:le}},[ct,It]),je=t.trim()||X.length>0,ze=pe.length>0,Ze=je||ze,Ye=J.isWorking,mt=i.useMemo(()=>P?W===P&&!!L:!1,[W,L,P]),ye=i.useCallback(()=>{if(!je||!P)return;const le=t.replace(/^\n+|\n+$/g,""),se=X.map(ce=>({...ce}));it(P,{content:le,attachments:se.length>0?se:void 0}),n(""),se.length>0&&K(),Ne||C.current?.focus()},[je,P,t,X,it,K,Ne]),ie=async le=>{if(le?.preventDefault(),!Ze||!P&&!O)return;if(r?.({instant:!0,force:!0}),!R||!B){console.warn("Cannot send message: provider or model not selected");return}let se="",ce=[],ue;const Me=[];for(let Fe=0;Fe<pe.length;Fe++){const Je=pe[Fe],{sanitizedText:Pe,mention:ot}=ld(Je.content,me);!ue&&ot?.name&&(ue=ot.name),Fe===0?(se=Pe,ce=Je.attachments??[]):Me.push({text:Pe,attachments:Je.attachments})}if(je){const Fe=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Je,mention:Pe}=ld(Fe,me),ot=X.map(Dt=>({...Dt}));!ue&&Pe?.name&&(ue=Pe.name),pe.length===0?(se=Je,ce=ot):Me.push({text:Je,attachments:ot.length>0?ot:void 0})}if(!se&&Me.length===0)return;P&&ze&&xt(P),n(""),X.length>0&&K(),Ne&&C.current?.blur();const qe=se.trimStart();if(qe.startsWith("/")){const Fe=qe.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Fe==="undo"&&P){await he.getState().handleSlashUndo(P),r?.({instant:!0,force:!0});return}else if(Fe==="redo"&&P){await he.getState().handleSlashRedo(P),r?.({instant:!0,force:!0});return}else if(Fe==="timeline"&&P){V(!0),n("");return}else if(Fe==="compact"&&P){try{const{opencodeClient:Je}=await as(async()=>{const{opencodeClient:Dt}=await Promise.resolve().then(()=>Dg);return{opencodeClient:Dt}},void 0),Pe=Je.getDirectory();if((await Je.getApiClient().session.summarize({sessionID:P,directory:Pe||void 0,providerID:R,modelID:B})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Je){console.error("Failed to compact session:",Je),te.error("Failed to compact session")}n("");return}}const Ke=[...ce,...Me.flatMap(Fe=>Fe.attachments??[])];await I(se,R,B,G,ce,ue,Me.length>0?Me:void 0,z).catch(Fe=>{const Je=Fe instanceof Error?Fe.message:typeof Fe=="string"?Fe:String(Fe??""),Pe=Je.toLowerCase();console.error("Message send failed:",Je||Fe);const ot=Pe.includes("timeout")||Pe.includes("timed out")||Pe.includes("may still be processing")||Pe.includes("being processed")||Pe.includes("failed to fetch")||Pe.includes("networkerror")||Pe.includes("network error")||Pe.includes("gateway timeout")||Pe==="failed to send message";if(Pe.includes("payload too large")||Pe.includes("413")||Pe.includes("entity too large")){te.error("Attachments are too large to send. Please try reducing the number or size of images."),Ke.length>0&&qs.setState({attachedFiles:Ke});return}ot||(Ke.length>0&&qs.setState({attachedFiles:Ke}),te.error(Je||"Message failed to send. Attachments restored."))}),Ne||C.current?.focus()},de=i.useRef(ie);de.current=ie,i.useEffect(()=>{const le=De.current==="busy"||De.current==="cooldown",se=Mt==="idle",ce=P&&q.has(P)&&(()=>{const ue=q.get(P);return ue?Date.now()-ue.timestamp<2e3:!1})();le&&se&&pe.length>0&&!ne.current&&!ce&&(ne.current=!0,setTimeout(()=>{P&&R&&B&&de.current(),ne.current=!1},100)),De.current=Mt},[Mt,pe.length,P,R,B,q]);const We=le=>{if(!Fl(le)){if(m&&D.current&&(le.key==="Enter"||le.key==="ArrowUp"||le.key==="ArrowDown"||le.key==="Escape"||le.key==="Tab")){le.preventDefault(),D.current.handleKeyDown(le.key);return}if(y&&E.current&&(le.key==="Enter"||le.key==="ArrowUp"||le.key==="ArrowDown"||le.key==="Escape"||le.key==="Tab")){le.preventDefault(),E.current.handleKeyDown(le.key);return}if(v&&T.current&&(le.key==="Enter"||le.key==="ArrowUp"||le.key==="ArrowDown"||le.key==="Escape"||le.key==="Tab")){le.preventDefault(),T.current.handleKeyDown(le.key);return}if(l&&S.current&&(le.key==="Enter"||le.key==="ArrowUp"||le.key==="ArrowDown"||le.key==="Escape"||le.key==="Tab")){le.preventDefault(),S.current.handleKeyDown(le.key);return}if(le.key==="Tab"&&!m&&!y&&!l){le.preventDefault(),Z();return}if(le.key==="Enter"&&!le.shiftKey&&!Ne){le.preventDefault();const se=le.ctrlKey||le.metaKey,ce=je&&P&&Mt!=="idle";Le?se||!ce?ie():ye():se&&ce?ye():ie()}}},Ge=i.useCallback(()=>{fe.current&&(clearTimeout(fe.current),fe.current=null),xe(!0),fe.current=setTimeout(()=>{xe(!1),fe.current=null},1800)},[]),bt=i.useCallback(()=>{H(),Ge(),U()},[U,H,Ge]),Z=()=>{const le=me.filter(Me=>Pv(Me.mode));if(le.length<=1)return;const ce=(le.findIndex(Me=>Me.name===G)+1)%le.length,ue=le[ce];ge(ue.name),P&&ae(P,ue.name)},we=i.useCallback(()=>{const le=C.current;if(!le)return;le.style.height="auto";const se=le.ownerDocument?.defaultView,ce=se?se.getComputedStyle(le):null,ue=ce?parseFloat(ce.lineHeight):NaN,Me=ce?parseFloat(ce.paddingTop):NaN,qe=ce?parseFloat(ce.paddingBottom):NaN,Ke=22,Je=Number.isNaN(Me)||Number.isNaN(qe)?16:Me+qe,ot=(Number.isNaN(ue)?Ke:ue)*Iv+Je,Dt=le.scrollHeight||le.offsetHeight,Nt=Math.min(Dt,ot);le.style.height=`${Nt}px`,le.style.maxHeight=`${ot}px`,A(vs=>vs&&vs.height===Nt&&vs.maxHeight===ot?vs:{height:Nt,maxHeight:ot})},[]);i.useLayoutEffect(()=>{we()},[we,t,Ne]);const ve=i.useCallback((le,se)=>{if(le.startsWith("/")){const Ke=le.indexOf(" "),Fe=le.indexOf(`
88
- `),Je=Math.min(Ke===-1?le.length:Ke,Fe===-1?le.length:Fe);if(se<=Je&&Ke===-1){const Pe=le.substring(1,Je);g(Pe),f(!0),c(!1),h(!1),w(!1);return}}f(!1);const ce=le.substring(0,se),ue=ce.lastIndexOf("#");if(ue!==-1){const Ke=ue>0?ce[ue-1]:null,Fe=ce.substring(ue+1),Je=Fe.includes(" ")||Fe.includes(`
89
- `);if((!Ke||/\s/.test(Ke))&&!Je){b(Fe),h(!0),c(!1);return}}h(!1),b("");const Me=ce.lastIndexOf("/");if(Me!==-1){const Ke=Me>0?ce[Me-1]:null,Fe=ce.substring(Me+1),Je=Fe.includes(" ")||Fe.includes(`
90
- `);if((!Ke||/\s/.test(Ke))&&!Je){x(Fe),w(!0),c(!1),h(!1);return}}w(!1),x("");const qe=ce.lastIndexOf("@");if(qe!==-1){const Ke=ce.substring(qe+1);!Ke.includes(" ")&&!Ke.includes(`
91
- `)?(u(Ke),c(!0)):c(!1)}else c(!1)},[b,g,u,h,f,c,w,x]),Ue=i.useCallback(le=>{if(!le)return;const se=C.current;if(!se){const Ke=t+le;n(Ke),ve(Ke,Ke.length),requestAnimationFrame(()=>we());return}const ce=se.selectionStart??t.length,ue=se.selectionEnd??t.length,Me=`${t.substring(0,ce)}${le}${t.substring(ue)}`;n(Me);const qe=ce+le.length;requestAnimationFrame(()=>{const Ke=C.current;Ke&&(Ke.selectionStart=qe,Ke.selectionEnd=qe),we()}),ve(Me,qe)},[we,t,ve]),_e=le=>{const se=le.target.value,ce=le.target.selectionStart??se.length;n(se),we(),ve(se,ce)},et=i.useCallback(async le=>{const se=new Map;Array.from(le.clipboardData.files||[]).forEach(qe=>{qe.type.startsWith("image/")&&se.set(`${qe.name}-${qe.size}`,qe)}),Array.from(le.clipboardData.items||[]).forEach(qe=>{if(qe.kind==="file"&&qe.type.startsWith("image/")){const Ke=qe.getAsFile();Ke&&se.set(`${Ke.name}-${Ke.size}`,Ke)}});const ce=Array.from(se.values());if(ce.length===0||!P&&!O)return;le.preventDefault();const ue=le.clipboardData.getData("text");ue&&Ue(ue);let Me=0;for(const qe of ce){const Ke=he.getState().attachedFiles.length;try{await Y(qe),he.getState().attachedFiles.length>Ke&&(Me+=1)}catch(Fe){console.error("Clipboard image attach failed",Fe),te.error(Fe instanceof Error?Fe.message:"Failed to attach image from clipboard")}}Me>0&&te.success(`Attached ${Me} image${Me>1?"s":""} from clipboard`)},[Y,P,O,Ue]),pt=le=>{const se=C.current?.selectionStart||0,ue=t.substring(0,se).lastIndexOf("@");if(ue!==-1){const Me=t.substring(0,ue)+le.name+t.substring(se);n(Me)}c(!1),u(""),C.current?.focus()},ft=le=>{const ce=C.current?.selectionStart??t.length,Me=t.substring(0,ce).lastIndexOf("#");if(Me!==-1){const qe=t.substring(0,Me)+`#${le} `+t.substring(ce);n(qe);const Ke=Me+le.length+2;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=Ke,C.current.selectionEnd=Ke),we(),ve(qe,Ke)})}h(!1),b(""),C.current?.focus()},Pt=le=>{const ce=C.current?.selectionStart??t.length,Me=t.substring(0,ce).lastIndexOf("/");if(Me!==-1){const qe=t.substring(0,Me)+`${le} `+t.substring(ce);n(qe);const Ke=Me+le.length+1;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=Ke,C.current.selectionEnd=Ke),we(),ve(qe,Ke)})}w(!1),x(""),C.current?.focus()},At=le=>{n(`/${le.name} `);const se=C.current;se&&(se._commandMetadata=le),f(!1),g(""),setTimeout(()=>{C.current&&(C.current.focus(),C.current.setSelectionRange(C.current.value.length,C.current.value.length))},0)};i.useEffect(()=>{P&&C.current&&!Ne&&C.current.focus()},[P,Ne]),i.useEffect(()=>{W&&W!==P&&H()},[W,P,H]);const Te=le=>{le.preventDefault(),le.stopPropagation(),(P||O)&&!o&&a(!0)},st=le=>{le.preventDefault(),le.stopPropagation(),le.currentTarget===le.target&&a(!1)},Ve=async le=>{if(le.preventDefault(),le.stopPropagation(),a(!1),!P&&!O)return;const se=Array.from(le.dataTransfer.files);let ce=0;for(const ue of se){const Me=he.getState().attachedFiles.length;try{await Y(ue),he.getState().attachedFiles.length>Me&&(ce+=1)}catch(qe){console.error("File attach failed",qe),te.error(qe instanceof Error?qe.message:"Failed to attach file")}}ce>0&&te.success(`Attached ${ce} file${ce>1?"s":""}`)},Xe=i.useCallback(async le=>{let se=0;for(const ce of le){const ue=he.getState().attachedFiles.length;try{await re(ce.path,ce.name),he.getState().attachedFiles.length>ue&&(se+=1)}catch(Me){console.error("Server file attach failed",Me),te.error(Me instanceof Error?Me.message:"Failed to attach file")}}se>0&&te.success(`Attached ${se} file${se>1?"s":""}`)},[re]),kt=i.useRef(null),[Lt,ts]=i.useState(!1),ns=i.useCallback(async le=>{let se=0;const ce=Array.isArray(le)?le:Array.from(le);for(const ue of ce){const Me=he.getState().attachedFiles.length;try{await Y(ue),he.getState().attachedFiles.length>Me&&(se+=1)}catch(qe){console.error("File attach failed",qe),te.error(qe instanceof Error?qe.message:"Failed to attach file")}}se>0&&te.success(`Attached ${se} file${se>1?"s":""}`)},[Y]),ps=i.useCallback(async()=>{try{const se=await(await fetch("/api/vscode/pick-files")).json(),ce=Array.isArray(se?.files)?se.files:[],ue=Array.isArray(se?.skipped)?se.skipped:[];if(ue.length>0){const qe=ue.map(Ke=>`${Ke?.name||"file"}: ${Ke?.reason||"skipped"}`).join(`
92
- `);te.error(`Some files were skipped:
93
- ${qe}`)}const Me=ce.map(qe=>{if(!qe?.dataUrl)return null;try{const[Ke,Fe]=qe.dataUrl.split(","),Je=qe.mimeType||Ke?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Fe)return null;const Pe=atob(Fe),ot=new Uint8Array(Pe.length);for(let Nt=0;Nt<Pe.length;Nt++)ot[Nt]=Pe.charCodeAt(Nt);const Dt=new Blob([ot],{type:Je});return new File([Dt],qe.name||"file",{type:Je})}catch(Ke){return console.error("Failed to decode VS Code picked file",Ke),null}}).filter(Boolean);Me.length>0&&await ns(Me)}catch(le){console.error("VS Code file pick failed",le),te.error(le instanceof Error?le.message:"Failed to pick files in VS Code")}},[ns]),pr=i.useCallback(()=>{if(Wt()){ps();return}kt.current?.click()},[ps]),Bt=i.useCallback(async le=>{const se=le.target.files;se&&(await ns(se),le.target.value="")},[ns]),Nr="gap-x-1.5 gap-y-0",Rn=Wt(),Ba=Ne?"px-1.5 py-1.5":Rn?"px-1.5 py-1":"px-2.5 py-1.5",za=Ne?"h-9 w-9":Rn?"h-[22px] w-[22px]":"h-7 w-7",Hr=Ne?"h-5 w-5":Rn?"h-4 w-4":"h-[18px] w-[18px]",Ur=_(za,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),dn=!Ne&&mt&&Ye?e.jsx("button",{type:"button",onClick:bt,className:_(Ur,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Cn,{className:_(Hr)})}):e.jsx("button",{type:Ne?"button":"submit",disabled:!Ze||!P&&!O,onPointerDownCapture:le=>{!Ne||le.pointerType!=="touch"||!Ze||!P&&!O||(Se.current=!0,le.preventDefault(),le.stopPropagation(),ie())},onClick:le=>{if(Ne){if(Se.current){Se.current=!1;return}le.preventDefault(),ie()}},className:_(Ur,Ze&&(P||O)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(Sa,{className:_(Hr)})}),_n=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:kt,type:"file",multiple:!0,className:"hidden",onChange:Bt,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(cv,{onFilesSelected:Xe,multiSelect:!0,presentation:Ne?"modal":"dropdown",open:Lt,onOpenChange:ts,children:Ne?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:Ur,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(Du,{className:_(Hr,"text-current")})})}),e.jsxs(Qt,{align:"start",children:[e.jsxs(Et,{onSelect:()=>{requestAnimationFrame(()=>pr())},children:[e.jsx(sa,{}),"Attach files"]}),e.jsxs(Et,{onSelect:()=>{requestAnimationFrame(()=>{ts(!0)})},children:[e.jsx(wh,{}),"Attach from project"]})]})]})]})]}),Wa=s?e.jsx("button",{type:"button",onClick:s,className:Ur,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(sn,{className:_(Hr,"text-current")})}):null,go=e.jsxs(e.Fragment,{children:[_n,Wa]}),Ha=J.statusText;i.useEffect(()=>{const le=!!J.wasAborted;!Oe.current&&le&&!ee&&(Ge(),P&&Q(P)),Oe.current=le},[Q,P,ee,Ge,J.wasAborted]),i.useEffect(()=>()=>{fe.current&&(clearTimeout(fe.current),fe.current=null)},[]);const Ua=Ne&&Ye;return e.jsxs("form",{onSubmit:ie,className:_("pt-0 pb-2 md:pb-4",Ne&&Be?"ios-keyboard-safe-area":"bottom-safe-area"),"data-keyboard-avoid":"true",style:Ne&&Ce>0&&!Be?{marginBottom:`${Ce}px`}:void 0,children:[e.jsx(kv,{isWorking:J.isWorking,statusText:Ha,isGenericStatus:J.isGenericStatus,isWaitingForPermission:J.isWaitingForPermission,wasAborted:J.wasAborted,abortActive:J.abortActive,completionId:J.lastCompletionId,isComplete:J.isComplete,showAbort:Ua,onAbort:bt,showAbortStatus:ee}),e.jsxs("div",{ref:M,className:_("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Te,onDragLeave:st,onDrop:Ve,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:Ur,onClick:()=>pr(),title:"Attach files","aria-label":"Attach files",children:e.jsx(sa,{className:_(Hr,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(nv,{}),e.jsx(Qm,{onEditMessage:le=>{n(le),setTimeout(()=>{C.current?.focus()},0)}}),e.jsxs("div",{className:_("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:Tt,children:[m&&e.jsx(Ym,{ref:D,searchQuery:p,onCommandSelect:At,onClose:()=>f(!1)}),y&&e.jsx(Xm,{ref:E,searchQuery:j,onAgentSelect:ft,onClose:()=>h(!1)}),v&&e.jsx(Jm,{ref:T,searchQuery:N,onSkillSelect:Pt,onClose:()=>w(!1)}),l&&e.jsx(ov,{ref:S,searchQuery:d,onFileSelect:pt,onClose:()=>c(!1)}),e.jsx(Ss,{ref:C,"data-chat-input":"true",value:t,onChange:_e,onKeyDown:We,onPaste:et,onPointerDownCapture:rt,placeholder:P||O?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!P&&!O,className:_("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",Ne?"py-2.5":"pt-4 pb-2","focus-visible:outline-none focus-visible:ring-0"),style:{flex:"none",height:k?`${k.height}px`:void 0,maxHeight:k?`${k.maxHeight}px`:void 0},rows:1}),e.jsx("div",{className:_("rounded-b-xl bg-transparent",Ba,Ne?"flex items-center gap-x-1.5":_("flex items-center justify-between",Nr)),"data-chat-input-footer":"true",children:Ne?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:go}),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(id,{className:_("w-full flex items-center justify-end min-w-0")})}),dn]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:_("flex items-center flex-shrink-0",Nr),children:go}),e.jsxs("div",{className:_("flex items-center flex-1 justify-end",Nr,"md:gap-x-3"),children:[e.jsx(id,{className:_("flex-1 min-w-0 justify-end")}),dn]})]})})]})]})]})};function hi({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:_("bg-accent animate-pulse rounded-xl",s),...r})}const bd=(s,r,t,n,o=4)=>{const a=[];for(let l=0;l<o;l++)for(let c=0;c<o;c++){const d=c/o,u=(c+1)/o,m=l/o,f=(l+1)/o,p=(v,w,N)=>v+(w-v)*N,g=(v,w,N,x,k,A)=>{const C=p(v,w,k),M=p(x,N,k);return p(C,M,A)},y={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${y.x} ${y.y} L${h.x} ${h.y} L${j.x} ${j.y} L${b.x} ${b.y} Z`,row:l,col:c})}return a},$l=({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 l=a?"white":"black",c=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,y={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},v={x:50-m*f,y:g+m*p},w={x:50+m*f,y:g+m*p},N={x:50,y:g+m},k=`matrix(0.866, 0.5, -0.866, 0.5, 50, ${(y.y+h.y+b.y+j.y)/4})`,A=bd(h,b,N,v),C=bd(b,j,w,N),M=Ae.useMemo(()=>{const S=[];for(let D=0;D<32;D++)S.push(.1+Math.random()*.5);return S},[]);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${v.x} ${v.y} L${N.x} ${N.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),A.map((S,D)=>e.jsx("path",{d:S.path,fill:u,opacity:M[D]},`left-${D}`)),e.jsx("path",{d:`M${b.x} ${b.y} L${j.x} ${j.y} L${w.x} ${w.y} L${N.x} ${N.y} Z`,fill:c,stroke:l,strokeWidth:"2",strokeLinejoin:"round"}),C.map((S,D)=>e.jsx("path",{d:S.path,fill:u,opacity:M[D+16]},`right-${D}`)),e.jsx("path",{d:`M${y.x} ${y.y} L${h.x} ${h.y} L${b.x} ${b.y} L${j.x} ${j.y} Z`,fill:"none",stroke:l,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:`${k} 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 Fv({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:l=!0,mode:c="popLayout"}){const[d,u]=Ae.useState(0),m=Ae.Children.toArray(s);Ae.useEffect(()=>{if(!l)return;const p=t*1e3,g=setInterval(()=>{u(y=>{const h=(y+1)%m.length;return a?.(h),h})},p);return()=>clearInterval(g)},[m.length,t,a,l]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:_("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(jh,{mode:c,initial:!1,children:e.jsx(xn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const Rv=["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"],_v=()=>{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($l,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(Fv,{className:"text-body-md",interval:4,transition:{duration:.5},children:Rv.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},gi=i.memo(_v),Ov={'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"}},$v={'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 Pr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Pr.instance||(Pr.instance=new Pr),Pr.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 Ll(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]=i.useState(!1);return i.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:_("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},Lv=({isUser:s,providerID:r,agentName:t,modelName:n,variant:o,isDarkTheme:a})=>{const{src:l,onError:c,hasLogo:d}=Wm(r);return e.jsx(gs,{children:e.jsx("div",{className:_("pl-3","mb-2"),children:e.jsx("div",{className:_("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(Os,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&l?e.jsx("img",{src:l,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:c}):e.jsx(dr,{className:"h-4 w-4",style:{color:`var(${Ar(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:_("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:_("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)]",Ar(t).class),children:[e.jsx(sn,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:t})]}),!s&&o&&e.jsxs("div",{className:_("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(dr,{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})]})]})]})})})})},Bv=i.memo(Lv),vd=(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},wd=()=>{if(!Wt()||typeof window>"u")return _c;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=vd({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=vd({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return _c},of=()=>{const[s,r]=i.useState(wd);return i.useEffect(()=>{if(!Wt()||typeof window>"u")return;const t=n=>{r(wd())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},af=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(l=>r.push(l.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(l=>{const c=l.querySelectorAll("td"),d=[];c.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},lf=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
94
- `)?`"${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(`
95
- `)},zv=({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(`
96
- `)},Wv=({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((l,c)=>t(o[c]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
97
- `)},Hv=(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)},Uv=({tableRef:s})=>{const[r,t]=i.useState(!1),[n,o]=i.useState(!1),a=i.useRef(null);i.useEffect(()=>{const c=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[]);const l=async c=>{const d=s.current?.querySelector("table");if(d)try{const u=af(d),m=c==="csv"?lf(u):zv(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(_t,{className:"size-3.5"}):e.jsx(Ys,{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:()=>l("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:()=>l("tsv"),children:"TSV"})]})]})},Vv=({tableRef:s})=>{const[r,t]=i.useState(!1),n=i.useRef(null);i.useEffect(()=>{const a=l=>{n.current&&!n.current.contains(l.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const l=s.current?.querySelector("table");if(l)try{const c=af(l),d=a==="csv"?lf(c):Wv(c);Hv(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(c){console.error("Failed to download table:",c)}};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(Fr,{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"})]})]})},Gv=({children:s,className:r})=>{const t=i.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(Uv,{tableRef:t}),e.jsx(Vv,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:_("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},qv=({children:s,className:r,style:t,...n})=>{const[o,a]=i.useState(!1),l=i.useRef(null),c=i.useMemo(()=>{if(!t)return t;const m={...t},f=y=>{if(typeof y!="string")return{value:void 0,vars:{}};const[h,...j]=y.split(";").map(v=>v.trim()).filter(Boolean),b={};for(const v of j){const w=v.indexOf(":");if(w===-1)continue;const N=v.slice(0,w).trim(),x=v.slice(w+1).trim();!N.startsWith("--")||x.length===0||(b[N]=x)}return{value:h,vars:b}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[y,h]of Object.entries(p.vars))m[y]=h;const g=f(t.color);g.value&&(m.color=g.value,m["--shiki-light"]=g.value);for(const[y,h]of Object.entries(g.vars))m[y]=h;return m},[t]),d=()=>l.current&&l.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:l,children:[e.jsx("pre",{...n,className:_(r),style:c,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(_t,{className:"size-3.5"}):e.jsx(Ys,{className:"size-3.5"})})})]})},cf={pre:qv,table:Gv},Kv=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:l="assistant"})=>{const c=of(),d=i.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=l==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:_("break-words",o),children:e.jsx(Au,{mode:a?"streaming":"static",shikiTheme:c,className:u,controls:{code:!1,table:!1},components:cf,children:s})});return n?e.jsx(gs,{children:m},d):m},Zr=({content:s,className:r,variant:t="assistant"})=>{const n=of(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:_("break-words",r),children:e.jsx(Au,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:cf,children:s})})},Qv={thinking:{label:"Thinking",Icon:dr},justification:{label:"Justification",Icon:ll}},df=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
98
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
99
- `).trim(),Yv=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
100
- `),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},Bl=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=i.useState(!1),l=i.useMemo(()=>Yv(s),[s]),{label:c,Icon:d}=Qv[r];return i.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:_("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:_("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:_("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(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Rs,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:c})]}),l&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:l})})]}),o&&e.jsx("div",{className:_("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(gt,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},uf=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=i.useMemo(()=>df(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Bl,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},Xv=s=>df(s),Jv=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const l=s,c=l.text,d=typeof c=="string"?c:l.content||l.value||"",u=i.useMemo(()=>a?Xv(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=i.useRef(m);if(m||f)return p.current=!0,null;const g=l.time;return!(g&&typeof g.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(Bl,{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(Kv,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},Zv=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,ew=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[l,c]=i.useState(!1),[d,u]=i.useState(!1),m=i.useRef(null);i.useEffect(()=>{const g=m.current;if(!g||l)return;const y=()=>{u(g.scrollHeight>g.clientHeight)};y();const h=new ResizeObserver(y);return h.observe(g),()=>h.disconnect()},[a,l]);const f=i.useCallback(()=>{(d||l)&&c(g=>!g)},[d,l]);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),y=a.slice(0,g),h=a.slice(g+t.token.length);return e.jsxs(e.Fragment,{children:[y,e.jsx("a",{href:Zv(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:_("break-words whitespace-pre-wrap font-sans typography-markdown",!l&&"line-clamp-3",(d||l)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},tw=i.memo(ew),sw=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},rw=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,nw=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",jd=(s,r)=>!s||typeof s!="object"?String(s):Ly(s,r||""),xi=(s,r,t)=>{let n=sw(s);if((r==="edit"||r==="multiedit")&&rw(n)&&(n=nw(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},ow=(s,r)=>{try{const t=s.trim().split(`
101
- `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,l,c]=a,d=Math.floor(l.length/2),u=!c.endsWith("/");n.push({name:c.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:_("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:br.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}},aw=(s,r,t)=>{try{const n=s.trim().split(`
102
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const l=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(l){const[,c,d,u]=l,m=u!==void 0?d:"",f=u!==void 0?u:d;o[c]||(o[c]=[]),o[c].push({lineNum:m,content:f})}}),e.jsxs("div",{className:_("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:br.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,l])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:_("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:l.map((c,d)=>!c.lineNum&&!c.content?null:e.jsxs("div",{className:_("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:[c.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",c.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:c.content||" "})]})]},d))})]},a))]})}catch{return null}},iw=(s,r,t)=>{try{const n=s.trim().split(`
103
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(l=>{const c=l.lastIndexOf("/"),d=c>0?l.substring(0,c):"/",u=c>=0?l.substring(c+1):l;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:_("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:br.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(l=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:_("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[l,"/"]}),e.jsx("div",{className:_("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[l].sort().map(c=>e.jsxs("div",{className:_("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:c})]},c))})]},l))]})}catch{return null}},lw=(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 l="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:l,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:l,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:l,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:_("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:br.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,l)=>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||l))})]}),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,l)=>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||l))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_t,{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,l)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(_t,{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||l))})]}),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,l)=>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||l))})]})]})}catch{return null}},cw=(s,r,t)=>{try{return e.jsx("div",{className:_("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:br.tool.popup,children:e.jsx(Zr,{content:s,variant:"tool"})})}catch{return null}},mf=s=>{const r=s.split(`
104
- `);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 l=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),c=l?parseInt(l[1]):0,d=l?parseInt(l[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:c,newStart:d,lines:u}),o=f;continue}o++}return n},el=(s,r,t)=>Oy(r,s,t),ff=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(Sh,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Eu,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(eo,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(_r,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(Hs,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(kh,{className:r}):t==="glob"?e.jsx(Nh,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(_i,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(_i,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(Iu,{className:r}):t==="skill"?e.jsx(Pu,{className:r}):t==="question"?e.jsx(Ch,{className:r}):t.startsWith("git")?e.jsx(zt,{className:r}):e.jsx(Ma,{className:r})},dw=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},uw=({start:s,end:r,active:t})=>{const[n,o]=i.useState(()=>Date.now());return i.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:dw(s,r,n)})},mw=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
105
- `);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}},tl=(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},fw=s=>{const r=s.match(/^User has answered your questions:\s*(.+?)\.\s*You can now/s);if(!r)return null;const t=[],n=r[1],o=/"([^"]+)"="([^"]*(?:[^"\\]|\\.)*)"/g;let a;for(;(a=o.exec(n))!==null;)t.push({question:a[1],answer:a[2]});return t.length>0?t:null},pw=(s,r,t,n)=>{const o=r,a=o.metadata,l=o.input;if(s.tool==="question"&&l?.questions&&Array.isArray(l.questions)){const d=l.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((s.tool==="edit"||s.tool==="multiedit")&&l){const d=l?.filePath||l?.file_path||l?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return tl(d,n,t)}if((s.tool==="read"||s.tool==="write")&&l){const d=l?.filePath||l?.file_path||l?.path;if(typeof d=="string")return tl(d,n,t)}if(s.tool==="bash"&&l?.command&&typeof l.command=="string"){const d=l.command.split(`
106
- `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&l?.description&&typeof l.description=="string")return t?l.description.substring(0,40):l.description.substring(0,80);if(s.tool==="skill"&&l?.name&&typeof l.name=="string")return l.name;const c=l?.description||a?.description||"title"in r&&r.title||"";return typeof c=="string"?c:""},sl=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(gt,{outerClassName:_("w-full min-w-0 flex-none overflow-hidden",r,n),className:_("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})}),hw=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"},gw=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),xw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const l=he(h=>h.setCurrentSession),c=i.useMemo(()=>s.filter(h=>h.state?.status==="completed"),[s]),d=typeof o=="string"?gw(o):"",u=d.length>0,[m,f]=i.useState(!1),p=h=>{h.stopPropagation(),a&&l(a)};if(c.length===0&&!u&&!a)return null;const g=r?c:c.slice(-6),y=Math.max(0,c.length-g.length);return e.jsxs("div",{className:_("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:[c.length>0?e.jsx(sl,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[y>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",y," more…"]}):null,g.map((h,j)=>{const b=typeof h.tool=="string"&&h.tool.trim().length>0?h.tool:"tool",v=hw(h),w=Cl(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:ff(b)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:w}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:v})]},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(ta,{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:_("space-y-1",(c.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(Ft,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Rs,{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(sl,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Zr,{content:d,variant:"tool"})})}):null]}):null]})},yw=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mf(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,l)=>e.jsxs("div",{className:_("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(or,{style:r,language:fr(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})})]},l))})]},o))}),bw=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
107
- `),a=fr(t??"")||el(s,"write",t?{filePath:t}:void 0),l=Math.max(o.length,1),c=l===1?"line 1":`lines 1-${l}`;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} (${c})`}),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(or,{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))})]})},vw=({content:s,filePath:r,displayPath:t})=>{const n=Gi(r),o=r.toLowerCase().endsWith(".svg"),a=i.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"}})})]})},ww=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:l})=>{const c=r,d=c.metadata,u=c.input,m=c.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",g=typeof d?.diff=="string"?d.diff:null,y=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=y?io(y):!1,v=j?y?tl(y,o,n):"New file":null,w=i.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?jd(u,s.tool):typeof u.content=="string"?u.content??"":jd(u,s.tool),[u,s.tool]),N=w.trim().length>0,x=(A,C)=>e.jsx(sl,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:A}),k=()=>{if(s.tool==="question"){if(r.status==="completed"&&f){const A=fw(p);if(A&&A.length>0)return x(e.jsx("div",{className:"space-y-2",children:A.map((C,M)=>e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:C.question}),e.jsx("div",{className:"typography-meta text-foreground whitespace-pre-wrap",children:C.answer})]},M))}),{maxHeightClass:"max-h-[40vh]"})}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:"Awaiting response..."})}if(s.tool==="todowrite"||s.tool==="todoread"){if(r.status==="completed"&&f){const A=lw(p,{unstyled:!0});return x(A??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 A=ow(p,{unstyled:!0});return x(A??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 A=aw(p,n,{unstyled:!0});return x(A??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 A=iw(p,n,{unstyled:!0});return x(A??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 x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Zr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const A=cw(p,t,{unstyled:!0});return x(A??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 x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Zr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return x(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Zr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&g)return x(e.jsx(yw,{diff:g,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const A=xi(p,s.tool,d),C=A.split(`
108
- `),M=typeof u?.offset=="number"?u.offset:0,S=typeof u?.limit=="number"?u.limit:void 0,D=E=>E.trim().startsWith("(");return x(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:C.map((E,T)=>{const I=D(E),P=M+T+1,O=!I&&(S===void 0||T<S);return e.jsxs("div",{className:_("typography-code font-mono flex w-full min-w-0",I&&"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:O?P:""}),e.jsx("div",{className:"flex-1 min-w-0",children:I?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:E}):e.jsx(or,{style:t,language:el(A,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})})]},T)})}),{className:"p-1"})}return x(e.jsx(or,{style:t,language:el(xi(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...zo.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:xi(p,s.tool,d)}),{className:"p-1"})}return x(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:_("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]",l?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"||s.tool==="question"?k():e.jsxs(e.Fragment,{children:[j&&b?e.jsx("div",{className:"my-1",children:x(e.jsx(vw,{content:h,filePath:y,displayPath:v??"New file"}))}):j?e.jsx("div",{className:"my-1",children:x(e.jsx(bw,{content:h,syntaxTheme:t,filePath:y,displayPath:v??"New file"}))}):N?e.jsx("div",{className:"my-1",children:x(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:w}),{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:"}),k()]}),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})]})]})})},Xo=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:l=!1,hasNextTool:c=!1})=>{const d=s.state,u=vt(P=>P.currentDirectory),m=s.tool.toLowerCase()==="task",f=d.status==="completed"||d.status==="error",p=d.status==="running"||d.status==="pending",g=d.status==="error",y=i.useRef(r);i.useEffect(()=>{!f&&!m||y.current!==r&&(y.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const h=d,j=h.metadata,b=h.input,v=h.time,w=i.useRef({}),N=i.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,w.current={}),m){if(typeof v?.start=="number"){const P=w.current.start;(typeof P!="number"||v.start<P)&&(w.current.start=v.start)}typeof v?.end=="number"&&(w.current.end=v.end)}const x=m?w.current.start??v?.start:v?.start,k=m?w.current.end??v?.end:v?.end,A=i.useMemo(()=>{if(!m)return;const P=j;return typeof P?.sessionId=="string"?P.sessionId:void 0},[m,j]),C=i.useMemo(()=>{if(!m)return[];const P=j?.summary;return Array.isArray(P)?P.filter(O=>typeof O=="object"&&O!==null):[]},[m,j]),M=i.useRef(C.length);i.useEffect(()=>{m&&M.current!==C.length&&(M.current=C.length,a?.("structural"))},[m,a,C.length]);const S=s.tool==="edit"||s.tool==="multiedit"?mw(j):null,D=pw(s,d,o,u),E=Cl(s.tool).displayName,T=i.useContext(Ml),I=P=>{if(m||!T?.editor){t(s.id);return}let O;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(O=b?.filePath||b?.file_path||b?.path||j?.filePath||j?.file_path||j?.path),typeof O=="string"){P.stopPropagation();let U=O;O.startsWith("/")||(U=u.endsWith("/")?u+O:u+"/"+O),T.editor.openFile(U)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:_("group/tool flex items-center gap-2 pr-2 pl-px py-1.5 rounded-xl cursor-pointer"),onClick:I,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:P=>{P.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:_("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&g?{color:"var(--status-error)"}:{},children:ff(s.tool)}),e.jsx("div",{className:_("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(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Rs,{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:[D&&e.jsx("span",{className:_("truncate",o&&"max-w-[120px]"),children:D}),S&&e.jsxs("span",{className:"text-muted-foreground/60 flex-shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",S.added]})," ",e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",S.removed]})]}),typeof x=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(uw,{start:x,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(C.length>0||p||f||A)?e.jsx(xw,{entries:C,isExpanded:r,hasPrevTool:l,hasNextTool:c,output:typeof h.output=="string"?h.output:void 0,sessionId:A}):null,!m&&r?e.jsx(ww,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:l,hasNextTool:c}):null]})},jw=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
109
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
110
- `).trim(),Sw=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=i.useMemo(()=>jw(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Bl,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},kw=i.memo(Sw),Nw=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(", ")},Sd=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}),Cw=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},Mw=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:l,onContentChange:c,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=i.useRef(r),[p,g]=i.useState(0);i.useEffect(()=>{if(f.current===r)return;const b=f.current===!1;f.current=r,c?.("structural"),r&&b&&g(v=>v+1)},[r,c]);const y=i.useMemo(()=>Sd(d?s.filter(b=>b.part.id&&u.has(b.id)):s),[s,d,u]),h=Nw(y),j=Cw(y);return y.length===0?null:e.jsx(gs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:_("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:_("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(to,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:_("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(Ft,{className:"h-3.5 w-3.5"}):e.jsx(Rs,{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:_("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:y.map((b,v)=>{const w=b.part.id||`group-part-${v}`,N=j[w],x=`${w}-exp${p}`;switch(b.kind){case"tool":return e.jsx(gs,{children:e.jsx(Xo,{part:b.part,isExpanded:a.has(w),onToggle:l,syntaxTheme:n,isMobile:o,onContentChange:c,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},x);case"reasoning":return e.jsx(gs,{children:e.jsx(uf,{part:b.part,messageId:b.messageId,onContentChange:c})},x);case"justification":return e.jsx(gs,{children:e.jsx(kw,{part:b.part,messageId:b.messageId,onContentChange:c})},x);default:return null}})})]})})},Dw=i.memo(Mw),Aw=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:_("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),yi=i.memo(Aw),pf=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},hf=s=>{if(s.type!=="text")return!1;const r=pf(s);return!r||r.trim().length===0},Ew=(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"))},Iw=s=>{const r=s/1e3;if(r<60)return`${r.toFixed(1)}s`;const t=Math.floor(r/60),n=Math.round(r%60);return`${t}m ${n}s`},Pw=(s,r)=>{const t=i.useRef(null),n=i.useRef(null),[o,a]=i.useState(!1),l=i.useRef(s);l.current=s;const c=i.useRef(r);c.current=r;const d=i.useRef(!1),u=r.size>0;return i.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=l.current;if(!m)return;const f=Array.from(c.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),i.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]),i.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},Tw=new Set(["task"]),gn=s=>typeof s=="string"&&Tw.has(s.toLowerCase()),Fw=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:l,onShowPopup:c,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=i.useState(!1),g=i.useRef(null),y=i.useMemo(()=>r.filter(C=>C.type!=="text"?!1:!hf(C)),[r]),h=d?.token;let j=!1;const b=!!a,v=!!l,w=!!(n??t),N=!!o,x=i.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),k=i.useCallback(()=>{!w||!b||!N||typeof window>"u"||(x(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[b,x,N,w]);i.useEffect(()=>{N||(p(!1),x())},[x,N]);const A=i.useCallback(C=>{!a||!N||(C.stopPropagation(),C.preventDefault(),a(),w&&k())},[N,w,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:w&&b&&N?k:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:y.map((C,M)=>{let S;return d&&h&&!j&&pf(C).includes(h)&&(S=d,j=!0),e.jsx(gs,{children:e.jsx(tw,{part:C,messageId:s,isMobile:t,agentMention:S})},`user-text-${M}`)})}),e.jsx(qm,{files:r,onShowPopup:c}),b&&N||u||m?e.jsxs("div",{className:_("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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),u()},children:e.jsx(Zn,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:C=>C.stopPropagation(),onClick:C=>{C.stopPropagation(),m()},children:e.jsx(zt,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Fork from here"})]}),b&&N&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{type:"button",variant:"ghost",size:"icon","data-visible":f||v?"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:C=>C.stopPropagation(),onClick:A,onFocus:()=>p(!0),onBlur:()=>{v||p(!1)},children:v?e.jsx(_t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy message"})]})]}):null]})},Rw=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:l,hasTouchInput:c,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:g,hasTextContent:y=!1,onCopyMessage:h,copiedMessage:j=!1,onAuxiliaryContentComplete:b,showReasoningTraces:v=!1,turnGroupingContext:w,errorMessage:N})=>{const[x,k]=i.useState(!1),A=i.useRef(null),C=!!h,M=!!j,S=!!(c??l),D=!t,E=i.useMemo(()=>r.filter(ie=>!hf(ie)).filter(ie=>ie.type!=="compaction"),[r]),T=i.useMemo(()=>E.filter(ie=>ie.type==="tool"),[E]),I=i.useMemo(()=>E.filter(ie=>ie.type==="text"),[E]),P=he(ie=>ie.createSessionFromAssistantMessage),O=$e(ie=>ie.openMultiRunLauncherWithPrompt),U=w?.isLastAssistantInTurn??!1,Q=n==="stop",W=T.length>0,L=i.useMemo(()=>T.some(ie=>{const We=(ie.state??{})?.status;return We==="pending"||We==="running"||We==="started"}),[T]),H=i.useCallback(ie=>{const de=ie.state??{},We=de?.status;if(We==="pending"||We==="running"||We==="started")return!1;const Ge=de?.time??{},bt=typeof Ge?.end=="number"?Ge.end:void 0,Z=typeof Ge?.start=="number"?Ge.start:void 0;return!(typeof bt!="number"||typeof Z=="number"&&bt<Z)},[]),q=i.useMemo(()=>T.length===0?!0:L?!1:T.every(ie=>H(ie)),[T,L,H]),X=i.useMemo(()=>I.length===0?!0:I.every(ie=>typeof ie.time?.end=="number"),[I]),Y=i.useMemo(()=>E.filter(ie=>ie.type==="reasoning"),[E]),re=i.useMemo(()=>Y.length===0?!0:Y.every(ie=>typeof ie.time?.end=="number"),[Y]),K=typeof n!="string",ae=Y.length>0&&W&&(L||K||!q),F=i.useMemo(()=>W?I.length===0?K||L||!q:!0:I.length>0?ae:!1,[I.length,K,L,W,ae,q]),$=D||F&&(!X||!q||L||K)||ae,R=D||W&&(L||K||!q),B=D||ae,z=W||Y.length>0,G=I.length===0,ge=z&&G&&!R&&!B&&q&&re,oe=i.useRef(!1),me=i.useRef(!1);i.useEffect(()=>{me.current=!1},[s]),i.useEffect(()=>{if(!ge){oe.current=!1;return}oe.current||(oe.current=!0,b?.())},[ge,b]),i.useEffect(()=>{if(D){me.current=!1;return}if(W){me.current=!1;return}Y.length!==0&&(B||!re||me.current||(me.current=!0,g?.("structural")))},[D,W,g,re,Y.length,B]);const Ne=!!y&&!D,Ce=i.useCallback(()=>{A.current!==null&&typeof window<"u"&&(window.clearTimeout(A.current),A.current=null)},[]),Be=i.useCallback(()=>{!S||!C||!Ne||typeof window>"u"||(Ce(),k(!0),A.current=window.setTimeout(()=>{k(!1),A.current=null},1800))},[C,Ce,Ne,S]);i.useEffect(()=>{Ne||(k(!1),Ce())},[Ce,Ne]);const V=i.useCallback(ie=>{!h||!Ne||(ie.stopPropagation(),ie.preventDefault(),h(),S&&Be())},[Ne,S,h,Be]),J=i.useCallback(ie=>{ie.stopPropagation(),ie.preventDefault(),P&&P(s)},[P,s]),ee=i.useCallback(ie=>{ie.stopPropagation(),ie.preventDefault();const de=Sl(I);if(!de.trim())return;const We=`${Zx}
111
-
112
- ${de}`;O(We)},[I,O]);i.useEffect(()=>()=>{Ce()},[Ce]);const xe=i.useMemo(()=>{const ie={},de=T.filter(We=>gn(We.tool)||R?!1:H(We));return de.forEach((We,Ge)=>{ie[We.id]={hasPrev:Ge>0,hasNext:Ge<de.length-1}}),ie},[T,R,H]),fe=i.useMemo(()=>w?.activityParts??[],[w]),Oe=i.useMemo(()=>w?fe.filter(ie=>ie.messageId===s):[],[fe,s,w]),Se=i.useMemo(()=>w?w.activityGroupSegments.filter(ie=>ie.anchorMessageId===s):[],[s,w]),Le=i.useMemo(()=>{const ie=new Map;return Oe.forEach(de=>{ie.set(de.part,de)}),ie},[Oe]),pe=i.useMemo(()=>w?(v?fe:fe.filter(de=>de.kind==="tool")).filter(de=>{if(de.kind!=="tool")return!0;const We=de.part.tool;return!gn(We)}):[],[fe,v,w]),[it,xt]=i.useState(!1);i.useEffect(()=>{if(!w)return;const ie=w.activityGroupSegments.some(de=>de.afterToolPartId!==null);(pe.length>1||ie&&pe.length>0)&&xt(!0)},[w,pe.length]);const Mt=!!(w&&it),De=i.useMemo(()=>{if(!w)return[];if(!Mt)return[];if(!w.isWorking)return[];const ie=[];return Oe.forEach(de=>{if(w.previewedPartIds.has(de.id)||!v&&de.kind!=="tool")return;const We=de.part;if(de.kind==="tool"){const Ge=We;if(gn(Ge.tool)||R||!H(Ge))return}else if(de.kind==="reasoning"){if(!v||B||typeof We.time?.end!="number")return}else if(de.kind==="justification"&&(!v||$||typeof We.time?.end!="number"))return;ie.push(de)}),ie},[Oe,H,$,B,R,v,Mt,w]),ne=i.useMemo(()=>{const ie=new Set;return De.forEach(de=>{ie.add(de.id)}),ie},[De]),{isAnimating:rt}=Pw(w,ne),be=!!(w&&Mt&&pe.length>0&&Se.length>0),ke=i.useMemo(()=>T.filter(ie=>gn(ie.tool)),[T]),Qe=i.useMemo(()=>{const ie=[],de=Ge=>{!w||!be||Se.filter(bt=>(bt.afterToolPartId??null)===Ge).forEach(bt=>{const Z=v?bt.parts:bt.parts.filter(we=>we.kind==="tool");Z.length!==0&&ie.push(e.jsx(Dw,{parts:Z,isExpanded:w.isGroupExpanded,onToggle:w.toggleGroup,syntaxTheme:a,isMobile:l,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,isWorking:w.isWorking,previewedPartIds:w.previewedPartIds,diffStats:w.diffStats},`progressive-group-${bt.id}`))})};de(null),ke.forEach(Ge=>{ie.push(e.jsx(gs,{children:e.jsx(Xo,{part:Ge,isExpanded:d.has(Ge.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Ge.id}`)),de(Ge.id)});const We=[];return E.forEach((Ge,bt)=>{const Z=Le.get(Ge);if(!Z||!w)return;let we=null,ve=null;if(!Mt){if(Z.kind==="tool"){const _e=Ge;if(gn(_e.tool))return;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))return;const At=xe[_e.id];ve=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`),we=ft&&typeof pt?.end=="number"?pt.end:null}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve});return}if(!w.isWorking||w.isGroupExpanded||w.previewedPartIds.has(Z.id)||!v&&Z.kind!=="tool")return;const Ue=ne.has(Z.id);switch(Z.kind){case"tool":{const _e=Ge;if(gn(_e.tool))break;const pt=_e.state?.time,ft=H(_e);if(!(!R&&ft))break;const At=xe[_e.id],Te=e.jsx(gs,{children:e.jsx(Xo,{part:_e,isExpanded:d.has(_e.id),onToggle:u,syntaxTheme:a,isMobile:l,onContentChange:g,hasPrevTool:At?.hasPrev??!1,hasNextTool:At?.hasNext??!1})},`tool-${_e.id}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:Te},`migrating-tool-${_e.id}`):Te,we=ft&&typeof pt?.end=="number"?pt.end:null;break}case"reasoning":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!B))break;const ft=e.jsx(gs,{children:e.jsx(uf,{part:Ge,messageId:s,onContentChange:g})},`reasoning-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-reasoning-${bt}`):ft,we=et?_e?.end??null:null;break}case"justification":{if(!v)break;const _e=Ge.time,et=typeof _e?.end=="number";if(!(et&&!$))break;const ft=e.jsx(gs,{children:e.jsx(Jv,{part:Ge,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:g,renderAsReasoning:!0})},`assistant-text-${bt}`);ve=Ue?e.jsx(yi,{isMigrating:rt,children:ft},`migrating-text-${bt}`):ft,we=et?_e?.end??null:null;break}}ve&&We.push({part:Ge,index:bt,endTime:we,element:ve})}),We.sort((Ge,bt)=>Ge.endTime===null&&bt.endTime===null?Ge.index-bt.index:Ge.endTime===null?1:bt.endTime===null?-1:Ge.endTime-bt.endTime),We.forEach(({element:Ge})=>{ie.push(Ge)}),ie},[Le,Se,d,rt,l,H,s,g,m,u,ne,$,B,R,Mt,v,a,xe,w,E,ke,be]),tt=w?.turnId,He=he(ie=>ie.currentSessionId),Re=St(ie=>{if(!tt||!He)return;const de=ie.messages.get(He);if(!de)return;const We=de.find(Z=>Z.info?.id===tt);if(!We)return;const bt=We.info.summary?.body;return typeof bt=="string"&&bt.trim().length>0?bt:void 0}),nt=typeof w?.summaryBody=="string"&&w.summaryBody.trim().length>0?w.summaryBody:Re,yt=i.useRef(void 0);nt&&nt.trim().length>0&&(yt.current=nt);const ct=i.useRef(tt);ct.current!==tt&&(ct.current=tt,yt.current=void 0);const It=yt.current,Tt=w?.isLastAssistantInTurn&&It&&It.trim().length>0,je=!!N,ze=U&&y&&(Q||!!N),[Ze,Ye]=i.useState(!1),mt=i.useMemo(()=>{if(!U||!Q)return;const ie=w?.userMessageCreatedAt;if(!(typeof ie!="number"||typeof o!="number")&&!(o<=ie))return Iw(o-ie)},[U,Q,w?.userMessageCreatedAt,o]),ye=e.jsxs(e.Fragment,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:J,children:e.jsx(Mh,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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:ie=>ie.stopPropagation(),onClick:ee,children:e.jsx(Bm,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),h&&e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{type:"button",variant:"ghost",size:"icon","data-visible":x||M?"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",!Ne&&"opacity-50"),disabled:!Ne,"aria-label":"Copy message text","aria-hidden":!Ne,onPointerDown:ie=>ie.stopPropagation(),onClick:V,onFocus:()=>{Ne&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(_t,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Ys,{className:"h-3.5 w-3.5"})})}),e.jsx(lt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:_("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&C&&Ne?Be: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:[Qe,je&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Zr,{content:N??""})})},"assistant-error"),Tt&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Ye(!0),onMouseLeave:()=>Ye(!1),children:[e.jsx(Zr,{content:It}),ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:_("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",Ze&&"opacity-100 pointer-events-auto"),children:ye})]})]})},"summary-body")]}),e.jsx(qm,{files:r,onShowPopup:m}),!Tt&&ze&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[mt?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Jl,{className:"h-3.5 w-3.5"}),mt]}):e.jsx("span",{}),e.jsx("div",{className:"flex items-center 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:ye})]})]})})},_w=({isUser:s,...r})=>s?e.jsx(Fw,{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(Rw,{...r}),kd=i.memo(_w),bi=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}},Ow=i.lazy(()=>as(()=>import("./ToolOutputDialog-D8JjsNSh.js"),__vite__mapDeps([2,0,1,3,4]))),$w=new Set(["task","edit","multiedit","write","bash"]),Nd=s=>typeof s=="string"&&$w.has(s.toLowerCase());function vi(s){const r=i.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 sr=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},Lw=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:l})=>{const{isMobile:c,hasTouchInput:d}=$t(),{currentTheme:u}=Wr(),m=i.useRef(null),f=he(ul(Te=>({lifecyclePhase:Te.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const st=s.info.sessionID??Te.currentSessionId??null;return st?(Te.streamingMessageIds.get(st)??null)===s.info.id:!1})(),currentSessionId:Te.currentSessionId,getCurrentAgent:Te.getCurrentAgent,getSessionAgentSelection:Te.getSessionAgentSelection,getAgentModelForSession:Te.getAgentModelForSession,getSessionModelSelection:Te.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:y,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:b,getSessionModelSelection:v}=f,w=at(Te=>Te.providers),N=$e(Te=>Te.showReasoningTraces),x=$e(Te=>Te.toolCallExpansion);i.useEffect(()=>{y&&Pr.getInstance().recordSessionStart(y)},[y]);const[k,A]=i.useState(null),[C,M]=i.useState(!1),[S,D]=i.useState(new Set),[E,T]=i.useState({open:!1,title:"",content:""});i.useEffect(()=>{D(new Set)},[s.info.id,x]);const P=i.useMemo(()=>bi(s.info),[s.info]).isUser,O=i.useMemo(()=>P?s.parts.map(Te=>Te.type==="compaction"?{type:"text",text:"/compact"}:Te):s.parts,[P,s.parts]),U=i.useMemo(()=>{if(P||!r)return null;const Te=sr(r.info,"clientRole"),st=sr(r.info,"role");if((typeof Te=="string"?Te:typeof st=="string"?st:void 0)!=="user")return null;const Xe=sr(r.info,"mode"),kt=sr(r.info,"providerID"),Lt=sr(r.info,"modelID"),ts=sr(r.info,"variant"),ns=typeof Xe=="string"&&Xe.trim().length>0?Xe:void 0,ps=typeof kt=="string"&&kt.trim().length>0?kt:void 0,pr=typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0,Bt=typeof ts=="string"&&ts.trim().length>0?ts:void 0;return!ns&&!ps&&!pr&&!Bt?null:{agentName:ns,providerId:ps,modelId:pr,variant:Bt}},[P,r]),Q=i.useMemo(()=>{if(P)return;const Te=sr(s.info,"mode");if(typeof Te=="string"&&Te.trim().length>0)return Te;if(U?.agentName)return U.agentName;const st=s.info.sessionID;if(!st)return;const Ve=h(st);return Ve||(j(st)??void 0)},[P,s.info,U,h,j]),W=s.info.sessionID,L=P?null:sr(s.info,"providerID"),H=P?null:sr(s.info,"modelID"),q=i.useMemo(()=>{if(P||!W)return null;if(U?.providerId&&U?.modelId)return{providerId:U.providerId,modelId:U.modelId};if(Q){const st=b(W,Q);if(st?.providerId&&st?.modelId)return st}const Te=v(W);return Te?.providerId&&Te?.modelId?Te:null},[P,W,Q,U,b,v]),X=i.useMemo(()=>P?null:typeof L=="string"&&L.trim().length>0?L:q?.providerId??null,[P,L,q]),Y=i.useMemo(()=>P?null:typeof H=="string"&&H.trim().length>0?H:q?.modelId??null,[P,H,q]),re=i.useMemo(()=>{if(!P&&X&&Y&&w.length>0){const Te=w.find(st=>st.id===X);if(Te?.models&&Array.isArray(Te.models)){const Xe=Te.models.find(kt=>kt.id===Y)?.name;return typeof Xe=="string"?Xe:void 0}}},[P,X,Y,w]),K=i.useMemo(()=>{if(P||!X||!Y)return!1;const Te=w.find(Xe=>Xe.id===X);if(!Te?.models||!Array.isArray(Te.models))return!1;const Ve=Te.models.find(Xe=>Xe.id===Y)?.variants;return!!(Ve&&Object.keys(Ve).length>0)},[P,Y,X,w]),ae=vi(Q),F=vi(X??void 0),$=vi(re),R=ae??void 0,B=F??null,z=$??void 0,G=i.useMemo(()=>{const Te=s.info.time;return typeof Te?.completed=="number"?Te.completed:null},[s.info.time]),ge=i.useMemo(()=>P?!0:!!(G&&G>0),[P,G]),oe=i.useMemo(()=>{const Te=s.info.finish;return typeof Te=="string"?Te:void 0},[s.info]),me=i.useMemo(()=>Ew(O,{includeReasoning:N}),[O,N]),Ne=i.useMemo(()=>P||ge?me:[],[P,ge,me]),Ce=i.useMemo(()=>P?[]:me.filter(Te=>Te.type==="text"),[P,me]),Be=i.useMemo(()=>P?[]:me.filter(st=>st.type==="tool"),[P,me]),V=i.useMemo(()=>{if(x==="collapsed"||x==="activity")return S;const Te=new Set;for(const Ve of Be){const Xe=Ve.tool;Ve.id&&Nd(Xe)&&Te.add(Ve.id)}if(l?.isFirstAssistantInTurn)for(const Ve of l.activityParts){if(Ve.kind!=="tool")continue;const Xe=Ve.part;Xe.id&&Nd(Xe.tool)&&Te.add(Xe.id)}const st=new Set(Te);for(const Ve of S)st.has(Ve)?st.delete(Ve):st.add(Ve);return st},[S,x,Be,l]),J=i.useMemo(()=>{if(!P)return;const Te=s.parts.find(kt=>kt.type==="agent");if(!Te)return;const st=Te,Ve=typeof st.name=="string"?st.name:void 0;if(!Ve)return;const Xe=st.source&&typeof st.source.value=="string"&&st.source.value.trim().length>0?st.source.value:`#${Ve}`;return{name:Ve,token:Xe}},[P,s.parts]),ee=typeof oe!="string",xe=i.useMemo(()=>P?!1:Ce.length===0||Be.length===0?ee:!0,[Ce.length,Be.length,ee,P]),fe=u?.metadata.variant,Oe=i.useMemo(()=>fe?fe==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[fe]),Se=i.useMemo(()=>u?Ll(u):Oe?Ov:$v,[u,Oe]),Le=i.useMemo(()=>P?!1:Pr.getInstance().shouldAnimateMessage(s.info,y||s.info.sessionID),[s.info,y,P]),pe=i.useRef(!1),it=i.useMemo(()=>r?bi(r.info):null,[r]),xt=i.useMemo(()=>t?bi(t.info):null,[t]),Mt=i.useMemo(()=>P||!xt?!1:!xt.isUser&&xt.role==="assistant",[P,xt]),De=i.useMemo(()=>ge?"completed":p||(g?"streaming":"completed"),[ge,p,g]),ne=i.useMemo(()=>{if(P)return!0;const Te=l?.headerMessageId;if(Te){if(s.info.id===Te){if(De==="completed")return!0;const Ve=De==="streaming"||De==="cooldown",Xe=pe.current;return Ve&&!Xe&&(pe.current=!0),Xe||Ve}return!1}return it?it.isUser:!0},[P,it,l,De,s.info]),rt=i.useCallback(Te=>{navigator.clipboard.writeText(Te),A(Te),setTimeout(()=>A(null),2e3)},[]),be=l?.turnId,ke=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(ts=>ts.info?.id===be);if(!Xe)return;const Lt=Xe.info.summary?.body;return typeof Lt=="string"&&Lt.trim().length>0?Lt:void 0}),Qe=St(Te=>{if(!be)return;const st=s.info.sessionID;if(!st)return;const Ve=Te.messages.get(st);if(!Ve)return;const Xe=Ve.find(Lt=>Lt.info?.id===be);if(!Xe)return;const kt=Xe.info.variant;return typeof kt=="string"&&kt.trim().length>0?kt:void 0}),tt=P?void 0:Qe??U?.variant,He=!P&&K?tt??"Default":void 0,Re=typeof l?.summaryBody=="string"&&l.summaryBody.trim().length>0?l.summaryBody:ke,nt=i.useRef(void 0);Re&&Re.trim().length>0&&(nt.current=Re);const yt=i.useRef(be);yt.current!==be&&(yt.current=be,nt.current=void 0);const ct=nt.current,It=i.useMemo(()=>{if(P)return;const Te=s.info?.error;if(!Te)return;const st=typeof Te.data?.message=="string"?Te.data.message:void 0,Ve=typeof Te.message=="string"?Te.message:void 0,Xe=typeof Te.name=="string"?Te.name:void 0,kt=st||Ve||Xe;if(kt)return`Opencode failed to send message with error:
113
- \`${kt}\``},[P,s.info]),Tt=i.useMemo(()=>P?Ne.filter(Ve=>Ve.type==="text").map(Ve=>(Ve.text||Ve.content||"").trim()).filter(Ve=>Ve.length>0).join(`
114
- `).replace(/\n\s*\n+/g,`
115
- `):It&&It.trim().length>0?It:ct&&ct.trim().length>0?ct:Sl(Ne),[It,ct,Ne,P]),je=Tt.length>0,ze=i.useCallback(()=>{navigator.clipboard.writeText(Tt),M(!0),setTimeout(()=>M(!1),2e3)},[Tt]),Ze=he(Te=>Te.revertToMessage),Ye=he(Te=>Te.forkFromMessage),mt=i.useCallback(()=>{!W||!s.info.id||Ze(W,s.info.id)},[W,s.info.id,Ze]),ye=i.useCallback(()=>{!W||!s.info.id||Ye(W,s.info.id)},[W,s.info.id,Ye]),ie=i.useCallback(Te=>{D(st=>{const Ve=new Set(st);return Ve.has(Te)?Ve.delete(Te):Ve.add(Te),Ve})},[]),de=o??null,We=i.useRef(!1),Ge=i.useRef(!1),bt=i.useRef(!1),Z=i.useRef(!1),we=i.useRef(!1);i.useEffect(()=>{Ge.current=!1,bt.current=!1,Z.current=!1,we.current=!1,We.current=!1},[s.info.id]);const ve=i.useCallback(()=>{P||We.current||(We.current=!0,n?.("structural"))},[P,n]),Ue=i.useCallback(Te=>{Te.image&&T(Te)},[]),_e=i.useCallback(Te=>{T(st=>({...st,open:Te}))},[]),et=!!sr(s.info,"animationSettled"),pt=De==="streaming",ft=i.useMemo(()=>P?!1:me.some(Te=>Te.type==="reasoning"),[P,me]),Pt=Le&&!et&&!pt,At=!P&&Le&&Ce.length>0&&!xe;return i.useEffect(()=>{if(de?.onStreamingCandidate){if(!At){bt.current&&(ft&&de?.onReasoningBlock?de.onReasoningBlock():de?.onReservationCancelled&&de.onReservationCancelled(),bt.current=!1);return}we.current||(we.current=!0,de.onStreamingCandidate(),bt.current=!0)}},[de,At,ft]),i.useEffect(()=>{de?.onAnimationStart&&Pt&&(Z.current||(de.onAnimationStart(),Z.current=!0))},[de,Pt]),i.useEffect(()=>{if(P)return;const Te=de?.onAnimatedHeightChange;if(!Te||!(Pt||At))return;const Ve=m.current;if(!Ve)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Te(Ve.getBoundingClientRect().height);return}let Xe=null;const kt=ts=>{if(typeof window>"u"){Te(ts);return}Xe!==null&&window.cancelAnimationFrame(Xe),Xe=window.requestAnimationFrame(()=>{Te(ts)})},Lt=new ResizeObserver(ts=>{const ns=ts[0];ns&&kt(ns.contentRect.height)});return Lt.observe(Ve),kt(Ve.getBoundingClientRect().height),()=>{Xe!==null&&(window.cancelAnimationFrame(Xe),Xe=null),Lt.disconnect()}},[Pt,P,de,At]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:_("group w-full",ne?"pt-2":"pt-0",P?"pb-2":Mt?"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:P?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(kd,{messageId:s.info.id,parts:me,isUser:P,isMessageCompleted:ge,messageFinish:oe,syntaxTheme:Se,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:rt,expandedTools:S,onToggleTool:ie,onShowPopup:Ue,streamPhase:De,allowAnimation:Pt,onContentChange:n,shouldShowHeader:!1,hasTextContent:je,onCopyMessage:ze,copiedMessage:C,showReasoningTraces:N,onAuxiliaryContentComplete:ve,agentMention:J,onRevert:mt,onFork:P?ye:void 0,errorMessage:It})})})}):e.jsxs("div",{children:[ne&&e.jsx(Bv,{isUser:P,providerID:B,agentName:R,modelName:z,variant:He,isDarkTheme:Oe}),e.jsx(kd,{messageId:s.info.id,parts:me,isUser:P,isMessageCompleted:ge,messageFinish:oe,messageCompletedAt:G??void 0,syntaxTheme:Se,isMobile:c,hasTouchInput:d,copiedCode:k,onCopyCode:rt,expandedTools:V,onToggleTool:ie,onShowPopup:Ue,streamPhase:De,allowAnimation:Pt,onContentChange:n,shouldShowHeader:ne,hasTextContent:je,onCopyMessage:ze,copiedMessage:C,onAuxiliaryContentComplete:ve,showReasoningTraces:N,agentMention:J,turnGroupingContext:l,errorMessage:It})]})})}),e.jsx(i.Suspense,{fallback:null,children:e.jsx(Ow,{popup:E,onOpenChange:_e,syntaxTheme:Se,isMobile:c})})]})},Bw=i.memo(Lw),zw=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:mf(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,l)=>e.jsxs("div",{className:_("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(or,{style:r,language:fr(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})})]},l))})]},o))}),Ww=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
116
- `),o=fr(t??"")||"text",a=t?.split("/").pop()||"New file",l=Math.max(n.length,1),c=l===1?"line 1":`lines 1-${l}`;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} (${c})`}),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(or,{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))})]})},Hw=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(xr,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(Eu,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(_r,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(_i,{className:r}):e.jsx(Ma,{className:r})},Uw=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},Vw=({permission:s,onResponse:r})=>{const[t,n]=i.useState(!1),[o,a]=i.useState(!1),{respondToPermission:l}=he(),{currentTheme:c}=Wr(),d=i.useMemo(()=>Ll(c),[c]),u=async b=>{n(!0);try{await l(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,v="")=>{const w=s.metadata[b];return typeof w=="string"?w:typeof w=="number"?String(w):v},g=b=>{const v=s.metadata[b];return typeof v=="number"?v:void 0},y=b=>!!s.metadata[b],h=Uw(m),j=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const w=p("command")||p("cmd")||p("script"),N=p("description"),x=p("cwd")||p("working_directory")||p("directory")||p("path"),k=g("timeout");return e.jsxs(e.Fragment,{children:[N&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:N}),x&&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:x})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),w&&e.jsx("div",{children:e.jsx(or,{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:w})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const w=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),x=y("replace_all")||y("replaceAll");return e.jsxs(e.Fragment,{children:[x&&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(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(zw,{diff:N,syntaxTheme:d,filePath:w})})]})}if(f==="write"||f==="create"||f==="file_write"){const w=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(gt,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Ww,{content:N,syntaxTheme:d,filePath:w})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const w=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",x=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),A=g("timeout"),C=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[w&&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:w})]})]}),x&&Object.keys(x).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(gt,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(or,{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(x,null,2)})})]}),k&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Body:"}),e.jsx(gt,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(or,{language:typeof k=="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 k=="object"?JSON.stringify(k,null,2):String(k)})})]}),(A||C)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[A&&e.jsxs("span",{children:["Timeout: ",A,"ms"]}),A&&C&&e.jsx("span",{children:" • "}),C&&e.jsxs("span",{children:["Response format: ",C]})]})]})}const b=p("command")||p("content")||p("action")||p("operation"),v=p("description");return e.jsxs(e.Fragment,{children:[v&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:v}),b&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(gt,{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&&!v&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(gt,{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(tn,{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:[Hw(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:_("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(_t,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:_("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(cr,{className:"h-3 w-3"}),(()=>{const b=s.always||s.metadata.always||[];if(b.length===0)return"Always Allow";const w=b.slice(0,2).join(", ");return b.length>2?`Always: ${w}...`:`Always: ${w}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:_("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(cr,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:_("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"})})]})]})})})},wi="summary",Gw=({question:s})=>{const{respondToQuestion:r,rejectQuestion:t}=he(),[n,o]=i.useState("0"),[a,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState({}),[f,p]=i.useState({}),[g,y]=i.useState({}),h=i.useMemo(()=>s.questions??[],[s.questions]),j=n===wi,b=j?-1:Math.max(0,Math.min(h.length-1,Number(n)||0)),v=j?null:h[b];i.useEffect(()=>{o("0"),m({}),p({}),y({}),d(!1)},[s.id]);const w=i.useMemo(()=>{const I=h.map((P,O)=>({value:String(O),label:P.header?.trim()||`Q${O+1}`}));return h.length>1&&I.push({value:wi,label:"Summary"}),I},[h]),N=i.useCallback(I=>{if(!!f[I])return(g[I]??"").trim()||"(no answer)";const O=u[I]??[];return O.length>0?O.join(", "):"(no answer)"},[f,g,u]),x=!!v?.multiple,k=u[b]??[],A=!!f[b],C=i.useMemo(()=>{if(h.length===0)return!1;for(let I=0;I<h.length;I+=1){if(!!f[I]){if(!(g[I]??"").trim())return!1;continue}if((u[I]??[]).length===0)return!1}return!0},[f,g,h.length,u]),M=i.useCallback(()=>{const I=[];for(let P=0;P<h.length;P+=1){if(!!f[P]){const U=(g[P]??"").trim();I.push(U?[U]:[]);continue}I.push(u[P]??[])}return I},[f,g,h.length,u]),S=i.useCallback(I=>{v&&(p(P=>({...P,[b]:!1})),m(P=>{const O=P[b]??[];if(x){const Q=O.includes(I)?O.filter(W=>W!==I):[...O,I];return{...P,[b]:Q}}return{...P,[b]:[I]}}))},[b,v,x]),D=i.useCallback(()=>{p(I=>({...I,[b]:!0})),m(I=>({...I,[b]:[]}))},[b]),E=i.useCallback(async()=>{if(C){l(!0);try{const I=M();await r(s.sessionID,s.id,I),d(!0)}catch{}finally{l(!1)}}},[M,s.id,s.sessionID,C,r]),T=i.useCallback(async()=>{l(!0);try{await t(s.sessionID,s.id),d(!0)}catch{}finally{l(!1)}},[s.id,s.sessionID,t]);return c||h.length===0?null: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",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(tn,{className:"h-3.5 w-3.5 text-primary"}),e.jsx("span",{className:"typography-meta font-medium text-muted-foreground",children:"Input needed"})]})}),e.jsxs("div",{className:"px-2 py-2",children:[w.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:w.map(I=>{const P=n===I.value,O=I.value===wi;return e.jsxs("button",{type:"button",onClick:()=>o(I.value),className:_("px-2 py-0.5 typography-meta font-medium rounded transition-colors flex items-center gap-1",P?"bg-muted/40 text-foreground":"text-muted-foreground hover:text-foreground hover:bg-muted/20"),children:[O?e.jsx(Iu,{className:"h-3 w-3"}):null,I.label]},I.value)})}):null,j?e.jsx("div",{className:"space-y-2",children:h.map((I,P)=>{const O=N(P),U=O!=="(no answer)";return e.jsxs("button",{type:"button",onClick:()=>o(String(P)),className:"w-full text-left rounded px-1.5 py-1 hover:bg-muted/20 transition-colors",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:I.header||`Question ${P+1}`}),e.jsx("div",{className:_("typography-meta",U?"text-foreground":"text-muted-foreground/50 italic"),children:O})]},P)})}):v?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:v.question}),x?e.jsx("div",{className:"typography-micro text-muted-foreground mb-1.5",children:"Select multiple"}):null,e.jsxs("div",{className:"space-y-0.5",children:[v.options.map((I,P)=>{const O=k.includes(I.label),U=/\(recommended\)/i.test(I.label);return e.jsx("button",{type:"button",onClick:()=>S(I.label),disabled:a,className:_("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",O?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"mt-0.5 shrink-0",children:O?e.jsx(Dh,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(Oi,{className:"h-3.5 w-3.5 text-muted-foreground/50"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:_("typography-meta break-all",O?"text-foreground font-medium":"text-foreground/80"),children:I.label}),U?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),I.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:I.description}):null]})]})},`${P}:${I.label}`)}),e.jsx("button",{type:"button",onClick:D,disabled:a,className:_("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",A?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uo,{className:_("h-3.5 w-3.5",A?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:_("typography-meta",A?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),A?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:I=>{if(I){I.style.height="auto";const P=20,O=P*2,U=P*4;I.style.height=`${Math.min(Math.max(I.scrollHeight,O),U)}px`}},value:g[b]??"",onChange:I=>{const P=I.target;P.style.height="auto";const O=20,U=O*2,Q=O*4;P.style.height=`${Math.min(Math.max(P.scrollHeight,U),Q)}px`,y(W=>({...W,[b]:P.value}))},placeholder:"Your answer",disabled:a,rows:2,className:"w-full bg-transparent border border-border/30 focus:border-primary rounded px-2 py-1 outline-none typography-meta text-foreground placeholder:text-muted-foreground/50 transition-colors resize-none overflow-hidden",autoFocus:!0})}):null]})]}):null]}),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",{type:"button",onClick:E,disabled:a||!C,className:_("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-success)/0.1)] text-[var(--status-success)] hover:bg-[rgb(var(--status-success)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(_t,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:T,disabled:a,className:_("flex items-center gap-1 px-2 py-1 typography-meta font-medium rounded transition-colors","bg-[rgb(var(--status-error)/0.1)] text-[var(--status-error)] hover:bg-[rgb(var(--status-error)/0.2)]","disabled:opacity-50 disabled:cursor-not-allowed"),children:[e.jsx(Ht,{className:"h-3 w-3"}),"Dismiss"]}),a?e.jsx("div",{className:"ml-auto",children:e.jsx("div",{className:"animate-spin h-3 w-3 border border-primary border-t-transparent rounded-full"})}):null]})]})})})},qw=new Set(["task"]),Cd=s=>typeof s=="string"&&qw.has(s.toLowerCase()),Kw=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},Qw=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}}},Yw=s=>{const r=Qw(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let b=0,v=0,w=0;o.forEach(N=>{if(!N)return;const x=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(x!==0||k!==0)&&(w+=1),b+=x,v+=k}),w>0&&(t={additions:b,deletions:v,files:w})}let a=!1,l=!1;s.assistantMessages.forEach(b=>{b.parts.forEach(v=>{v.type==="tool"?a=!0:v.type==="reasoning"&&(l=!0)})});const c=[];let d=0;s.assistantMessages.forEach(b=>{const v=b.info.id;b.info.finish,b.parts.forEach(w=>{const N=typeof w.id=="string"&&w.id.trim().length>0?w.id:`${v}-activity-${d++}`;if(w.type==="tool"){const k=w.state?.time,A=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"tool",part:w,endedAt:A});return}if(w.type==="reasoning"){const x=w.text??w.content;if(typeof x!="string"||x.trim().length===0)return;const k=w.time,A=typeof k?.end=="number"?k.end:void 0;c.push({id:N,turnId:s.turnId,messageId:v,kind:"reasoning",part:w,endedAt:A});return}})});const u=[],m=new WeakMap;c.forEach(b=>{m.set(b.part,b)});const f=new Map,p=[],g=new Map;let y=null;s.assistantMessages.forEach(b=>{const v=b.info.id;b.parts.forEach(w=>{if(w.type==="tool"){const k=w.tool;if(Cd(k)){const A=typeof w.id=="string"&&w.id.trim().length>0?w.id:`${v}-task-${p.length+1}`;f.has(A)||(f.set(A,v),p.push(A)),y=A;return}}const N=m.get(w);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(Cd(k))return}const x=g.get(y)??[];x.push(N),g.set(y,x)})});const h=b=>{if(b.length===0)return;const v=new Map;b.forEach(x=>{v.set(x.messageId,(v.get(x.messageId)??0)+1)});let w,N=0;for(const x of s.assistantMessages){const k=v.get(x.info.id)??0;if(k>0&&!w&&(w=x.info.id),N+=k,N>=2)return x.info.id}return w};return[null,...p].forEach(b=>{const v=g.get(b)??[];if(v.length===0)return;const w=b===null?h(v):f.get(b);w&&u.push({id:`${s.turnId}:${w}:${b??"start"}`,anchorMessageId:w,afterToolPartId:b,parts:v})}),{activityParts:c,activityGroupSegments:u,hasTools:a,hasReasoning:l,summaryBody:r,diffStats:t}},Xw=s=>{const{isWorking:r}=Ol(),t=i.useMemo(()=>Kw(s),[s]),n=i.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=i.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=i.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.turnId,Yw(j))}),h},[t]),[l,c]=i.useState(()=>new Map),d=$e(h=>h.toolCallExpansion),u=d==="activity"||d==="detailed";i.useEffect(()=>{c(new Map)},[d]);const m=i.useCallback(h=>{const j=l.get(h);return j||{isExpanded:u,previewedPartIds:new Set}},[l,u]),f=i.useCallback(h=>{c(j=>{const b=new Map(j),v=b.get(h)??{isExpanded:u,previewedPartIds:new Set};return b.set(h,{...v,isExpanded:!v.isExpanded}),b})},[u]),p=i.useCallback((h,j)=>{j.length!==0&&c(b=>{const v=new Map(b),w=v.get(h)??{isExpanded:u,previewedPartIds:new Set},N=new Set(w.previewedPartIds);return j.forEach(x=>{x&&x.trim().length>0&&N.add(x)}),v.set(h,{...w,previewedPartIds:N}),v})},[u]),g=i.useCallback(h=>o.get(h),[o]),y=i.useCallback(h=>{const j=o.get(h);if(!j||!j.assistantMessages.some(Q=>Q.info.id===h))return;const v=a.get(j.turnId),w=v?.activityParts??[],N=v?.activityGroupSegments??[],x=!!v?.hasTools,k=!!v?.hasReasoning,A=v?.summaryBody,C=v?.diffStats,M=j.assistantMessages[0]?.info.id,S=h===M,D=j.assistantMessages[j.assistantMessages.length-1]?.info.id,E=h===D,T=M,I=m(j.turnId),P=r&&n===j.turnId,O=j.userMessage.info.time,U=typeof O?.created=="number"?O.created:void 0;return{turnId:j.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:E,summaryBody:A,activityParts:w,activityGroupSegments:N,headerMessageId:T,hasTools:x,hasReasoning:k,diffStats:C,userMessageCreatedAt:U,isWorking:P,isGroupExpanded:I.isExpanded,previewedPartIds:I.previewedPartIds,toggleGroup:()=>f(j.turnId),markPartsPreviewed:Q=>p(j.turnId,Q)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:g,getContextForMessage:y}},Jw=({messages:s,permissions:r,questions:t,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:l,onLoadOlder:c,scrollToBottom:d,pendingAnchorId:u})=>{i.useEffect(()=>{r.length===0&&t.length===0||n("permission")},[r,t,n]);const m=i.useMemo(()=>{const p=new Set;return s.filter(g=>{const y=g.info?.id;if(typeof y=="string"){if(p.has(y))return!1;p.add(y)}return!0}).map(g=>({...g,parts:Nv(g.parts)}))},[s]),{getContextForMessage:f}=Xw(m);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:l?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:c,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:m.map((p,g)=>e.jsx(Bw,{message:p,previousMessage:g>0?m[g-1]:void 0,nextMessage:g<m.length-1?m[g+1]:void 0,onContentChange:n,animationHandlers:o(p.info.id),scrollToBottom:d,isPendingAnchor:u===p.info.id,turnGroupingContext:f(p.info.id)},p.info.id))}),(t.length>0||r.length>0)&&e.jsxs("div",{children:[t.map(p=>e.jsx(Gw,{question:p},p.id)),r.map(p=>e.jsx(Vw,{permission:p},p.id))]})]})},Zw=i.memo(Jw);function e0(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const gf=i.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:l,className:c,children:d,...u},m)=>{const f=i.useRef(null),p=i.useRef("none"),g=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const y=i.useMemo(()=>{const v={...l};return v["--scroll-shadow-size"]=`${t}px`,v},[t,l]),h=i.useCallback((v,w,N,x,k)=>{const A=`${x}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;w&&N?(v.dataset[A]="true",v.removeAttribute(`data-${x}-scroll`),v.removeAttribute(`data-${k}-scroll`)):(v.dataset[`${x}Scroll`]=String(w),v.dataset[`${k}Scroll`]=String(N),v.removeAttribute(`data-${x}-${k}-scroll`))},[]),j=i.useCallback(v=>{["top","bottom","top-bottom","left","right","left-right"].forEach(w=>{v.removeAttribute(`data-${w}-scroll`)})},[]),b=i.useCallback(()=>{const v=f.current;if(!v)return;if(!n){j(v);return}const w=s==="vertical"?v.scrollTop>r:v.scrollLeft>r;let N=s==="vertical"?v.scrollTop+v.clientHeight+r<v.scrollHeight:v.scrollLeft+v.clientWidth+r<v.scrollWidth;o&&s==="vertical"&&(N=!1),h(v,w,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const x=w&&N?"both":w?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";x!==p.current&&(p.current=x,a?.(x))},[j,o,n,r,a,s,h]);return i.useEffect(()=>{const v=f.current;if(!v)return;const w=()=>b(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>b()):null,x=typeof MutationObserver<"u"?new MutationObserver(()=>b()):null;return b(),v.addEventListener("scroll",w,{passive:!0}),N?.observe(v),x?.observe(v,{childList:!0,subtree:!0,characterData:!0}),()=>{v.removeEventListener("scroll",w),N?.disconnect(),x?.disconnect()}},[b]),e.jsx("div",{...u,ref:e0(f,m),className:c,"data-orientation":s,"data-scroll-shadow":g??!0,style:y,children:d})});gf.displayName="ScrollShadow";const t0=160,s0=({containerRef:s})=>{const[r,t]=i.useState(!0),n=i.useRef(!0),o=i.useRef(!1),a=i.useRef(null),l=i.useRef(null),c=i.useRef(0),d=i.useRef(0),u=i.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,l.current=null},[]),m=i.useCallback(w=>{const N=s.current;if(!N){u();return}l.current===null&&(l.current=w);const x=Math.min(1,(w-l.current)/t0),k=1-Math.pow(1-x,3),A=c.current,C=d.current,M=A+(C-A)*k;if(N.scrollTop=M,x<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=C,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=i.useCallback((w,N)=>{const x=s.current;if(!x)return;const k=Math.max(0,w),A=N?.instant??!1;if(o.current=!1,typeof window>"u"||A){u(),x.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(k-x.scrollTop)<=.5){x.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}c.current=x.scrollTop,d.current=k,l.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=i.useCallback(()=>{o.current=!0},[]),g=i.useCallback(()=>{o.current=!0},[]),y=i.useCallback(()=>o.current,[]),h=i.useCallback(()=>s.current?.scrollTop??0,[s]),j=i.useCallback(()=>s.current?.scrollHeight??0,[s]),b=i.useCallback(()=>s.current?.clientHeight??0,[s]),v=i.useCallback(()=>{const w=s.current;if(!w)return;o.current&&a.current!==null&&u();const N=w.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return i.useEffect(()=>{const w=s.current;if(w)return w.addEventListener("wheel",g,{passive:!0}),w.addEventListener("touchstart",g,{passive:!0}),()=>{w.removeEventListener("wheel",g),w.removeEventListener("touchstart",g)}},[s,g]),i.useEffect(()=>()=>{u()},[u]),i.useMemo(()=>({handleScroll:v,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:y,getScrollTop:h,getScrollHeight:j,getClientHeight:b}),[v,f,p,r,y,h,j,b])},Md=typeof window<"u"?i.useLayoutEffect:i.useEffect,Dd=50,Ad=40,r0=.2,n0=.1,o0=150,zs=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},a0=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},i0=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:l,sessionActivityPhase:c})=>{const d=i.useRef(null),u=s0({containerRef:d}),[m,f]=i.useState(null),[p,g]=i.useState(0),[y,h]=i.useState(!1),[j,b]=i.useState(null),v=i.useRef(null),w=i.useRef(null),N=i.useRef(r.length),x=i.useRef(r.length>0?zs(r[0]):null),k=i.useRef(r.length>0?zs(r[r.length-1]):null),A=i.useRef(0),C=i.useRef(0),M=i.useRef(void 0),S=i.useRef(null),D=i.useRef(!1),E=i.useRef(!1),T=i.useRef(null),I=s?c?.get(s)??"idle":"idle",P=i.useCallback(F=>{const $=Math.max(0,F);A.current!==$&&(A.current=$,g($))},[]),O=i.useCallback(()=>{const F=d.current;F&&(C.current=F.clientHeight)},[]),U=i.useCallback(()=>{if(!m)return null;const F=d.current;return F?F.querySelector(`[data-message-id="${m}"]`):null},[m]),Q=i.useCallback(()=>{const F=d.current,$=A.current;if(!F||$<=0)return!0;const R=F.scrollHeight-$;return F.scrollTop+F.clientHeight<R},[]),W=i.useCallback((F,$)=>{const R=F.offsetHeight,B=F.offsetTop;if(R>$*r0){const G=$*n0;return B+R-G}else return B-Dd},[]),L=i.useCallback(()=>{const F=d.current;if(!F||!S.current)return;const $=U();if(!$)return;const R=F.clientHeight,B=F.scrollHeight,G=W($,R)+R,ge=A.current,oe=B-ge;if(!D.current&&oe<G){const me=G-oe;me>ge&&(P(me),s&&S.current&&n(s,S.current,me))}},[W,s,U,n,P]),H=i.useCallback(()=>{const F=d.current;if(!F){h(!1);return}if(j){h(!1);return}if(!(F.scrollHeight>F.clientHeight)){h(!1);return}const R=F.scrollHeight-F.scrollTop-F.clientHeight,B=A.current;if(B>0){const z=F.scrollHeight-B,G=F.scrollTop+F.clientHeight;h(G<z)}else h(R>Ad)},[j]),q=i.useCallback(F=>{const $=d.current;if(!$)return;const R=$.scrollHeight-$.scrollTop-$.clientHeight;if(E.current&&I==="idle"&&!a&&!F?.force&&R>Ad)return;F?.force&&(E.current=!1);const z=$.scrollHeight-$.clientHeight;u.scrollToPosition(Math.max(0,z),F)},[I,a,u]),X=i.useCallback(F=>{if(v.current===F)return;v.current=F,b(F);const $=d.current;if(!$){b(null);return}const R=$.scrollHeight,B=A.current,z=R-B,G=C.current>0?C.current:$.clientHeight,oe=z-Dd,me=oe+G;let Ne=0;z<me&&(Ne=me-z),Ne!==B&&P(Ne),s&&n(s,F,Ne),D.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(oe,{instant:!0}),window.requestAnimationFrame(()=>{b(null)})})},[s,u,n,P]),Y=i.useCallback(F=>{const $=d.current;if(!$||!s)return;F?.isTrusted&&(E.current=!0),u.handleScroll(),H(),I==="idle"&&A.current>0&&Q()&&(P(0),S.current=null,f(null),n(s,null,0));const{scrollTop:R,scrollHeight:B,clientHeight:z}=$,G=(R+z/2)/Math.max(B,1),ge=Math.floor(G*r.length);t(s,ge)},[s,I,Q,u,r.length,n,H,P,t]);i.useEffect(()=>{const F=d.current;if(F)return F.addEventListener("scroll",Y,{passive:!0}),()=>{F.removeEventListener("scroll",Y)}},[Y]),Md(()=>{if(typeof window>"u")return;O();const F=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{O()},o0)};return window.addEventListener("resize",F),()=>{window.removeEventListener("resize",F),M.current!==void 0&&window.clearTimeout(M.current)}},[O]),i.useEffect(()=>{if(s&&s!==w.current){w.current=s,Pr.getInstance().recordSessionStart(s),N.current=r.length,x.current=r.length>0?zs(r[0]):null,k.current=r.length>0?zs(r[r.length-1]):null;const F=o(s);I!=="idle"&&F&&F.anchorId?(S.current=F.anchorId,v.current=F.anchorId,D.current=!0,f(F.anchorId),A.current=F.spacerHeight,g(F.spacerHeight),window.requestAnimationFrame(()=>{const R=d.current;if(!R)return;const B=R.querySelector(`[data-message-id="${F.anchorId}"]`);if(B){const z=R.clientHeight,G=W(B,z);u.scrollToPosition(G,{instant:!0})}})):(v.current=null,S.current=null,D.current=!1,f(null),A.current=0,g(0),window.requestAnimationFrame(()=>{q({instant:!0,force:!0})})),b(null),h(!1),E.current=!1,T.current=null}},[I,s,q,r.length,o]),Md(()=>{if(a){N.current=r.length,x.current=r.length>0?zs(r[0]):null,k.current=r.length>0?zs(r[r.length-1]):null;return}if(w.current!==s)return;const F=N.current,$=r.length;if($>F&&F>0){const R=x.current,B=zs(r[0]),z=zs(r[$-1]),G=k.current,ge=R!==null&&B!==R,oe=G!==null&&z!==G,me=ge&&!oe,Ne=oe&&!ge;if(me){S.current=null,D.current=!1,f(null),P(0),N.current=$,x.current=B,k.current=z;return}if(Ne){const Be=r.slice(F,$).find(a0);if(Be){const V=zs(Be);V&&(S.current=V,f(V),X(V))}else L()}}N.current=$,x.current=r.length>0?zs(r[0]):null,k.current=r.length>0?zs(r[r.length-1]):null},[s,a,L,X,r]),i.useEffect(()=>{const F=d.current;if(!F||typeof ResizeObserver>"u")return;const $=new ResizeObserver(()=>{L(),H()});return $.observe(F),()=>{$.disconnect()}},[L,H]),i.useEffect(()=>{if(typeof window>"u"){H();return}const F=window.requestAnimationFrame(()=>{H()});return()=>{window.cancelAnimationFrame(F)}},[s,r.length,H]),i.useEffect(()=>{m&&(L(),H())},[m,L,H]),i.useEffect(()=>{const F=T.current;T.current=I,F!==null&&F!=="idle"&&I==="idle"&&A.current>0&&Q()&&S.current!==null&&(P(0),S.current=null,D.current=!1,f(null),s&&n(s,null,0))},[I,s,Q,n,P]),i.useEffect(()=>{H()},[p,H]);const re=i.useRef(new Map),K=i.useCallback(()=>{L(),H()},[L,H]),ae=i.useCallback(F=>{const $=re.current.get(F);if($)return $;const R={onChunk:()=>{L()},onComplete:()=>{L()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{L()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return re.current.set(F,R),R},[L]);return{scrollRef:d,handleMessageContentChange:K,getAnimationHandlers:ae,showScrollButton:y,scrollToBottom:q,spacerHeight:p,pendingAnchorId:j,hasActiveAnchor:m!==null}};function l0(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),l=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:l<7?`${l}d ago`:new Date(s).toLocaleDateString()}const c0=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=he(h=>h.currentSessionId),o=St(h=>n?h.messages.get(n)||[]:[]),a=he(h=>h.revertToMessage),l=he(h=>h.forkFromMessage),c=he(h=>h.loadSessions),[d,u]=i.useState(null),[m,f]=i.useState(""),p=i.useMemo(()=>o.filter(j=>j.info.role==="user").reverse(),[o]),g=i.useMemo(()=>{if(!m.trim())return p;const h=m.toLowerCase();return p.filter(j=>Ed(j.parts).toLowerCase().includes(h))},[p,m]),y=async h=>{if(n){u(h);try{await l(n,h),await c(),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(ys,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(cr,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ms,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(lr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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=Ed(h.parts),b=h.info.time.created,v=l0(b),w=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:[w,"."]}),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:v}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{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(Zn,{className:"h-4 w-4"})})}),e.jsx(lt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{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(),y(h.info.id)},disabled:d===h.info.id,children:d===h.info.id?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(zt,{className:"h-4 w-4"})})}),e.jsx(lt,{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(Zn,{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(zt,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function Ed(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const xf=()=>{const{currentSessionId:s,messages:r,permissions:t,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:l,loadMoreMessages:c,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,sessionMemoryState:f,openNewSessionDraft:p,isSyncing:g,messageStreamStates:y,trimToViewportWindow:h,sessionActivityPhase:j,newSessionDraft:b}=he(),{isTimelineDialogOpen:v,setTimelineDialogOpen:w}=$e(),N=i.useMemo(()=>s?o.get(s)??null:null,[s,o]),{isMobile:x}=$t(),k=!!b?.open;i.useEffect(()=>{!s&&!k&&p()},[s,k,p]);const A=i.useMemo(()=>s?r.get(s)||[]:[],[s,r]),C=i.useMemo(()=>s?t.get(s)||[]:[],[s,t]),M=i.useMemo(()=>s?n.get(s)||[]:[],[s,n]);i.useMemo(()=>[...C,...M],[C,M]);const{scrollRef:S,handleMessageContentChange:D,getAnimationHandlers:E,showScrollButton:T,scrollToBottom:I,spacerHeight:P,pendingAnchorId:O,hasActiveAnchor:U}=i0({currentSessionId:s,sessionMessages:A,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,isSyncing:g,isMobile:x,sessionActivityPhase:j}),W=!!i.useMemo(()=>s?f.get(s)??null:null,[s,f])?.hasMoreAbove,[L,H]=i.useState(!1);i.useEffect(()=>{H(!1)},[s]);const q=i.useRef(null);i.useLayoutEffect(()=>{if(!(!s||s===q.current)&&(q.current=s,!U)){const re=S.current;re&&(re.scrollTop=re.scrollHeight-re.clientHeight)}},[s,S,U]);const X=i.useCallback(async()=>{if(!s||L)return;const re=S.current,K=re?.scrollHeight??null,ae=re?.scrollTop??null;H(!0);try{if(await c(s,"up"),re&&K!==null&&ae!==null){const F=re.scrollHeight-K;re.scrollTop=ae+F}}finally{H(!1)}},[s,L,c,S]),Y=i.useCallback(re=>{const K=S.current;if(!K)return;const ae=K.querySelector(`[data-message-id="${re}"]`);if(ae){const F=K.getBoundingClientRect(),B=ae.getBoundingClientRect().top-F.top+K.scrollTop-50;K.scrollTo({top:B,behavior:"smooth"})}},[S]);return i.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await l(s)}finally{typeof window>"u"?I():window.requestAnimationFrame(()=>{I()})}})()},[s,l,r,I]),!s&&!k?e.jsx("div",{className:"flex flex-col h-full bg-background",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(gi,{})}):!s&&k?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(gi,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(To,{scrollToBottom:I})})]}):s?a&&A.length===0&&!N&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:x?{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(K=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(hi,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(hi,{className:"h-4 w-24"}),e.jsx(hi,{className:"h-20 w-full"})]})]},K))})}),e.jsx(To,{scrollToBottom:I})]}):A.length===0&&!N?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:x?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(gi,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(To,{scrollToBottom:I})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:x?{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(gf,{className:"absolute inset-0 overflow-y-auto overflow-x-hidden z-0 chat-scroll overlay-scrollbar-target",ref:S,style:{contain:"strict","--scroll-shadow-size":"48px"},"data-scroll-shadow":"true","data-scrollbar":"chat",hideBottomShadow:!!O,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(Zw,{messages:A,permissions:C,questions:M,onMessageContentChange:D,getAnimationHandlers:E,hasMoreAbove:W,isLoadingOlder:L,onLoadOlder:X,scrollToBottom:I,pendingAnchorId:O}),P>0&&U&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:P},"aria-hidden":"true"})]})}),e.jsx(kl,{containerRef:S})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[T&&A.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ie,{variant:"outline",size:"sm",onClick:()=>I({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(Fn,{className:"h-4 w-4"})})}),e.jsx(To,{scrollToBottom:I})]}),e.jsx(c0,{open:v,onOpenChange:w,onScrollToMessage:Y})]}):null};class yf extends i.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(Tl,{className:"w-full max-w-md",children:[e.jsx(Pm,{className:"text-center",children:e.jsxs(Tm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(Ah,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(Fm,{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(Ie,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Fs,{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 Xn=()=>{const s=he(r=>r.currentSessionId);return e.jsx(yf,{sessionId:s||void 0,children:e.jsx(xf,{})})},Id=12,d0=[{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"}],u0=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=d0,onComplete:a})=>{const l=Ae.useRef(!1);Ae.useEffect(()=>{!s&&l.current&&a?.(),s&&(l.current=!0)},[s,a]);const c=Ae.useMemo(()=>Array.from({length:Id},(d,u)=>{const m=Math.PI*2*u/Id;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:_("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:c.map((m,f)=>{const p=m.x*d.radius,g=m.y*d.radius,y={"--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:y},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},m0=({durationMs:s=3400}={})=>{const[r,t]=Ae.useState({isActive:!1,cycle:0}),n=Ae.useRef(null),o=Ae.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=Ae.useCallback(()=>{o(),t(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Ae.useCallback(()=>{o(),t(c=>({isActive:!0,cycle:c.cycle+1})),n.current=window.setTimeout(()=>{t(c=>c.isActive?{...c,isActive:!1}:c),n.current=null},s)},[o,s]);return Ae.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:l,dismissFireworks:a}},bf=i.createContext(void 0),Pd=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=m0(),a=i.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(bf.Provider,{value:a,children:[s,e.jsx(u0,{isActive:r,burstKey:t})]})},f0=()=>{const s=i.useContext(bf);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},In=Vt()(Jt(Es((s,r)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:t=>{s({selectedProfileId:t})},loadProfiles:async()=>{s({isLoading:!0});const t=r().profiles;try{const n=await Tx();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 $x();if(t&&t.userName&&t.userEmail){const n={id:"global",name:"Global Identity",userName:t.userName,userEmail:t.userEmail,authType:t.sshCommand?"ssh":void 0,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}},loadDiscoveredCredentials:async()=>{try{const t=await Ox();return s({discoveredCredentials:t}),!0}catch(t){return console.error("Failed to discover git credentials:",t),s({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const t=n=>{if(typeof n!="string")return null;const o=n.trim();return o.length>0?o:null};try{let n=null;if(es()){const o=await Lr();n=t(o?.defaultGitIdentityId)}else{const o=Qs()?.settings;if(o)try{const l=(await o.load())?.settings||{};n=t(l.defaultGitIdentityId)}catch{}if(n===null)try{const a=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(a.ok){const l=await a.json().catch(()=>null);n=t(l?.defaultGitIdentityId)}}catch{}}return s({defaultGitIdentityId:n}),!0}catch(n){return console.error("Failed to load default git identity setting:",n),!1}},setDefaultGitIdentityId:async t=>{try{const n=typeof t=="string"?t.trim():"",o=n.length>0?n:"";return await ss({defaultGitIdentityId:o}),s({defaultGitIdentityId:o.length>0?o:null}),!0}catch(n){return console.error("Failed to save default git identity setting:",n),!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 Fx(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(l=>l.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await Rx(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 _x(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)},getUnimportedCredentials:()=>{const{profiles:t,discoveredCredentials:n}=r();return n.filter(o=>!t.some(a=>a.authType==="token"&&a.host===o.host))}}),{name:"git-identities-store",storage:Is(()=>ds()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=In);const p0=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),h0=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:l=!1})=>{const[c,d]=i.useState(!1),[u,m]=i.useState(""),[f,p]=i.useState(!1),[g,y]=i.useState(""),[h,j]=i.useState(!1),b=i.useRef(null),v=i.useMemo(()=>p0(g),[g]),w=i.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(S=>S.toLowerCase().includes(M)):r},[u,r]),N=i.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(S=>S.toLowerCase().includes(M)):t},[u,t]),x=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>b.current?.focus(),50)},A=async()=>{if(!(!v||h)){j(!0);try{await a(v),y(""),p(!1),d(!1)}finally{j(!1)}}},C=()=>{y(""),p(!1)};return i.useEffect(()=>{c||(m(""),p(!1),y(""))},[c]),e.jsxs(qt,{open:c,onOpenChange:d,children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:l,children:[e.jsx(zt,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(Ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{sideOffset:8,children:["Switch branch (",r.length," local · ",t.length," remote)"]})]}),e.jsx(Qt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:e.jsxs(_m,{className:"h-full min-h-0",children:[e.jsx(Om,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs($m,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Lm,{children:"No branches found."}),e.jsx(kn,{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:M=>y(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),A()):M.key==="Escape"&&(M.preventDefault(),C())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),e.jsx("button",{type:"button",onClick:A,disabled:!v||h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:h?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(Xt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:C,disabled:h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Ht,{className:"size-4"})})]}):e.jsxs(ls,{onSelect:k,children:[e.jsx(Xt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(ha,{}),e.jsxs(kn,{heading:"Local branches",children:[w.map(M=>e.jsxs(ls,{onSelect:()=>x(M),children:[e.jsxs("span",{className:"flex flex-1 flex-col",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:M}),(n?.[M]?.ahead||n?.[M]?.behind)&&e.jsxs("span",{className:"typography-micro text-muted-foreground",children:[n[M].ahead||0," ahead ·"," ",n[M].behind||0," behind"]})]}),s===M&&e.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${M}`)),w.length===0&&e.jsx(ls,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ha,{}),e.jsxs(kn,{heading:"Remote branches",children:[N.map(M=>e.jsx(ls,{onSelect:()=>x(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx(ls,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},g0=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),x0=({currentBranch:s,onRename:r})=>{const[t,n]=i.useState(!1),[o,a]=i.useState(s||""),[l,c]=i.useState(!1),d=i.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const g=g0(o);if(g===s){n(!1);return}c(!0);try{await r(s,g),n(!1),a("")}finally{c(!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(zt,{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:l,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:l?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(_t,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:l,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(zt,{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(Ie,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(uo,{className:"size-4"})})]})},y0=({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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(jr,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(lt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(Fn,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(lt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(co,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(lt,{sideOffset:8,children:"Push changes"})]})]})},b0={branch:zt,briefcase:pl,house:fl,graduation:ml,code:_s,heart:Tu,user:Os},v0={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 vf(s){return s&&v0[s]||"var(--primary)"}const Td=({icon:s,className:r,colorToken:t})=>{const n=b0[s??"branch"]??Os;return e.jsx(n,{className:r,style:{color:vf(t)}})},w0=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(qt,{children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Kt,{asChild:!0,children:e.jsxs(Ie,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:vf(s?.color)},disabled:o,children:[n?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(Td,{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(Ft,{className:"size-4 opacity-60"})]})})}),e.jsxs(lt,{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(Qt,{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(Et,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Td,{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))})]})},j0=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:l,onPush:c,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:g,isApplyingIdentity:y,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(x0,{currentBranch:s.current,onRename:m}):e.jsx(h0,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(dt,{delayDuration:800,children:[e.jsx(ut,{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(co,{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(Fn,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(lt,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(y0,{syncAction:o,onFetch:a,onPull:l,onPush:c,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(w0,{activeProfile:f,identities:p,onSelect:g,isApplying:y})]}):null,S0=({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(il,{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(Ie,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(Fn,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),wf={"?":{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"}},k0=wf.M;function N0(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 C0(s){const r=N0(s);return wf[r]??k0}const M0=i.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:l,stats:c}){const d=Ae.useMemo(()=>C0(r),[r]),u=d.description,m=c?.insertions??0,f=c?.deletions??0,p=Ae.useCallback(h=>{h.key===" "?(h.preventDefault(),n()):h.key==="Enter"&&(h.preventDefault(),o())},[n,o]),g=Ae.useCallback(h=>{h.preventDefault(),h.stopPropagation(),n()},[n]),y=Ae.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(cl,{className:"size-4 text-primary"}):e.jsx(dl,{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(dt,{delayDuration:200,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:y,disabled:l,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:l?e.jsx(rs,{className:"size-3.5 animate-spin"}):e.jsx(jr,{className:"size-3.5"})})}),e.jsx(lt,{sideOffset:8,children:"Revert changes"})]})]})})}),D0=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:l,onViewDiff:c,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(Ie,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ie,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:l,disabled:u===0,children:"None"})]})]})]}),e.jsx(gt,{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(M0,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>c(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function on({className:s,variant:r,...t}){return e.jsx(Ie,{variant:r,size:"sm",className:_("h-7 px-2 py-0",s),...t})}const ji=38,Fd=200,A0=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=i.useRef(null);return i.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${ji}px`;const l=Math.min(Math.max(a.scrollHeight,ji),Fd);a.style.height=`${l}px`},[s]),e.jsx(Ss,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:_("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:ji,maxHeight:Fd}})},E0=({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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(Fn,{className:"size-4"})})}),e.jsx(lt,{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))})]})},I0=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:l,isGeneratingMessage:c,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,g=r.trim()&&p&&m===null;return e.jsxs(po,{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(ho,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(E0,{highlights:n,onInsert:o,onClear:a}),e.jsx(A0,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:l,disabled:c||m!==null||s===0||f,"aria-label":"Generate commit message",children:c?e.jsx(rs,{className:"size-4 animate-spin"}):e.jsx(Cu,{className:"size-4 text-primary"})})}),e.jsx(lt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(on,{variant:"outline",onClick:d,disabled:!g||c,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(il,{className:"size-4"}),"Commit"]})}),e.jsx(on,{variant:"default",onClick:u,disabled:!g||c,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(co,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function Rd(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 P0(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 T0=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:_("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:Rd(s.date),children:Rd(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(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:l=>{l.stopPropagation(),a(s.hash)},children:e.jsx(Ys,{className:"size-3"})})}),e.jsx(lt,{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(rs,{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(l=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:_("font-semibold w-3 text-center",P0(l.changeType)),children:l.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:l.path,children:l.path}),!l.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",l.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",l.deletions]})]}),l.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},l.path))})})]}),F0=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],R0=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:l,loadingCommitHashes:c,onCopyHash:d})=>{const[u,m]=i.useState(!0);return s?e.jsxs(po,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Ta,{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(ks,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ns,{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(nn,{placeholder:"Commits"})}),e.jsx(Cs,{children:F0.map(f=>e.jsx(Ut,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(Na,{className:"size-4 text-muted-foreground"}):e.jsx(Ft,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(ho,{children:e.jsx(gt,{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(T0,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:l.get(f.hash)??[],isLoadingFiles:c.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let Wn=null;const _0=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=vt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??void 0},O0=()=>{const{git:s}=kr(),r=_0(),{currentSessionId:t,worktreeMetadata:n}=he(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:l,defaultGitIdentityId:c,loadProfiles:d,loadGlobalIdentity:u,loadDefaultGitIdentityId:m}=In(),f=Nl(r??null),p=wm(r??null),g=jm(r??null),y=Py(r??null),h=Ty(r??null),j=Gt(ye=>ye.isLoadingStatus),b=Gt(ye=>ye.isLoadingLog),{setActiveDirectory:v,fetchAll:w,fetchStatus:N,fetchBranches:x,fetchLog:k,fetchIdentity:A,setLogMaxCount:C}=Gt(),M=i.useMemo(()=>!Wn||Wn.directory!==r?null:Wn,[r]),[S,D]=i.useState(M?.commitMessage??""),[E,T]=i.useState(null),[I,P]=i.useState(null),[O,U]=i.useState(25),[Q,W]=i.useState(!1),{triggerFireworks:L}=f0(),H=i.useRef(new Map),q=i.useRef(0),X=i.useCallback(()=>{q.current+=1,W(!0)},[]),Y=i.useCallback(()=>{q.current=Math.max(0,q.current-1),q.current===0&&W(!1)},[]),[re,K]=i.useState(()=>new Set(M?.selectedPaths??[])),[ae,F]=i.useState(!1),[$,R]=i.useState(new Set),[B,z]=i.useState(!1),[G,ge]=i.useState([]),oe=i.useCallback(()=>{ge([])},[]),[me,Ne]=i.useState(new Set),[Ce,Be]=i.useState(new Map),[V,J]=i.useState(new Set),[ee,xe]=i.useState(null),fe=i.useCallback(ye=>{navigator.clipboard.writeText(ye).then(()=>{te.success("Commit hash copied")}).catch(()=>{te.error("Failed to copy")})},[]),Oe=i.useCallback(ye=>{Ne(ie=>{const de=new Set(ie);return de.has(ye)?de.delete(ye):de.add(ye),de})},[]);i.useEffect(()=>{if(!r||!s)return;const ye=Array.from(me).filter(ie=>!Ce.has(ie)&&!V.has(ie));ye.length!==0&&(J(ie=>{const de=new Set(ie);return ye.forEach(We=>de.add(We)),de}),ye.forEach(ie=>{s.getCommitFiles(r,ie).then(de=>{Be(We=>new Map(We).set(ie,de.files))}).catch(de=>{console.error("Failed to fetch commit files:",de),Be(We=>new Map(We).set(ie,[]))}).finally(()=>{J(de=>{const We=new Set(de);return We.delete(ie),We})})}))},[me,r,s,Ce,V]),i.useEffect(()=>()=>{if(!r){Wn=null;return}Wn={directory:r,selectedPaths:Array.from(re),commitMessage:S}},[S,r,re]),i.useEffect(()=>{d(),u(),m()},[d,u,m]),i.useEffect(()=>{if(!r||!s?.getRemoteUrl){xe(null);return}s.getRemoteUrl(r).then(xe).catch(()=>xe(null))},[r,s]),i.useEffect(()=>{r&&(v(r),Gt.getState().directories.get(r)?.status||w(r,s,{force:!0}))},[r,v,w,s]);const Se=i.useCallback(async(ye=!0)=>{if(r)try{await Promise.all([N(r,s),x(r,s)])}catch(ie){if(ye){const de=ie instanceof Error?ie.message:"Failed to refresh repository state";te.error(de)}}},[r,s,N,x]),Le=i.useCallback(async()=>{r&&await k(r,s,O)},[r,s,k,O]),pe=i.useCallback(async()=>{r&&await A(r,s)},[r,s,A]);i.useEffect(()=>{if(!r||!s?.hasLocalIdentity||f!==!0)return;const ye=typeof c=="string"?c.trim():"";if(!ye||ye==="global"||H.current.get(r)===ye)return;let de=!1;return(async()=>{try{const Ge=await s.hasLocalIdentity(r);if(de||Ge)return;X(),await s.setGitIdentity(r,ye),H.current.set(r,ye),await pe()}catch(Ge){console.warn("Failed to auto-apply default git identity:",Ge)}finally{de||Y()}})(),()=>{de=!0}},[X,r,c,Y,s,f,pe]);const it=i.useMemo(()=>{if(!p)return[];const ye=p.files??[],ie=new Map;return ye.forEach(de=>{ie.set(de.path,de)}),Array.from(ie.values()).sort((de,We)=>de.path.localeCompare(We.path))},[p]);i.useEffect(()=>{if(!p||it.length===0){K(new Set),F(!1);return}K(ye=>{const ie=new Set,de=ye??new Set;return it.forEach(We=>{de.has(We.path)?ie.add(We.path):ae||ie.add(We.path)}),ie})},[p,it,ae]);const xt=async ye=>{if(r){T(ye);try{if(ye==="fetch")await s.gitFetch(r),te.success("Fetched latest updates");else if(ye==="pull"){const ie=await s.gitPull(r);te.success(`Pulled ${ie.files.length} file${ie.files.length===1?"":"s"}`)}else ye==="push"&&(await s.gitPush(r),te.success("Pushed to remote"));await Se(!1),await Le()}catch(ie){const de=ie instanceof Error?ie.message:`Failed to ${ye==="pull"?"pull":ye}`;te.error(de)}finally{T(null)}}},Mt=async(ye={})=>{if(!r)return;if(!S.trim()){te.error("Please enter a commit message");return}const ie=Array.from(re).sort();if(ie.length===0){te.error("Select at least one file to commit");return}const de=ye.pushAfter?"commitAndPush":"commit";P(de);try{await s.createGitCommit(r,S.trim(),{files:ie}),te.success("Commit created successfully"),D(""),K(new Set),F(!1),oe(),await Se(),ye.pushAfter?(await s.gitPush(r),te.success("Pushed to remote"),L(),await Se(!1)):await Se(!1),await Le()}catch(We){const Ge=We instanceof Error?We.message:"Failed to create commit";te.error(Ge)}finally{P(null)}},De=i.useCallback(async()=>{if(r){if(re.size===0){te.error("Select at least one file to describe");return}z(!0);try{const{message:ye}=await s.generateCommitMessage(r,Array.from(re)),ie=ye.subject?.trim()??"",de=Array.isArray(ye.highlights)?ye.highlights:[];ie&&D(ie),ge(de),te.success("Commit message generated")}catch(ye){const ie=ye instanceof Error?ye.message:"Failed to generate commit message";te.error(ie)}finally{z(!1)}}},[r,re,s]),ne=async ye=>{if(!r||!p)return;const ie=p.current??null;try{await s.createBranch(r,ye,ie??"HEAD"),te.success(`Created branch ${ye}`);let de=!1;try{await s.checkoutBranch(r,ye),await s.gitPush(r,{remote:"origin",branch:ye,options:["--set-upstream"]}),de=!0}catch(We){const Ge=We instanceof Error?We.message:"Unable to push new branch to origin.";te.warning("Branch created locally",{description:e.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",Ge]})})}finally{if(ie)try{await s.checkoutBranch(r,ie)}catch(We){console.warn("Failed to restore original branch after creation:",We)}}await Se(),await Le(),de&&te.success(`Upstream set for ${ye}`)}catch(de){const We=de instanceof Error?de.message:"Failed to create branch";throw te.error(We),de}},rt=async(ye,ie)=>{if(r)try{await s.renameBranch(r,ye,ie),te.success(`Renamed branch ${ye} to ${ie}`),await Se(),await Le()}catch(de){const We=de instanceof Error?de.message:`Failed to rename branch ${ye} to ${ie}`;te.error(We)}},be=async ye=>{if(!r)return;const ie=ye.replace(/^remotes\//,"");if(p?.current!==ie)try{await s.checkoutBranch(r,ie),te.success(`Checked out ${ie}`),await Se(),await Le()}catch(de){const We=de instanceof Error?de.message:`Failed to checkout ${ie}`;te.error(We)}},ke=async ye=>{if(r){X();try{await s.setGitIdentity(r,ye.id),te.success(`Applied "${ye.name}" to repository`),await pe()}catch(ie){const de=ie instanceof Error?ie.message:"Failed to apply git identity";te.error(de)}finally{Y()}}},Qe=i.useMemo(()=>g?.all?g.all.filter(ye=>!ye.startsWith("remotes/")).sort():[],[g]),tt=i.useMemo(()=>g?.all?g.all.filter(ye=>ye.startsWith("remotes/")).map(ye=>ye.replace(/^remotes\//,"")).sort():[],[g]),He=i.useMemo(()=>{const ye=new Map;l&&ye.set(l.id,l);let ie=null;if(ee)try{let de=ee.trim();de.startsWith("git@")&&(de="https://"+de.slice(4).replace(":","/")),de.endsWith(".git")&&(de=de.slice(0,-4));const We=new URL(de);ie=We.hostname+We.pathname}catch{}for(const de of a){if(de.authType!=="token"){ye.set(de.id,de);continue}const We=de.host;if(!We){ye.set(de.id,de);continue}if(!We.includes("/")){ye.set(de.id,de);continue}ie&&ie===We&&ye.set(de.id,de)}return Array.from(ye.values())},[a,l,ee]),Re=i.useMemo(()=>{if(h?.userName&&h?.userEmail){const ye=a.find(ie=>ie.userName===h.userName&&ie.userEmail===h.userEmail);return ye||(l&&l.userName===h.userName&&l.userEmail===h.userEmail?l:{id:"local-config",name:h.userName,userName:h.userName,userEmail:h.userEmail,sshKey:h.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return l??null},[h,a,l]),nt=it.length,yt=re.size,ct=j||E!==null||I!==null,It=nt>0,Tt=ye=>{K(ie=>{const de=new Set(ie);return de.has(ye)?de.delete(ye):de.add(ye),de}),F(!0)},je=()=>{const ye=new Set(it.map(ie=>ie.path));K(ye),F(!0)},ze=()=>{K(new Set),F(!0)},Ze=i.useCallback(async ye=>{if(r){R(ie=>{const de=new Set(ie);return de.add(ye),de});try{await s.revertGitFile(r,ye),te.success(`Reverted ${ye}`),await Se(!1)}catch(ie){const de=ie instanceof Error?ie.message:"Failed to revert changes";te.error(de)}finally{R(ie=>{const de=new Set(ie);return de.delete(ye),de})}}},[r,Se,s]),Ye=i.useCallback(()=>{if(G.length===0)return;const ye=G.map(ie=>ie.trim()).filter(Boolean);if(ye.length===0){oe();return}D(ie=>{const de=ie.trim(),We=de.length>0?`
117
-
118
- `:"";return`${de}${We}${ye.join(`
119
- `)}`.trim()})},[G,oe]),mt=i.useCallback(ye=>{U(ye),r&&(C(r,ye),k(r,s,ye))},[r,C,k,s]);return r?j&&f===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(rs,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):f===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx(zt,{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(j0,{status:p,localBranches:Qe,remoteBranches:tt,branchInfo:g?.branches,syncAction:E,onFetch:()=>xt("fetch"),onPull:()=>xt("pull"),onPush:()=>xt("push"),onCheckoutBranch:be,onCreateBranch:ne,onRenameBranch:rt,activeIdentityProfile:Re,availableIdentities:He,onSelectIdentity:ke,isApplyingIdentity:Q,isWorktreeMode:!!o}),e.jsx(gt,{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:[It?e.jsx(D0,{changeEntries:it,selectedPaths:re,diffStats:p?.diffStats,revertingPaths:$,onToggleFile:Tt,onSelectAll:je,onClearSelection:ze,onViewDiff:ye=>$e.getState().navigateToDiff(ye),onRevertFile:Ze}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(S0,{behind:p?.behind??0,onPull:()=>xt("pull"),isPulling:E==="pull"})}),it.length>0&&e.jsx(I0,{selectedCount:yt,commitMessage:S,onCommitMessageChange:D,generatedHighlights:G,onInsertHighlights:Ye,onClearHighlights:oe,onGenerateMessage:De,isGeneratingMessage:B,onCommit:()=>Mt({pushAfter:!1}),onCommitAndPush:()=>Mt({pushAfter:!0}),commitAction:I,isBusy:ct})]}),e.jsx(R0,{log:y,isLogLoading:b,logMaxCount:O,onLogMaxCountChange:mt,expandedCommitHashes:me,onToggleCommit:Oe,commitFilesMap:Ce,loadingCommitHashes:V,onCopyHash:fe})]})})]}):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."})})},$0=1e6;function qr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Fo=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),_d=Vt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=qr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=qr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o),u=!c||c.terminalSessionId!==n.sessionId?Fo(o):c??Fo(o);return l.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:l}})},setConnecting:(t,n)=>{const o=qr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o)??Fo(o);return l.set(o,{...c,isConnecting:n,updatedAt:Date.now()}),{sessions:l}})},appendToBuffer:(t,n)=>{if(!n)return;const o=qr(t);s(a=>{const l=new Map(a.sessions),c=l.get(o)??Fo(o),d=a.nextChunkId,u={id:d,data:n},m=[...c.bufferChunks,u];let f=c.bufferLength+n.length;for(;f>$0&&m.length>1;){const g=m.shift();if(!g)break;f-=g.data.length}const p=m.map(g=>g.data).join("");return l.set(o,{...c,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:l,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=qr(t);s(o=>{const a=new Map(o.sessions),l=a.get(n);return l&&a.set(n,{...l,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=qr(t);s(o=>{const a=new Map(o.sessions),l=a.get(n);return l?(a.set(n,{...l,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=qr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),jf=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),L0=[{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'}],B0=[{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'}],Sf=s=>Object.fromEntries(s.map(r=>[r.id,r])),Od=Sf(L0),Kr=Sf(B0),z0="ibm-plex-sans",Jo="ibm-plex-mono";function W0(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 H0(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 U0(){return Si||(Si=Ph.load()),Si}function V0(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 rl=i.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:l,className:c,enableTouchScroll:d},u)=>{const m=i.useRef(null),f=i.useRef(null),p=i.useRef(null),g=i.useRef(null),y=i.useRef(t),h=i.useRef(n),j=i.useRef(null),b=i.useRef(""),v=i.useRef(null),w=i.useRef(!1),N=i.useRef(null),x=i.useRef(null),k=i.useRef(null),A=i.useRef(0),C=i.useRef(null),[,M]=i.useReducer(W=>W+1,0),[S,D]=i.useReducer(W=>W+1,0);y.current=t,h.current=n;const E=i.useCallback((W,L)=>{const H=C.current,q=m.current;if(!H||!q)return;const X=q.getBoundingClientRect(),Y=X.left+X.width/2,re=X.top+X.height-12,K=typeof W=="number"?W:Y,ae=typeof L=="number"?L:re,F=8,$=Math.max(F,Math.min(X.width-F,K-X.left)),R=Math.max(F,Math.min(X.height-F,ae-X.top));H.style.left=`${$}px`,H.style.top=`${R}px`,H.style.bottom="";try{H.focus({preventScroll:!0})}catch{try{H.focus()}catch{}}},[]),T=i.useCallback(()=>{b.current="",v.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(v.current),v.current=null,w.current=!1,N.current=null},[]),I=i.useCallback(()=>{const W=g.current,L=p.current,H=m.current;if(!W||!L||!H)return;const q=H.getBoundingClientRect();if(!(q.width<24||q.height<24))try{W.fit();const X={cols:L.cols,rows:L.rows},Y=j.current;(!Y||Y.cols!==X.cols||Y.rows!==X.rows)&&(j.current=X,h.current(X.cols,X.rows))}catch{}},[]),P=i.useCallback(()=>{if(w.current)return;const W=p.current;if(!W){T();return}if(!b.current)return;const L=b.current;b.current="",w.current=!0,W.write(L,()=>{w.current=!1,b.current&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,P()}):P())})},[T]),O=i.useCallback(()=>{v.current===null&&(typeof window<"u"?v.current=window.requestAnimationFrame(()=>{v.current=null,P()}):P())},[P]),U=i.useCallback(W=>{W&&(b.current+=W,O())},[O]),Q=i.useCallback(()=>{if(x.current?.(),x.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){A.current=0;return}const W=m.current;if(!W)return;const L=p.current;if(!L)return;A.current=0;const H=2.2,q=2.8,X=25,Y=.25,re=8,K=.05,ae=.015,F={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},$=()=>typeof performance<"u"?performance.now():Date.now(),R=Math.max(12,Math.round(l*1.35));let B=0;const z=J=>{if(!J)return!1;const ee=L.getViewportY(),xe=B+J,fe=Math.trunc(xe/R);return B=xe-fe*R,fe!==0&&L.scrollLines(fe),L.getViewportY()!==ee},G=()=>{F.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(F.rafId),F.rafId=null},ge={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const J=Object.assign(F,{pointerId:null,startX:null,startY:null,moved:!1}),ee=6,xe=Le=>{if(Le.pointerType==="touch"){G(),J.pointerId=Le.pointerId,J.startX=Le.clientX,J.startY=Le.clientY,J.moved=!1,J.lastY=Le.clientY,J.lastTime=$(),J.velocity=0;try{W.setPointerCapture(Le.pointerId)}catch{}}},fe=Le=>{if(Le.pointerType!=="touch"||J.pointerId!==Le.pointerId)return;if(J.startX!==null&&J.startY!==null&&!J.moved){const ke=Le.clientX-J.startX,Qe=Le.clientY-J.startY;Math.hypot(ke,Qe)>=ee&&(J.moved=!0)}if(J.lastY===null){J.lastY=Le.clientY,J.lastTime=$();return}const pe=J.lastY,it=J.lastTime??$(),xt=$();J.lastY=Le.clientY,J.lastTime=xt;const Mt=pe-Le.clientY;if(Math.abs(Mt)<1)return;const De=Math.max(xt-it,8),ne=H+Math.min(q,Math.abs(Mt)/X),rt=Mt*ne,be=rt/De;J.velocity=J.velocity*(1-Y)+be*Y,J.velocity>re?J.velocity=re:J.velocity<-re&&(J.velocity=-re),J.moved&&(Le.cancelable&&Le.preventDefault(),Le.stopPropagation()),z(rt)},Oe=Le=>{if(Le.pointerType!=="touch"||J.pointerId!==Le.pointerId)return;const pe=!J.moved;J.pointerId=null,J.startX=null,J.startY=null,J.moved=!1,J.lastY=null,J.lastTime=null;try{W.releasePointerCapture(Le.pointerId)}catch{}if(pe){E(Le.clientX,Le.clientY);return}if(typeof window>"u")return;if(Math.abs(J.velocity)<K){J.velocity=0;return}let it=$();const xt=()=>{const Mt=$(),De=Math.max(Mt-it,8);it=Mt;const ne=z(J.velocity*De)??!1,rt=Math.sign(J.velocity),be=Math.max(0,Math.abs(J.velocity)-ae*De);if(J.velocity=be*rt,!ne||be<=K){G(),J.velocity=0;return}J.rafId=window.requestAnimationFrame(xt)};J.rafId=window.requestAnimationFrame(xt)};W.addEventListener("pointerdown",xe,ge),W.addEventListener("pointermove",fe,ge),W.addEventListener("pointerup",Oe,ge),W.addEventListener("pointercancel",Oe,ge);const Se=W.style.touchAction;W.style.touchAction="manipulation",x.current=()=>{G(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,W.removeEventListener("pointerdown",xe,ge),W.removeEventListener("pointermove",fe,ge),W.removeEventListener("pointerup",Oe,ge),W.removeEventListener("pointercancel",Oe,ge),W.style.touchAction=Se};return}const me=6,Ne=J=>{J.touches.length===1&&(G(),F.lastY=J.touches[0].clientY,F.lastTime=$(),F.velocity=0,F.startX=J.touches[0].clientX,F.startY=J.touches[0].clientY,F.didMove=!1)},Ce=J=>{if(J.touches.length!==1){F.lastY=null,F.lastTime=null,F.velocity=0,F.startX=null,F.startY=null,F.didMove=!1,G();return}const ee=J.touches[0].clientX,xe=J.touches[0].clientY;if(F.startX!==null&&F.startY!==null&&!F.didMove){const De=ee-F.startX,ne=xe-F.startY;Math.hypot(De,ne)>=me&&(F.didMove=!0)}if(F.lastY===null){F.lastY=xe,F.lastTime=$();return}const fe=F.lastY,Oe=F.lastTime??$(),Se=$();F.lastY=xe,F.lastTime=Se;const Le=fe-xe;if(Math.abs(Le)<1)return;const pe=Math.max(Se-Oe,8),it=H+Math.min(q,Math.abs(Le)/X),xt=Le*it,Mt=xt/pe;F.velocity=F.velocity*(1-Y)+Mt*Y,F.velocity>re?F.velocity=re:F.velocity<-re&&(F.velocity=-re),F.didMove&&(J.preventDefault(),J.stopPropagation()),z(xt)},Be=J=>{const ee=!F.didMove;F.lastY=null,F.lastTime=null;const xe=F.velocity;if(F.startX=null,F.startY=null,F.didMove=!1,ee){const Se=J.changedTouches?.[0];E(Se?.clientX,Se?.clientY);return}if(typeof window>"u")return;if(Math.abs(xe)<K){F.velocity=0;return}let fe=$();const Oe=()=>{const Se=$(),Le=Math.max(Se-fe,8);fe=Se;const pe=z(F.velocity*Le)??!1,it=Math.sign(F.velocity),xt=Math.max(0,Math.abs(F.velocity)-ae*Le);if(F.velocity=xt*it,!pe||xt<=K){G(),F.velocity=0;return}F.rafId=window.requestAnimationFrame(Oe)};F.rafId=window.requestAnimationFrame(Oe)};W.addEventListener("touchstart",Ne,ge),W.addEventListener("touchmove",Ce,ge),W.addEventListener("touchend",Be,ge),W.addEventListener("touchcancel",Be,ge);const V=W.style.touchAction;W.style.touchAction="manipulation",x.current=()=>{G(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),A.current=0,W.removeEventListener("touchstart",Ne,ge),W.removeEventListener("touchmove",Ce,ge),W.removeEventListener("touchend",Be,ge),W.removeEventListener("touchcancel",Be,ge),W.style.touchAction=V}},[d,E,l]);return i.useEffect(()=>{let W=!1,L=null,H=null,q=[];const X=m.current;return X?(X.tabIndex=0,(async()=>{try{const re=await U0();if(W)return;const K=H0(a,l,o,re),ae=new Eh(K),F=new Ih;L=ae,p.current=ae,g.current=F,ae.loadAddon(F),ae.open(X),D();const $=V0(X);$?($.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=$,M()):f.current=null,I(),Q(),ae.focus(),q=[ae.onData(R=>{y.current(R)})],H=new ResizeObserver(()=>{I()}),H.observe(X),typeof window<"u"&&window.setTimeout(()=>{I()},0)}catch{}})(),()=>{W=!0,x.current?.(),x.current=null,q.forEach(re=>re.dispose()),H?.disconnect(),L?.dispose(),p.current=null,g.current=null,f.current=null,j.current=null,T()}):void 0},[I,a,l,Q,o,T]),i.useEffect(()=>{const W=p.current;W&&(W.reset(),T(),j.current=null,I(),W.focus())},[s,S,I,T]),i.useEffect(()=>(Q(),()=>{x.current?.(),x.current=null}),[Q,s]),i.useEffect(()=>{const W=p.current;if(!W)return;if(r.length===0){N.current!==null&&(W.reset(),T(),I());return}const L=N.current;let H;if(L===null)H=r;else{const q=r.findIndex(X=>X.id===L);H=q>=0?r.slice(q+1):r}H.length>0&&U(H.map(q=>q.data).join("")),N.current=r[r.length-1].id},[r,S,U,I,T]),i.useImperativeHandle(u,()=>({focus:()=>{if(d){E();return}p.current?.focus()},clear:()=>{const W=p.current;W&&(W.reset(),T(),I())},fit:()=>{I()}}),[d,E,I,T]),e.jsxs("div",{ref:m,className:_("relative h-full w-full terminal-viewport-container",c),style:{backgroundColor:o.background},onClick:W=>{d?E(W.clientX,W.clientY):p.current?.focus()},children:[d?e.jsx("textarea",{ref:C,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:0,zIndex:1,background:"transparent",color:"transparent",caretColor:"transparent",resize:"none",overflow:"hidden",whiteSpace:"nowrap",border:"none",padding:0,margin:0,outline:"none"},onInput:W=>{const L=String(W.currentTarget.value||"");if(!L)return;const H=L.replace(/\r\n|\r|\n/g,"\r");y.current(H),W.currentTarget.value=""},onKeyDown:W=>{W.key==="Backspace"&&(W.currentTarget.value||y.current(""))}}):null,f.current&&!d?e.jsx(kl,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});rl.displayName="TerminalViewport";const $d=13,G0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Ro={ctrl:"5",cmd:"3"},q0={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},K0=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${Ro[r]}A`;case"arrow-down":return`\x1B[1;${Ro[r]}B`;case"arrow-right":return`\x1B[1;${Ro[r]}C`;case"arrow-left":return`\x1B[1;${Ro[r]}D`}return G0[s]??null},Q0=()=>{const{terminal:s}=kr(),{currentTheme:r}=Wr(),{monoFont:t}=jf(),{isMobile:n,hasTouchInput:o}=$t(),{currentSessionId:a,sessions:l,worktreeMetadata:c}=he(),d=a?c.get(a)??void 0:void 0,u=i.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const ee=l.find(fe=>fe.id===a),xe=typeof ee?.directory=="string"?ee.directory:null;return xe&&xe.length>0?xe:null},[a,l,d]),{currentDirectory:m,homeDirectory:f}=vt(),p=u||m||null,g=i.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),y=_d(),h=y.sessions,j=y.setTerminalSession,b=y.setConnecting,v=y.appendToBuffer,w=y.clearTerminalSession,N=y.removeTerminalSession,x=y.clearBuffer,k=i.useMemo(()=>{if(p)return h.get(p)},[h,p]),A=k?.terminalSessionId??null,C=k?.bufferChunks??[],M=k?.bufferLength??0,S=k?.isConnecting??!1,D=A,[E,T]=i.useState(null),[I,P]=i.useState(!1),[O,U]=i.useState(null),[Q,W]=i.useState(!1),L=i.useRef(null),H=i.useRef(null),q=i.useRef(D),X=i.useRef(p),Y=i.useRef(null),K=$e(ee=>ee.activeMainTab)==="terminal";i.useEffect(()=>{q.current=D},[D]),i.useEffect(()=>{X.current=p},[p]),i.useEffect(()=>{!n&&O!==null&&U(null)},[n,O,U]),i.useEffect(()=>{!D&&O!==null&&U(null)},[D,O,U]);const ae=i.useCallback(()=>{L.current?.(),L.current=null,H.current=null},[]);i.useEffect(()=>()=>{ae(),q.current=null},[ae]);const F=i.useCallback(ee=>{if(H.current===ee)return;ae();const xe=s.connect(ee,{onEvent:fe=>{const Oe=X.current;if(Oe)switch(fe.type){case"connected":{(fe.runtime||fe.ptyBackend)&&console.log(`[Terminal] connected runtime=${fe.runtime??"unknown"} pty=${fe.ptyBackend??"unknown"}`),b(Oe,!1),T(null),P(!1),Y.current?.focus();break}case"reconnecting":{const Se=fe.attempt??0,Le=fe.maxAttempts??3;T(`Reconnecting (${Se}/${Le})...`),P(!1);break}case"data":{fe.data&&v(Oe,fe.data);break}case"exit":{const Se=typeof fe.exitCode=="number"?fe.exitCode:null,Le=typeof fe.signal=="number"?fe.signal:null;v(Oe,`\r
120
- [Process exited${Se!==null?` with code ${Se}`:""}${Le!==null?` (signal ${Le})`:""}]\r
121
- `),w(Oe),b(Oe,!1),T("Terminal session ended"),P(!1),ae();break}}},onError:(fe,Oe)=>{const Se=X.current;if(!Se)return;const Le=Oe?`Connection failed: ${fe.message}`:fe.message||"Terminal stream connection error";T(Le),P(!!Oe),Oe&&(b(Se,!1),ae(),N(Se))}},q0);L.current=()=>{xe.close(),H.current=null},H.current=ee},[v,w,ae,N,b,s,T]);i.useEffect(()=>{let ee=!1;if(!p){T(a?"No working directory available for terminal.":"Select a session to open the terminal."),ae();return}return(async()=>{const fe=p;if(!X.current||X.current!==fe)return;let Se=_d.getState().getTerminalSession(fe)?.terminalSessionId??null;if(!Se){T(null),P(!1),b(fe,!0);try{const Le=await s.createSession({cwd:fe});if(ee){try{await s.close(Le.sessionId)}catch{}return}j(fe,Le),Se=Le.sessionId}catch(Le){ee||(T(Le instanceof Error?Le.message:"Failed to start terminal session"),P(!0),b(fe,!1));return}}!Se||ee||(q.current=Se,F(Se))})(),()=>{ee=!0,q.current=null,ae()}},[a,p,D,N,b,j,F,ae,s]);const $=i.useCallback(async()=>{if(!p||Q)return;W(!0),T(null),P(!1),ae();const ee=q.current;try{if(s.restartSession&&ee){const xe=await s.restartSession(ee,{cwd:p});j(p,xe),q.current=xe.sessionId,F(xe.sessionId)}else{if(ee)try{await s.close(ee)}catch{}N(p)}}catch(xe){T(xe instanceof Error?xe.message:"Failed to restart terminal"),P(!0)}finally{W(!1)}},[p,Q,ae,s,j,F,N]),R=i.useCallback(async()=>{if(p&&!Q){W(!0),T(null),P(!1),ae();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),x(p),Y.current?.clear(),await new Promise(ee=>setTimeout(ee,100));try{b(p,!0);const ee=await s.createSession({cwd:p});j(p,ee),q.current=ee.sessionId,F(ee.sessionId)}catch(ee){T(ee instanceof Error?ee.message:"Failed to create terminal"),P(!0),b(p,!1)}finally{W(!1)}}},[p,Q,ae,s,N,x,b,j,F]),B=i.useCallback(()=>{if(!p)return;x(p),Y.current?.clear(),Y.current?.focus();const ee=q.current;ee&&s.sendInput(ee,"\f").catch(xe=>{T(xe instanceof Error?xe.message:"Failed to refresh prompt")})},[x,p,T,s]),z=i.useCallback(ee=>{if(!ee)return;let xe=ee,fe=!1;if(O&&ee.length>0){const Se=ee[0];if(Se.length===1&&/[a-zA-Z]/.test(Se)){const Le=Se.toUpperCase();(O==="ctrl"||O==="cmd")&&(xe=String.fromCharCode(Le.charCodeAt(0)&31),fe=!0)}fe||(fe=!0)}const Oe=q.current;Oe&&(s.sendInput(Oe,xe).catch(Se=>{T(Se instanceof Error?Se.message:"Failed to send input")}),fe&&(U(null),Y.current?.focus()))},[O,U,s]),G=i.useCallback((ee,xe)=>{const fe=q.current;fe&&s.resize({sessionId:fe,cols:ee,rows:xe}).catch(()=>{})},[s]),ge=i.useCallback(ee=>{U(xe=>xe===ee?null:ee),Y.current?.focus()},[U]),oe=i.useCallback(ee=>{const xe=K0(ee,O);xe&&(z(xe),U(null),Y.current?.focus())},[O,z,U]);i.useEffect(()=>{if(!n||!O||!D)return;const ee=xe=>{if(xe.repeat)return;const fe=xe.key;if(!fe||fe==="Control"||fe==="Meta"||fe==="Alt"||fe==="Shift")return;const Oe=fe.length===1?fe.toLowerCase():fe,Se=xe.code??"",Le=Se.startsWith("Key")&&Se.length===4?Se.slice(3).toUpperCase():null,pe=fe.length===1&&/[a-zA-Z]/.test(fe)?fe.toUpperCase():Le,it={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(Oe in it){xe.preventDefault(),xe.stopPropagation(),oe(it[Oe]);return}if(O==="ctrl"&&pe&&pe.length===1&&pe>="A"&&pe<="Z"){const xt=String.fromCharCode(pe.charCodeAt(0)&31);xe.preventDefault(),xe.stopPropagation(),z(xt),U(null),Y.current?.focus()}};return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[O,oe,z,n,U,D]);const me=i.useMemo(()=>{const ee=Kr[Jo].stack;if(typeof window>"u")return(Kr[t]??Kr[Jo]).stack;const fe=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return fe&&fe.trim().length>0?fe.trim():(Kr[t]??Kr[Jo]).stack??ee},[t]),Ne=i.useMemo(()=>W0(r),[r]),Ce=i.useMemo(()=>`${p??"no-dir"}::${D??"pending"}`,[p,D]);i.useEffect(()=>{if(!K)return;const ee=Y.current;if(!ee)return;const xe=()=>{ee.fit()};if(typeof window<"u"){const fe=window.requestAnimationFrame(()=>{xe(),ee.focus()}),Oe=[220,400].map(Se=>window.setTimeout(xe,Se));return()=>{window.cancelAnimationFrame(fe),Oe.forEach(Se=>window.clearTimeout(Se))}}xe()},[K,Ce,D]);const Be=E?.includes("Reconnecting"),V=E?Be?e.jsx(Th,{size:20,className:"text-amber-400"}):e.jsx(Ht,{size:20,className:"text-destructive"}):D&&!S&&!Q?e.jsx(Bo,{size:20,className:"text-emerald-400"}):S||Q?e.jsx(Oi,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(Oi,{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:$,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const J=!D||S||Q;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:[V,e.jsxs(Ie,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:B,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(Xs,{size:16}),"Clear"]}),e.jsxs(Ie,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:$,disabled:Q,title:"Restart terminal session",type:"button",children:[e.jsx(Fs,{size:16,className:_((S||Q)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>oe("esc"),disabled:J,children:"Esc"}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("tab"),disabled:J,children:[e.jsx(Zl,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:O==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ge("ctrl"),disabled:J,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:O==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>ge("cmd"),disabled:J,children:[e.jsx(an,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-up"),disabled:J,children:[e.jsx(co,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-left"),disabled:J,children:[e.jsx(Fu,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-down"),disabled:J,children:[e.jsx(Fn,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("arrow-right"),disabled:J,children:[e.jsx(Zl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ie,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>oe("enter"),disabled:J,children:[e.jsx(Zn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Ne.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:K?n?e.jsx(rl,{ref:ee=>{Y.current=ee},sessionKey:Ce,chunks:C,onInput:z,onResize:G,theme:Ne,fontFamily:me,fontSize:$d,enableTouchScroll:o},Ce):e.jsx(gt,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(rl,{ref:ee=>{Y.current=ee},sessionKey:Ce,chunks:C,onInput:z,onResize:G,theme:Ne,fontFamily:me,fontSize:$d,enableTouchScroll:o},Ce)}):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}),I&&e.jsx(Ie,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:R,disabled:Q,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},Y0=s=>s.slice().sort((r,t)=>r.type!==t.type?r.type==="directory"?-1:1:r.name.localeCompare(t.name)),Dr=s=>s.replace(/\\/g,"/"),X0=new Set(["node_modules"]),J0=s=>X0.has(s),Z0=s=>{const r=Dr(s);return r==="node_modules"||r.endsWith("/node_modules")||r.includes("/node_modules/")},ej=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=he(),{currentDirectory:n}=vt(),o=s?t.get(s)??void 0:void 0,l=r.find(c=>c.id===s)?.directory;return o?.path??l??n??""},tj=2e5,Ld=2e5,sj=new Set(["js","jsx","ts","tsx","mjs","cjs","mts","cts","html","htm","xhtml","css","scss","sass","less","styl","stylus","vue","svelte","astro","sh","bash","zsh","fish","ps1","psm1","bat","cmd","py","pyw","pyx","pxd","pxi","rb","erb","rake","gemspec","php","phtml","php3","php4","php5","phps","java","kt","kts","scala","sc","groovy","gradle","c","h","cpp","cc","cxx","hpp","hxx","hh","m","mm","cs","fs","fsx","fsi","go","rs","swift","dart","lua","pl","pm","pod","r","R","rmd","jl","hs","lhs","ex","exs","erl","hrl","clj","cljs","cljc","edn","lisp","cl","el","scm","ss","rkt","ml","mli","re","rei","nim","zig","v","cr","main.kts","sql","psql","plsql","graphql","gql","sol","asm","s","S","mk","nix","tf","tfvars","pp","ansible"]),rj=new Set(["json","jsonc","json5","jsonl","ndjson","geojson","yaml","yml","toml","xml","xsl","xslt","xsd","dtd","plist","ini","cfg","conf","config","env","properties","csv","tsv","lock"]),nj=new Set(["png","jpg","jpeg","gif","svg","webp","ico","icns","bmp","tiff","tif","psd","ai","eps","raw","cr2","nef","heic","heif","avif","jxl"]),oj=new Set(["md","mdx","markdown","mdown","mkd","txt","text","rtf","doc","docx","odt","pdf","rst","adoc","asciidoc","org","tex","latex","bib"]),Bd=s=>{const r=s?.toLowerCase();return r&&sj.has(r)?e.jsx(_s,{className:"h-4 w-4 flex-shrink-0 text-blue-500"}):r&&rj.has(r)?e.jsx(_s,{className:"h-4 w-4 flex-shrink-0 text-yellow-500"}):r&&nj.has(r)?e.jsx(mr,{className:"h-4 w-4 flex-shrink-0 text-green-500"}):r&&oj.has(r)?e.jsx(eo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(eo,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})},aj=()=>{const{files:s,runtime:r}=kr(),{currentTheme:t}=Wr(),n=i.useMemo(()=>Ll(t),[t]),{isMobile:o}=$t(),a=ej(),l=Dr(a),c=Ia(je=>je.searchFiles),[d,u]=i.useState(""),m=Oa(d,200),f=i.useRef(null),[p,g]=i.useState(!1),[y,h]=i.useState(o),[j,b]=i.useState(new Set),[v,w]=i.useState({}),N=i.useRef(new Set),x=i.useRef(new Set),[k,A]=i.useState([]),[C,M]=i.useState(!1),[S,D]=i.useState(null),[E,T]=i.useState(""),[I,P]=i.useState(!1),[O,U]=i.useState(null),[Q,W]=i.useState(""),[L,H]=i.useState(null),[q,X]=i.useState(""),Y=i.useRef(!1),re=i.useRef(null),K=he(je=>je.sendMessage),ae=he(je=>je.currentSessionId),{currentProviderId:F,currentModelId:$,currentAgentName:R,currentVariant:B}=at(),z=wt(je=>je.getSessionAgentSelection),G=wt(je=>je.getAgentModelForSession),ge=wt(je=>je.getAgentModelVariantForSession),oe=$e(je=>je.setActiveMainTab),{inputBarOffset:me,isKeyboardOpen:Ne}=$e(),Ce=i.useCallback((je,ze)=>{if(ze&&L){const Ze=Math.min(L.start,je),Ye=Math.max(L.end,je);H({start:Ze,end:Ye})}else H({start:je,end:je})},[L]),Be=i.useCallback((je,ze)=>{if(ze.preventDefault(),ze.shiftKey&&L){Ce(je,!0);return}Y.current=!0,re.current=je,H({start:je,end:je})},[Ce,L]),V=i.useCallback(je=>{if(!Y.current||re.current===null)return;const ze=Math.min(re.current,je),Ze=Math.max(re.current,je);H({start:ze,end:Ze})},[]),J=i.useCallback(()=>{Y.current=!1},[]),ee=i.useCallback(je=>{if(L){const ze=Math.min(L.start,L.end,je),Ze=Math.max(L.start,L.end,je);if(je<L.start||je>L.end){H({start:ze,end:Ze});return}}H({start:je,end:je})},[L]);i.useEffect(()=>{const je=()=>{Y.current=!1};return document.addEventListener("mouseup",je),()=>document.removeEventListener("mouseup",je)},[]),i.useEffect(()=>{H(null),X("")},[S?.path]),i.useEffect(()=>{if(!L)return;const je=Ze=>{const Ye=Ze.target;document.querySelector("[data-comment-ui]")?.contains(Ye)||Ye.closest("[data-line-number]")||Ye.closest("[data-sonner-toast]")||Ye.closest("[data-sonner-toaster]")||(H(null),X(""))},ze=setTimeout(()=>{document.addEventListener("click",je)},100);return()=>{clearTimeout(ze),document.removeEventListener("click",je)}},[L]);const xe=i.useCallback((je,ze)=>{const Ze=je.split(`
122
- `),Ye=Math.max(1,ze.start),mt=Math.min(Ze.length,ze.end);return Ye>mt?"":Ze.slice(Ye-1,mt).join(`
123
- `)},[]),fe=i.useCallback(async()=>{if(!L||!q.trim()||!S)return;if(!ae){te.error("Select a session to send comment");return}const je=z(ae)||R,ze=je?G(ae,je):null,Ze=ze?.providerId||F,Ye=ze?.modelId||$;if(!Ze||!Ye){te.error("Select a model to send comment");return}const mt=je&&Ze&&Ye?ge(ae,je,Ze,Ye)??B:B,ye=xe(E,L),ie=fr(S.path)||"text",de=S.name,We=L.start,Ge=L.end,bt=`Comment on \`${de}\` lines ${We}-${Ge}:
124
- \`\`\`${ie}
125
- ${ye}
126
- \`\`\`
127
-
128
- ${q}`;X(""),H(null),oe("chat");try{await K(bt,Ze,Ye,je,void 0,void 0,void 0,mt)}catch(Z){console.error("Failed to send comment",Z)}},[L,q,S,E,ae,F,$,R,B,xe,K,oe,z,G,ge]),Oe=i.useCallback((je,ze)=>{const Ze=ze.filter(Ye=>Ye&&typeof Ye.name=="string"&&Ye.name.length>0).filter(Ye=>!Ye.name.startsWith(".")).filter(Ye=>!J0(Ye.name)).map(Ye=>{const mt=Ye.name,ye=Dr(Ye.path||`${je}/${mt}`),ie=Ye.isDirectory?"directory":"file",de=ie==="file"&&mt.includes(".")?mt.split(".").pop()?.toLowerCase():void 0;return{name:mt,path:ye,type:ie,extension:de}});return Y0(Ze)},[]),Se=i.useCallback(async je=>{const ze=Dr(je.trim());if(ze&&!(N.current.has(ze)||x.current.has(ze))){x.current=new Set(x.current),x.current.add(ze);try{let Ze;r.isDesktop?Ze=(await s.listDirectory(ze,{respectGitignore:!0})).entries.map(ye=>({name:ye.name,path:ye.path,isDirectory:ye.isDirectory})):Ze=(await Ee.listLocalDirectory(ze,{respectGitignore:!0})).map(ye=>({name:ye.name,path:ye.path,isDirectory:ye.isDirectory}));const Ye=Oe(ze,Ze);N.current=new Set(N.current),N.current.add(ze),w(mt=>({...mt,[ze]:Ye}))}catch{w(Ze=>({...Ze,[ze]:Ze[ze]??[]}))}finally{x.current=new Set(x.current),x.current.delete(ze)}}},[s,Oe,r.isDesktop]),Le=i.useCallback(async()=>{const je=Dr(a.trim());je&&(N.current=new Set,x.current=new Set,b(new Set),w({}),await Se(je))},[a,Se]);i.useEffect(()=>{a&&(Le(),D(null),T(""),U(null),W(""),g(!1))},[a,Le]);const pe=i.useCallback((je,ze)=>{const Ze=je.trim().toLowerCase();if(!Ze)return 0;const Ye=ze.toLowerCase();let mt=0,ye=-1,ie=0;for(let de=0;de<Ze.length;de+=1){const We=Ze[de];if(!We||We===" ")continue;const Ge=Ye.indexOf(We,ye+1);if(Ge===-1)return null;const bt=Ge-ye-1;if(bt===0?ie+=1:ie=0,mt+=10,mt+=Math.max(0,18-Ge),mt-=Math.max(0,bt),Ge===0)mt+=12;else{const Z=Ye[Ge-1];(Z==="/"||Z==="_"||Z==="-"||Z==="."||Z===" ")&&(mt+=10)}mt+=ie>0?12:0,ye=Ge}return mt+=Math.max(0,24-Math.round(Ye.length/3)),mt},[]);i.useEffect(()=>{if(!a){A([]),M(!1);return}const je=m.trim();if(!je){A([]),M(!1);return}const ze=je.toLowerCase();let Ze=!1;return M(!0),c(a,je,150).then(Ye=>{if(Ze)return;const ye=Ye.filter(de=>!Z0(de.path)).map(de=>{const We=de.relativePath||de.name||de.path,Ge=pe(ze,We);return Ge===null?null:{hit:de,score:Ge,labelLength:We.length}}).filter(Boolean);ye.sort((de,We)=>We.score-de.score||de.labelLength-We.labelLength||de.hit.path.localeCompare(We.hit.path));const ie=ye.map(({hit:de})=>({name:de.name,path:Dr(de.path),type:"file",extension:de.extension,relativePath:de.relativePath}));A(ie)}).catch(()=>{Ze||A([])}).finally(()=>{Ze||M(!1)}),()=>{Ze=!0}},[a,m,pe,c]);const it=i.useCallback(async je=>{if(s.readFile)return(await s.readFile(je)).content??"";const ze=await fetch(`/api/fs/read?path=${encodeURIComponent(je)}`);if(!ze.ok){const Ze=await ze.json().catch(()=>({error:ze.statusText}));throw new Error(Ze.error||"Failed to read file")}return ze.text()},[s]),xt=i.useCallback(async je=>{D(je),U(null),W("");const ze=io(je.path);o&&g(!0);const Ze=je.path.toLowerCase().endsWith(".svg");if(r.isDesktop&&ze&&!Ze){T(""),P(!0);return}if(!r.isDesktop&&ze&&!Ze){T(""),P(!1);return}P(!0);try{const Ye=await it(je.path);T(Ye)}catch(Ye){T(""),U(Ye instanceof Error?Ye.message:"Failed to read file")}finally{P(!1)}},[o,it,r.isDesktop]),Mt=i.useCallback(async je=>{const ze=Dr(je);b(Ze=>{const Ye=new Set(Ze);return Ye.has(ze)?Ye.delete(ze):Ye.add(ze),Ye}),N.current.has(ze)||await Se(ze)},[Se]),De=i.useCallback((je,ze)=>(v[je]??[]).map(Ye=>{const mt=Ye.type==="directory",ye=mt&&j.has(Ye.path),ie=S?.path===Ye.path,de=mt&&x.current.has(Ye.path);return e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:()=>{mt?Mt(Ye.path):xt(Ye)},className:_("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",ie?"bg-accent/70":"hover:bg-accent/40"),style:{paddingLeft:`${8+ze*12}px`},children:[mt?de?e.jsx(rs,{className:"h-4 w-4 flex-shrink-0 animate-spin"}):ye?e.jsx(Fh,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):e.jsx(Rh,{className:"h-4 w-4 flex-shrink-0 text-primary/60"}):Bd(Ye.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:Ye.path,children:Ye.name})]}),mt&&ye&&e.jsx("ul",{className:"flex flex-col gap-1",children:De(Ye.path,ze+1)})]},Ye.path)}),[v,j,xt,S?.path,Mt]),ne=S?.path&&fr(S.path)||"text",rt=E.length>Ld?`${E.slice(0,Ld)}
129
-
130
- … truncated …`:E,be=rt.length<=tj,ke=!!(S?.path&&io(S.path)),Qe=!!(S?.path&&S.path.toLowerCase().endsWith(".svg")),tt=i.useMemo(()=>{if(!S?.path)return"";const je=Dr(S.path);if(l&&je.startsWith(l)){const ze=je.slice(l.length);return ze.startsWith("/")?ze.slice(1):ze}return je},[S?.path,l]),He=!!(S&&(!ke||Qe)&&E.length>0),Re=S?.path&&ke?r.isDesktop?Qe?`data:${Gi(S.path)};utf8,${encodeURIComponent(E)}`:Q:Qe?`data:${Gi(S.path)};utf8,${encodeURIComponent(E)}`:`/api/fs/raw?path=${encodeURIComponent(S.path)}`:"",nt=i.useCallback(({rows:je,stylesheet:ze,useInlineStyles:Ze})=>{const Ye=Math.max(3,String(je.length).length+1);return e.jsx("div",{"data-code-viewer":!0,children:je.map((mt,ye)=>{const ie=ye+1,de=L!==null&&ie>=L.start&&ie<=L.end;return e.jsxs("div",{"data-line-row":ie,"data-selected":de?"true":void 0,onMouseEnter:o?void 0:()=>V(ie),style:{display:"flex",alignItems:"flex-start",lineHeight:"1.5rem",position:"relative",backgroundColor:de?"color-mix(in srgb, var(--accent) 70%, transparent)":void 0},children:[e.jsx("span",{"data-line-number":ie,onMouseDown:o?void 0:We=>Be(ie,We),onMouseUp:o?void 0:J,onClick:o?()=>ee(ie):void 0,style:{width:`calc(${Ye}ch + 0.75rem + 0.75rem)`,flexShrink:0,paddingLeft:"0.75rem",paddingRight:"1.75ch",textAlign:"right",color:"hsl(var(--muted-foreground))",opacity:.35,fontSize:"0.8em",lineHeight:"1.5rem",userSelect:"none",WebkitUserSelect:"none",MozUserSelect:"none",msUserSelect:"none",cursor:"pointer",touchAction:"manipulation"},children:ie}),e.jsx("code",{style:{flex:1,minWidth:0,display:"block",whiteSpace:y?"pre-wrap":"pre",overflowWrap:y?"break-word":"normal",tabSize:2,paddingRight:"0.75rem",userSelect:L?"none":void 0,WebkitUserSelect:L?"none":void 0},children:_h({node:mt,stylesheet:ze,useInlineStyles:Ze,key:ye})})]},ye)})})},[y,L,o,Be,V,J,ee]);i.useEffect(()=>{let je=!1;return(async()=>{if(!r.isDesktop||!S?.path||!ke||Qe){W("");return}U(null);try{if(s.readFileBinary){const ye=await s.readFileBinary(S.path);je||W(ye.dataUrl);return}const Ye=(await as(()=>import("./vendor-.bun-CqCnPJev.js").then(ye=>ye.cz),__vite__mapDeps([0,1]))).convertFileSrc;if(!Ye)return;const mt=Ye(S.path,"asset");je||W(mt)}catch(Ze){je||(W(""),U(Ze instanceof Error?Ze.message:"Failed to read file"))}finally{je||P(!1)}})(),()=>{je=!0}},[s,ke,Qe,r.isDesktop,S?.path]);const yt=()=>!L||!S?null:e.jsx("div",{"data-comment-ui":!0,className:"flex flex-col items-center gap-2 px-4",style:{width:"min(100vw - 1rem, 42rem)"},children:e.jsxs("div",{className:"w-full rounded-xl border bg-background flex flex-col relative shadow-lg",style:{borderColor:"var(--primary)"},children:[e.jsx(Ss,{value:q,onChange:je=>{X(je.target.value);const ze=je.target;ze.style.height="auto";const Ye=20*5+8;ze.style.height=`${Math.min(ze.scrollHeight,Ye)}px`},placeholder:"Type your comment...",className:"min-h-[28px] max-h-[108px] resize-none border-0 px-3 pt-2 pb-1 shadow-none rounded-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 dark:bg-transparent focus-visible:outline-none overflow-y-auto",autoFocus:!o,rows:1,onKeyDown:je=>{je.key==="Enter"&&(je.metaKey||je.ctrlKey)&&(je.preventDefault(),fe()),je.key==="Escape"&&(je.preventDefault(),H(null),X(""))}}),e.jsxs("div",{className:"px-2.5 py-1 flex items-center justify-between gap-x-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[S.name,":",L.start,"-",L.end]}),e.jsxs("div",{className:"flex items-center gap-x-1.5",children:[!o&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Yt(),"+⏎"]}),e.jsx("button",{type:"button",onTouchEnd:je=>{q.trim()&&(je.preventDefault(),fe())},onClick:()=>{o||fe()},disabled:!q.trim(),className:_("h-7 w-7 flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",q.trim()?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send comment",children:e.jsx(Sa,{className:"h-[18px] w-[18px]"})})]})]})]})}),ct=e.jsxs("div",{className:"relative flex h-full min-h-0 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 px-3 py-1.5 flex-shrink-0",children:[o&&p&&e.jsx("button",{type:"button",onClick:()=>g(!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(Ru,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"typography-ui-label font-medium truncate",children:S?S.name:"Select a file"}),S&&!o&&e.jsx("div",{className:"typography-meta text-muted-foreground truncate",title:tt,children:tt})]}),e.jsxs("div",{className:"flex items-center gap-0",children:[S&&!ke&&e.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>h(!y),className:_("h-5 w-5 p-0 transition-opacity",y?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"),title:y?"Disable line wrap":"Enable line wrap",children:e.jsx(wu,{className:"size-4"})}),He&&e.jsxs(Ie,{variant:"ghost",size:"sm",onClick:async()=>{try{await navigator.clipboard.writeText(E),te.success("Copied")}catch{te.error("Copy failed")}},className:"gap-1",children:[e.jsx(ku,{className:"h-4 w-4"}),"Copy"]})]})]}),e.jsx("div",{className:"flex-1 min-h-0 relative",children:e.jsx(gt,{outerClassName:"h-full",className:"h-full",children:S?I?e.jsxs("div",{className:"p-3 flex items-center gap-2 typography-ui text-muted-foreground",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Loading…"]}):O?e.jsx("div",{className:"p-3 typography-ui text-[color:var(--status-error)]",children:O}):ke?e.jsx("div",{className:"flex h-full items-center justify-center p-3",children:e.jsx("img",{src:Re,alt:S?.name??"Image",className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border/30 bg-primary/10"})}):e.jsx("div",{className:"py-3",children:e.jsx(or,{language:be?ne:"text",style:n,PreTag:"div",renderer:nt,customStyle:{margin:0,padding:0,background:"transparent",fontSize:"var(--text-code)",lineHeight:"1.5rem",overflowX:"auto",overflowY:"visible",whiteSpace:"normal"},codeTagProps:{style:{fontStyle:"normal",lineHeight:"1.5rem"}},children:rt},L?`${L.start}-${L.end}`:"none")}):e.jsx("div",{className:"p-3 typography-ui text-muted-foreground",children:"Pick a file from the tree."})})}),L&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-50 flex flex-col justify-end",style:{paddingBottom:o?"var(--oc-keyboard-inset, 0px)":"0px"},children:e.jsx("div",{className:_("pointer-events-auto pb-2 transition-none w-full flex justify-center",o&&Ne?"ios-keyboard-safe-area":"bottom-safe-area"),style:{marginBottom:o&&!Ne&&me>0?`${me}px`:"16px"},"data-keyboard-avoid":"true",children:yt()})})]}),It=!!(l&&v[l]),Tt=e.jsxs("section",{className:_("flex min-h-0 flex-col overflow-hidden",o?"h-full w-full bg-background":"h-full rounded-xl border border-border/60 bg-background/70"),children:[e.jsxs("div",{className:_("flex items-center gap-2 py-2",o?"px-3":"px-2"),children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(lr,{className:"pointer-events-none absolute left-2 top-2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{ref:f,value:d,onChange:je=>u(je.target.value),placeholder:"Search files…",className:"h-8 pl-8 pr-8 typography-meta"}),d.trim().length>0&&e.jsx("button",{type:"button","aria-label":"Clear search",className:"absolute right-2 top-2 inline-flex h-4 w-4 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{u(""),f.current?.focus()},children:e.jsx(Ht,{className:"h-4 w-4"})})]}),e.jsx(Ie,{variant:"ghost",size:"sm",onClick:()=>{Le()},className:"h-8 w-8 p-0 flex-shrink-0",children:e.jsx(jr,{className:"h-4 w-4"})})]}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:_("py-2",o?"px-3":"px-2"),children:e.jsx("ul",{className:"flex flex-col",children:C?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Searching…"]}):k.length>0?k.map(je=>{const ze=S?.path===je.path;return e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>{xt(je)},className:_("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors",ze?"bg-accent/70":"hover:bg-accent/40"),children:[Bd(je.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",style:{direction:"rtl",textAlign:"left"},title:je.path,children:je.relativePath??je.path})]})},je.path)}):It?De(l,0):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading…"})})})]});return e.jsx("div",{className:"flex h-full min-h-0 overflow-hidden bg-background",children:o?p?ct:Tt:e.jsxs("div",{className:"flex flex-1 min-h-0 min-w-0 gap-3 px-3 pb-3 pt-2",children:[e.jsx("div",{className:"w-72 flex-shrink-0 min-h-0 overflow-hidden",children:Tt}),e.jsx("div",{className:"flex-1 min-h-0 min-w-0 overflow-hidden rounded-xl border border-border/60 bg-background",children:ct})]})})},kf=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:ll},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:dr},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:an},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:Pu},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:to},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:zt},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:en}],ij={},lj={},cj={};kf.forEach(s=>{ij[s.id]=s.label,lj[s.id]=s.description,cj[s.id]=s});const dj=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",uj=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},zd=s=>{const r=uj(s);if(r.length===0)return;const t={};for(const l of r)l.permission&&((t[l.permission]||={})[l.pattern]=l.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 l of o){const c=t[l],d=Object.keys(c);if(d.length===1&&d[0]==="*"&&l!=="*"){const u=c["*"],m=dj(l);if(n){if(u===n)continue}else if(u===m)continue;a[l]=u}else l==="*"&&d.length===1&&d[0]==="*"?a[l]=c["*"]:a[l]=c}return Object.keys(a).length>0?a:void 0},mj=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedAgentName:a,agents:l,setSelectedAgent:c,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=zr(),{setSidebarOpen:p}=$e(),{isMobile:g}=$t(),[y,h]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const b=y?"bg-transparent":j?"bg-background":"bg-sidebar",v=()=>{const E="new-agent";let T=E,I=1;for(;l.some(P=>P.name===T);)T=`${E}-${I}`,I++;d({name:T,scope:"user"}),c(T),s?.(),g&&p(!1)},w=async E=>{if(Qr(E)){te.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${E.name}"?`)&&(await m(E.name)?te.success(`Agent "${E.name}" deleted successfully`):te.error("Failed to delete agent"))},N=async E=>{Qr(E)&&window.confirm(`Are you sure you want to reset agent "${E.name}" to its default configuration?`)&&(await m(E.name)?te.success(`Agent "${E.name}" reset to default`):te.error("Failed to reset agent"))},x=E=>{const T=E.name;let I=1,P=`${T}-copy`;for(;l.some(W=>W.name===P);)I++,P=`${T}-copy-${I}`;const O=E,U=E.model?.providerID&&E.model?.modelID?`${E.model.providerID}/${E.model.modelID}`:null,Q=E;d({name:P,scope:O.scope||"user",description:E.description,model:U,temperature:E.temperature,top_p:E.topP,prompt:E.prompt,mode:E.mode,permission:zd(E.permission),disable:Q.disable}),c(P),g&&p(!1)},k=E=>{o(E.name),t(E)},A=async()=>{if(!r)return;const E=n.trim().replace(/\s+/g,"-");if(!E){te.error("Agent name is required");return}if(E===r.name){t(null);return}if(l.some(O=>O.name===E)){te.error("An agent with this name already exists");return}const T=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,I=r;await u({name:E,description:r.description,model:T,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:zd(r.permission),disable:I.disable,scope:I.scope})?await m(r.name)?(te.success(`Agent renamed to "${E}"`),c(E)):te.error("Failed to remove old agent after rename"):te.error("Failed to rename agent"),t(null)},C=E=>{switch(E){case"primary":return e.jsx(sn,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(Ou,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(_u,{className:"h-3 w-3 text-primary"});default:return null}},M=l.filter(E=>!em(E)),S=M.filter(Qr),D=M.filter(E=>!Qr(E));return e.jsxs("div",{className:_("flex h-full flex-col",b),children:[e.jsx("div",{className:_("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 ",M.length]}),e.jsx(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Xt,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:M.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(so,{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:[S.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"}),S.map(E=>e.jsx(Wd,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),s?.(),g&&p(!1)},onReset:()=>N(E),onDuplicate:()=>x(E),getAgentModeIcon:C},E.name))]}),D.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"}),D.map(E=>e.jsx(Wd,{agent:E,isSelected:a===E.name,onSelect:()=>{c(E.name),s?.(),g&&p(!1)},onRename:()=>k(E),onDelete:()=>w(E),onDuplicate:()=>x(E),getAgentModeIcon:C},E.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:E=>!E&&t(null),children:e.jsxs(fs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Agent"}),e.jsxs(Ms,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:E=>o(E.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:E=>{E.key==="Enter"&&A()}}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:A,children:"Rename"})]})]})})]})},Wd=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:l,getAgentModeIcon:c})=>{const d=s;return e.jsx("div",{className:_("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}),c(s.mode),(d.scope||Qr(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:Qr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(uo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:u=>{u.stopPropagation(),l()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Fs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Et,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Ps({className:s,variant:r,...t}){return e.jsx(Ie,{variant:r,size:"sm",className:_("h-6 px-2 text-xs",s),...t})}const fj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),pj=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=fj.format(s);return r.endsWith(".0")?r.slice(0,-2):r},$a=({providerId:s,modelId:r,onChange:t,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:l}=at(),c=$e(Y=>Y.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=$e(),{favoriteModelsList:f,recentModelsList:p}=Rl(),{isMobile:g}=$t(),y=c||g,[h,j]=i.useState(!1),[b,v]=i.useState(new Set),[w,N]=i.useState(!1),[x,k]=i.useState(""),[A,C]=i.useState(0),M=i.useRef([]),S=i.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),D=i.useMemo(()=>S?a.filter(Y=>S.has(String(Y.id))):a,[a,S]),E=()=>j(!1),T=Y=>{v(re=>{const K=new Set(re);return K.has(Y)?K.delete(Y):K.add(Y),K})};i.useEffect(()=>{w||(k(""),C(0))},[w]),i.useEffect(()=>{C(0)},[x]);const I=Y=>{const re=Y?.name||Y?.id||"",K=String(re);return K.length>40?K.substring(0,37)+"...":K},P=(Y,re)=>{const K=`${Y}/${re}`;return l.get(K)},O=(Y,re)=>{t(Y,re),Y&&re&&m(Y,re),N(!1)},U=(Y,re)=>{if(!x.trim())return!0;const K=x.toLowerCase();return Y.toLowerCase().includes(K)||re.toLowerCase().includes(K)},Q=(Y,re,K,ae,F,$)=>{const R=P(re,K),B=pj(R?.limit?.context),z=s===re&&r===K,G=u(re,K);return e.jsxs("div",{ref:ge=>{M.current[F]=ge},className:_("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",$?"bg-accent":"hover:bg-accent/50"),onClick:()=>O(re,K),onMouseEnter:()=>C(F),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:I(Y)}),B?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:B}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[z&&e.jsx(_t,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:ge=>{ge.preventDefault(),ge.stopPropagation(),d(re,K)},className:_("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",G?"text-yellow-500":"text-muted-foreground"),"aria-label":G?"Unfavorite":"Favorite",title:G?"Remove from favorites":"Add to favorites",children:G?e.jsx(yr,{className:"h-3.5 w-3.5"}):e.jsx(wn,{className:"h-3.5 w-3.5"})})]})]},`${ae}-${re}-${K}`)},W=f.filter(({model:Y,providerID:re})=>{if(S&&!S.has(re))return!1;const ae=a.find($=>$.id===re)?.name||re,F=I(Y);return U(F,ae)}),L=p.filter(({model:Y,providerID:re})=>{if(S&&!S.has(re))return!1;const ae=a.find($=>$.id===re)?.name||re,F=I(Y);return U(F,ae)}),H=D.map(Y=>{const K=(Array.isArray(Y.models)?Y.models:[]).filter(ae=>{const F=I(ae);return U(F,Y.name||Y.id||"")});return{...Y,models:K}}).filter(Y=>Y.models.length>0),q=W.length>0||L.length>0||H.length>0,X=()=>y?e.jsx(ws,{open:h,onClose:E,title:"Select Model",children:e.jsxs("div",{className:"space-y-1",children:[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:"Favorites"}),e.jsx("div",{className:"border-t border-border/20",children:f.map(({model:Y,providerID:re,modelID:K})=>{const ae=re===s&&K===r;return e.jsxs("div",{className:_("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ae?"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:()=>{O(re,K),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:I(Y)})]})}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),d(re,K)},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(yr,{className:"h-4 w-4"})})]},`fav-mobile-${re}-${K}`)})})]}),p.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:p.map(({model:Y,providerID:re,modelID:K})=>{const ae=re===s&&K===r;return e.jsxs("div",{className:_("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",ae?"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:()=>{O(re,K),E()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:I(Y)})]})}),e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),d(re,K)},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(wn,{className:"h-4 w-4"})})]},`recent-mobile-${re}-${K}`)})})]}),D.map(Y=>{const re=Array.isArray(Y.models)?Y.models:[];if(re.length===0)return null;const K=Y.id===s,ae=b.has(Y.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:()=>T(Y.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cs,{providerId:Y.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y.name}),K&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ae?e.jsx(Ft,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Rs,{className:"h-3 w-3 text-muted-foreground"})]}),ae&&e.jsx("div",{className:"border-t border-border/20",children:re.map(F=>{const $=Y.id===s&&F.id===r;return e.jsxs("div",{className:_("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",$?"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:()=>{O(Y.id,F.id),E()},children:e.jsx("span",{className:"font-medium truncate",children:I(F)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:R=>{R.preventDefault(),R.stopPropagation(),d(Y.id,F.id)},className:_("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(Y.id,F.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(Y.id,F.id)?"Unfavorite":"Favorite",children:u(Y.id,F.id)?e.jsx(yr,{className:"h-4 w-4"}):e.jsx(wn,{className:"h-4 w-4"})}),$&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},F.id)})})]},Y.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:()=>{O("",""),E()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[y?e.jsxs("button",{type:"button",onClick:()=>j(!0),className:_("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(cs,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(xr,{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(Ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(qt,{open:w,onOpenChange:N,children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:_("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(cs,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(xr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(xr,{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(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Qt,{className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",align:"start",children:(()=>{const Y=[];W.forEach(({model:F,providerID:$,modelID:R})=>{Y.push({model:F,providerID:$,modelID:R,section:"fav"})}),L.forEach(({model:F,providerID:$,modelID:R})=>{Y.push({model:F,providerID:$,modelID:R,section:"recent"})}),H.forEach(F=>{F.models.forEach($=>{Y.push({model:$,providerID:F.id,modelID:$.id,section:"provider"})})});const re=Y.length,K=F=>{if(F.key==="ArrowDown"){F.preventDefault(),F.stopPropagation();const $=(A+1)%Math.max(1,re);C($),setTimeout(()=>{M.current[$]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(F.key==="ArrowUp"){F.preventDefault(),F.stopPropagation();const $=(A-1+Math.max(1,re))%Math.max(1,re);C($),setTimeout(()=>{M.current[$]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(F.key==="Enter"){F.preventDefault(),F.stopPropagation();const $=Y[A];$&&O($.providerID,$.modelID)}else F.key==="Escape"&&(F.preventDefault(),F.stopPropagation(),N(!1))};let ae=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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(jt,{type:"text",placeholder:"Search models",value:x,onChange:F=>k(F.target.value),onKeyDown:K,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(gt,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:_("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>O("",""),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(_t,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(js,{}),!q&&x&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),W.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),W.map(({model:F,providerID:$,modelID:R})=>{const B=ae++;return Q(F,$,R,"fav",B,A===B)})]}),L.length>0&&e.jsxs(e.Fragment,{children:[W.length>0&&e.jsx(js,{}),e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(cr,{className:"h-4 w-4"}),"Recent"]}),L.map(({model:F,providerID:$,modelID:R})=>{const B=ae++;return Q(F,$,R,"recent",B,A===B)})]}),(W.length>0||L.length>0)&&H.length>0&&e.jsx(js,{}),H.map((F,$)=>e.jsxs(i.Fragment,{children:[$>0&&e.jsx(js,{}),e.jsxs(Ir,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(cs,{providerId:F.id,className:"h-4 w-4 flex-shrink-0"}),F.name]}),F.models.map(R=>{const B=ae++;return Q(R,F.id,R.id,"provider",B,A===B)})]},F.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"})]})})()})]}),X()]})},hj=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],wr=s=>s==="allow"||s==="ask"||s==="deny",gj=s=>{if(wr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(wr(r))return r}},xj=s=>{if(wr(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=gj(n);o!==void 0&&(r[t]=o)}return{entries:r}},yj=s=>{const r={...s},t=r["*"];return wr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},La=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",Zo=(s,r)=>r==="default"?La(s):r,Hd=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=Zo(n,r),l=La(n);if(!(wr(o)&&o!==l)){if(wr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const c=o,d=Object.keys(c),u=c["*"];if(u!==void 0&&u!==l)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},Nf=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},bj=s=>{const r=Nf(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,l]of Object.entries(t)){if(a==="*"){o[a]=l;continue}const c=La(a);if(n){if(l===n)continue}else if(l===c)continue;o[a]=l}return{entries:o}},vj=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:l}=zr();at();const c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[g,y]=i.useState(""),[h,j]=i.useState("subagent"),[b,v]=i.useState(""),[w,N]=i.useState(void 0),[x,k]=i.useState(void 0),[A,C]=i.useState(""),[M,S]=i.useState("default"),[D,E]=i.useState({}),[T,I]=i.useState(""),[P,O]=i.useState(!1),U=vt(B=>B.currentDirectory??null),[Q,W]=i.useState([]),L=ao(B=>B.permissions);i.useEffect(()=>{let B=!1;return(async()=>{const G=await Ee.listToolIds({directory:U});if(B)return;const ge=new Set(["write","patch","multiedit"]),oe=G.map(me=>typeof me=="string"?me.trim():"").filter(Boolean).filter(me=>me!=="*").filter(me=>me!=="invalid").filter(me=>!ge.has(me));W(Array.from(new Set(oe)).sort((me,Ne)=>me.localeCompare(Ne)))})(),()=>{B=!0}},[U]);const H=i.useMemo(()=>{const B=new Set;for(const z of o){const G=Nf(z.permission);if(G)for(const ge of G)ge.permission&&ge.permission!=="*"&&ge.permission!=="invalid"&&B.add(ge.permission)}for(const z of L.values())for(const G of z){const ge=G.permission?.trim();ge&&ge!=="invalid"&&B.add(ge)}for(const z of Q)B.add(z);return Array.from(B).sort((z,G)=>z.localeCompare(G))},[o,L,Q]),q=i.useCallback(B=>{const z=D[B];if(wr(z))return z;if(z&&typeof z=="object"&&!Array.isArray(z)){const G=z["*"];if(wr(G))return G}},[D]),X=i.useCallback(B=>{const z=D[B];return!z||typeof z!="object"||Array.isArray(z)?0:Object.keys(z).filter(ge=>ge!=="*").length},[D]),Y=i.useCallback((B,z)=>{B!=="*"&&E(G=>{const ge={...G},oe=ge[B],me=Zo(B,M),Ne=La(B),Ce=z===me&&z===Ne;if(oe&&typeof oe=="object"&&!Array.isArray(oe)){const Be={...oe};Be["*"]=z;const V=Object.keys(Be).filter(J=>J!=="*");return Ce&&V.length===0?(delete ge[B],ge):(ge[B]=Be,ge)}return Ce?(delete ge[B],ge):(ge[B]=z,ge)})},[M]),re=i.useCallback(B=>{E(z=>{if(!(B in z))return z;const G={...z};return delete G[B],G})},[]),K=i.useMemo(()=>{const B=Object.entries(D).filter(([z])=>z!=="*");return B.sort(([z],[G])=>z.localeCompare(G)),B},[D]),ae=i.useMemo(()=>{const B=new Set;for(const z of hj)B.add(z);for(const z of H)B.add(z);for(const z of Object.keys(D))B.delete(z);return Array.from(B).sort((z,G)=>z.localeCompare(G))},[H,D]),F=i.useCallback(B=>{const z=T.trim();if(!z)return;const G=Zo(z,M);if(B===G){const ge=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;te.message(`"${z}" already matches ${ge} (${G}).`),I("");return}Y(z,B),I("")},[T,Y,M]),$=i.useCallback(B=>B==="webfetch"?"WebFetch":B==="websearch"?"WebSearch":B==="codesearch"?"CodeSearch":B==="doom_loop"?"Doom Loop":B==="external_directory"?"External Directory":B==="todowrite"?"TodoWrite":B==="todoread"?"TodoRead":B.split(/[_-]+/g).filter(Boolean).map(z=>z.charAt(0).toUpperCase()+z.slice(1)).join(" "),[]);i.useEffect(()=>{I("");const B=z=>{const G=yj(z);S(G.defaultOverride),E(Hd(G.overrides,G.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),y(a.description||""),j(a.mode||"subagent"),v(a.model||""),N(a.temperature),k(a.top_p),C(a.prompt||"");const z=xj(a.permission);B(z.entries);return}if(c&&s===c.name){y(c.description||""),j(c.mode||"subagent"),c.model?.providerID&&c.model?.modelID?v(`${c.model.providerID}/${c.model.modelID}`):v(""),N(c.temperature),k(c.topP),C(c.prompt||"");const z=bj(c.permission);B(z.entries)}},[a,d,c,s]);const R=async()=>{const B=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!B){te.error("Agent name is required");return}if(d&&o.some(z=>z.name===B)){te.error("An agent with this name already exists");return}O(!0);try{const z=b.trim(),G={name:B,description:g.trim()||void 0,mode:h,model:z===""?null:z,temperature:w,top_p:x,prompt:A.trim()||void 0,permission:(()=>{const oe=Hd(D,M),me=M==="default"?oe:{"*":M,...oe},Ne=["doom_loop","external_directory"];for(const Be of Ne)if(!(Be in me)){const V=D[Be];wr(V)?me[Be]=V:me[Be]=Zo(Be,M)}return Object.keys(me).length===0?d?void 0:null:me})(),scope:d?f:void 0};let ge;d?(ge=await t(G),ge&&l(null)):ge=await n(B,G),ge?te.success(d?"Agent created successfully":"Agent updated successfully"):te.error(d?"Failed to create agent":"Failed to update agent")}catch(z){console.error("Error saving agent:",z);const G=z instanceof Error&&z.message?z.message:"An error occurred while saving";te.error(G)}finally{O(!1)}};return s?e.jsx(gt,{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(jt,{value:u,onChange:B=>m(B.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(ks,{value:f,onValueChange:B=>p(B),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{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(Os,{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(Ut,{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(ur,{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(Ss,{value:g,onChange:B=>y(B.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(Ps,{variant:h==="primary"?"default":"outline",onClick:()=>j("primary"),className:_("gap-2",h==="primary"?void 0:"text-foreground"),children:[e.jsx(sn,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Ps,{variant:h==="subagent"?"default":"outline",onClick:()=>j("subagent"),className:_("gap-2",h==="subagent"?void 0:"text-foreground"),children:[e.jsx(_u,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Ps,{variant:h==="all"?"default":"outline",onClick:()=>j("all"),className:_("gap-2",h==="all"?void 0:"text-foreground"),children:[e.jsx(Ou,{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($a,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(B,z)=>{v(B&&z?`${B}/${z}`:"")}})]}),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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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 z=Math.max(0,(w!==void 0?w:.7)-.1);N(parseFloat(z.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(qa,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:w!==void 0?w:"",onChange:B=>{const z=B.target.value;if(z===""){N(void 0);return}const G=parseFloat(z);!isNaN(G)&&G>=0&&G<=2&&N(G)},onBlur:B=>{const z=B.target.value;if(z!==""){const G=parseFloat(z);if(!isNaN(G)){const ge=Math.max(0,Math.min(2,G));N(parseFloat(ge.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 z=Math.min(2,(w!==void 0?w:.7)+.1);N(parseFloat(z.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(Xt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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 z=Math.max(0,(x!==void 0?x:.9)-.1);k(parseFloat(z.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(qa,{className:"h-3.5 w-3.5"})}),e.jsx(jt,{type:"text",inputMode:"decimal",value:x!==void 0?x:"",onChange:B=>{const z=B.target.value;if(z===""){k(void 0);return}const G=parseFloat(z);!isNaN(G)&&G>=0&&G<=1&&k(G)},onBlur:B=>{const z=B.target.value;if(z!==""){const G=parseFloat(z);if(!isNaN(G)){const ge=Math.max(0,Math.min(1,G));k(parseFloat(ge.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 z=Math.min(1,(x!==void 0?x:.9)+.1);k(parseFloat(z.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(Xt,{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(Ss,{value:A,onChange:B=>C(B.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(Ie,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>S("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(Ie,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>S("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ie,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>S("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ie,{size:"sm",variant:M==="deny"?"default":"outline",onClick:()=>S("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:M==="default"?"Uses OpenCode defaults unless overridden below.":"Applies to any permission without an explicit override below."}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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(ks,{value:T,onValueChange:I,children:[e.jsx(Ns,{className:"h-8 w-full sm:w-72",children:T?e.jsx("span",{className:"truncate",children:$(T)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(Cs,{children:ae.map(B=>e.jsx(Ut,{value:B,className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx("span",{children:$(B)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:B})]})},B))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ie,{size:"sm",variant:"outline",disabled:!T,onClick:()=>F("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Ie,{size:"sm",variant:"outline",disabled:!T,onClick:()=>F("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Ie,{size:"sm",variant:"outline",disabled:!T,onClick:()=>F("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),K.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:M==="default"?"No overrides configured. Everything follows OpenCode defaults.":`No overrides configured. All permissions default to "${M}" for this agent.`}):e.jsx("div",{className:"space-y-4",children:K.map(([B])=>{const z=q(B),G=X(B),ge=$(B);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:ge}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:B}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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']}),G>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",G," pattern rules preserved"]}):null]})})]})]}),e.jsxs(Ie,{size:"sm",variant:"outline",onClick:()=>re(B),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(qa,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ie,{size:"sm",variant:z==="allow"?"default":"outline",onClick:()=>Y(B,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ie,{size:"sm",variant:z==="ask"?"default":"outline",onClick:()=>Y(B,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ie,{size:"sm",variant:z==="deny"?"default":"outline",onClick:()=>Y(B,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},B)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:R,disabled:P,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Da,{className:"h-3 w-3"}),P?"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(so,{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"})]})})},wj=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedCommandName:a,commands:l,setSelectedCommand:c,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Br(),{setSidebarOpen:p}=$e(),{isMobile:g}=$t(),[y,h]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const b=y?"bg-transparent":j?"bg-background":"bg-sidebar",v=()=>{const S="new-command";let D=S,E=1;for(;l.some(T=>T.name===D);)D=`${S}-${E}`,E++;d({name:D,scope:"user"}),c(D),s?.(),g&&p(!1)},w=async S=>{if(yn(S)){te.error("Built-in commands cannot be deleted");return}window.confirm(`Are you sure you want to delete command "${S.name}"?`)&&(await m(S.name)?te.success(`Command "${S.name}" deleted successfully`):te.error("Failed to delete command"))},N=async S=>{yn(S)&&window.confirm(`Are you sure you want to reset command "${S.name}" to its default configuration?`)&&(await m(S.name)?te.success(`Command "${S.name}" reset to default`):te.error("Failed to reset command"))},x=S=>{const D=S.name;let E=1,T=`${D}-copy`;for(;l.some(I=>I.name===T);)E++,T=`${D}-copy-${E}`;d({name:T,scope:S.scope||"user",description:S.description,template:S.template,agent:S.agent,model:S.model,subtask:S.subtask}),c(T),g&&p(!1)},k=S=>{o(S.name),t(S)},A=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-");if(!S){te.error("Command name is required");return}if(S===r.name){t(null);return}if(l.some(E=>E.name===S)){te.error("A command with this name already exists");return}await u({name:S,description:r.description,template:r.template,agent:r.agent,model:r.model,subtask:r.subtask})?await m(r.name)?(te.success(`Command renamed to "${S}"`),c(S)):te.error("Failed to remove old command after rename"):te.error("Failed to rename command"),t(null)},C=l.filter(yn),M=l.filter(S=>!yn(S));return e.jsxs("div",{className:_("flex h-full flex-col",b),children:[e.jsx("div",{className:_("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 ",l.length]}),e.jsx(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:v,children:e.jsx(Xt,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(_r,{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:[C.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"}),[...C].sort((S,D)=>S.name.localeCompare(D.name)).map(S=>e.jsx(Ud,{command:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),g&&p(!1)},onReset:()=>N(S),onDuplicate:()=>x(S)},S.name))]}),M.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"}),[...M].sort((S,D)=>S.name.localeCompare(D.name)).map(S=>e.jsx(Ud,{command:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),g&&p(!1)},onRename:()=>k(S),onDelete:()=>w(S),onDuplicate:()=>x(S)},S.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(fs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Command"}),e.jsxs(Ms,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:S=>o(S.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&A()}}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:A,children:"Rename"})]})]})})]})},Ud=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:l})=>e.jsx("div",{className:_("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||yn(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:yn(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),a()},children:[e.jsx(uo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:c=>{c.stopPropagation(),l()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),o()},children:[e.jsx(Fs,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Et,{onClick:c=>{c.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),Cf=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=zr(),a=o(),l=$e(y=>y.isMobile),{isMobile:c}=$t(),d=l||c,[u,m]=i.useState(!1);i.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=y=>{r(y)},g=()=>d?e.jsx(ws,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(y=>{const h=y.name===s;return e.jsxs("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",h?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(y.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:y.name}),y.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:y.description})]}),h&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},y.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:_("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(so,{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(Ft,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("div",{className:_("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(so,{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(Ft,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Qt,{className:"max-w-[300px]",children:[a.map(y=>e.jsx(Et,{className:"typography-meta",onSelect:()=>p(y.name),children:e.jsx("span",{className:"font-medium",children:y.name})},y.name)),e.jsx(Et,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),g()]})},jj=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:l}=Br(),c=s?r(s):null,d=!!(a&&a.name===s&&!c),[u,m]=i.useState(""),[f,p]=i.useState("user"),[g,y]=i.useState(""),[h,j]=i.useState(""),[b,v]=i.useState(""),[w,N]=i.useState(""),[x,k]=i.useState(!1),[A,C]=i.useState(!1);i.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),y(a.description||""),j(a.agent||""),v(a.model||""),N(a.template||""),k(a.subtask||!1)):c&&(y(c.description||""),j(c.agent||""),v(c.model||""),N(c.template||""),k(c.subtask||!1))},[c,d,s,o,a]);const M=async()=>{const S=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!S){te.error("Command name is required");return}if(!w.trim()){te.error("Command template is required");return}if(d&&o.some(D=>D.name===S)){te.error("A command with this name already exists");return}C(!0);try{const D=h.trim(),E=b.trim(),T=w.trim(),I={name:S,description:g.trim()||void 0,agent:D===""?null:D,model:E===""?null:E,template:T,subtask:x,scope:d?f:void 0};let P;d?(P=await t(I),P&&l(null)):P=await n(S,I),P?te.success(d?"Command created successfully":"Command updated successfully"):te.error(d?"Failed to create command":"Failed to update command")}catch(D){console.error("Error saving command:",D),te.error("An error occurred while saving")}finally{C(!1)}};return s?e.jsx(gt,{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(jt,{value:u,onChange:S=>m(S.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(ks,{value:f,onValueChange:S=>p(S),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{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(Os,{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(Ut,{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(ur,{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(Ss,{value:g,onChange:S=>y(S.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(Cf,{agentName:h,onChange:S=>j(S)}),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($a,{providerId:b?b.split("/")[0]:"",modelId:b?b.split("/")[1]:"",onChange:(S,D)=>{v(S&&D?`${S}/${D}`:"")}}),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:x,onChange:S=>k(S.target.checked),className:"sr-only"}),e.jsx("div",{className:_("w-5 h-5 rounded border-2 flex items-center justify-center",x?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:x&&e.jsx(_t,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(Ss,{value:w,onChange:S=>N(S.target.value),placeholder:`Your command template here...
131
-
132
- Use $ARGUMENTS to reference user input.
133
- Use !\`shell command\` to inject shell output.
134
- 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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(Ie,{size:"sm",variant:"default",onClick:M,disabled:A,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Da,{className:"h-3 w-3"}),A?"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(_r,{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"})]})})},Sj=({onItemSelect:s})=>{const[r,t]=i.useState(null),[n,o]=i.useState(""),{selectedSkillName:a,skills:l,setSelectedSkill:c,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Gs(),{setSidebarOpen:g}=$e(),{isMobile:y}=$t(),[h,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{f()},[f]);const v=h?"bg-transparent":b?"bg-background":"bg-sidebar",w=()=>{const S="new-skill";let D=S,E=1;for(;l.some(T=>T.name===D);)D=`${S}-${E}`,E++;d({name:D,scope:"user",description:""}),c(D),s?.(),y&&g(!1)},N=async S=>{window.confirm(`Are you sure you want to delete skill "${S.name}"?`)&&(await m(S.name)?te.success(`Skill "${S.name}" deleted successfully`):te.error("Failed to delete skill"))},x=async S=>{const D=S.name;let E=1,T=`${D}-copy`;for(;l.some(P=>P.name===T);)E++,T=`${D}-copy-${E}`;const I=await p(S.name);if(!I){te.error("Failed to load skill details for duplication");return}d({name:T,scope:S.scope||"user",description:(I.sources.md.fields.includes("description"),""),instructions:""}),c(T),y&&g(!1)},k=S=>{o(S.name),t(S)},A=async()=>{if(!r)return;const S=n.trim().replace(/\s+/g,"-").toLowerCase();if(!S){te.error("Skill name is required");return}if(S===r.name){t(null);return}if(l.some(T=>T.name===S)){te.error("A skill with this name already exists");return}if(!await p(r.name)){te.error("Failed to load skill details"),t(null);return}await u({name:S,description:"Renamed skill",scope:r.scope})?await m(r.name)?(te.success(`Skill renamed to "${S}"`),c(S)):te.error("Failed to remove old skill after rename"):te.error("Failed to rename skill"),t(null)},C=l.filter(S=>S.scope==="project"),M=l.filter(S=>S.scope==="user");return e.jsxs("div",{className:_("flex h-full flex-col",v),children:[e.jsx("div",{className:_("border-b px-3",y?"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 ",l.length]}),e.jsx(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:w,children:e.jsx(Xt,{className:"size-4"})})]})}),e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:l.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx($u,{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:[C.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"}),C.map(S=>e.jsx(Vd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>x(S)},S.name))]}),M.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"}),M.map(S=>e.jsx(Vd,{skill:S,isSelected:a===S.name,onSelect:()=>{c(S.name),s?.(),y&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>x(S)},S.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:S=>!S&&t(null),children:e.jsxs(fs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Skill"}),e.jsxs(Ms,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(jt,{value:n,onChange:S=>o(S.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&A()}}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:A,children:"Rename"})]})]})})]})},Vd=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:_("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(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Et,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(uo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Et,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})});function Mf({tabs:s,value:r,onValueChange:t,className:n,isInteractive:o=!0,animate:a=!0}){const l=i.useRef(null),c=i.useRef(null),d=i.useCallback(()=>{const u=l.current,m=c.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:g}=m,y=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(y).toFixed(2)}% round 8px)`},[]);return i.useLayoutEffect(()=>{d()},[d,r,s.length]),i.useEffect(()=>{const u=l.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:_("relative isolate w-full",n),children:[e.jsx("div",{ref:l,"aria-hidden":!0,className:_("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?c:null,type:"button",onClick:()=>{o&&t(u.value)},className:_("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:_("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const kj=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Nj=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},Cj=async()=>{try{if(es())return await Lr();const s=Qs()?.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}},Mj=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=mo(),a=In(S=>S.defaultGitIdentityId),l=In(S=>S.loadDefaultGitIdentityId),[c,d]=i.useState(""),[u,m]=i.useState(""),[f,p]=i.useState(""),[g,y]=i.useState([]),[h,j]=i.useState(null),[b,v]=i.useState(!1),[w,N]=i.useState([]),[x,k]=i.useState(null);i.useEffect(()=>{s&&(d(""),m(""),p(""),j(null),v(!1),N([]),k(null),l(),(async()=>{const S=await Cj(),D=Array.isArray(S?.skillCatalogs)?S?.skillCatalogs:[];y(D||[])})())},[s,l]);const A=i.useMemo(()=>{const S=u.trim(),D=f.trim();return g.some(E=>{const T=(E.source||"").trim(),I=(E.subpath||"").trim();return T===S&&I===D})},[g,u,f]),C=async()=>{const S=u.trim();if(!S){te.error("Repository source is required");return}c.trim()||d(Nj(S)),v(!1),j(null);const D=await t({source:S,subpath:f.trim()||void 0,gitIdentityId:x||void 0});if(!D.ok){if(D.error?.kind==="authRequired"){if(Wt()){te.error("Private repositories are not supported in VS Code yet");return}const T=D.error.identities||[];if(N(T),!x&&T.length>0){const I=a&&a!=="global"&&T.some(P=>P.id===a)?a:T[0].id;k(I)}te.error("Authentication required. Select a Git identity and scan again.");return}te.error(D.error?.message||"Failed to scan repository");return}const E=D.items?.length||0;if(j(E),E===0){te.error("No skills found in this repository"),v(!1);return}N([]),v(!0),te.success(`Found ${E} skill(s)`)},M=async()=>{const S=c.trim(),D=u.trim(),E=f.trim();if(!S){te.error("Catalog name is required");return}if(!D){te.error("Repository source is required");return}if(!b){te.error("Scan the repository before adding this catalog");return}if(A){te.error("This catalog already exists");return}const T={id:kj(),label:S,source:D,...E?{subpath:E}:{},...x?{gitIdentityId:x}:{}},I=[...g,T];try{await ss({skillCatalogs:I}),y(I),te.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(P){te.error(P instanceof Error?P.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(ys,{children:[e.jsx(bs,{children:"Add skills catalog"}),e.jsxs(Ms,{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(jt,{value:c,onChange:S=>d(S.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(jt,{value:u,onChange:S=>{m(S.target.value),v(!1),j(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(jt,{value:f,onChange:S=>{p(S.target.value),v(!1),j(null)},placeholder:"e.g. skills"})]}),w.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(ks,{value:x||"",onValueChange:S=>k(S),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:w.find(S=>S.id===x)?.name||"Choose identity"})}),e.jsx(Cs,{align:"start",children:w.map(S=>e.jsx(Ut,{value:S.id,className:"pr-2 [&>span:first-child]:hidden",children:S.name},S.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,h!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",h," skill(s) found"]}):null,A?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Ie,{variant:"outline",onClick:()=>{C()},disabled:o||!u.trim(),className:"gap-2",children:[e.jsx(Oh,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ie,{variant:"default",onClick:()=>{M()},disabled:!b||A||!c.trim()||!u.trim(),children:"Add catalog"})]})]})})},Dj=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=i.useState({});i.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const l=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},c=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(ys,{children:[e.jsx(bs,{children:"Skills already exist"}),e.jsx(Ms,{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(Ie,{variant:"outline",size:"sm",onClick:()=>l("skip"),children:"Skip all"}),e.jsx(Ie,{variant:"outline",size:"sm",onClick:()=>l("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(ks,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ns,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Ut,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(on,{onClick:()=>n(o),disabled:!c,children:"Continue"})]})]})})},Aj=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=mo(),[a,l]=i.useState("user"),[c,d]=i.useState(!1),[u,m]=i.useState([]),[f,p]=i.useState(null);i.useEffect(()=>{s&&(l("user"),d(!1),m([]),p(null))},[s]);const g=async y=>{const h={skillDir:y.skillDir};t?.clawdhub&&(h.clawdhub={slug:t.clawdhub.slug,version:t.clawdhub.version});const j=await n({source:y.source,subpath:y.subpath,gitIdentityId:t?.gitIdentityId,scope:y.scope,selections:[h],conflictPolicy:"prompt",conflictDecisions:y.conflictDecisions});if(j.ok){te.success("Skill installed successfully"),r(!1);return}if(j.error?.kind==="conflicts"){p({source:y.source,subpath:y.subpath,scope:y.scope,skillDir:y.skillDir}),m(j.error.conflicts),d(!0);return}if(j.error?.kind==="authRequired"){te.error(j.error.message||"Authentication required");return}te.error(j.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(ys,{children:[e.jsx(bs,{children:"Install skill"}),e.jsxs(Ms,{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(y=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:y},y))})]}):null}),e.jsxs(Js,{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(ks,{value:a,onValueChange:y=>l(y),children:[e.jsx(Ns,{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(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(Cs,{align:"start",children:[e.jsx(Ut,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Ut,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ur,{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(Ie,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Ie,{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(Dj,{open:c,onOpenChange:d,conflicts:u,onConfirm:y=>{f&&(g({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:y}),d(!1))}})]}):null},Ej=async()=>{try{if(es())return await Lr();const s=Qs()?.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}},Ij=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:l,isLoadingCatalog:c,lastCatalogError:d}=mo(),[u,m]=i.useState(""),[f,p]=i.useState(!1),[g,y]=i.useState(!1),[h,j]=i.useState(null),[b,v]=i.useState(!1);i.useEffect(()=>{l()},[l]);const w=i.useMemo(()=>o?n[o]||[]:[],[n,o]),N=i.useMemo(()=>{const C=u.trim().toLowerCase();return C?w.filter(M=>{const S=M.skillName.toLowerCase(),D=(M.description||"").toLowerCase(),E=(M.frontmatterName||"").toLowerCase();return S.includes(C)||D.includes(C)||E.includes(C)}):w},[w,u]),x=i.useMemo(()=>t.find(C=>C.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),A=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){v(!0);try{const C=await Ej(),S=(Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[]).filter(D=>D.id!==o);await ss({skillCatalogs:S}),await l({refresh:!0})}finally{v(!1)}}};return e.jsx(gt,{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(Mf,{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(ks,{value:o||"",onValueChange:C=>a(C),children:[e.jsx(Ns,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x?.label||"Select source"})}),e.jsx(Cs,{align:"start",children:t.map(C=>e.jsx(Ut,{value:C.id,className:"pr-2 [&>span:first-child]:hidden",children:C.label},C.id))})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ie,{type:"button",variant:"outline",onClick:()=>{l({refresh:!0})},disabled:c,className:"gap-2",children:[e.jsx(jr,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(Ie,{type:"button",variant:"outline",onClick:()=>{A()},disabled:b,className:"gap-2",children:[e.jsx(Xs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ie,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Xt,{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(jt,{value:u,onChange:C=>m(C.target.value),placeholder:"Search skills…",className:"max-w-md"}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:c?"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(C=>{const M=C.installed?.isInstalled,S=C.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:C.skillName}),M?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 (",S||"unknown",")"]}):null,C.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"})]}),C.description?e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 line-clamp-2",children:C.description}):e.jsx("div",{className:"typography-micro text-muted-foreground mt-0.5",children:"No description provided"}),C.clawdhub?e.jsxs("div",{className:"typography-micro text-muted-foreground mt-1 flex items-center gap-3",children:[C.clawdhub.owner?e.jsxs("span",{children:["by ",C.clawdhub.owner]}):null,e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Fr,{className:"h-3 w-3"}),C.clawdhub.downloads?.toLocaleString()??0]}),(C.clawdhub.stars??0)>0?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(wn,{className:"h-3 w-3"}),C.clawdhub.stars]}):null,e.jsxs("span",{children:["v",C.clawdhub.version]})]}):null,C.warnings?.length?e.jsx("div",{className:"typography-micro text-muted-foreground mt-1",children:C.warnings.join(" · ")}):null]}),e.jsx(Ie,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!C.installable,onClick:()=>{j(C),y(!0)},children:"Install"})]})},`${C.sourceId}:${C.skillDir}`)})}),e.jsx(Mj,{open:f,onOpenChange:p}),e.jsx(Aj,{open:g,onOpenChange:y,item:h})]})})},Pj=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:l,setSkillDraft:c,setSelectedSkill:d}=Gs(),u=s?r(s):null,m=!!(l&&l.name===s&&!u),f=!!(s&&!u&&!l),[p,g]=i.useState("manual");i.useEffect(()=>{!m&&p!=="manual"&&g("manual")},[m,p]),i.useEffect(()=>{f&&d(null)},[f,d]);const y=m?e.jsx(Mf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:g,animate:!1}):null,[h,j]=i.useState(""),[b,v]=i.useState("user"),[w,N]=i.useState(""),[x,k]=i.useState(""),[A,C]=i.useState([]),[M,S]=i.useState([]),[D,E]=i.useState(!1),[T,I]=i.useState(!1),[P,O]=i.useState(""),[U,Q]=i.useState(""),[W,L]=i.useState(!1),[H,q]=i.useState(""),[X,Y]=i.useState(""),[re,K]=i.useState(null),[ae,F]=i.useState(!1),[$,R]=i.useState(""),B=m?h.trim()!==""||w.trim()!==""||x.trim()!==""||M.length>0:w!==P||x!==U,z=re?X!==$:H.trim()!=="";i.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&l)j(l.name||""),v(l.scope||"user"),N(l.description||""),k(l.instructions||""),O(""),Q(""),C([]),S(l.pendingFiles||[]);else if(s&&u){I(!0);try{const Be=await t(s);if(Be){const V=Be.sources.md;N(V.description||""),k(V.instructions||""),O(V.description||""),Q(V.instructions||""),C(V.supportingFiles||[])}}catch(Be){console.error("Failed to load skill details:",Be)}finally{I(!1)}}})()},[u,m,s,a,l,t,p]);const G=async()=>{const Ce=m?h.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!Ce){te.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(Ce)||Ce.length>64){te.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!w.trim()){te.error("Description is required");return}if(m&&a.some(Be=>Be.name===Ce)){te.error("A skill with this name already exists");return}E(!0);try{const Be={name:Ce,description:w.trim(),instructions:x.trim()||void 0,scope:m?b:void 0,supportingFiles:m&&M.length>0?M:void 0};let V;m?(V=await n(Be),V&&(c(null),S([]),d(Ce))):(V=await o(Ce,Be),V&&(O(w.trim()),Q(x.trim()))),V?te.success(m?"Skill created successfully":"Skill updated successfully"):te.error(m?"Failed to create skill":"Failed to update skill")}catch(Be){console.error("Error saving skill:",Be),te.error("An error occurred while saving")}finally{E(!1)}},ge=()=>{K(null),q(""),Y(""),R(""),L(!0)},oe=async Ce=>{if(K(Ce),q(Ce),m){const V=M.find(J=>J.path===Ce)?.content||"";Y(V),R(V),L(!0);return}if(s){F(!0),L(!0);try{const{readSupportingFile:Be}=Gs.getState(),V=await Be(s,Ce);Y(V||""),R(V||"")}catch{te.error("Failed to load file content"),Y(""),R("")}finally{F(!1)}}},me=async()=>{if(!H.trim()){te.error("File name is required");return}const Ce=H.trim(),Be=re!==null;if(m){if(Be)S(ee=>ee.map(xe=>xe.path===re?{path:Ce,content:X}:xe)),te.success(`File "${Ce}" updated`);else{if(M.some(ee=>ee.path===Ce)){te.error("A file with this name already exists");return}S(ee=>[...ee,{path:Ce,content:X}]),te.success(`File "${Ce}" added`)}L(!1),K(null);return}if(!s){te.error("No skill selected");return}const{writeSupportingFile:V}=Gs.getState();if(await V(s,Ce,X)){te.success(Be?`File "${Ce}" updated`:`File "${Ce}" created`),L(!1),K(null);const ee=await t(s);ee&&C(ee.sources.md.supportingFiles||[])}else te.error(Be?"Failed to update file":"Failed to create file")},Ne=async Ce=>{if(m){S(Be=>Be.filter(V=>V.path!==Ce)),te.success(`File "${Ce}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${Ce}"?`)){const{deleteSupportingFile:Be}=Gs.getState();if(await Be(s,Ce)){te.success(`File "${Ce}" deleted`);const J=await t(s);J&&C(J.sources.md.supportingFiles||[])}else te.error("Failed to delete file")}};return m&&p==="external"?e.jsx(Ij,{mode:p,onModeChange:g}):!s&&!l||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($u,{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"})]})}):T?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(gt,{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?y: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(jt,{value:h,onChange:Ce=>j(Ce.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(ks,{value:b,onValueChange:Ce=>v(Ce),children:[e.jsxs(Ns,{className:"!h-9 w-auto gap-1.5",children:[b==="user"?e.jsx(Os,{className:"h-4 w-4"}):e.jsx(ur,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:b})]}),e.jsxs(Cs,{align:"end",children:[e.jsx(Ut,{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(Os,{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(Ut,{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(ur,{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(Ss,{value:w,onChange:Ce=>N(Ce.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(Ss,{value:x,onChange:Ce=>k(Ce.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(Ie,{variant:"outline",size:"sm",onClick:ge,className:"gap-1.5",children:[e.jsx(Xt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const Ce=m?M:A;return Ce.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:Ce.map(Be=>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:()=>oe(Be.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(nr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children:Be.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(Ie,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:V=>{V.stopPropagation(),Ne(Be.path)},children:e.jsx(Xs,{className:"h-3.5 w-3.5"})})]},Be.path))})})()]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:G,disabled:D||!B,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(Da,{className:"h-3 w-3"}),D?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ms,{open:W,onOpenChange:Ce=>{L(Ce),Ce||K(null)},children:e.jsxs(fs,{className:"max-w-2xl max-h-[85vh] flex flex-col",keyboardAvoid:!0,children:[e.jsxs(ys,{className:"flex-shrink-0",children:[e.jsx(bs,{children:re?"Edit Supporting File":"Add Supporting File"}),e.jsx(Ms,{children:re?"Modify the file content":"Create a new file in the skill directory"})]}),ae?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(jt,{value:H,onChange:Ce=>q(Ce.target.value),placeholder:"example.md or docs/reference.txt",className:"text-foreground placeholder:text-muted-foreground",disabled:re!==null}),!re&&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(Ss,{value:X,onChange:Ce=>Y(Ce.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"ghost",onClick:()=>{L(!1),K(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(on,{onClick:me,disabled:ae||!z,children:re?"Save Changes":"Create File"})]})]})})]})})},Tj="__add_provider__",Fj=({onItemSelect:s})=>{const r=at(u=>u.providers),t=at(u=>u.selectedProviderId),n=at(u=>u.setSelectedProvider),{isMobile:o}=$t(),[a,l]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),c=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||l(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":c?"bg-background":"bg-sidebar";return e.jsxs("div",{className:_("flex h-full flex-col",d),children:[e.jsx("div",{className:_("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(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(Tj),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Xt,{className:"size-4"})})]})}),e.jsx(gt,{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(to,{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:_("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(cs,{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)})})]})},Rj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Gd=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=Rj.format(s);return r.endsWith(".0")?r.slice(0,-2):r},qd="__add_provider__",Pn=s=>typeof s=="object"&&s!==null,Kd=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()},_j=s=>{if(!Pn(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>Pn(o)));return r},Oj=s=>{if(typeof s=="string")return{id:s};if(!Pn(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}},$j=s=>{let r=[];Array.isArray(s)?r=s:Pn(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>Oj(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},Lj=()=>{const s=at(R=>R.providers),r=at(R=>R.selectedProviderId),t=at(R=>R.setSelectedProvider),n=at(R=>R.getModelMetadata),[o,a]=i.useState({}),[l,c]=i.useState(!1),[d,u]=i.useState({}),[m,f]=i.useState(null),[p,g]=i.useState(""),[y,h]=i.useState(null),[j,b]=i.useState({}),[v,w]=i.useState({}),[N,x]=i.useState([]),[k,A]=i.useState(!1),[C,M]=i.useState(null),[S,D]=i.useState(""),[E,T]=i.useState(""),[I,P]=i.useState(!1);i.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),i.useEffect(()=>{let R=!0;return(async()=>{c(!0);try{const z=await fetch("/api/provider/auth",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Auth methods request failed (${z.status})`);const G=await z.json().catch(()=>({}));if(!R)return;a(_j(G))}catch(z){if(!R)return;console.error("Failed to load provider auth methods:",z),te.error("Failed to load provider authentication methods")}finally{R&&c(!1)}})(),()=>{R=!1}},[]),i.useEffect(()=>{let R=!0;return(async()=>{A(!0),M(null);try{const z=await fetch("/api/provider",{method:"GET",headers:{Accept:"application/json"}});if(!z.ok)throw new Error(`Provider list request failed (${z.status})`);const G=await z.json().catch(()=>({}));if(!R)return;x($j(G))}catch(z){if(!R)return;console.error("Failed to load available providers:",z),M("Unable to load provider list")}finally{R&&A(!1)}})(),()=>{R=!1}},[]);const O=i.useMemo(()=>new Set(s.map(R=>R.id)),[s]),U=i.useMemo(()=>N.filter(R=>!O.has(R.id)),[N,O]);i.useEffect(()=>{if(r===qd){if(!S&&U.length>0){D(U[0].id);return}S&&!U.some(R=>R.id===S)&&D(U[0]?.id??"")}},[r,S,U]);const Q=s.find(R=>R.id===r),W=async R=>{const B=d[R]?.trim()??"";if(!B){te.error("API key is required");return}const z=`api:${R}`;f(z);try{const G=await fetch(`/api/auth/${encodeURIComponent(R)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:B})}),ge=await G.json().catch(()=>null);if(!G.ok){const oe=ge?.error||"Failed to save API key";throw new Error(oe)}te.success("API key saved"),u(oe=>({...oe,[R]:""})),await qn({scopes:["providers"],mode:"active"}),t(R)}catch(G){console.error("Failed to save API key:",G),te.error("Failed to save API key")}finally{f(null)}},L=async(R,B)=>{const z=`oauth:${R}:${B}`;f(z);try{const G=await fetch(`/api/provider/${encodeURIComponent(R)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:B})}),ge=await G.json().catch(()=>null);if(!G.ok){const J=ge?.error||"Failed to start OAuth flow";throw new Error(J)}const oe=Pn(ge)?ge:{},me=Pn(oe.data)?oe.data:oe,Ne=typeof me.url=="string"&&me.url||typeof me.verification_uri_complete=="string"&&me.verification_uri_complete||typeof me.verification_uri=="string"&&me.verification_uri||void 0,Ce=typeof me.instructions=="string"&&me.instructions||typeof me.message=="string"&&me.message||void 0,Be=typeof me.user_code=="string"&&me.user_code||typeof me.code=="string"&&me.code||typeof me.userCode=="string"&&me.userCode||void 0;if(!Ne&&!Ce&&!Be)throw new Error("No OAuth details returned");const V=`${R}:${B}`;w(J=>({...J,[V]:{url:Ne,instructions:Ce,userCode:Be}})),Ne&&window.open(Ne,"_blank","noopener,noreferrer"),h({providerId:R,methodIndex:B}),te.message("Complete the OAuth flow in your browser")}catch(G){console.error("Failed to start OAuth flow:",G),te.error("Failed to start OAuth flow")}finally{f(null)}},H=async(R,B)=>{const z=`${R}:${B}`,G=j[z]?.trim(),ge=`oauth-complete:${R}:${B}`;f(ge);try{const oe={method:B};G&&(oe.code=G);const me=await fetch(`/api/provider/${encodeURIComponent(R)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(oe)}),Ne=await me.json().catch(()=>null);if(!me.ok){const Ce=Ne?.error||"Failed to complete OAuth flow";throw new Error(Ce)}te.success("OAuth connection completed"),b(Ce=>({...Ce,[z]:""})),h(null),await qn({scopes:["providers"],mode:"active"}),t(R)}catch(oe){console.error("Failed to complete OAuth flow:",oe),te.error("Failed to complete OAuth flow")}finally{f(null)}},q=async R=>{try{await navigator.clipboard.writeText(R),te.success("OAuth link copied")}catch(B){console.error("Failed to copy OAuth link:",B),te.error("Failed to copy OAuth link")}},X=async R=>{try{await navigator.clipboard.writeText(R),te.success("Device code copied")}catch(B){console.error("Failed to copy device code:",B),te.error("Failed to copy device code")}},Y=async R=>{const B=`disconnect:${R}`;f(B);try{const z=await fetch(`/api/provider/${encodeURIComponent(R)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),G=await z.json().catch(()=>null);if(!z.ok){const ge=G?.error||"Failed to disconnect provider";throw new Error(ge)}te.success("Provider disconnected"),await qn({scopes:["providers"],mode:"active"})}catch(z){console.error("Failed to disconnect provider:",z),te.error("Failed to disconnect provider")}finally{f(null)}},re=r===qd;if(!re&&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(to,{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(re)return e.jsx(gt,{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."})]}),k?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading providers…"}):C?e.jsx("p",{className:"typography-meta text-muted-foreground",children:C}):U.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(qt,{open:I,onOpenChange:R=>{P(R),R||T("")},children:[e.jsx(Kt,{asChild:!0,children:e.jsxs("button",{type:"button",className:_("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:S?"text-foreground":"text-muted-foreground",children:S?U.find(R=>R.id===S)?.name||S:"Select provider"}),e.jsx(Ft,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(Qt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:R=>R.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:R=>R.stopPropagation(),children:[e.jsx(lr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:E,onChange:R=>T(R.target.value),onKeyDown:R=>R.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(gt,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const R=U.filter(B=>{const z=E.toLowerCase();return(B.name||B.id).toLowerCase().includes(z)||B.id.toLowerCase().includes(z)});return R.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):R.map(B=>e.jsxs(Et,{onSelect:()=>{D(B.id),P(!1),T("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:B.name||B.id}),S===B.id&&e.jsx(_t,{className:"h-4 w-4 text-primary"})]},B.id))})()})]})]})]}),S&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?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(jt,{type:"password",value:d[S]??"",onChange:R=>u(B=>({...B,[S]:R.target.value})),placeholder:"sk-..."}),e.jsx(Ie,{size:"sm",onClick:()=>W(S),disabled:m===`api:${S}`,className:"h-8",children:m===`api:${S}`?"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 B=(o[S]??[]).filter(z=>Kd(z)==="oauth");return B.length===0?null:e.jsx("div",{className:"space-y-3",children:B.map((z,G)=>{const ge=z.label||z.name||`OAuth method ${G+1}`,oe=`${S}:${G}`,me=y?.providerId===S&&y?.methodIndex===G;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:ge}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>L(S,G),disabled:m===`oauth:${S}:${G}`,className:"h-8",children:"Connect"})]}),v[oe]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[oe]?.instructions}),v[oe]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[oe]?.userCode,readOnly:!0}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>X(v[oe]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[oe]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[oe]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[oe]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>q(v[oe]?.url??""),className:"h-8",children:"Copy link"})]})]}),me&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:j[oe]??"",onChange:Ne=>b(Ce=>({...Ce,[oe]:Ne.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ie,{size:"sm",onClick:()=>H(S,G),disabled:m===`oauth-complete:${S}:${G}`,className:"h-8",children:m===`oauth-complete:${S}:${G}`?"Saving…":"Complete"})]})]},`${S}-${ge}`)})})})()]})]})]})});if(!Q)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(to,{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 K=Array.isArray(Q.models)?Q.models:[],F=(o[Q.id]??[]).filter(R=>Kd(R)==="oauth"),$=K.filter(R=>{const B=typeof R?.name=="string"?R.name:"",z=typeof R?.id=="string"?R.id:"",G=p.trim().toLowerCase();return G?B.toLowerCase().includes(G)||z.toLowerCase().includes(G):!0});return e.jsx(gt,{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(cs,{providerId:Q.id,className:"h-5 w-5"}),e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:Q.name||Q.id})]}),e.jsxs("p",{className:"typography-body text-muted-foreground",children:["Provider ID: ",Q.id]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),l?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(jt,{type:"password",value:d[Q.id]??"",onChange:R=>u(B=>({...B,[Q.id]:R.target.value})),placeholder:"sk-..."}),e.jsx(Ie,{size:"sm",onClick:()=>W(Q.id),disabled:m===`api:${Q.id}`,className:"h-8",children:m===`api:${Q.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(Ie,{size:"sm",variant:"outline",onClick:()=>Y(Q.id),disabled:m===`disconnect:${Q.id}`,className:"h-8 text-destructive hover:text-destructive hover:bg-destructive/10",children:m===`disconnect:${Q.id}`?"Disconnecting…":"Disconnect provider"})}),F.length>0&&e.jsx("div",{className:"space-y-3",children:F.map((R,B)=>{const z=R.label||R.name||`OAuth method ${B+1}`,G=`${Q.id}:${B}`,ge=y?.providerId===Q.id&&y?.methodIndex===B;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:z}),(R.description||R.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(R.description||R.help)})]}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>L(Q.id,B),disabled:m===`oauth:${Q.id}:${B}`,className:"h-8",children:"Connect"})]}),v[G]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:v[G]?.instructions}),v[G]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[G]?.userCode,readOnly:!0}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>X(v[G]?.userCode??""),className:"h-8",children:"Copy code"})]}),v[G]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:v[G]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ie,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:v[G]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ie,{size:"sm",variant:"outline",onClick:()=>q(v[G]?.url??""),className:"h-8",children:"Copy link"})]})]}),ge&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(jt,{value:j[G]??"",onChange:oe=>b(me=>({...me,[G]:oe.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ie,{size:"sm",onClick:()=>H(Q.id,B),disabled:m===`oauth-complete:${Q.id}:${B}`,className:"h-8",children:m===`oauth-complete:${Q.id}:${B}`?"Saving…":"Complete"})]})]},`${Q.id}-${z}`)})})]})]}),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(jt,{value:p,onChange:R=>g(R.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:$.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):$.map(R=>{const B=typeof R?.id=="string"?R.id:"",z=typeof R?.name=="string"?R.name:B,G=B?n(Q.id,B):void 0,ge=Gd(G?.limit?.context),oe=Gd(G?.limit?.output),me=[];return G?.tool_call&&me.push({key:"tools",icon:Ma,label:"Tool calling"}),G?.reasoning&&me.push({key:"reasoning",icon:dr,label:"Reasoning"}),G?.attachment&&me.push({key:"image",icon:mr,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:z}),(ge||oe)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[ge?`${ge} ctx`:"",ge&&oe?" · ":"",oe?`${oe} out`:""]}),me.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:me.map(({key:Ne,icon:Ce,label:Be})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Be,"aria-label":Be,children:e.jsx(Ce,{className:"h-3 w-3"})},Ne))})]},B)})})]})]})})},Bj={branch:zt,briefcase:pl,house:fl,graduation:ml,code:_s,heart:Tu},zj={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},Wj=({onItemSelect:s})=>{const{selectedProfileId:r,defaultGitIdentityId:t,profiles:n,globalIdentity:o,setSelectedProfile:a,deleteProfile:l,loadProfiles:c,loadGlobalIdentity:d,loadDiscoveredCredentials:u,loadDefaultGitIdentityId:m,setDefaultGitIdentityId:f,getUnimportedCredentials:p}=In(),{setSidebarOpen:g}=$e(),{isMobile:y}=$t(),[h,j]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),b=i.useMemo(()=>Wt(),[]);i.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]);const v=p();i.useEffect(()=>{c(),d(),u(),m()},[c,d,u,m]);const w=C=>{a(`import:${C.host}:${C.username}`),s?.(),y&&g(!1)},N=h?"bg-transparent":b?"bg-background":"bg-sidebar",x=()=>{a("new"),s?.(),y&&g(!1)},k=async C=>{window.confirm(`Are you sure you want to delete profile "${C.name}"?`)&&(await l(C.id)?te.success(`Profile "${C.name}" deleted successfully`):te.error("Failed to delete profile"))},A=async C=>{const M=t===C?null:C;if(!await f(M)){te.error("Failed to update default identity");return}te.success(M?"Default identity updated":"Default identity unset")};return e.jsxs("div",{className:_("flex h-full flex-col",N),children:[e.jsx("div",{className:_("border-b px-3",y?"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 ",n.length]}),e.jsx(Ie,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:x,children:e.jsx(Xt,{className:"size-4"})})]})}),e.jsxs(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[o&&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(Qd,{profile:o,isSelected:r==="global",isDefault:t==="global",onSelect:()=>{a("global"),s?.(),y&&g(!1)},onToggleDefault:()=>A("global"),onDelete:void 0,isReadOnly:!0})]}),n.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"}),n.length===0&&!o&&v.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(zt,{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:n.map(C=>e.jsx(Qd,{profile:C,isSelected:r===C.id,isDefault:t===C.id,onSelect:()=>{a(C.id),s?.(),y&&g(!1)},onToggleDefault:()=>A(C.id),onDelete:()=>k(C)},C.id))}),v.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:"Discovered Credentials"}),e.jsx("p",{className:"px-2 pb-2 typography-micro text-muted-foreground/60",children:"Found in ~/.git-credentials"}),v.map(C=>e.jsx(Uj,{credential:C,onImport:()=>w(C)},`${C.host}-${C.username}`))]})]})]})},Qd=({profile:s,isSelected:r,isDefault:t=!1,onSelect:n,onToggleDefault:o,onDelete:a,isReadOnly:l=!1})=>{const c=Bj[s.icon||"branch"]||zt,d=zj[s.color||""],u=s.authType||"ssh";return e.jsx("div",{className:_("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:n,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(c,{className:"w-4 h-4 flex-shrink-0",style:{color:d}}),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:u}),t&&e.jsx("span",{className:"typography-micro text-primary bg-primary/12 px-1 rounded flex-shrink-0 leading-none pb-px border border-primary/25",children:"default"})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:u==="token"&&s.host?s.host:s.userEmail})]}),(o||!l&&a)&&e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{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(Or,{className:"h-3.5 w-3.5"})})}),e.jsxs(Qt,{align:"end",className:"w-fit min-w-28",children:[o&&e.jsx(Et,{onClick:m=>{m.stopPropagation(),o()},children:t?"Unset default":"Set as default"}),!l&&a&&e.jsxs(Et,{onClick:m=>{m.stopPropagation(),a()},className:"text-destructive focus:text-destructive",children:[e.jsx(Xs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})},Hj=s=>{const r=s.split("/");return r.length>=3?r[r.length-1]:s},Uj=({credential:s,onImport:r})=>{const t=Hj(s.host),n=s.host.includes("/");return e.jsx("div",{className:"group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200 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("div",{className:"flex min-w-0 flex-1 flex-col gap-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:t})}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:n?s.host:s.username})]}),e.jsxs(Ie,{size:"sm",variant:"ghost",onClick:r,className:"h-6 px-2 text-xs gap-1 opacity-100 transition-opacity md:opacity-0 md:group-hover:opacity-100",children:[e.jsx(Fr,{className:"h-3 w-3"}),"Import"]})]})})},Yd=[{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)"}],Vj=[{key:"branch",Icon:zt,label:"Branch"},{key:"briefcase",Icon:pl,label:"Work"},{key:"house",Icon:fl,label:"Personal"},{key:"graduation",Icon:ml,label:"School"},{key:"code",Icon:_s,label:"Code"}],Gj=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=In(),a=i.useMemo(()=>{if(s?.startsWith("import:")){const[,I,P]=s.split(":");return{host:I,username:P}}return null},[s]),l=i.useMemo(()=>s&&s!=="new"&&!a?r(s):null,[s,r,a]),c=s==="new"||a!==null,d=s==="global",[u,m]=i.useState(""),[f,p]=i.useState(""),[g,y]=i.useState(""),[h,j]=i.useState("ssh"),[b,v]=i.useState(""),[w,N]=i.useState(""),[x,k]=i.useState("keyword"),[A,C]=i.useState("branch"),[M,S]=i.useState(!1);i.useEffect(()=>{if(a){const I=a.host.split("/"),P=I.length>=3?I[I.length-1]:a.host;m(P),p(a.username),y(""),j("token"),v(""),N(a.host),k("string"),C("code")}else c?(m(""),p(""),y(""),j("ssh"),v(""),N(""),k("keyword"),C("branch")):l&&(m(l.name),p(l.userName),y(l.userEmail),j(l.authType||"ssh"),v(l.sshKey||""),N(l.host||""),k(l.color||"keyword"),C(l.icon||"branch"))},[l,c,s,a]);const D=async()=>{if(!f.trim()||!g.trim()){te.error("User name and email are required");return}if(h==="token"&&!w.trim()){te.error("Host is required for token-based authentication");return}S(!0);try{const I={name:u.trim()||f.trim(),userName:f.trim(),userEmail:g.trim(),authType:h,sshKey:h==="ssh"&&b.trim()||null,host:h==="token"&&w.trim()||null,color:x,icon:A};let P;if(c)P=await t(I);else if(s)P=await n(s,I);else return;P?te.success(c?"Profile created successfully":"Profile updated successfully"):te.error(c?"Failed to create profile":"Failed to update profile")}catch(I){console.error("Error saving profile:",I),te.error("An error occurred while saving")}finally{S(!1)}},E=async()=>{if(!(!s||c)&&confirm("Are you sure you want to delete this profile?"))try{await o(s)?te.success("Profile deleted successfully"):te.error("Failed to delete profile")}catch(I){console.error("Error deleting profile:",I),te.error("An error occurred while deleting")}},T=i.useMemo(()=>Yd.find(P=>P.key===x)?.cssVar||"var(--syntax-keyword)",[x]);return s?e.jsx(gt,{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:a?"Import Credential":c?"New Git Profile":d?"Global Identity":u||"Edit Profile"}),e.jsx("p",{className:"typography-body text-muted-foreground mt-1",children:a?`Import token credential for ${a.host} - please fill in your email address`:c?"Create a new Git identity profile for your repositories":d?"System-wide Git identity from global configuration (read-only)":"Configure Git identity settings for this profile"})]}),!d&&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(jt,{value:u,onChange:I=>m(I.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:Yd.map(I=>e.jsx("button",{onClick:()=>k(I.key),className:_("w-8 h-8 rounded-lg border-2 transition-all",x===I.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:I.cssVar},title:I.label},I.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:Vj.map(I=>{const P=I.Icon;return e.jsx("button",{onClick:()=>C(I.key),className:_("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",A===I.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:I.label,children:e.jsx(P,{className:"w-4 h-4",style:{color:T}})},I.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 ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(jt,{value:f,onChange:I=>p(I.target.value),placeholder:"John Doe",required:!d,readOnly:d,disabled:d}),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 ",!d&&e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(jt,{type:"email",value:g,onChange:I=>y(I.target.value),placeholder:"john@example.com",required:!d,readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git user.email configuration value"})]}),!d&&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:["Authentication Type",e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["SSH: Uses SSH key for authentication",e.jsx("br",{}),"Token: Uses personal access token from ~/.git-credentials"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>j("ssh"),className:_("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",h==="ssh"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx($h,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>j("token"),className:_("flex items-center gap-2 px-3 py-1.5 rounded-md border transition-all",h==="token"?"border-primary bg-accent":"border-border hover:border-primary/50"),children:[e.jsx(Lh,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"Token (HTTPS)"})]})]})]}),h==="ssh"&&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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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 SSH Git operations.",e.jsx("br",{}),"Common paths: ~/.ssh/id_rsa, ~/.ssh/id_ed25519"]})]})]}),e.jsx(jt,{value:b,onChange:I=>v(I.target.value),placeholder:"/Users/username/.ssh/id_rsa",readOnly:d,disabled:d}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Path to SSH private key for authentication (optional)"})]}),h==="token"&&!d&&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:["Host ",e.jsx("span",{className:"text-destructive",children:"*"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{sideOffset:8,className:"max-w-xs",children:["The Git host this credential applies to.",e.jsx("br",{}),"Token will be read from ~/.git-credentials for this host.",e.jsx("br",{}),"Examples: github.com, gitlab.com"]})]})]}),e.jsx(jt,{value:w,onChange:I=>N(I.target.value),placeholder:"github.com",required:!0}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Git host for token authentication (from ~/.git-credentials)"})]}),!d&&e.jsxs("div",{className:"flex justify-between border-t border-border/40 pt-4",children:[!c&&e.jsxs(Ie,{size:"sm",variant:"destructive",onClick:E,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Xs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:_("flex gap-2",c&&"ml-auto"),children:e.jsxs(Ie,{size:"sm",variant:"default",onClick:D,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(Da,{className:"h-3 w-3"}),M?"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(Os,{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 ki(s,r,t){return Math.min(t,Math.max(r,s))}const va=Ae.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:l,onBlur:c,onKeyDown:d,disabled:u,...m},f)=>{const p=Ae.useRef(null);Ae.useImperativeHandle(f,()=>p.current);const[g,y]=Ae.useState(()=>String(s));Ae.useEffect(()=>{document.activeElement!==p.current&&y(String(s))},[s]);const h=Ae.useCallback(()=>{p.current?.focus()},[]),j=Ae.useCallback(S=>{const D=ki(S,t,n);r(D),y(String(D))},[n,t,r]),b=Ae.useCallback(()=>{const S=Number(g);return Number.isFinite(S)?S:s},[g,s]),v=Ae.useCallback(()=>{j(b()+o),h()},[j,b,h,o]),w=Ae.useCallback(()=>{j(b()-o),h()},[j,b,h,o]),N=S=>{const D=S.target.value;y(D);const E=Number(D);Number.isFinite(E)&&r(ki(E,t,n))},x=S=>{const D=Number(g);if(!Number.isFinite(D))y(String(s));else{const E=ki(D,t,n);E!==D&&r(E),y(String(E))}c?.(S)},k=S=>{if(S.key==="ArrowUp"){S.preventDefault(),v();return}if(S.key==="ArrowDown"){S.preventDefault(),w();return}d?.(S)},A=b(),C=u||A<=t,M=u||A>=n;return e.jsxs("div",{className:_("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",l),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:x,onKeyDown:k,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("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:M,onClick:v,className:_("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(Na,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:C,onClick:w,className:_("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(Ft,{className:"h-3.5 w-3.5"})})]})]})});va.displayName="NumberInput";const qj=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Xd=[{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"}],Jd=[{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."}],Zd=[{id:"single",label:"Single file",description:"Show one file at a time in the Diff tab."},{id:"stacked",label:"All files",description:"Stack all changed files together in the Diff tab."}],zl=({visibleSettings:s})=>{const{isMobile:r}=$t(),t=$e(x=>x.showReasoningTraces),n=$e(x=>x.setShowReasoningTraces),o=$e(x=>x.toolCallExpansion),a=$e(x=>x.setToolCallExpansion),l=$e(x=>x.fontSize),c=$e(x=>x.setFontSize),d=$e(x=>x.padding),u=$e(x=>x.setPadding),m=$e(x=>x.inputBarOffset),f=$e(x=>x.setInputBarOffset),p=$e(x=>x.diffLayoutPreference),g=$e(x=>x.setDiffLayoutPreference),y=$e(x=>x.diffViewMode),h=$e(x=>x.setDiffViewMode),j=rr(x=>x.queueModeEnabled),b=rr(x=>x.setQueueMode),{themeMode:v,setThemeMode:w}=Wr(),N=x=>s?s.includes(x):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[N("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:qj.map(x=>e.jsx(Ps,{variant:v===x.value?"default":"outline",className:_(v===x.value?void 0:"text-foreground"),onClick:()=>w(x.value),children:x.label},x.value))})]}),N("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:l,onChange:x=>c(Number(x.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(va,{value:l,onValueChange:c,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Ps,{type:"button",variant:"ghost",onClick:()=>c(100),disabled:l===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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("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:x=>u(Number(x.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(Ps,{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(Fs,{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:x=>u(Number(x.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(va,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Ps,{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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("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:x=>f(Number(x.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(Ps,{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(Fs,{className:"h-3.5 w-3.5"})})]})]}),N("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:Xd.find(x=>x.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Xd.map(x=>e.jsx(Ps,{variant:o===x.value?"default":"outline",className:_(o===x.value?void 0:"text-foreground"),onClick:()=>a(x.value),children:x.label},x.value))})]}),N("diffLayout")&&!r&&!Wt()&&e.jsxs("div",{className:"space-y-6",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:Jd.map(x=>e.jsx(Ps,{variant:p===x.id?"default":"outline",className:_(p===x.id?void 0:"text-foreground"),onClick:()=>g(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Jd.find(x=>x.id===p)?.description})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff view (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose whether the Diff tab defaults to a single file or all files."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Zd.map(x=>e.jsx(Ps,{variant:y===x.id?"default":"outline",className:_(y===x.id?void 0:"text-foreground"),onClick:()=>h(x.id),children:x.label},x.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Zd.find(x=>x.id===y)?.description})]})]}),N("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:x=>n(x.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),N("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:j,onChange:x=>b(x.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:j?`Enter queues messages, ${Yt()}+Enter sends immediately.`:`Enter sends immediately, ${Yt()}+Enter queues messages.`})]})]})},eu="https://github.com/btriapitsyn/openchamber",Kj=800,Df=()=>{const[s,r]=i.useState(!1),[t,n]=i.useState(!1),o=Aa(),{isMobile:a}=$t(),l=o.info?.currentVersion||"unknown",c=i.useRef(!1);i.useEffect(()=>{if(o.checking)n(!0),c.current=!0;else if(t){const u=setTimeout(()=>{n(!1),c.current&&!o.available&&!o.error&&(te.success("You are on the latest version"),c.current=!1)},Kj);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:()=>qn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Fs,{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",l]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:_("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(Fr,{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:eu,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx($i,{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(Lu,{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(Li,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Qi,{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:l})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Lo,{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:_("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(Fr,{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:_("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:eu,target:"_blank",rel:"noopener noreferrer",className:_("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx($i,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:_("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Li,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Qi,{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})]})},Qj=1440*60*1e3,Af=5,tu=1440*60*1e3,Ni=s=>s.time?.updated??s.time?.created??0,su=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=Af,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*Qj,l=[...s].sort((d,u)=>Ni(u)-Ni(d)),c=new Set(l.slice(0,n).map(d=>d.id));return l.filter(d=>{if(!d?.id||c.has(d.id)||d.id===r||d.share)return!1;const u=Ni(d);return u?u<a:!1}).map(d=>d.id)},Ef=s=>{const r=s?.autoRun!==!1,t=he(h=>h.sessions),n=he(h=>h.currentSessionId),o=he(h=>h.isLoading),a=he(h=>h.deleteSessions),l=$e(h=>h.autoDeleteEnabled),c=$e(h=>h.autoDeleteAfterDays),d=$e(h=>h.autoDeleteLastRunAt),u=$e(h=>h.setAutoDeleteLastRunAt),[m,f]=i.useState(!1),p=i.useRef(!1),g=i.useMemo(()=>c<=0?[]:su({sessions:t,currentSessionId:n,cutoffDays:c}),[c,n,t]),y=i.useCallback(async({force:h=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!l||c<=0)&&!h)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const j=Date.now();if(!h&&d&&j-d<tu)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const b=su({sessions:t,currentSessionId:n,cutoffDays:c,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())}},[c,l,d,n,a,o,t,u]);return i.useEffect(()=>{if(!r||!l||c<=0||o||t.length===0)return;const h=Date.now();d&&h-d<tu||y()},[c,l,d,r,o,t.length,y]),{candidates:g,isRunning:m,runCleanup:y,keepRecentCount:Af}},Ci=1,Mi=365,If=()=>{const{isMobile:s}=$t(),r=$e(p=>p.autoDeleteEnabled),t=$e(p=>p.autoDeleteAfterDays),n=$e(p=>p.setAutoDeleteEnabled),o=$e(p=>p.setAutoDeleteAfterDays),[a,l]=i.useState(String(t));i.useEffect(()=>{l(String(t))},[t]);const{candidates:c,isRunning:d,runCleanup:u}=Ef({autoRun:!1}),m=c.length,f=i.useCallback(async()=>{const p=await u({force:!0});if(p.deletedIds.length===0&&p.failedIds.length===0){te.message("No sessions eligible for deletion");return}p.deletedIds.length>0&&te.success(`Deleted ${p.deletedIds.length} session${p.deletedIds.length===1?"":"s"}`),p.failedIds.length>0&&te.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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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(l(g),g.trim()==="")return;const y=Number(g);if(!Number.isFinite(y))return;const h=Math.min(Mi,Math.max(Ci,Math.round(y)));o(h)},onBlur:()=>{if(a.trim()===""){l(String(t));return}const p=Number(a);if(!Number.isFinite(p)){l(String(t));return}const g=Math.min(Mi,Math.max(Ci,Math.round(p)));o(g),l(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(va,{value:t,onValueChange:o,min:Ci,max:Mi,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(Ps,{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]})]})},ru="opencode",nu="big-pickle",Yj=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===ru)?.models.some(o=>o.id===nu))return{providerId:ru,modelId:nu};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Pf=()=>{const s=at(S=>S.setProvider),r=at(S=>S.setModel),t=at(S=>S.setAgent),n=at(S=>S.setCurrentVariant),o=at(S=>S.setSettingsDefaultModel),a=at(S=>S.setSettingsDefaultVariant),l=at(S=>S.setSettingsDefaultAgent),c=at(S=>S.settingsAutoCreateWorktree),d=at(S=>S.setSettingsAutoCreateWorktree),u=at(S=>S.providers),[m,f]=i.useState(),[p,g]=i.useState(),[y,h]=i.useState(),[j,b]=i.useState(!0),v=i.useMemo(()=>Yj(m,u),[m,u]);i.useEffect(()=>{(async()=>{try{let D=null;if(es())D=await Lr();else{const E=Qs()?.settings;if(E)try{const I=(await E.load())?.settings;I&&(D={defaultModel:typeof I.defaultModel=="string"?I.defaultModel:void 0,defaultVariant:typeof I.defaultVariant=="string"?I.defaultVariant:void 0,defaultAgent:typeof I.defaultAgent=="string"?I.defaultAgent:void 0})}catch{}if(!D){const T=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});T.ok&&(D=await T.json())}}if(D){const E=typeof D.defaultModel=="string"&&D.defaultModel.trim().length>0?D.defaultModel.trim():void 0,T=typeof D.defaultVariant=="string"&&D.defaultVariant.trim().length>0?D.defaultVariant.trim():void 0,I=typeof D.defaultAgent=="string"&&D.defaultAgent.trim().length>0?D.defaultAgent.trim():void 0;E!==void 0&&f(E),T!==void 0&&g(T),I!==void 0&&h(I)}}catch(D){console.warn("Failed to load defaults settings:",D)}finally{b(!1)}})()},[]);const w=i.useCallback(async(S,D)=>{const E=S&&D?`${S}/${D}`:void 0;f(E),g(void 0),a(void 0),n(void 0),o(E),S&&D&&u.find(I=>I.id===S)&&(s(S),r(D));try{if(await ss({defaultModel:E??"",defaultVariant:""}),!es()){const T=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:E})});T.ok||console.warn("Failed to save default model to server:",T.status,T.statusText)}}catch(T){console.warn("Failed to save default model:",T)}},[u,n,s,r,o,a]),N="__default__",x=i.useCallback(async S=>{const D=S===N?void 0:S||void 0;g(D),a(D),n(D);try{await ss({defaultVariant:D??""})}catch(E){console.warn("Failed to save default variant:",E)}},[n,a]),k=i.useCallback(async S=>{const D=S||void 0;h(D),l(D),S&&t(S);try{await ss({defaultAgent:D??""})}catch(E){console.warn("Failed to save default agent:",E)}},[t,l]),A=i.useMemo(()=>{if(!v.providerId||!v.modelId)return[];const E=u.find(T=>T.id===v.providerId)?.models.find(T=>T.id===v.modelId)?.variants;return E?Object.keys(E):[]},[v.modelId,v.providerId,u]),C=A.length>0;i.useEffect(()=>{!C&&p&&(g(void 0),a(void 0),n(void 0),ss({defaultVariant:""}).catch(()=>{}))},[p,n,a,C]);const M=i.useCallback(async S=>{const D=S.target.checked;d(D);try{await ss({autoCreateWorktree:D})}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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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($a,{providerId:v.providerId,modelId:v.modelId,onChange:w})]}),C&&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(ks,{value:p??N,onValueChange:x,children:[e.jsx(Ns,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(nn,{placeholder:"Thinking"})}),e.jsxs(Cs,{children:[e.jsx(Ut,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),A.map(S=>e.jsx(Ut,{value:S,className:"pr-2 [&>span:first-child]:hidden",children:S},S))]})]})]}),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(Cf,{agentName:y||"",onChange:k})]})]}),(v.providerId||y)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",v.providerId&&e.jsxs("span",{className:"text-foreground",children:[v.providerId,"/",v.modelId,C?` (${p??"default"})`:""]}),v.providerId&&y&&" / ",y&&e.jsx("span",{className:"text-foreground",children:y})]}),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:c,onChange:M}),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:c?`New session (Worktree): ${Yt()} + N • New session (Standard): Shift + ${Yt()} + N`:`New session (Standard): ${Yt()} + N • New session (Worktree): Shift + ${Yt()} + N`})]})]})},Jn="opencode",ou="big-pickle",Xj=(s,r)=>{if(s){const o=s.split("/");if(o.length===2&&o[0]&&o[1])return{providerId:o[0],modelId:o[1]}}if(r.find(o=>o.id===Jn)?.models.some(o=>o.id===ou))return{providerId:Jn,modelId:ou};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},Jj=()=>{const s=at(d=>d.settingsCommitMessageModel),r=at(d=>d.setSettingsCommitMessageModel),t=at(d=>d.providers),[n,o]=i.useState(!0),a=i.useMemo(()=>t.filter(d=>d.id===Jn),[t]),l=i.useMemo(()=>{const d=s?.startsWith(`${Jn}/`)?s:void 0;return Xj(d,a)},[s,a]);i.useEffect(()=>{(async()=>{try{let u=null;if(es())u=await Lr();else{const m=Qs()?.settings;if(m)try{const p=(await m.load())?.settings;p&&(u={commitMessageModel:typeof p.commitMessageModel=="string"?p.commitMessageModel:void 0})}catch{}if(!u){const f=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});f.ok&&(u=await f.json())}}if(u){const m=typeof u.commitMessageModel=="string"&&u.commitMessageModel.trim().length>0?u.commitMessageModel.trim():void 0;r(m)}}catch(u){console.warn("Failed to load git settings:",u)}finally{o(!1)}})()},[r]);const c=i.useCallback(async(d,u)=>{const m=d&&u?`${d}/${u}`:void 0;r(m);try{await ss({commitMessageModel:m??""})}catch(f){console.warn("Failed to save commit message model:",f)}},[r]);return n?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:"Commit Messages"}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{sideOffset:8,className:"max-w-xs",children:"Configure how commit messages are generated."})]})]})}),e.jsx("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:"Model for generation"}),e.jsx($a,{providerId:l.providerId,modelId:l.modelId,onChange:c,allowedProviderIds:[Jn]}),e.jsxs("p",{className:"typography-meta text-muted-foreground mt-1",children:["This model will be used to analyze diffs and suggest commit messages.",!s&&e.jsxs(e.Fragment,{children:[" Default: ",e.jsx("span",{className:"text-foreground",children:"opencode/big-pickle"})]})]})]})})]})},Zj=()=>{const s=Ot(F=>F.getActiveProject()),r=Ot(F=>F.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=Nl(t),a=jm(t),{sessions:l,getWorktreeMetadata:c}=he(),[d,u]=i.useState(n?.branchPrefix??""),[m,f]=i.useState(n?.baseBranch??"HEAD"),[p,g]=i.useState([]),[y,h]=i.useState(!1),[j,b]=i.useState(!1),[v,w]=i.useState(null),[N,x]=i.useState(null),[k,A]=i.useState([]),[C,M]=i.useState(!1),S=".openchamber",D=i.useCallback((F,$)=>{const R=F.replace(/\\/g,"/").replace(/\/+$/,""),B=!R||R==="/"?`/${S}`:`${R}/${S}`;return $?`${B}/${$}`:B},[]),E=i.useCallback(async()=>{if(!(!t||v===!1))try{const $=(await Mn(t)).map(G=>Dn(t,G)),B=`${D(t,"")}/`,z=$.filter(G=>G.path.startsWith(B));A(z)}catch{}},[t,v,D]);i.useEffect(()=>{if(!t)return;let F=!1;return b(!0),M(!0),w(null),x(null),A([]),(async()=>{try{const $=await cn(t);if(F)return;if(w($),$){const[R,B]=await Promise.all([vl(t),Mn(t).catch(()=>[])]);if(!F){R&&x({all:R.all,current:R.current});const z=B.map(me=>Dn(t,me)),ge=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${S}`}/`,oe=z.filter(me=>me.path.startsWith(ge));A(oe)}}}catch{}finally{F||(b(!1),M(!1))}})(),()=>{F=!0}},[t]),i.useEffect(()=>{if(!t)return;let F=!1;return h(!0),(async()=>{try{const $=await fo(t);F||g($.length>0?$:[""])}catch{F||g([""])}finally{F||h(!1)}})(),()=>{F=!0}},[t]),i.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const T=N??a,I=v??o,P=i.useMemo(()=>{const F=[],$=T?.current?`Current (HEAD: ${T.current})`:"Current (HEAD)";return F.push({value:"HEAD",label:$,group:"special"}),T&&(T.all.filter(z=>!z.startsWith("remotes/")).sort((z,G)=>z.localeCompare(G)).forEach(z=>{F.push({value:z,label:z,group:"local"})}),T.all.filter(z=>z.startsWith("remotes/")).map(z=>z.replace(/^remotes\//,"")).sort((z,G)=>z.localeCompare(G)).forEach(z=>{F.push({value:z,label:z,group:"remote"})})),F},[T]),O=i.useRef(null),U=i.useCallback(F=>{u(F),O.current=F},[]),Q=i.useCallback(F=>{s?.id&&(r(s.id,{branchPrefix:F}),O.current=null)},[s?.id,r]),W=i.useCallback(()=>{Q(d)},[d,Q]);i.useEffect(()=>()=>{O.current!==null&&s?.id&&r(s.id,{branchPrefix:O.current})},[s?.id,r]);const L=i.useCallback(F=>{f(F),s?.id&&r(s.id,{baseBranch:F})},[s?.id,r]),H=i.useCallback((F,$)=>{g(R=>{const B=[...R];return B[F]=$,B})},[]),q=i.useCallback(()=>{g(F=>[...F,""])},[]),X=i.useCallback(F=>{g($=>$.filter((R,B)=>B!==F))},[]),Y=i.useCallback(async()=>{if(!t)return;const F=p.filter($=>$.trim().length>0);await lm(t,F)},[t,p]),re=i.useCallback(()=>{Y()},[Y]),K=i.useCallback(F=>{const $=F.path.replace(/\\/g,"/").replace(/\/+$/,""),R=l.filter(me=>{if(c(me.id)?.path===F.path)return!0;const Ce=me.directory;return!!(Ce&&Ce.replace(/\\/g,"/").replace(/\/+$/,"")===$)}),B=new Set(R.map(me=>me.id)),z=me=>{const Ne=l.filter(Be=>{const V=Be.parentID;return V&&me.has(V)});if(Ne.length===0)return[];const Ce=new Set(Ne.map(Be=>Be.id));return[...Ne,...z(Ce)]},G=z(B),ge=new Set,oe=[...R,...G].filter(me=>ge.has(me.id)?!1:(ge.add(me.id),!0));En.requestDelete({sessions:oe,mode:"worktree",worktree:F})},[l,c]),ae=i.useMemo(()=>l.map(F=>F.id).join(","),[l]);return i.useEffect(()=>{v&&t&&E()},[ae,v,t,E]),t?j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):I===!1?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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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(jt,{value:d,onChange:F=>U(F.target.value),onBlur:W,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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(lt,{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(ks,{value:m,onValueChange:L,children:[e.jsx(Ns,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(nn,{placeholder:"Select a branch"})}),e.jsxs(Cs,{children:[e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Default"}),P.filter(F=>F.group==="special").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.value))]}),P.some(F=>F.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Local branches"}),P.filter(F=>F.group==="local").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.value))]})]}),P.some(F=>F.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(xa,{}),e.jsxs(Jr,{children:[e.jsx(Nn,{children:"Remote branches"}),P.filter(F=>F.group==="remote").map(F=>e.jsx(Ut,{value:F.value,children:F.label},F.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."]})]}),y?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((F,$)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:F,onChange:R=>H($,R.target.value),onBlur:re,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{X($),setTimeout(Y,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"})})]},$)),e.jsxs("button",{type:"button",onClick:q,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Xt,{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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(is,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(lt,{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"})]}),C?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading worktrees..."}):k.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:k.map(F=>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:F.label||F.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:F.relativePath||F.path})]}),e.jsx("button",{type:"button",onClick:()=>K(F),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 ${F.branch||F.label}`,children:e.jsx(Xs,{className:"h-4 w-4"})})]},F.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},eS=()=>{const s=$e(d=>d.nativeNotificationsEnabled),r=$e(d=>d.setNativeNotificationsEnabled),t=$e(d=>d.notificationMode),n=$e(d=>d.setNotificationMode),[o,a]=i.useState("default");i.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission)},[]);const l=async d=>{if(d&&typeof Notification<"u"&&Notification.permission==="default")try{const u=await Notification.requestPermission();a(u),u==="granted"?r(!0):te.error("Notification permission denied",{description:"Please enable notifications in your browser settings."})}catch(u){console.error("Failed to request notification permission:",u),te.error("Failed to request notification permission")}else r(!!(d&&o==="granted"))},c=typeof Notification<"u"&&Notification.permission==="granted";return rn()?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:"Native Notifications"}),e.jsx("p",{className:"typography-ui text-muted-foreground",children:"Show browser notifications when an assistant completes a task."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Enable native notifications"}),e.jsx(pa,{checked:s&&c,onCheckedChange:l,className:"data-[state=checked]:bg-status-info"})]}),s&&c&&e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("span",{className:"typography-ui text-foreground",children:"Always notify"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"When off, only notifies if the window is out of focus."})]}),e.jsx(pa,{checked:t==="always",onCheckedChange:d=>n(d?"always":"hidden-only"),className:"data-[state=checked]:bg-status-info"})]}),o==="denied"&&e.jsx("p",{className:"typography-micro text-destructive",children:"Notification permission denied. Enable notifications in your browser settings."}),o==="granted"&&!s&&e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Notifications are enabled in your browser. Toggle the switch above to activate them."})]}):null},tS=({section:s})=>{const{isMobile:r}=$t(),t=r&&rn();if(!s)return e.jsxs(gt,{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(zl,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Pf,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(If,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(Df,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(sS,{});case"chat":return e.jsx(rS,{});case"sessions":return e.jsx(nS,{});case"git":return e.jsx(oS,{});case"notifications":return e.jsx(aS,{});default:return null}};return e.jsx(gt,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},sS=()=>e.jsx(zl,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),rS=()=>e.jsx(zl,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),nS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Pf,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(If,{})})]}),oS=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(Jj,{}),e.jsxs("div",{className:"border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1 mb-4",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Worktree"}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Configure worktree branch defaults and manage existing worktrees."})]}),e.jsx(Zj,{})]})]}),aS=()=>e.jsx(eS,{}),iS=[{id:"visual",label:"Visual",items:["Theme","Font","Spacing"]},{id:"chat",label:"Chat",items:["Tools","Diff","Reasoning"]},{id:"sessions",label:"Sessions",items:["Defaults","Retention"]},{id:"git",label:"Git",items:["Commit Messages","Worktree"],hideInVSCode:!0},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],lS=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=$t(),n=t&&rn(),[o,a]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=i.useMemo(()=>Wt(),[]),c=i.useMemo(()=>rn(),[]);i.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=i.useMemo(()=>iS.filter(m=>!(m.webOnly&&!c||m.hideInVSCode&&l)),[c,l]),u=o?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:_("flex h-full flex-col",u),children:[e.jsx(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:d.map(m=>{const f=s===m.id;return e.jsx("div",{className:_("group relative 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",{onClick:()=>r(m.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:m.label}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 leading-tight",children:m.items.join(" · ")})]})},m.id)})}),n&&e.jsx("div",{className:"border-t px-3 py-4",children:e.jsx(Df,{})})]})},cS=s=>{let r=kf.filter(o=>o.id!=="sessions");s&&(r=r.filter(o=>o.id!=="git-identities"));const t=r.find(o=>o.id==="settings"),n=r.filter(o=>o.id!=="settings");return t?[t,...n]:r},Di=200,Ai=500,dS=264,uS=940,nl=({onClose:s,forceMobile:r})=>{const t=$t(),n=r??t.isMobile,[o,a]=i.useState("settings"),[l,c]=i.useState("visual"),[d,u]=i.useState(!1),[m,f]=i.useState(()=>typeof window<"u"?Math.min(Ai,Math.max(Di,Math.floor(window.innerWidth*.2))):dS),[p,g]=i.useState(!1),[y,h]=i.useState(!1),[j,b]=i.useState(0),v=i.useRef(null),w=i.useRef(0),N=i.useRef(m),[x,k]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),A=i.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=i.useMemo(()=>Wt(),[]),M=i.useMemo(()=>cS(C),[C]);i.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),i.useEffect(()=>{const $=v.current;if(!$)return;const R=new ResizeObserver(B=>{for(const z of B)b(z.contentRect.width)});return R.observe($),b($.clientWidth),()=>R.disconnect()},[]);const S=Ot($=>$.projects),D=Ot($=>$.activeProjectId),E=Ot($=>$.setActiveProject),T=i.useMemo(()=>[...S].sort(($,R)=>($.label||$.path).localeCompare(R.label||R.path)),[S]),I=i.useMemo(()=>T.length===0?null:T.find($=>$.id===D)??T[0],[D,T]),P=i.useCallback($=>$.replace(/[-_]/g," ").replace(/\b\w/g,R=>R.toUpperCase()),[]),O=i.useMemo(()=>{if(!I)return"Project";const $=I.label&&I.label.trim().length>0?I.label:I.path.split("/").filter(Boolean).pop()||I.path;return P($)},[I,P]),U=T.length>0&&!C,Q=j===0||j>=uS;i.useEffect(()=>{if(o==="agents"){setTimeout(()=>{zr.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Br.getState().loadCommands()},0);return}o==="skills"&&(Gs.getState().loadSkills(),mo.getState().loadCatalog())},[D,o]),i.useEffect(()=>{if(typeof window>"u")return;const $=()=>{if(!p){const R=Math.min(Ai,Math.max(Di,Math.floor(window.innerWidth*.2)));f(R)}};return window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[p]),i.useEffect(()=>{if(!y)return;const $=B=>{const z=B.clientX-w.current,G=Math.min(Ai,Math.max(Di,N.current+z));f(G),g(!0)},R=()=>h(!1);return window.addEventListener("pointermove",$),window.addEventListener("pointerup",R,{once:!0}),()=>{window.removeEventListener("pointermove",$),window.removeEventListener("pointerup",R)}},[y]);const W=$=>{h(!0),w.current=$.clientX,N.current=m,$.preventDefault()},L=i.useCallback(async $=>{if(!$.target.closest("button, a, input, select, textarea")&&$.button===0&&x)try{const{getCurrentWindow:R}=await as(async()=>{const{getCurrentWindow:z}=await import("./vendor-.bun-CqCnPJev.js").then(G=>G.cA);return{getCurrentWindow:z}},__vite__mapDeps([0,1]));await R().startDragging()}catch(R){console.error("Failed to start window dragging:",R)}},[x]),H=i.useCallback(async $=>{if($.button===0&&x)try{const{getCurrentWindow:R}=await as(async()=>{const{getCurrentWindow:z}=await import("./vendor-.bun-CqCnPJev.js").then(G=>G.cA);return{getCurrentWindow:z}},__vite__mapDeps([0,1]));await R().startDragging()}catch(R){console.error("Failed to start window dragging:",R)}},[x]),q=i.useCallback($=>{a($),u(!1)},[]),X=i.useCallback(()=>{n&&u(!0)},[n]),Y=()=>{switch(o){case"settings":return e.jsx(lS,{selectedSection:l,onSelectSection:$=>{c($),X()}});case"agents":return e.jsx(mj,{onItemSelect:X});case"commands":return e.jsx(wj,{onItemSelect:X});case"skills":return e.jsx(Sj,{onItemSelect:X});case"providers":return e.jsx(Fj,{onItemSelect:X});case"git-identities":return e.jsx(Wj,{onItemSelect:X});default:return null}},re=()=>{switch(o){case"agents":return e.jsx(vj,{});case"commands":return e.jsx(jj,{});case"skills":return e.jsx(Pj,{});case"providers":return e.jsx(Lj,{});case"git-identities":return e.jsx(Gj,{});case"settings":return e.jsx(tS,{section:l});default:return null}},K=Yt(),ae=i.useMemo(()=>x&&A?"pl-[5.75rem]":"",[x,A]),F=x&&A;return e.jsxs("div",{ref:v,className:_("flex h-full flex-col overflow-hidden",x?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:L,className:_("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&ae,x?"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(Ru,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:_("flex items-center",n?"gap-1":"h-full"),children:[!n&&F&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),M.map(({id:$,label:R,icon:B})=>{const z=o===$,G=B;return n?e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{onClick:()=>q($),className:_("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",z?"text-foreground":"text-muted-foreground"),"aria-pressed":z,"aria-label":R,children:e.jsx(G,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(lt,{children:e.jsx("p",{children:R})})]},$):e.jsxs(i.Fragment,{children:[e.jsxs("button",{onClick:()=>q($),onMouseDown:z?H:void 0,className:_("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",z?"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",z?"text-foreground":"text-muted-foreground"),"aria-pressed":z,"aria-label":R,children:[e.jsx(G,{className:"h-4 w-4",weight:"regular"}),Q&&e.jsx("span",{children:R})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},$)})]}),(s||U)&&e.jsxs("div",{className:_("flex items-center gap-2",n?"":"pr-3"),children:[U&&e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:O,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(ur,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:O,className:_("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:O}),e.jsx(Ft,{className:"size-4 opacity-50"})]})}),e.jsx(Qt,{align:"end",className:"w-auto",children:e.jsx(ua,{value:I?.id??"",onValueChange:$=>{$&&E($)},children:T.map($=>{const R=$.label?.trim()?$.label.trim():$.path.split("/").filter(Boolean).pop()||$.path,B=P(R);return e.jsx(ma,{value:$.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:B})},$.id)})})})]}),s&&e.jsxs(dt,{delayDuration:500,children:[e.jsx(ut,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",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",!n&&"app-region-no-drag"),children:e.jsx(Ht,{className:"h-5 w-5"})})}),e.jsx(lt,{children:e.jsxs("p",{children:["Close Settings (",K,"+,)"]})})]})]})]}),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(os,{children:re()})}):e.jsx("div",{className:_("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(os,{children:Y()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:_("relative overflow-hidden border-r",x?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":C?"bg-background":"bg-sidebar",y?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:_("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",y?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:W,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(os,{children:Y()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(os,{children:re()})})]})})]})},mS=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:l,isMultiRunLauncherOpen:c,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=$e(),{isMobile:m}=$t(),[f,p]=i.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");i.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),sv({enabled:!0});const g=Aa(b=>b.checkForUpdates);i.useEffect(()=>{const b=setTimeout(()=>{g()},3e3);return()=>clearTimeout(b)},[g]),i.useEffect(()=>{$e.getState().isMobile!==m&&t(m)},[m,t]),i.useEffect(()=>{if(typeof window>"u")return;let b;const v=()=>{b!==void 0&&window.clearTimeout(b),b=window.setTimeout(()=>{$e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",v),()=>{window.removeEventListener("resize",v),b!==void 0&&window.clearTimeout(b)}},[]),i.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const b=document.documentElement;let v=0,w=!1,N=0,x=null;const k=$e.getState().setKeyboardOpen,A=()=>{x&&(x.style.setProperty("--oc-keyboard-avoid-offset","0px"),x.removeAttribute("data-keyboard-avoid-active"),x=null)},C=I=>{if(!I)return null;const P=I.closest("[data-keyboard-avoid]");if(P)return P;if(I.classList.contains("overlay-scrollbar-container")){const O=I.parentElement;if(O instanceof HTMLElement)return O}return I},M=()=>{v=0,w=!0,b.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},S=()=>{const I=window.visualViewport,P=I?Math.round(I.height):window.innerHeight,O=I?Math.max(0,Math.round(I.offsetTop)):0;b.style.setProperty("--oc-visual-viewport-offset-top",`${O}px`);const U=document.activeElement,Q=U?.tagName,L=Q==="INPUT"||Q==="TEXTAREA"||Q==="SELECT"||!!U?.isContentEditable,H=Math.round(b.clientHeight||window.innerHeight),q=P+O,X=Math.max(0,H-q),re=X>=(L?120:180)?X:0;if(w)re===0&&(w=!1),v=0;else if(v===0)re>0&&L&&(v=re);else{const $=!L&&P>N+6;re===0?(v=0,k(!1)):$?M():(re>0&&L||re>v)&&(v=re,k(!0))}b.style.setProperty("--oc-keyboard-inset",`${v}px`),N=P;const ae=/iPad|iPhone|iPod/.test(navigator.userAgent)&&v>0?34:0;b.style.setProperty("--oc-keyboard-home-indicator",`${ae}px`);const F=L?C(U):null;if(!m||!F||!U)A();else{F!==x&&(A(),x=F);const $=O+P,B=U.getBoundingClientRect().bottom-$,z=8,G=Math.max(v,re),ge=B>z&&G>0?Math.min(B,G):0,oe=x;oe&&(oe.style.setProperty("--oc-keyboard-avoid-offset",`${ge}px`),oe.setAttribute("data-keyboard-avoid-active","true"))}if(m&&L){const $=document.scrollingElement;$&&$.scrollTop!==0&&($.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};S();const D=window.visualViewport;D?.addEventListener("resize",S),D?.addEventListener("scroll",S),window.addEventListener("resize",S),window.addEventListener("orientationchange",S);const E=I=>{const P=I.target;if(!P)return;const O=P.tagName;(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable)&&(w=!1),S()};document.addEventListener("focusin",E,!0);const T=I=>{const P=I.target;if(!P)return;const O=P.tagName;if(O==="INPUT"||O==="TEXTAREA"||O==="SELECT"||P.isContentEditable){const Q=I.relatedTarget,W=Q?.tagName;if(W==="INPUT"||W==="TEXTAREA"||W==="SELECT"||Q?.isContentEditable)return;M()}};return document.addEventListener("focusout",T,!0),()=>{D?.removeEventListener("resize",S),D?.removeEventListener("scroll",S),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("focusin",E,!0),document.removeEventListener("focusout",T,!0),A()}},[m]);const y=i.useMemo(()=>{switch(r){case"git":return e.jsx(O0,{});case"diff":return e.jsx(gb,{});case"terminal":return e.jsx(Q0,{});case"files":return e.jsx(aj,{});default:return null}},[r]),h=r==="chat",j=a&&!m;return e.jsx(Gb,{children:e.jsxs("div",{className:_("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(Tb,{}),e.jsx(_b,{}),e.jsx(zb,{}),m?e.jsxs(e.Fragment,{children:[!(a||c)&&e.jsx(Lc,{}),e.jsx("div",{className:_("flex flex-1 overflow-hidden bg-background",(a||c)&&"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:_("absolute inset-0",!h&&"invisible"),children:e.jsx(os,{children:e.jsx(Xn,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:y})})]})}),e.jsx(ws,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(ga,{mobileVariant:!0})}),c&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(os,{children:e.jsx(rd,{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(os,{children:e.jsx(nl,{onClose:()=>l(!1)})})})]}):e.jsxs(e.Fragment,{children:[!j&&e.jsx(Db,{isOpen:s,isMobile:m,children:e.jsx(ga,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:_("absolute inset-0 flex flex-col",(j||c)&&"invisible"),children:[e.jsx(Lc,{}),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:_("absolute inset-0",!h&&"invisible"),children:e.jsx(os,{children:e.jsx(Xn,{})})}),y&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(os,{children:y})})]})})]}),c&&e.jsx("div",{className:_("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(os,{children:e.jsx(rd,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),j&&e.jsx("div",{className:_("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(os,{children:e.jsx(nl,{onClose:()=>l(!1)})})})]}),!j&&e.jsx(Sb,{})]})})},fS=550,pS=700,hS=280,gS=()=>{const s=kr(),r=i.useMemo(()=>(typeof window<"u"?window.__VSCODE_CONFIG__?.viewMode:null)==="editor"?"editor":"sidebar",[]),t=i.useMemo(()=>{const T=typeof window<"u"?window.__VSCODE_CONFIG__?.initialSessionId:null;return typeof T=="string"&&T.trim().length>0?T.trim():null},[]),n=i.useRef(!1),[o,a]=i.useState("sessions"),[l,c]=i.useState(0),d=i.useRef(null),u=he(T=>T.currentSessionId),m=he(T=>T.sessions),f=i.useMemo(()=>u?m.find(T=>T.id===u)?.title||"Session":null,[u,m]),p=he(T=>!!T.newSessionDraft?.open),g=he(T=>T.openNewSessionDraft),[y,h]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),j=at(T=>T.isInitialized),b=at(T=>T.initializeApp),v=he(T=>T.loadSessions),w=he(T=>T.loadMessages),N=he(T=>T.messages),[x,k]=i.useState(()=>j),[A,C]=i.useState(!1),M=i.useRef(0);i.useEffect(()=>{u&&a("chat")},[u]),i.useEffect(()=>{const T=s.vscode;T&&T.executeCommand("openchamber.setActiveSession",u,f)},[f,u,s.vscode]),i.useEffect(()=>{r!=="editor"&&!u&&!p&&o==="chat"&&a("sessions")},[u,p,o,r]);const S=i.useCallback(()=>{a("sessions")},[]);i.useEffect(()=>{const T=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(T==="connected"||T==="connecting"||T==="error"||T==="disconnected")&&h(T);const I=P=>{const U=P.detail?.status;(U==="connected"||U==="connecting"||U==="error"||U==="disconnected")&&h(U)};return window.addEventListener("openchamber:connection-status",I),()=>window.removeEventListener("openchamber:connection-status",I)},[]),i.useEffect(()=>{const T=I=>{const O=I.detail?.view;O==="settings"?a("settings"):O==="chat"?a("chat"):O==="sessions"&&a("sessions")};return window.addEventListener("openchamber:navigate",T),()=>window.removeEventListener("openchamber:navigate",T)},[]),i.useEffect(()=>{(async()=>{if(A||x||y!=="connected")return;const I=Date.now();if(!(I-M.current<750)){M.current=I,C(!0);try{const P=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();P&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:j}),j||await b();const O=at.getState();if(!O.isInitialized||!O.isConnected||O.providers.length===0||O.agents.length===0)return;await v();const U=he.getState().error;if(P&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:O.providers.length,agents:O.agents.length,sessions:he.getState().sessions.length,sessionsError:U}),typeof U=="string"&&U.length>0)return;k(!0)}catch{}finally{C(!1)}}})()},[y,j,x,b,A,v]),i.useEffect(()=>{if(r==="editor"&&!n.current&&!(!x||y!=="connected")){if(!t){n.current=!0,g();return}m.some(T=>T.id===t)&&(n.current=!0,he.getState().setCurrentSession(t))}},[y,x,t,g,m,r]),i.useEffect(()=>{(async()=>{if(!x||y!=="connected"||o!=="chat"||p||!u)return;if(!(N.has(u)&&(N.get(u)?.length||0)>0))try{await w(u)}catch{}})()},[y,u,o,x,w,N,p]),i.useEffect(()=>{const T=d.current;if(!T)return;const I=new ResizeObserver(P=>{for(const O of P)c(O.contentRect.width)});return I.observe(T),c(T.clientWidth),()=>I.disconnect()},[]);const D=l>0&&l<fS,E=l>=pS;return i.useEffect(()=>{E&&o==="sessions"&&r==="sidebar"&&a("chat")},[E,o,r]),e.jsx("div",{ref:d,className:"h-full w-full bg-background text-foreground flex flex-col",children:r==="editor"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(_o,{title:m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]}):o==="settings"?e.jsx(nl,{onClose:()=>a(E?"chat":"sessions"),forceMobile:D}):E?e.jsxs("div",{className:"flex h-full",children:[e.jsx("div",{className:"h-full border-r border-border overflow-hidden flex-shrink-0",style:{width:hS},children:e.jsx(ga,{mobileVariant:!0,allowReselect:!0,hideDirectoryControls:!0,showOnlyMainWorkspace:!0})}),e.jsxs("div",{className:"flex-1 flex flex-col min-w-0",children:[e.jsx(_o,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]})]}):o==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(_o,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ga,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>a("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(_o,{title:p&&!u?"New session":m.find(T=>T.id===u)?.title||"Chat",showBack:!0,onBack:S,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(os,{children:e.jsx(Xn,{})})})]})})},_o=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:l,showContextUsage:c})=>{const{getCurrentModel:d}=at(),u=he(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,y=u(p,g);return e.jsxs("div",{className:"flex items-center gap-1.5 pl-1 pr-2 py-1 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-7 w-7 items-center justify-center 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(Fu,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1",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(Xt,{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(so,{className:"h-5 w-5"})}),l&&e.jsx(Ki,{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(en,{className:"h-5 w-5"})}),c&&y&&y.totalTokens>0&&e.jsx(Vi,{totalTokens:y.totalTokens,percentage:y.percentage,contextLimit:y.contextLimit,outputLimit:y.outputLimit??0,size:"compact"})]})},ol=".openchamber",Oo=s=>{const r=Ot.getState(),t=r.activeProjectId,n=t?r.projects.find(c=>c.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?Rt(s):"",a=`/${ol}/`,l=o.indexOf(a);return l>0?o.slice(0,l):s?Rt(s):null},Rt=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},au=s=>{const r=Rt(s);return!r||r==="/"?`/${ol}`:`${r}/${ol}`},xS=(s,r)=>{const t=Rt(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const l=Rt(o);if(l)return l}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},yS=async s=>{const r=Rt(s);if(!r)return[];try{const n=(await Ee.listLocalDirectory(r)).filter(o=>o.isDirectory);return xS(r,n)}catch{return[]}},Er=(s,r)=>{const t=Rt(s),n=Rt(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},Tf=async(s,r)=>{const t=Rt(r);if(!t)return t;try{const n=await s.path.get({directory:t});return Rt(n.data?.directory??"")||t}catch{return t}},Ff=async(s,r)=>{const t=Rt(r);if(!t)return[];const n=await Tf(s,t),o=l=>l.filter(c=>{const d=Rt(c.directory??"");return d?Er(d,t)||n!==t&&Er(d,n):!1}),a=async l=>{const c=await s.session.list({directory:l});return Array.isArray(c.data)?c.data:[]};try{const l=o(await a(t));if(l.length>0)return l}catch{}if(n&&n!==t)try{const l=o(await a(n));if(l.length>0)return l}catch{}try{const l=await s.session.list(void 0),c=Array.isArray(l.data)?l.data:[];return o(c)}catch{return[]}},bS=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(Rt(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>Rt(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await Mn(r),a=new Map(o.map(l=>[Rt(l.worktree),l]));n.forEach(l=>{const c=a.get(l);c&&t.set(l,Dn(r,c))})}catch{}return t},Ei=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await bS(t,n),l=he.getState(),c=Array.from(new Set(o.map(p=>Rt(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<c.length;){const p=c[u];u+=1;const g=t.sessions.filter(v=>Rt(v.path)===p).map(v=>v.id),y=l.getSessionsByDirectory(p),h=Array.isArray(y)?y.map(v=>v.id):[];let j=[];if(h.length===0)try{j=(await Ff(r,p)).map(w=>w.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,c.length)},f)),m};function vS(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),l=r.length>=4&&!isNaN(a)&&String(a)===o,c=l?r.slice(2,-1):r.slice(2);if(c.length===0)return null;const d=c.join("/");return{groupSlug:t,provider:n,model:d,index:l?a:1}}const Tr=Vt()(Jt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=vt.getState().currentDirectory,n=Oo(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Rt(n),a=au(o),l=r().groups;s({isLoading:!0,error:null});try{const c=Ee.getApiClient(),d=await Tf(c,o),u=au(d);let m=new Map,f=[];try{f=await Mn(o),m=new Map(f.map(w=>[Rt(w.worktree),w]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await c.session.list({directory:o}),x=Array.isArray(N.data)?N.data:[];if(x.some(k=>{const A=Rt(k.directory??"");return Er(A,a)||Er(A,u)}))return x}catch{}const w=await c.session.list(void 0);return Array.isArray(w.data)?w.data:[]},g=async w=>{const N=new Map,x=5;let k=0;const A=async()=>{for(;k<w.length;){const C=w[k];k+=1;const M=Rt(C);if(M)try{(await Ff(c,M)).forEach(D=>N.set(D.id,D))}catch(S){console.debug("Failed to fetch sessions from worktree:",M,S)}}};return await Promise.all(Array.from({length:Math.min(x,w.length)},A)),Array.from(N.values())};let h=(await p()).filter(w=>{const N=Rt(w.directory??"");return N?Er(N,a)||Er(N,u):!1});if(h.length===0){const w=new Set;f.map(x=>Rt(x.worktree)).filter(x=>Er(x,a)||Er(x,u)).forEach(x=>w.add(x));const N=Array.from(new Set([a,u].map(x=>Rt(x)).filter(Boolean)));await Promise.all(N.map(async x=>{(await yS(x)).forEach(A=>w.add(A))})),w.size>0&&(h=await g(Array.from(w)))}const j=new Map;for(const w of h){const N=w.time?.updated??0;j.set(w.id,typeof N=="number"?N:0)}const b=new Map;for(const w of h){const N=vS(w.title);if(!N)continue;const x=Rt(w.directory),k=m.get(x),A={id:w.id,path:x,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?Dn(o,k):void 0},C=b.get(N.groupSlug);C?C.push(A):b.set(N.groupSlug,[A])}const v=Array.from(b.entries()).map(([w,N])=>{const x=N.reduce((k,A)=>{const C=j.get(A.id)??0;return Math.max(k,C)},0);return{name:w,sessions:N.sort((k,A)=>{const C=k.providerId.localeCompare(A.providerId);if(C!==0)return C;const M=k.modelId.localeCompare(A.modelId);return M!==0?M:k.instanceNumber-A.instanceNumber}),lastActive:x||Date.now(),sessionCount:N.length}});v.sort((w,N)=>w.name.localeCompare(N.name)),s({groups:v,isLoading:!1,error:null})}catch(c){console.error("Failed to load agent groups:",c),s({groups:l.length>0?l:[],isLoading:!1,error:c instanceof Error?c.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(l=>l.name===t);if(!n)return!1;const o=vt.getState().currentDirectory,a=Oo(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const l=Ee.getApiClient(),c=await Ei({apiClient:l,group:n,projectDirectory:Rt(a),worktreePaths:n.sessions.map(f=>f.path)}),d=he.getState(),u=new Set;c.forEach(({worktreePath:f,sessionIds:p,metadata:g})=>{p.forEach(y=>{u.add(y),g&&(d.setWorktreeMetadata(y,g),d.setSessionDirectory(y,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(l){return s({error:l instanceof Error?l.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=Rt(n);if(!a)return!1;const l=vt.getState().currentDirectory,c=Oo(l);if(!c)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=Ee.getApiClient(),u=await Ei({apiClient:d,group:o,projectDirectory:Rt(c),worktreePaths:[a]}),m=he.getState(),f=new Set;u.forEach(({worktreePath:y,sessionIds:h,metadata:j})=>{h.forEach(b=>{f.add(b),j&&(m.setWorktreeMetadata(b,j),m.setSessionDirectory(b,y))})});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(y=>y.name===t);if(!g)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const y=r().selectedSessionId,h=new Set(g.sessions.map(j=>j.id));(!y||!h.has(y))&&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=Rt(n);if(!a)return!1;const c=Array.from(new Set(o.sessions.map(m=>Rt(m.path)).filter(Boolean))).filter(m=>m!==a);if(c.length===0)return!0;const d=vt.getState().currentDirectory,u=Oo(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=Ee.getApiClient(),f=await Ei({apiClient:m,group:o,projectDirectory:Rt(u),worktreePaths:c}),p=he.getState(),g=new Set;f.forEach(({worktreePath:h,sessionIds:j,metadata:b})=>{j.forEach(v=>{g.add(v),b&&(p.setWorktreeMetadata(v,b),p.setSessionDirectory(v,h))})});const{failedIds:y}=await p.deleteSessions(Array.from(g),{archiveWorktree:!0,silent:!0});if(y.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=>Rt(b.path)===a)??h?.sessions[0]??null;s({selectedSessionId:j?.id??null})}return y.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"})),wS=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`},jS=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=i.useState(!1),[a,l]=i.useState(!1),[c,d]=i.useState(!1),u=Tr(f=>f.deleteGroup),m=i.useCallback(async()=>{if(c)return;if(d(!0),te.info(`Deleting "${s.name}"...`),await u(s.name))te.success(`Deleted "${s.name}"`);else{const p=Tr.getState().error;te.error(p||`Failed to delete "${s.name}"`)}d(!1),l(!1)},[u,s.name,c]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:_("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(zt,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:wS(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(qt,{open:n,onOpenChange:o,children:[e.jsx(Kt,{asChild:!0,children:e.jsx("button",{type:"button",className:_("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(Or,{className:"h-3.5 w-3.5"})})}),e.jsx(Qt,{align:"end",className:"min-w-[140px]",children:e.jsx(Et,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),l(!0)},children:"Delete"})})]})})]})}),e.jsx(ms,{open:a,onOpenChange:l,children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Delete agent group"}),e.jsxs(Ms,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Js,{children:[e.jsx(Ie,{variant:"outline",onClick:()=>l(!1),disabled:c,children:"Cancel"}),e.jsx(Ie,{variant:"destructive",onClick:()=>{m()},disabled:c,children:c?"Deleting…":"Delete"})]})]})})]})},SS=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=i.useState(""),[l,c]=i.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Tr(),f=vt(j=>j.currentDirectory);i.useEffect(()=>{f&&m()},[f,m]);const p=5,g=i.useMemo(()=>{if(!o.trim())return d;const j=o.toLowerCase();return d.filter(b=>b.name.toLowerCase().includes(j))},[o,d]),y=l?g:g.slice(0,p),h=g.length-p;return e.jsxs("div",{className:_("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(lr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(jt,{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(Ie,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Xt,{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(Ft,{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(gt,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[y.map(j=>e.jsx(jS,{group:j,isSelected:r===j.name,onSelect:()=>t?.(j.name)},j.name)),!l&&h>0&&e.jsxs("button",{type:"button",onClick:()=>c(!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,")"]}),l&&g.length>p&&e.jsx("button",{type:"button",onClick:()=>c(!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"})]})]})]})},kS=10*1024*1024,NS=5,CS=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=i.useState(""),[a,l]=i.useState(""),[c,d]=i.useState([]),[u,m]=i.useState(""),[f,p]=i.useState("HEAD"),[g,y]=i.useState([]),[h,j]=i.useState(!1),[b,v]=i.useState([]),[w,N]=i.useState(!1),[x,k]=i.useState(!1),A=i.useRef(null),C=i.useRef(null),M=vt(K=>K.currentDirectory??null),{isGitRepository:S,isLoading:D}=_l(M),E=i.useMemo(()=>{if(typeof window>"u")return null;const K=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof K=="string"&&K.trim().length>0?K.trim():null},[]),T=i.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),I=Ot(K=>K.activeProjectId),P=Ot(K=>K.projects),O=i.useMemo(()=>{if(T&&E)return E;if(I){const R=P.find(B=>B.id===I);if(R?.path)return R.path}const K=M??E;if(!K)return null;const ae=K.replace(/\\/g,"/").replace(/\/+$/,"")||K,$=ae.indexOf("/.openchamber/");return $>0?ae.slice(0,$):ae.endsWith("/.openchamber")?ae.slice(0,ae.length-13):ae},[I,P,M,E,T]);i.useEffect(()=>{if(!O)return;let K=!1;return k(!0),(async()=>{try{const ae=await fo(O);K||v(ae)}catch{}finally{K||k(!1)}})(),()=>{K=!0}},[O]);const U=i.useCallback(K=>{c.length>=NS||d(ae=>[...ae,K])},[c.length]),Q=i.useCallback(K=>{d(ae=>ae.filter((F,$)=>$!==K))},[]),W=i.useCallback((K,ae)=>{d(F=>F.map(($,R)=>R===K?ae:$))},[]),L=async K=>{const ae=K.target.files;if(!ae)return;let F=0;for(let $=0;$<ae.length;$++){const R=ae[$];if(R.size>kS){te.error(`File "${R.name}" is too large (max 10MB)`);continue}try{const B=await new Promise((G,ge)=>{const oe=new FileReader;oe.onload=()=>G(oe.result),oe.onerror=ge,oe.readAsDataURL(R)}),z={id:ya(),filename:R.name,mimeType:R.type||"application/octet-stream",size:R.size,dataUrl:B};y(G=>[...G,z]),F++}catch(B){console.error("File attach failed",B),te.error(`Failed to attach "${R.name}"`)}}F>0&&te.success(`Attached ${F} file${F>1?"s":""}`),A.current&&(A.current.value="")},H=K=>{y(ae=>ae.filter(F=>F.id!==K))},q=h||t,X=!!(n.trim()&&a.trim()&&c.length>=1&&S&&!D),Y=async K=>{if(K.preventDefault(),!(!X||q)){j(!0);try{const ae=c.map(({providerID:R,modelID:B,displayName:z,variant:G})=>({providerID:R,modelID:B,displayName:z,variant:G})),F=g.length>0?g.map(R=>({mime:R.mimeType,filename:R.filename,url:R.dataUrl})):void 0,$=b.filter(R=>R.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:ae,agent:u||void 0,worktreeBaseBranch:f,files:F,setupCommands:$.length>0?$:void 0}),o(""),l(""),d([]),m(""),y([]),p("HEAD")}catch(ae){console.error("Failed to create agent group:",ae),te.error("Failed to create agent group")}finally{j(!1)}}},re=K=>{Fl(K)||K.key==="Enter"&&!K.shiftKey&&(K.preventDefault(),X&&!q&&Y(K))};return e.jsx("div",{className:_("flex flex-col items-center justify-center h-full w-full p-4",s),children:e.jsxs("form",{onSubmit:Y,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(jt,{id:"group-name",value:n,onChange:K=>o(K.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(zt,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Vm,{directory:M,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(po,{open:w,onOpenChange:N,children:[e.jsxs(Ta,{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(K=>K.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",b.filter(K=>K.trim()).length," configured)"]})]}),e.jsx(Ft,{className:_("h-4 w-4 text-muted-foreground transition-transform duration-200",w&&"rotate-180")})]}),e.jsx(ho,{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."]}),x?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[b.map((K,ae)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(jt,{value:K,onChange:F=>{const $=[...b];$[ae]=F.target.value,v($)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const F=b.filter(($,R)=>R!==ae);v(F)},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"})})]},ae)),e.jsxs("button",{type:"button",onClick:()=>v([...b,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Xt,{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(Gm,{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(Um,{selectedModels:c,onAdd:U,onRemove:Q,onUpdate:W,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(Ss,{ref:C,id:"prompt",value:a,onChange:K=>l(K.target.value),onKeyDown:re,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(K=>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:[K.mimeType.startsWith("image/")?e.jsx(mr,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(nr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:K.filename,children:K.filename}),e.jsx("button",{type:"button",onClick:()=>H(K.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},K.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:A,type:"file",multiple:!0,className:"hidden",onChange:L,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>A.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(Du,{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:[c.length," model",c.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!X||q,className:_("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",X?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:q?e.jsx(Bh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(Sa,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},MS=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Tr(),{setCurrentSession:l,currentSessionId:c}=he(),[d,u]=i.useState(null),[m,f]=i.useState(!1),p=i.useMemo(()=>t?s.sessions.find(w=>w.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),g=i.useCallback(w=>{n(w.id),l(w.id)},[n,l]);i.useEffect(()=>{if(s.sessions.length>0){const w=t?s.sessions.find(N=>N.id===t)??s.sessions[0]:s.sessions[0];w&&(w.id!==c&&l(w.id),t||n(w.id))}},[s.name,s.sessions,t,c,n,l]);const y=p?.id===c,h=i.useCallback(()=>{if(!p?.path){te.error("No worktree path available");return}navigator.clipboard.writeText(p.path).then(()=>{te.success("Worktree path copied")}).catch(()=>{te.error("Failed to copy path")})},[p?.path]),j=i.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),b=i.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),v=i.useCallback(async()=>{if(!(!d||m)){f(!0);try{if(d.kind==="remove")if(te.info("Removing worktree..."),await o(s.name,d.path))te.success("Worktree removed");else{const N=Tr.getState().error;te.error(N||"Failed to remove worktree");return}else if(te.info("Removing other worktrees..."),await a(s.name,d.path))te.success("Removed other worktrees");else{const N=Tr.getState().error;te.error(N||"Failed to remove other worktrees");return}u(null)}finally{f(!1)}}},[o,s.name,m,a,d]);return e.jsxs("div",{className:_("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(zt,{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(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsxs(Ie,{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(cs,{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(Ft,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(Qt,{align:"start",className:"w-[var(--radix-dropdown-menu-trigger-width)]",children:s.sessions.map(w=>e.jsxs(Et,{onClick:()=>g(w),className:"flex items-center gap-2 py-2",children:[e.jsx(cs,{providerId:w.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:w.modelId}),w.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",w.instanceNumber]})]}),w.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx(zt,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:w.worktreeMetadata?.label||w.branch})]})]}),p?.id===w.id&&e.jsx(_t,{className:"h-4 w-4 text-primary flex-shrink-0"})]},w.id))})]})}),e.jsxs(qt,{children:[e.jsx(Kt,{asChild:!0,children:e.jsx(Ie,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Or,{className:"h-4 w-4"})})}),e.jsxs(Qt,{align:"end",className:"min-w-[220px]",children:[e.jsx(Et,{onSelect:w=>{w.preventDefault(),j()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Et,{onSelect:w=>{w.preventDefault(),b()},children:"Leave this one, remove others"}),e.jsxs(Et,{onClick:w=>{w.stopPropagation(),h()},disabled:!p?.path,children:[e.jsx(Ys,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ms,{open:!!d,onOpenChange:w=>{w||u(null)},children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:d?.kind==="remove"?"Remove worktree":"Remove other worktrees"}),e.jsx(Ms,{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(Js,{children:[e.jsx(Ie,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ie,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{v()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?y?e.jsx(yf,{sessionId:p.id,children:e.jsx(xf,{})}):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(cs,{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"})})})]})},DS=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=i.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=at(w=>w.isInitialized),a=at(w=>w.initializeApp),l=he(w=>w.loadSessions),c=vt(w=>w.setDirectory),d=i.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Tr(),{createMultiRun:g,isLoading:y}=Yn();i.useEffect(()=>{if(!r)return;const w=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(w==="connected"||w==="connecting"||w==="error"||w==="disconnected")&&n(w);const N=x=>{const A=x.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&n(A)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),i.useEffect(()=>{if(!r||t!=="connected")return;const w=Date.now();if(w-d.current<750)return;d.current=w;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{c(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const k=at.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await l(),Zt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:he.getState().sessions.length})}catch{}})()},[t,o,a,r,l,c]);const h=i.useCallback(w=>{m(w)},[m]),j=i.useCallback(()=>{m(null)},[m]),b=i.useCallback(async w=>{te.info(`Creating agent group "${w.name}" with ${w.models.length} model(s)...`);const N=await g(w);if(N){te.success(`Agent group "${w.name}" created with ${N.sessionIds.length} session(s)`);const x=N.groupSlug,k=async(A=6)=>{for(let C=0;C<A;C+=1){if(await p(),Tr.getState().groups.some(S=>S.name===x))return!0;await new Promise(S=>setTimeout(S,500))}return!1};try{await he.getState().loadSessions()}catch{}await k(),m(x)}else{const x=Yn.getState().error;te.error(x||"Failed to create agent group")}},[g,p,m]),v=f();return e.jsxs("div",{className:_("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(SS,{selectedGroupName:u,onGroupSelect:h,onNewAgent:j})}),e.jsx("div",{className:"flex-1 min-w-0",children:v?e.jsx(MS,{group:v}):e.jsx(CS,{onCreateGroup:b,isCreating:y})})]})},Ii=({...s})=>{const{theme:r="system"}=zh();return e.jsx(Wh,{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})},AS=(s=5e3)=>{const[r,t]=Ae.useState(null);return Ae.useEffect(()=>{if(!es())return;let n=!1,o=null;const a=async()=>{const l=await cg();n||(t(l),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},ES=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:l}=he(),c=AS(4e3),d=i.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=i.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(Tl,{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(Hh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(Ie,{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," / ",us.MAX_SESSIONS]})]})]}),c&&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:c.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:[c.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:c.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:[us.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:[us.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:[us.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(gt,{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(Uh,{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>us.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(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsxs(Ie,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(Xs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(lt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{l()},children:"Evict LRU"})}),e.jsx(lt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(dt,{delayDuration:1e3,children:[e.jsx(ut,{asChild:!0,children:e.jsx(Ie,{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(lt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},IS="openchamber-message-cursors",Tn="cursors",PS=1,Rf="openchamber.messageCursors",Wl=()=>typeof window<"u",Hl=()=>Wl()&&typeof indexedDB<"u",_f=()=>Hl()?new Promise((s,r)=>{const t=indexedDB.open(IS,PS);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Tn)||n.createObjectStore(Tn)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),Of=()=>{if(!Wl())return{};try{const s=window.localStorage.getItem(Rf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},TS=s=>{if(Wl())try{window.localStorage.setItem(Rf,JSON.stringify(s))}catch{}},FS=async(s,r,t)=>{if(!s||!r)return;if(Hl())try{const o=await _f();await new Promise((a,l)=>{const c=o.transaction(Tn,"readwrite");c.objectStore(Tn).put({messageId:r,completedAt:t},s),c.oncomplete=()=>a(),c.onerror=()=>l(c.error??new Error("Cursor write failed")),c.onabort=()=>l(c.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=Of();n[s]={messageId:r,completedAt:t},TS(n)},RS=async s=>{if(!s)return null;if(Hl())try{const t=await _f(),n=await new Promise((o,a)=>{const l=t.transaction(Tn,"readonly"),d=l.objectStore(Tn).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),l.onerror=()=>a(l.error??new Error("Cursor read failed")),l.onabort=()=>a(l.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return Of()[s]??null},_S=50,OS=750,iu=new WeakMap,lu=s=>{if(!s||!Array.isArray(s))return 0;const r=iu.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 iu.set(s,t),t},$S=10,cu=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<$S?null:n},du=(s,r)=>{const t=cu(s),n=cu(r);return!t||!n||t.length!==n.length?!0:t>n},al=new Map,uu=(s,r)=>{const t=`${s}:${r}`,n=al.get(t);if(n&&n.sessionId===s)return n.message;const l=(he.getState().messages.get(s)||[]).find(c=>c.info.id===r)||null;return al.set(t,{sessionId:s,message:l}),l},LS=s=>{const r=s.split(/[-_]/),t=[];let n=0;for(;n<r.length;){const o=r[n];if(/^\d+$/.test(o)&&n+1<r.length&&/^\d+$/.test(r[n+1])){const a=`${o}.${r[n+1]}`;t.push(a),n+=2;continue}t.push(o),n+=1}return t.map(o=>o.charAt(0).toUpperCase()+o.slice(1)).join(" ")},BS=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:l,currentSessionId:c,applySessionMetadata:d,sessions:u,getWorktreeMetadata:m,loadMessages:f,loadSessions:p,updateSession:g,removeSessionFromStore:y}=he(),{checkConnection:h}=at(),j=$e(De=>De.nativeNotificationsEnabled),b=$e(De=>De.notificationMode),v=vt(De=>De.currentDirectory),w=i.useMemo(()=>{if(!c)return;try{const ne=m?.(c);if(ne?.path)return ne.path}catch(ne){console.warn("Failed to inspect worktree metadata for session directory:",ne)}const De=u.find(ne=>ne.id===c);if(De&&typeof De.directory=="string"&&De.directory.trim().length>0)return De.directory.trim()},[c,m,u]),N=i.useMemo(()=>{if(w&&w.length>0)return w;if(typeof v=="string"&&v.trim().length>0)return v.trim()},[w,v]);i.useEffect(()=>{let De=!1;const ne=async()=>{try{const be=await Ee.listPendingPermissions();if(De||be.length===0)return;be.forEach(ke=>{o(ke)})}catch{}},rt=async()=>{try{const ke=Ot.getState().projects.map(Re=>Re.path),Qe=u.map(Re=>Re.directory),tt=[N,...ke,...Qe],He=await Ee.listPendingQuestions({directories:tt});if(De||He.length===0)return;He.forEach(Re=>{a(Re)})}catch{}};return ne(),rt(),()=>{De=!0}},[o,a,N,u]);const x=i.useCallback(De=>{if(typeof De!="string")return null;const ne=De.trim();if(!ne)return null;const rt=ne.replace(/\\/g,"/");return rt.length>1?rt.replace(/\/+$/,""):rt},[]),k=i.useCallback(De=>{if(!De)return null;try{const rt=m?.(De),be=x(rt?.path??null);if(be)return be}catch{}const ne=u.find(rt=>rt.id===De);return x(ne?.directory??null)},[m,x,u]),A=$e(De=>De.setEventStreamStatus),C=i.useRef(null),M=i.useCallback((De,ne)=>{const rt=ne??null,be=C.current;if(!(be&&be.status===De&&be.hint===rt)){if(C.current={status:De,hint:rt},Zt()){const Qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[De]??"[INFO]",tt=rt?`${Qe} SSE ${De}: ${rt}`:`${Qe} SSE ${De}`;console.info(tt)}A(De,rt)}},[A]),S=i.useCallback((De,ne)=>{if(!De)return Promise.resolve();const rt=Date.now();if(L.current)return L.current;if(rt-H.current<OS)return Promise.resolve();const be=f(De).catch(ke=>{console.warn(`[useEventStream] Failed to resync messages (${ne}):`,ke)}).finally(()=>{L.current=null,H.current=Date.now()});return L.current=be,be},[f]),D=i.useCallback(async De=>{Zt()&&console.info("[useEventStream] Bootstrapping state:",De);try{await Promise.all([p(),c?S(c,De):Promise.resolve()])}catch(ne){console.warn("[useEventStream] Bootstrap failed:",De,ne)}},[c,p,S]),E=i.useCallback((De,ne,rt)=>{Zt()&&console.debug(`[MessageTracker] ${De}: ${ne}`,rt)},[]),T=i.useCallback(De=>{Zt()&&console.debug(`[MessageTracker] ${De}: reported`)},[]),I=i.useRef(null),P=i.useRef(null),O=i.useRef(0);i.useRef(new Set);const U=i.useRef(new Map),Q=i.useRef(null),W=i.useRef(!1),L=i.useRef(null),H=i.useRef(0),q=i.useRef(new Set),X=i.useRef(new Set),Y=i.useRef(new Set),re=i.useRef(new Set),K=i.useCallback(()=>{if(typeof document>"u")return"visible";const De=document.visibilityState;return De==="hidden"&&document.hasFocus()?"visible":De},[]),ae=i.useRef(K()),F=i.useRef(typeof navigator>"u"?!0:navigator.onLine),$=i.useRef(!1),R=i.useRef(null),B=i.useRef(null),z=i.useRef(Date.now()),G=i.useRef(!1),ge=i.useCallback(De=>{const ne=Date.now();ne-z.current>25e3&&(D(De),z.current=ne)},[D]);i.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(G.current=!0)},[]);const oe=i.useRef(new Map),me=i.useRef(new Map),Ne=i.useRef(0),Ce=i.useRef(null),Be=i.useRef(c),V=i.useRef(null),J=i.useRef(null);i.useEffect(()=>{Be.current=c},[c]);const ee=i.useCallback((De,ne)=>{if(!De)return;const rt=Date.now(),be=U.current,ke=be.get(De);if(ke&&rt-ke<3e3)return;be.set(De,rt);const Qe=tt=>{if(typeof ne=="string"&&ne.trim().length>0)return ne.trim();try{const Re=m?.(tt);if(Re?.path)return Re.path}catch{}const He=u.find(Re=>Re.id===tt);return He&&typeof He.directory=="string"&&He.directory.trim().length>0?He.directory.trim():null};setTimeout(async()=>{try{const tt=Qe(De),He=tt?await Ee.withDirectory(tt,()=>Ee.getSession(De)):await Ee.getSession(De);if(He){const Re={};typeof He.title=="string"&&He.title.length>0&&(Re.title=He.title),He.summary!==void 0&&(Re.summary=He.summary),Object.keys(Re).length>0&&d(De,Re)}}catch(tt){console.warn("Failed to refresh session metadata:",tt)}},100)},[d,m,u]),xe=i.useCallback((De,ne)=>{if(he.getState().sessionActivityPhase?.get(De)===ne){me.current=new Map(he.getState().sessionActivityPhase??new Map);return}const be=oe.current.get(De);be&&(clearTimeout(be),oe.current.delete(De));const ke=new Map(he.getState().sessionActivityPhase??new Map);if(ke.set(De,ne),me.current=ke,he.setState({sessionActivityPhase:ke}),ne==="cooldown"){const Qe=setTimeout(()=>{if(oe.current.delete(De),he.getState().sessionActivityPhase?.get(De)==="cooldown"){const He=new Map(he.getState().sessionActivityPhase??new Map);He.set(De,"idle"),me.current=He,he.setState({sessionActivityPhase:He})}},2e3);oe.current.set(De,Qe)}},[]),fe=i.useCallback(async()=>{const De=Date.now();if(Ce.current)return Ce.current;if(De-Ne.current<1500)return;Ne.current=De;const ne=be=>{const ke=new Set,Qe=new Set(u.map(He=>He.id));Object.entries(be).forEach(([He,Re])=>{if(!He||!Re)return;ke.add(He);const nt=Re.type==="busy"||Re.type==="retry"?"busy":"idle";xe(He,nt)});const tt=he.getState().sessionActivityPhase;if(tt)for(const[He,Re]of tt.entries())Qe.has(He)&&(Re==="busy"||Re==="cooldown")&&!ke.has(He)&&xe(He,"idle")},rt=(async()=>{try{const be=await Ee.getGlobalSessionStatus();if(be&&Object.keys(be).length>0){ne(be);return}const ke=new Set;u.forEach(nt=>{const yt=k(nt.id);yt&&ke.add(yt)});const Qe=x(N??null);Qe&&ke.add(Qe);const tt=Array.from(ke);if(tt.length===0){const nt=await Ee.getSessionStatus();nt&&ne(nt);return}const He=await Promise.allSettled(tt.map(nt=>Ee.getSessionStatusForDirectory(nt))),Re={};if(He.forEach(nt=>{nt.status!=="fulfilled"||!nt.value||Object.assign(Re,nt.value)}),Object.keys(Re).length===0&&Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(yt=>yt==="busy"||yt==="cooldown")&&!await Ee.checkHealth().catch(()=>!1))return;ne(Re)}catch{}})().finally(()=>{Ce.current=null});return Ce.current=rt,rt},[N,x,k,u,xe]);i.useEffect(()=>{const De=c??null,ne=V.current,rt=k(De),be=J.current;ne&&De&&ne!==De&&be&&rt&&be!==rt&&fe(),V.current=De,J.current=rt},[c,fe,k]);const Oe=i.useCallback(De=>{if(z.current=Date.now(),Zt()&&console.debug("[useEventStream] Received event:",De.type,De.properties),!De.properties)return;const ne=De.properties;if(!new Set(["session.abort","session.error"]).has(De.type)){const be=(typeof ne.session=="object"&&ne.session!==null?ne.session:null)||(typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:null);if(be){const ke=be,Qe=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(Qe){const tt=typeof ke.title=="string"?ke.title:typeof ne.title=="string"?ne.title:void 0,He=typeof ke.summary=="object"&&ke.summary!==null?ke.summary:typeof ne.summary=="object"&&ne.summary!==null?ne.summary:void 0;if(tt!==void 0||He!==void 0){const Re={};tt!==void 0&&(Re.title=tt),He!==void 0&&(Re.summary=He),d(Qe,Re)}}}}switch(De.type){case"server.connected":h();break;case"global.disposed":case"server.instance.disposed":{D("server_disposed_event");break}case"openchamber:session-activity":{const be=typeof ne.sessionId=="string"?ne.sessionId:null,ke=typeof ne.phase=="string"?ne.phase:null;be&&(ke==="idle"||ke==="busy"||ke==="cooldown")&&(xe(be,ke),ee(be,typeof ne.directory=="string"?ne.directory:null));break}case"mcp.tools.changed":{const be=typeof ne.directory=="string"?ne.directory:N;Hn.getState().refresh({directory:be??null,silent:!0});break}case"session.status":if(G.current)break;{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=typeof ne.status=="object"&&ne.status!==null?ne.status:null,Qe=typeof ke?.type=="string"?ke.type:null;be&&Qe&&(xe(be,Qe==="busy"||Qe==="retry"?"busy":"idle"),ee(be,typeof ne.directory=="string"?ne.directory:null))}break;case"message.part.updated":{const be=typeof ne.part=="object"&&ne.part!==null?ne.part:null;if(!be)break;const ke=be,Qe=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,tt=typeof Qe.sessionID=="string"?Qe.sessionID:null,He=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof tt=="string"&&tt.length>0?tt:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,Re=typeof Qe.id=="string"?Qe.id:null,nt=typeof ke.messageID=="string"&&ke.messageID.length>0?ke.messageID:typeof Re=="string"&&Re.length>0?Re:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!He||!nt){Zt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ke.sessionID??tt??ne.sessionID,messageID:ke.messageID??Re??ne.messageID});break}const yt=He,ct=nt,It=he.getState().sessionMemoryState.get(yt)?.trimmedHeadMaxId;if(It&&!du(ct,It)){Zt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:yt,messageId:ct,trimmedHeadMaxId:It});break}let Tt="assistant";if(Qe&&typeof Qe.role=="string")Tt=Qe.role;else{const ze=uu(yt,ct);if(ze){const Ze=ze.info.role;typeof Ze=="string"&&(Tt=Ze)}}if(E(ct,"part_received",{role:Tt}),Tt==="user"&&ke.synthetic===!0){E(ct,"skipped_synthetic_user_part");break}const je={...be,type:be.type||"text"};E(ct,"addStreamingPart_called"),s(yt,ct,je,Tt);break}case"message.updated":{const be=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,ke=be,Qe=typeof ke.sessionID=="string"&&ke.sessionID.length>0?ke.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,tt=typeof ke.id=="string"&&ke.id.length>0?ke.id:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!Qe||!tt){Zt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ke.sessionID??ne.sessionID,messageID:ke.id??ne.messageID});break}const He=Qe,Re=tt,nt=he.getState().sessionMemoryState.get(He)?.trimmedHeadMaxId;if(nt&&!du(Re,nt)){Zt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:He,messageId:Re,trimmedHeadMaxId:nt});break}if(G.current&&Zt())try{const we=ne.parts||ke.parts||[],Ue=(Array.isArray(we)?we.filter(_e=>_e?.type==="text"):[]).map(_e=>{const et=_e;return typeof et?.text=="string"?et.text:typeof et?.content=="string"?et.content:""}).join(`
135
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Re,role:ke.role,status:ke.status,textLen:Ue.length,textPreview:Ue.slice(0,120),partsCount:Array.isArray(we)?we.length:0})}catch{}if(E(Re,"message_updated",{role:ke.role}),ke.role==="user"){const we=ne.parts||ke.parts,ve=Array.isArray(we)?we:[],Ue={...be,userMessageMarker:!0,clientRole:"user"};if(t(He,Re,Ue),ve.length>0)for(let _e=0;_e<ve.length;_e++){const et=ve[_e];if(et.synthetic===!0)continue;const pt={...et,type:et?.type||"text",sessionID:et?.sessionID||He,messageID:et?.messageID||Re};s(He,Re,pt,"user")}E(Re,"user_message_created_from_event",{partsCount:ve.length});break}const yt=uu(He,Re),ct=lu(yt?.parts||[]),It=yt?.info?.finish==="stop",Tt=ne.parts||ke.parts,je=Array.isArray(Tt)?Tt:[],ze=je.length>0,Ye=typeof(ke.time||{})?.completed=="number";if(!ze&&!Ye)break;const mt=be.finish,ye=typeof mt=="string"?mt:null,ie=ye==="stop";if(ke.role==="assistant"&&ze){const we=lu(je);if(ct>0&&we+_S<ct&&!ie){E(Re,"skipped_shrinking_update",{incomingLen:we,existingLen:ct});break}if(G.current){const Ue=ct>0&&we<ct,_e=je.some(pt=>{if(!pt||pt.type!=="text")return!1;const ft=pt;return typeof ft.text=="string"&&ft.text.length>0});if(Ue&&!(ie&&_e)){E(Re,"desktop_shrinking_update_suppressed",{incomingLen:we,existingLen:ct});break}}}if(t(He,Re,be),ze&&ke.role!=="user"){const Ue=(he.getState().messages.get(He)||[]).find(pt=>pt.info.id===Re),_e=!Ue||Ue.parts.length===0;E(Re,_e?"server_parts_injected":"server_parts_refreshed",{count:je.length});const et=G.current&&ke.role==="assistant"?je.filter(pt=>pt?.type!=="text"):je;for(let pt=0;pt<et.length;pt++){const ft=et[pt],Pt={...ft,type:ft?.type||"text",sessionID:ft?.sessionID||He,messageID:ft?.messageID||Re};s(He,Re,Pt,ke.role),E(Re,`server_part_${pt}`)}}const de=be.time,We=de?.completed,Ge=typeof We=="number"&&Number.isFinite(We),bt=ye==="stop"||It;if(be.role==="assistant"&&(Ge||bt)&&be.role==="assistant"){const ve=he.getState().messages.get(He)||[];let Ue=null,_e="";for(let Te=0;Te<ve.length;Te++){const st=ve[Te];st.info.role==="assistant"&&st.info.id>_e&&(_e=st.info.id,Ue=st.info.id)}if(c===He&&Re!==Ue)break;if(!bt&&G.current){E(Re,"desktop_completion_without_stop");break}const pt=Ge?We:Date.now();if(Ge||t(He,Re,{...be,time:{...de??{},completed:pt}}),E(Re,"completed",{timeCompleted:pt}),T(Re),FS(He,Re,pt),r(He,Re),ye==="stop"&&rn()&&j&&(b==="always"||ae.current==="hidden")){const st=Y.current;if(!st.has(Re)){st.add(Re);const Ve=Qs();if(Ve?.notifications){const Xe=ke.mode||"agent",kt=ke.modelID||"assistant",Lt=`${Xe.charAt(0).toUpperCase()+Xe.slice(1)} agent is ready`,ts=`${LS(kt)} completed the task`;Ve.notifications.notifyAgentCompletion({title:Lt,body:ts,tag:Re})}}}G.current||ye==="stop"&&he.getState().sessionActivityPhase?.get(He)==="busy"&&xe(He,"cooldown");const ft=be.sessionID,Pt=typeof ft=="string"&&ft.length>0?ft:He;ee(Pt,typeof ne.directory=="string"?ne.directory:null),be.summary&&typeof Pt=="string"&&n(Pt,null)}break}case"session.created":case"session.updated":{const be=typeof ne.info=="object"&&ne.info!==null?ne.info:typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:typeof ne.session=="object"&&ne.session!==null?ne.session:ne,ke=typeof be.id=="string"&&be.id.length>0?be.id:typeof be.sessionID=="string"&&be.sessionID.length>0?be.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(ke){const Qe=typeof be.time=="object"&&be.time!==null?be.time:typeof ne.time=="object"&&ne.time!==null?ne.time:null,tt=Qe&&typeof Qe.compacting=="number"?Qe.compacting:null;n(ke,tt);const He=typeof be.directory=="string"?be.directory:typeof ne.directory=="string"?ne.directory:null,Re={...be,id:ke,...He?{directory:He}:{}};g(Re)}break}case"session.deleted":{const be=typeof ne.sessionID=="string"?ne.sessionID:typeof ne.id=="string"?ne.id:null;be&&y(be);break}case"session.abort":{const be=typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,ke=typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;be&&ke&&r(be,ke);break}case"permission.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;o(be);const ke=`${be.sessionID}:${be.id}`;q.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().permissions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;q.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.warning("Permission required",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const be=ne;a(be);const ke=`${be.sessionID}:${be.id}`;if(rn()&&j&&(b==="always"||ae.current==="hidden")){const tt=re.current;if(!tt.has(ke)){tt.add(ke);const He=Qs();He?.notifications&&He.notifications.notifyAgentCompletion({title:"Input needed",body:"Agent is waiting for your response",tag:ke})}}X.current.has(ke)||setTimeout(()=>{if(Be.current===be.sessionID||!he.getState().questions.get(be.sessionID)?.some(Re=>Re.id===be.id))return;X.current.add(ke);const He=he.getState().sessions.find(Re=>Re.id===be.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-CqCnPJev.js").then(nt=>nt.cy);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.info("Input needed",{description:He,action:{label:"Open",onClick:()=>{$e.getState().setActiveMainTab("chat"),he.getState().setCurrentSession(be.sessionID)}}})})},0);break}case"question.replied":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=typeof ne.requestID=="string"?ne.requestID:null;be&&ke&&l(be,ke);break}case"todo.updated":{const be=typeof ne.sessionID=="string"?ne.sessionID:null,ke=Array.isArray(ne.todos)?ne.todos:null;be&&ke&&vv(be,ke);break}}},[c,j,b,s,r,t,o,a,l,h,ee,n,d,E,T,xe,g,y,D,N]),Se=i.useCallback(()=>{const De=K();return ae.current=De,De==="visible"&&F.current},[K]),Le=i.useCallback(()=>{Zt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:G.current,hasUnsubscribe:!!I.current,currentSessionId:Be.current,effectiveDirectory:N,onlineStatus:F.current,visibilityState:ae.current,lastEventTimestamp:z.current,reconnectAttempts:O.current})},[N]),pe=i.useCallback(async()=>!0,[]),it=i.useCallback(()=>{if(W.current){Zt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if(W.current=!0,P.current&&(clearTimeout(P.current),P.current=null),I.current){const De=I.current;I.current=null;try{De()}catch(ne){console.warn("[useEventStream] Error during unsubscribe:",ne)}}W.current=!1},[]),xt=i.useCallback(async De=>{if(Le(),!Se()){$.current=!0,F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}G.current&&(await pe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),De?.resetAttempts&&(O.current=0),it(),z.current=Date.now(),M("connecting",null),Zt()&&console.info("[useEventStream] Starting event stream...");const ne=be=>{console.warn("Event stream error:",be)},rt=()=>{const be=$.current;if(O.current=0,$.current=!1,z.current=Date.now(),M("connected",null),h(),Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(Qe=>Qe==="busy"||Qe==="cooldown")&&fe(),be)D("sse_reconnected");else{const Qe=Be.current;Qe&&setTimeout(()=>{S(Qe,"sse_reconnected").then(()=>ee(Qe)).catch(tt=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",tt)})},0)}};if(Zt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:N,isCleaningUp:W.current}),W.current){Zt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const be=Ee.subscribeToGlobalEvents(Qe=>{const tt=Qe.payload,He=Qe.payload,Re=typeof He.properties=="object"&&He.properties!==null?He.properties:{},nt=Qe.directory&&Qe.directory!=="global"?{...Re,directory:Qe.directory}:Re;Oe({type:typeof tt.type=="string"?tt.type:"",properties:nt})},ne,rt),ke=()=>{try{be()}catch(Qe){console.warn("[useEventStream] Error during unsubscribe:",Qe)}};W.current?ke():I.current=ke}catch(be){console.error("[useEventStream] Error during subscription:",be),ne(be)}},[Se,it,M,h,S,ee,Oe,N,fe,pe,Le,D]),Mt=i.useCallback(De=>{if(!Se()){$.current=!0,it(),F.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}const ne=O.current+1;O.current=ne;const rt=De??`Retrying (${ne})`;M("reconnecting",rt);const be=ne<=3?Math.min(1e3*Math.pow(2,ne-1),8e3):Math.min(2e3*Math.pow(2,ne-3),32e3),ke=Math.floor(Math.random()*250),Qe=be+ke;P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{xt({resetAttempts:!1})},Qe)},[Se,it,M,xt]);i.useEffect(()=>{const De=oe.current;typeof window<"u"&&(window.__messageTracker=E);let ne=null;G.current&&typeof window<"u"&&(ne=nt=>{const yt=typeof nt.detail?.sessionId=="string"?nt.detail.sessionId:null,ct=typeof nt.detail?.phase=="string"?nt.detail.phase:null;yt&&(ct==="idle"||ct==="busy"||ct==="cooldown")&&(xe(yt,ct),ee(yt))},window.addEventListener("openchamber:session-activity",ne));const rt=()=>{R.current&&(clearTimeout(R.current),R.current=null)},be=()=>{R.current||(R.current=setTimeout(()=>{const nt=K();ae.current=nt,nt!=="visible"?(it(),$.current=!0,M("paused","Paused while hidden")):rt()},5e3))},ke=()=>{if(ae.current=K(),ae.current==="visible"){if(rt(),ge("visibility_restore"),$.current||!I.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const nt=Be.current;nt&&(S(nt,"visibility_restore").catch(()=>{}),ee(nt)),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}}else M("paused","Paused while hidden"),be()},Qe=()=>{if(ae.current=K(),ae.current==="visible"&&(rt(),ge("window_focus"),$.current||!I.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const nt=Be.current;nt&&(ee(nt),S(nt,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(yt=>console.warn("[useEventStream] Failed to refresh messages:",yt))),fe(),M("connecting","Resuming stream"),xt({resetAttempts:!0})}},tt=()=>{F.current=!0,ge("network_restored"),($.current||!I.current)&&(M("connecting","Network restored"),xt({resetAttempts:!0}))},He=()=>{F.current=!1,$.current=!0,M("offline","Waiting for network"),it()};typeof document<"u"&&document.addEventListener("visibilitychange",ke),typeof window<"u"&&(window.addEventListener("online",tt),window.addEventListener("offline",He),window.addEventListener("focus",Qe));const Re=setTimeout(()=>{xt({resetAttempts:!0})},100);return B.current&&clearInterval(B.current),B.current=setInterval(()=>{if(!Se())return;const nt=Date.now();Array.from(he.getState().sessionActivityPhase?.values?.()??[]).some(ct=>ct==="busy"||ct==="cooldown")&&fe(),nt-z.current>45e3&&Promise.resolve().then(async()=>{try{await Ee.checkHealth()?z.current=Date.now():Mt("Refreshing stalled stream")}catch(ct){console.warn("Health check after stale stream failed:",ct),Mt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Re),ne&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ne),typeof document<"u"&&document.removeEventListener("visibilitychange",ke),typeof window<"u"&&(window.removeEventListener("online",tt),window.removeEventListener("offline",He),window.removeEventListener("focus",Qe)),rt(),B.current&&(clearInterval(B.current),B.current=null),De.forEach(nt=>clearTimeout(nt)),De.clear(),al.clear(),Y.current.clear(),re.current.clear(),$.current=!1,ae.current=K(),F.current=typeof navigator>"u"?!0:navigator.onLine,it(),Q.current&&(clearTimeout(Q.current),Q.current=null),M("idle",null)}},[N,E,K,it,M,xt,Mt,f,ee,xe,fe,Se,p,ge,S])},zS=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=he(),{toggleCommandPalette:a,toggleHelpDialog:l,toggleSidebar:c,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=$e(),{themeMode:p,setThemeMode:g}=Wr(),{working:y}=rf(),h=i.useRef(null),j=i.useRef(null),b=i.useRef(!1),v=i.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);i.useEffect(()=>{const w=N=>{if(Ds(N)&&N.key==="k"&&(N.preventDefault(),a()),Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=Qs()?.diagnostics;if(!k||(N.preventDefault(),b.current))return;b.current=!0,k.downloadLogs().then(({fileName:A,content:C})=>{const M=A||"openchamber.log",S=new Blob([C],{type:"text/plain;charset=utf-8"}),D=URL.createObjectURL(S),E=document.createElement("a");E.href=D,E.download=M,document.body.appendChild(E),E.click(),document.body.removeChild(E),URL.revokeObjectURL(D)}).finally(()=>{b.current=!1});return}if(Ds(N)&&N.key==="."&&(N.preventDefault(),l()),Ds(N)&&N.key.toLowerCase()==="n"){N.preventDefault();const x=Wt(),k=at.getState().settingsAutoCreateWorktree;if(x?!1:k?!N.shiftKey:N.shiftKey){u("chat"),d(!1),Ra();return}u("chat"),d(!1),s()}if(Ds(N)&&N.key==="/"){N.preventDefault();const x=["light","dark","system"],A=(x.indexOf(p)+1)%x.length;g(x[A])}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:x,setTimelineDialogOpen:k}=$e.getState();k(!x);return}if(Ds(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:x}=$e.getState();m(!x);return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:x,isSessionSwitcherOpen:k}=$e.getState();x?d(!k):c();return}if(Ds(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S,isModelSelectorOpen:D}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;N.preventDefault(),f(!D);return}if(Ds(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x||k||A||C||M||!(S==="chat"))return;const T=at.getState();if(T.getCurrentModelVariants().length===0)return;N.preventDefault(),T.cycleCurrentVariant();const P=at.getState().currentVariant,O=he.getState(),U=O.currentSessionId,Q=at.getState().currentAgentName,W=at.getState().currentProviderId,L=at.getState().currentModelId;U&&Q&&W&&L&&O.saveAgentModelVariantForSession(U,Q,W,L,P);return}if(N.key==="Escape"){const{isSettingsDialogOpen:x,isCommandPaletteOpen:k,isHelpDialogOpen:A,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=$e.getState();if(x){N.preventDefault(),m(!1),v();return}if(k||A||C||M||!(S==="chat")){v();return}const T=o;if(!(y.canAbort&&!!T)){v();return}const P=Date.now(),O=h.current;if(O&&P<O){N.preventDefault(),v(),r();return}N.preventDefault();const U=t(3e3)??P+3e3;h.current=U,j.current&&clearTimeout(j.current);const Q=Math.max(U-P,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&v()},Q||0);return}};return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[s,r,a,l,c,d,u,m,f,g,p,y,t,v,o]),i.useEffect(()=>()=>{v()},[v])},mu="openchamber:menu-action",WS=s=>{const{openNewSessionDraft:r}=he(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:l,setSettingsDialogOpen:c,setAboutDialogOpen:d}=$e(),{addProject:u}=Ot(),{requestAccess:m,startAccessing:f}=_a(),{setThemeMode:p}=Wr(),g=i.useRef(!1),y=i.useCallback(()=>{es()?m("").then(async h=>{if(!h.success||!h.path){h.error&&h.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:h.error});return}const j=await f(h.path);if(!j.success){te.error("Failed to open directory",{description:j.error||"Desktop could not grant file access."});return}u(h.path,{id:h.projectId})||te.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(h=>{console.error("Desktop: Error selecting directory:",h),te.error("Failed to select directory")}):En.requestDirectoryDialog()},[u,m,f]);i.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":c(!0);break;case"command-palette":t();break;case"new-session":l("chat"),a(!1),r();break;case"new-worktree-session":l("chat"),a(!1),Ra();break;case"change-workspace":y();break;case"open-git-tab":{const{activeMainTab:v}=$e.getState();l(v==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:v}=$e.getState();l(v==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:v}=$e.getState();l(v==="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 w=Qs()?.diagnostics;if(!w||g.current)break;g.current=!0,w.downloadLogs().then(({fileName:N,content:x})=>{const k=N||"openchamber.log",A=new Blob([x],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(A),M=document.createElement("a");M.href=C,M.download=k,document.body.appendChild(M),M.click(),document.body.removeChild(M),URL.revokeObjectURL(C),te.success("Logs saved",{description:`Downloaded to ~/Downloads/${k}`})}).catch(()=>{te.error("Failed to download logs")}).finally(()=>{g.current=!1});break}}};return window.addEventListener(mu,h),()=>window.removeEventListener(mu,h)},[r,t,n,o,a,l,c,d,p,s,y])},HS=s=>s.role==="assistant",fu=s=>{const r=s.info;if(!HS(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},ea=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},pu=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Kn(n)).join(" ").replace(/\s+/g," ").trim(),US=(s,r)=>{if(!s||!ea(s.info))return-1;const t=pu(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((l,c)=>{if(!ea(l.info))return;const d=pu(l),u=!!(t&&d&&d===t),m=typeof l.info?.time?.created=="number"?l.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=c,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=c,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(l=>{if(!ea(l.info))return!1;const c=typeof l.info?.time?.created=="number"?l.info.time.created:void 0;return typeof c!="number"?!1:Math.abs(c-n)<1e3}):-1},VS=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=he(),n=i.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=i.useRef(void 0),a=i.useRef(0),l=i.useCallback(async()=>{if(!s||n)return;const c=Date.now();if(!(c-a.current<2e3)){a.current=c;try{const d=r.get(s)||[],u=await Ee.getSessionMessages(s),m=await RS(s);if(!u)return;const f=d[d.length-1];if(f){const p=u.findIndex(h=>h.info.id===f.info.id),y=p===-1?US(f,u):p;if(y!==-1)if(y<u.length-1){const h=u.slice(y+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:b}=he.getState();b(s,j)}else{const h=u[y],j=d[d.length-1],b=fu(h),v=fu(j);if(b&&!v){console.log("[SYNC] Last message completed on server");const w=[...d.slice(0,-1),h],{syncMessages:N}=he.getState();N(s,w)}}else if(ea(f.info)){const h=u.slice(-us.VIEWPORT_MESSAGES);console.log("[SYNC] Local user message missing by ID; merging latest messages for deduplication");const{syncMessages:j}=he.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 y=u.slice(p+1).slice(-us.VIEWPORT_MESSAGES);if(y.length>0){console.log(`[SYNC] Restoring ${y.length} messages after cursor`);const{syncMessages:h}=he.getState();h(s,y)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-us.VIEWPORT_MESSAGES),{syncMessages:y}=he.getState();y(s,g)}}else if(u.length>0){const p=u.slice(-us.VIEWPORT_MESSAGES);console.log(`[SYNC] Loading last ${p.length} messages`);const{syncMessages:g}=he.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);i.useEffect(()=>{const c=()=>{console.log("[FOCUS] Window focused - checking for updates"),l()};return window.addEventListener("focus",c),()=>window.removeEventListener("focus",c)},[l]),i.useEffect(()=>{if(!s||n)return;const c=()=>{document.visibilityState==="visible"&&l(),o.current=setTimeout(c,3e4)};return o.current=setTimeout(c,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,l]),i.useEffect(()=>{const c=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),l())};return document.addEventListener("visibilitychange",c),()=>document.removeEventListener("visibilitychange",c)},[l])},GS=()=>{i.useEffect(()=>{let s=!1;return(async()=>{try{const t=await Ee.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const l=a,c=l.type==="busy"||l.type==="retry"?"busy":"idle";n.set(o,c)}),n.size>0&&he.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function qS(){const{git:s}=kr(),r=vt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=he(),{setActiveDirectory:a,startPolling:l,stopPolling:c,fetchAll:d}=Gt(),u=i.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]);i.useEffect(()=>{if(!u||!s){c();return}return a(u),d(u,s),l(s),()=>{c()}},[u,s,a,l,c,d])}function KS({children:s}){return qS(),e.jsx(e.Fragment,{children:s})}const QS=()=>{const[{isUpdating:s,message:r},t]=i.useState(()=>Eg());return i.useEffect(()=>Ag(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($l,{width:80,height:80,isAnimated:!0}),e.jsx("p",{className:"typography-body text-muted-foreground",children:r})]}):null},YS=({open:s,onOpenChange:r})=>{const[t,n]=i.useState(null);i.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:c}=await as(async()=>{const{getVersion:u}=await import("./vendor-.bun-CqCnPJev.js").then(m=>m.cB);return{getVersion:u}},__vite__mapDeps([0,1])),d=await c();n(d)}catch{n("1.5.0")}})():n("1.5.0")},[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($l,{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($i,{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(Lu,{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(Li,{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 Pi({apis:s,children:r}){return e.jsx(Ml.Provider,{value:s,children:r})}const XS="curl -fsSL https://opencode.ai/install | bash",JS=3e3;function ZS({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(Ys,{className:"h-4 w-4"})})]})}const ek=3e4;function tk({onCliAvailable:s}){const[r,t]=i.useState(!1),[n,o]=i.useState(!1),[a,l]=i.useState(!1);i.useEffect(()=>{const m=setTimeout(()=>o(!0),ek);return()=>clearTimeout(m)},[]),i.useEffect(()=>{l(typeof window.opencodeDesktop<"u")},[]);const c=i.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await as(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-CqCnPJev.js").then(y=>y.cA);return{getCurrentWindow:g}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=i.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=i.useCallback(async()=>{try{await navigator.clipboard.writeText(XS),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return i.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,JS);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:c,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(ta,{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(_t,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(ZS,{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(ta,{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 sk=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=$e();return e.jsx(YS,{open:s,onOpenChange:r})};function rk({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=at(),{error:o,clearError:a,loadSessions:l}=he(),c=vt(x=>x.currentDirectory),d=vt(x=>x.isSwitchingDirectory),[u,m]=i.useState(!1),{uiFont:f,monoFont:p}=jf(),[g,y]=i.useState(()=>s.runtime.isDesktop),[h,j]=i.useState(()=>s.runtime.isVSCode),[b,v]=i.useState(()=>s.runtime.isDesktop?dg():!0);i.useEffect(()=>{y(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),i.useEffect(()=>(oc(s),()=>oc(null)),[s]),i.useEffect(()=>{if(typeof document>"u")return;const x=document.documentElement,k=Od[f]?.stack??Od[z0].stack,A=Kr[p]?.stack??Kr[Jo].stack;x.style.setProperty("--font-sans",k),x.style.setProperty("--font-heading",k),x.style.setProperty("--font-family-sans",k),x.style.setProperty("--font-mono",A),x.style.setProperty("--font-family-mono",A),x.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),i.useEffect(()=>{if(t){const k=setTimeout(()=>{const A=document.getElementById("initial-loading");A&&(A.classList.add("fade-out"),setTimeout(()=>{A.remove()},300))},150);return()=>clearTimeout(k)}},[t]),i.useEffect(()=>{const x=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!t&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(x)},[t]),i.useEffect(()=>{(async()=>h||await r())()},[r,h]),i.useEffect(()=>{if(d)return;(async()=>h||n&&(Ee.setDirectory(c),await l()))()},[c,d,l,n,h]),BS(),zS();const w=i.useCallback(()=>{m(x=>!x)},[]);WS(w),VS(),GS(),Ef(),i.useEffect(()=>{const x=k=>{Ds(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(A=>!A))};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),i.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=i.useCallback(()=>{v(!0),window.location.reload()},[]);return g&&!b?e.jsx(os,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(tk,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(DS,{}),e.jsx(Ii,{})]})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(Pd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(gS,{}),e.jsx(Ii,{})]})})})}):e.jsx(os,{children:e.jsx(Pi,{apis:s,children:e.jsx(KS,{children:e.jsx(Pd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(mS,{}),e.jsx(Ii,{}),e.jsx(QS,{}),e.jsx(sk,{}),u&&e.jsx(ES,{onClose:()=>m(!1)})]})})})})})}const $f=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=vt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},Lf="/auth/session",nk=async()=>fetch(Lf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),hu=async s=>fetch(Lf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Ul=({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})]}),ok=({message:s="Preparing workspace…"})=>e.jsx(Ul,{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})})}),ak=({onRetry:s})=>e.jsx(Ul,{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(Ie,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),ik=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},lk=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},ck=({children:s})=>{const r=i.useMemo(()=>es(),[]),t=i.useMemo(()=>Wt(),[]),n=r||t,[o,a]=i.useState(()=>n?"authenticated":"pending"),[l,c]=i.useState(""),[d,u]=i.useState(!1),[m,f]=i.useState(""),p=i.useRef(null),g=i.useRef(n),y=i.useRef(!1),h=i.useCallback(async()=>{if(n){a("authenticated");return}a(b=>b==="authenticated"?b:"pending");try{const b=await nk();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]);i.useEffect(()=>{n||h()},[h,n]),i.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),i.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),i.useEffect(()=>{if(n||o!=="locked"||y.current||d)return;const b=ik();b&&(y.current=!0,lk(),u(!0),f(""),hu(b).then(v=>{if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(v=>{console.warn("Failed to submit URL token:",v),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),i.useEffect(()=>{n||o==="authenticated"&&!g.current&&(g.current=!0,(async()=>(await qu(),await Ku(),await $f()))())},[n,o]);const j=async b=>{if(b.preventDefault(),!(!l||d)){u(!0),f("");try{const v=await hu(l);if(v.ok){c(""),a("authenticated");return}if(v.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(v){console.warn("Failed to submit UI password:",v),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(ok,{}):o==="error"?e.jsx(ak,{onRetry:()=>{h()}}):o==="locked"?e.jsx(Ul,{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(jt,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:l,onChange:b=>{c(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(Ie,{type:"submit",size:"icon",disabled:!l||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Gh,{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})},Ti=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(c=>c+c).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,l=n&255;return`${o} ${a} ${l}`};class dk{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(`
136
- `)}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=Ti(r.colors.surface.muted),o=Ti(r.colors.surface.subtle),a=Ti(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 l=r.metadata.variant==="dark",c=l?.8:.95,d=l?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${c}) !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,c)} !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 {
137
- ${t}
138
- }
139
-
140
- .dark {
141
- ${t}
142
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
143
- ${t}
144
- }
145
-
146
- :root:not(.dark) {
147
- ${t}
148
- }`,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()?vg:hl;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),l=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${l}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),l=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${l}, ${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,l=(n>>8&255)-o,c=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c: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,l=(n>>8&255)+o,c=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(l<255?l<0?0:l:255)*256+(c<255?c<0?0:c: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 Vl={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"}}},Gl={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"}}},lo=[Vl,Gl];function wa(s){return lo.find(r=>r.metadata.id===s)}const Bf=Vl.metadata.id,zf=Gl.metadata.id,uk=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Wf=s=>s==="dark"?Gl:Vl,mk=s=>(lo.find(t=>t.metadata.variant===s)??Wf(s)).metadata.id,$o=(s,r)=>{const t=wa(s);return t&&t.metadata.variant===r?t:lo.find(o=>o.metadata.variant===r)??Wf(r)},fk=typeof window<"u"?i.useLayoutEffect:i.useEffect,ja=(s,r)=>{if(!s)return r==="light"?Bf:zf;const t=wa(s);return t&&t.metadata.variant===r?t.metadata.id:mk(r)},pk=s=>{let r=Bf,t=zf,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),l=localStorage.getItem("darkThemeId"),c=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(c!==null){if(c==="true")n="system";else if(d){const f=wa(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=ja(a,"light"),t=ja(l,"dark")}if(s){const o=wa(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function hk({children:s,defaultThemeId:r}){const t=Ae.useMemo(()=>new dk,[]),[n,o]=Ae.useState(()=>pk(r)),[a,l]=Ae.useState(()=>uk()),[c,d]=Ae.useState(()=>typeof window>"u"||!Wt()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=Ae.useMemo(()=>Wt(),[]),m=Ae.useMemo(()=>u&&c?c:n.themeMode==="light"?$o(n.lightThemeId,"light"):n.themeMode==="dark"||a?$o(n.darkThemeId,"dark"):$o(n.lightThemeId,"light"),[u,n,a,c]),f=Ae.useMemo(()=>u&&c?[c,...lo]:lo,[u,c]);Ae.useEffect(()=>{if(!u)return;const N=A=>{d(A);const C=A.metadata.variant==="dark"?"dark":"light",M=$e.getState();M.theme!==C&&M.setTheme(C)},x=A=>{const C=A.detail;C?.theme&&N(C.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",x),()=>window.removeEventListener("openchamber:vscode-theme",x)},[u]);const p=Ae.useCallback(N=>{if(typeof document>"u")return;const x=N.colors.surface.background;es()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=x;let k=document.querySelector('meta[name="theme-color"]');k||(k=document.createElement("meta"),k.setAttribute("name","theme-color"),document.head.appendChild(k)),k.setAttribute("content",x);const A=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let C=document.querySelector(`meta[name="theme-color"][media="${A}"]`);C||(C=document.createElement("meta"),C.setAttribute("name","theme-color"),C.setAttribute("media",A),document.head.appendChild(C)),C.setAttribute("content",x)},[]),g=Ae.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);fk(()=>{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]),Ae.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),x=k=>{l(k.matches)};return l(N.matches),N.addEventListener("change",x),()=>N.removeEventListener("change",x)},[n.themeMode]),Ae.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]),Ae.useEffect(()=>{ss({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]),Ae.useEffect(()=>{if(typeof window>"u")return;const N=x=>{const k=x.detail;k&&o(A=>{let C=A.themeMode;k.useSystemTheme===!0?C="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(C=k.themeVariant);let M=A.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=ja(k.lightThemeId,"light"));let S=A.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(S=ja(k.darkThemeId,"dark")),C===A.themeMode&&M===A.lightThemeId&&S===A.darkThemeId?A:{themeMode:C,lightThemeId:M,darkThemeId:S}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const y=Ae.useCallback(N=>{const x=f.find(k=>k.metadata.id===N);x&&o(k=>x.metadata.variant==="dark"?k.darkThemeId===x.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:x.metadata.id,themeMode:"dark"}:k.lightThemeId===x.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:x.metadata.id,themeMode:"light"})},[f]),h=Ae.useCallback(N=>{o(x=>x.themeMode===N?x:{...x,themeMode:N})},[]),j=Ae.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const x=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===x?k:{...k,themeMode:x})},[m.metadata.variant]),b=Ae.useCallback(N=>{const x=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");x&&o(k=>k.lightThemeId===x.metadata.id?k:{...k,lightThemeId:x.metadata.id})},[f]),v=Ae.useCallback(N=>{const x=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");x&&o(k=>k.darkThemeId===x.metadata.id?k:{...k,darkThemeId:x.metadata.id})},[f]),w={currentTheme:m,availableThemes:f,setTheme:y,isSystemPreference:n.themeMode==="system",setSystemPreference:j,themeMode:n.themeMode,setThemeMode:h,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:b,setDarkThemePreference:v};return e.jsx(Dl.Provider,{value:w,children:s})}const gk=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:l}=$e();return i.useLayoutEffect(()=>{t(),o(),l()},[r,t,n,o,a,l]),i.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return c.addEventListener("change",d),()=>{c.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},xk={getLastAssistantMessage(){const s=he.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}),l=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),c=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!l&&!c&&(!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:l,hasTools:c,hasStepMarkers:d,onlyStepMarkers:d&&!l&&!c}),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&&!l&&!c&&(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=he.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=vt.getState(),r=he.getState(),t=s.currentDirectory||null,n=Ee.getDirectory()??null,o=r.sessions||[],a=new Set,l={};o.forEach(k=>{const A=k.directory;typeof A=="string"&&A.trim().length>0?(a.add(A),l[A]=(l[A]??0)+1):l["(none)"]=(l["(none)"]??0)+1});const c=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(k){return{available:!1,error:k instanceof Error?k.message:String(k)}}})(),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 k=>{try{return await k.json()}catch{return null}},p=async k=>{try{return await k.text()}catch{return null}},g=async k=>{try{const A=await fetch(k);return A.ok?await f(A):{status:A.status}}catch(A){return{error:A instanceof Error?A.message:String(A)}}};let y=null,h=null,j=null,b=null;const v=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";y=await g(v);const w=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";h=await g(w),j=await g("/api/config/settings");try{const k=await fetch("/api/health"),A=k.headers.get("content-type")||"",C=await p(k);b={status:k.status,ok:k.ok,contentType:A,type:A.includes("application/json")?"json":"html",preview:C?C.slice(0,120):null}}catch(k){b={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await cn(t)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const x={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:y?.directory||y?.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:l},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:c,opencode:{pathInfo:y,projectInfo:h,health:b},openchamber:{settingsInfo:j}};return console.log("[DEBUG] App status snapshot:",x),x},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=he.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=he.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||[],l=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),c=a.some(d=>d.type==="tool");return a.length===0||!l&&!c});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:
149
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
150
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
151
- `),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)
152
- `),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=he.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const l=o.messages.get(a)||[],c=r?l:l.filter(p=>p.info.role==="assistant"),d={totalMessages:l.length,analyzedMessages:c.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(y=>typeof y=="number");return g.length>0?Math.max(...g):null},f=c.map((p,g)=>{const y=p.info??{},h=Array.isArray(p.parts)?p.parts:[],j=y.time??{},b=u(j.completed),v=b!==null,w=h.filter(E=>E.type==="tool"),N=h.filter(E=>E.type==="reasoning"),x=m(w.map(E=>u(E.state?.time?.end??E.state?.time?.start))),k=m(N.map(E=>u(E.time?.end??E.time?.start))),A=m([x,k].filter(E=>E!==null)),C=w.some(E=>["pending","running","started"].includes(E.state?.status)),M=N.some(E=>typeof E.time?.end!="number");w.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),v||(d.completedMissing+=1);const S=!!(v&&typeof x=="number"&&b<x);S&&(d.completedBeforeTool+=1);const D=!!(v&&typeof k=="number"&&b<k);return D&&(d.completedBeforeReasoning+=1),v&&C&&(d.runningToolsWhenCompleted+=1),v&&M&&(d.reasoningOpenWhenCompleted+=1),{index:g,messageId:y.id,role:y.role,completedAt:b,latestToolTimestamp:x,latestReasoningTimestamp:k,latestPartTimestamp:A,completed_missing:!v,completed_before_tool:S,completed_before_reasoning:D,running_tools_when_completed:!!(v&&C),reasoning_open_when_completed:!!(v&&M),has_tools:w.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=he.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"),l=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&l),p=s.messageStreamStates,g=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,y=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:",l),console.log("messageIsComplete:",f),console.log("lifecycle phase:",y?.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:l,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=xk,Zt()&&(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 gu=!1;const yk=()=>{if(gu||typeof window>"u")return;gu=!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&&ss(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};$e.subscribe(a=>{const l={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},c={};l.showReasoningTraces!==s.showReasoningTraces&&(c.showReasoningTraces=l.showReasoningTraces),l.autoDeleteEnabled!==s.autoDeleteEnabled&&(c.autoDeleteEnabled=l.autoDeleteEnabled),l.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(c.autoDeleteAfterDays=l.autoDeleteAfterDays),s=l,Object.keys(c).length>0&&o(c)})};let xu=!1;const yu="openchamber-typography-base",bk=()=>{if(typeof document>"u")return;const r=`:root {
153
- ${Object.entries(hl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
154
- `)}
155
- }
156
- `,t=document.getElementById(yu);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=yu,n.textContent=r,document.head.appendChild(n)},vk=()=>{xu||typeof window>"u"||(xu=!0,bk())},wk=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await qu();await Ku();yk();vk();await $f();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 l=o[o.length-1].info.tokens;l&&typeof l=="object"&&console.debug("Token breakdown:",{base:(l.input||0)+(l.output||0)+(l.reasoning||0),cache:l.cache?(l.cache.read||0)+(l.cache.write||0):0}),r.sessionContextUsage.get(t);const c=window.__zustand_config_store__;if(c){const d=c.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 Hf=document.getElementById("root");if(!Hf)throw new Error("Root element not found");qh.createRoot(Hf).render(e.jsx(Ae.StrictMode,{children:e.jsx(hk,{children:e.jsx(gk,{children:e.jsx(ck,{children:e.jsx(rk,{apis:wk})})})})}));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 kk=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ms as D,Zr as S,fs as a,Nm as b,_ as c,ow as d,aw as e,jd as f,fr as g,iw as h,cw as i,kk as m,mf as p,lw as r,zo as t};