@openchamber/web 1.4.8 → 1.4.9

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,128 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-.bun-94fMDU1C.js","assets/vendor--Jn2c0Clh.css","assets/ToolOutputDialog-Dn1Yyik_.js","assets/index-CyM2ZMJa.js","assets/index-RdQawb7R.css"])))=>i.map(i=>d[i]);
2
- import{t as Ef,c as If,F as Pf,j as e,R as Tf,T as Ff,P as Rf,C as _f,A as Of,a as $f,b as zt,d as Yt,p as As,e as Es,f as Lf,_ as as,g as c,r as Bf,i as Ht,I as zf,k as Wf,l as Hf,m as Uf,n as Vf,o as Gf,q as qf,s as Kf,u as Pt,v as Yf,S as Qf,L as Xf,w as iu,x as Jf,y as Zf,z as ep,B as De,D as $l,E as wi,G as tp,H as It,K as Ki,J as sp,U as cs,M as lu,N as rp,O as Ar,Z as np,Y as nr,Q as Pr,W as $t,V as da,X as op,$ as Yr,a0 as en,a1 as Qr,a2 as vi,a3 as Ps,a4 as cu,a5 as ap,a6 as ip,a7 as lp,a8 as cp,a9 as dp,aa as up,ab as mp,ac as Io,ad as fp,ae as pp,af as Go,ag as Er,ah as te,ai as ss,aj as yr,ak as tn,al as no,am as Kt,an as or,ao as hp,ap as gp,aq as du,ar as Yi,as as Xr,at as uu,au as ar,av as mu,aw as Sn,ax as xp,ay as ua,az as Us,aA as Ia,aB as yp,aC as Tr,aD as mr,aE as Gs,aF as bp,aG as qs,aH as wp,aI as Ll,aJ as vp,aK as jp,aL as Sp,aM as kp,aN as Np,aO as Cp,aP as Mp,aQ as Dp,aR as Ap,aS as Ep,aT as ur,aU as Pa,aV as Ip,aW as ir,aX as Qi,aY as Xi,aZ as Pp,a_ as Tp,a$ as Fp,b0 as Rp,b1 as _p,b2 as Op,b3 as $p,b4 as Lp,b5 as Bp,b6 as zp,b7 as Wp,b8 as Hp,b9 as Up,ba as Vp,bb as Gp,bc as qp,bd as Kp,be as Yp,bf as Qp,bg as fr,bh as qo,bi as br,bj as tr,bk as Xp,bl as Jp,bm as ma,bn as Zp,bo as Ji,bp as eh,bq as th,br as sh,bs as Qn,bt as rh,bu as nh,bv as oh,bw as ah,bx as ih,by as ji,bz as Po,bA as fa,bB as lh,bC as ch,bD as yn,bE as pn,bF as fu,bG as pu,bH as dh,bI as uh,bJ as Fs,bK as hu,bL as mh,bM as gu,bN as fh,bO as ph,bP as Si,bQ as xu,bR as yu,bS as hh,bT as hr,bU as Xn,bV as gh,bW as Bl,bX as xh,bY as ki,bZ as oo,b_ as In,b$ as yh,c0 as bu,c1 as Zi,c2 as el,c3 as tl,c4 as bh,c5 as wh,c6 as vh,c7 as zl,c8 as wu,c9 as jh,ca as Jn,cb as vu,cc as ju,cd as Ta,ce as pa,cf as Su,cg as Sh,ch as kh,ci as Nh,cj as Ni,ck as ku,cl as Ci,cm as Ch,cn as Mh,co as Dh,cp as Ah,cq as Eh,cr as Ih,cs as Ph,ct as Th,cu as Fh}from"./vendor-.bun-94fMDU1C.js";import{c as Rh,l as _h,g as Oh,r as $h,d as Lh,a as Bh,b as zh,e as Wh,u as Hh,f as Uh,h as Vh,i as Gh,j as qh,k as Kh,m as Yh}from"./index-CyM2ZMJa.js";const Zt=()=>typeof window<"u"&&typeof window.opencodeDesktop<"u",Ut=()=>typeof window>"u"?!1:window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode===!0,kn=()=>typeof window>"u"?!1:!Zt()&&!Ut(),Fr=()=>Zt()?window.opencodeDesktop??null:null,Nu=()=>{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},Cu=async()=>{const s=Fr();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},Qh=async()=>{const s=Fr();if(!s)return null;try{return await s.getServerInfo()}catch(r){return console.warn("Failed to read desktop server info",r),null}},Xh=()=>typeof window>"u"?!1:window.__OPENCHAMBER_DESKTOP_SERVER__?.cliAvailable??!1,sn=async()=>{const s=Nu();if(!s)return null;try{return await s.getSettings()}catch(r){return console.warn("Failed to read desktop settings",r),null}},Jh=async s=>{const r=Nu();if(!r)return null;try{return await r.updateSettings(s)}catch(t){return console.warn("[desktop] Failed to update desktop settings",t),null}},Zh=async s=>{const r=Fr();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)}}},eg=async s=>{const r=Fr();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)}}},tg=async s=>{const r=Fr();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)}}},sg=async()=>{const s=Fr();if(!s||!s.checkForUpdates)return null;try{return await s.checkForUpdates()}catch(r){return console.warn("Failed to check for updates",r),null}},rg=async s=>{const r=Fr();if(!r||!r.downloadUpdate)return!1;try{return await r.downloadUpdate(s),!0}catch(t){return console.warn("Failed to download update",t),!1}},ng=async()=>{const s=Fr();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 R(...s){return Ef(If(s))}const Mu=()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),Cs=s=>Mu()&&Zt()?s.metaKey:s.ctrlKey,Jt=()=>Mu()&&Zt()?"⌘":"Ctrl",Du=(s,r)=>{const t=s??"",n=Math.max(16,r?.maxLength??45);if(t.length<=n)return t;const o=t.split("/");if(o.length<=1)return t;const a=o.pop()??"";if(!a)return t;const i=Math.max(0,n-(a.length+2));if(i<=0)return`…/${a}`;let l="";for(const d of o){if(!d)continue;const u=l?`${l}/${d}`:d;if(u.length>i)break;l=u}if(!l){const d=o[0]??"";l=d?d.slice(0,i):""}return l?`${l}…/${a}`:`…/${a}`},Ko=s=>s?s==="/"?"/":s.replace(/\/+$/,""):"";function Vr(s,r){if(!s)return"";const t=Ko(s);if(t==="/")return"/";const n=r?Ko(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 Wl(s,r){if(!s)return"/";const t=Ko(s);if(!t||t==="/")return"/";const n=r?Ko(r):void 0;return n&&n!=="/"&&t===n?"~":t.split("/").pop()||t||"/"}function Is(s,r){return r?s?s.toLowerCase().includes(r.toLowerCase())?!0:new Pf([s],{threshold:.4,distance:100,ignoreLocation:!0}).search(r).length>0:!1:!0}function og({delayDuration:s=0,...r}){return e.jsx($f,{"data-slot":"tooltip-provider",delayDuration:s,...r})}function at({delayDuration:s=0,...r}){return e.jsx(og,{delayDuration:s,children:e.jsx(Tf,{"data-slot":"tooltip",...r})})}function it({...s}){return e.jsx(Ff,{"data-slot":"tooltip-trigger",...s})}function nt({className:s,sideOffset:r=0,children:t,...n}){return e.jsx(Rf,{children:e.jsxs(_f,{"data-slot":"tooltip-content",sideOffset:r,className:R("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(Of,{className:"bg-muted fill-muted z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-xl"})]})})}let Fa=null;const Hl=()=>{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}}},ag=()=>{if(typeof window>"u"||!window.localStorage)return Hl();const s=window.localStorage,r=Hl();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=()=>(Fa||(Fa=ag()),Fa),sl={markdown:"0.9375rem",code:"0.9063rem",uiHeader:"0.9375rem",uiLabel:"0.8750rem",meta:"0.875rem",micro:"0.875rem"},ig={markdown:"0.9063rem",code:"0.8750rem",uiHeader:"0.9063rem",uiLabel:"0.8438rem",meta:"0.8438rem",micro:"0.7813rem"};function Ul(s){return`--text-${s.replace(/([A-Z])/g,"-$1").toLowerCase()}`}const pr={semanticMarkdown:{fontSize:"var(--text-markdown)"},semanticCode:{fontSize:"var(--text-code)"},uiHeader:{fontSize:"var(--text-ui-header)"},uiLabel:{fontSize:"var(--text-ui-label)"},meta:{fontSize:"var(--text-meta)"},micro:{fontSize:"var(--text-micro)"},ui:{button:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-line-height)",letterSpacing:"var(--ui-button-letter-spacing)",fontWeight:"var(--ui-button-font-weight)"},buttonSmall:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-button-small-line-height)",letterSpacing:"var(--ui-button-small-letter-spacing)",fontWeight:"var(--ui-button-small-font-weight)"},buttonLarge:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-button-large-line-height)",letterSpacing:"var(--ui-button-large-letter-spacing)",fontWeight:"var(--ui-button-large-font-weight)"},label:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-label-line-height)",letterSpacing:"var(--ui-label-letter-spacing)",fontWeight:"var(--ui-label-font-weight)"},caption:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-caption-line-height)",letterSpacing:"var(--ui-caption-letter-spacing)",fontWeight:"var(--ui-caption-font-weight)"},badge:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-badge-line-height)",letterSpacing:"var(--ui-badge-letter-spacing)",fontWeight:"var(--ui-badge-font-weight)"},tooltip:{fontSize:"var(--text-micro)",lineHeight:"var(--ui-tooltip-line-height)",letterSpacing:"var(--ui-tooltip-letter-spacing)",fontWeight:"var(--ui-tooltip-font-weight)"},input:{fontSize:"var(--text-ui-label)",lineHeight:"var(--ui-input-line-height)",letterSpacing:"var(--ui-input-letter-spacing)",fontWeight:"var(--ui-input-font-weight)"},helperText:{fontSize:"var(--text-meta)",lineHeight:"var(--ui-helper-text-line-height)",letterSpacing:"var(--ui-helper-text-letter-spacing)",fontWeight:"var(--ui-helper-text-font-weight)"}},code:{inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"},block:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},lineNumbers:{fontSize:"var(--text-micro)",lineHeight:"var(--code-line-numbers-line-height)",letterSpacing:"var(--code-line-numbers-letter-spacing)",fontWeight:"var(--code-line-numbers-font-weight)"}},markdown:{body:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-line-height)",letterSpacing:"var(--markdown-body-letter-spacing)",fontWeight:"var(--markdown-body-font-weight)"},bodySmall:{fontSize:"var(--text-meta)",lineHeight:"var(--markdown-body-small-line-height)",letterSpacing:"var(--markdown-body-small-letter-spacing)",fontWeight:"var(--markdown-body-small-font-weight)"},bodyLarge:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-body-large-line-height)",letterSpacing:"var(--markdown-body-large-letter-spacing)",fontWeight:"var(--markdown-body-large-font-weight)"},blockquote:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-blockquote-line-height)",letterSpacing:"var(--markdown-blockquote-letter-spacing)",fontWeight:"var(--markdown-blockquote-font-weight)"},list:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-list-line-height)",letterSpacing:"var(--markdown-list-letter-spacing)",fontWeight:"var(--markdown-list-font-weight)"},link:{fontSize:"var(--text-markdown)",lineHeight:"var(--markdown-link-line-height)",letterSpacing:"var(--markdown-link-letter-spacing)",fontWeight:"var(--markdown-link-font-weight)"},code:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-line-height)",letterSpacing:"var(--markdown-code-letter-spacing)",fontWeight:"var(--markdown-code-font-weight)"},codeBlock:{fontSize:"var(--text-code)",lineHeight:"var(--markdown-code-block-line-height)",letterSpacing:"var(--markdown-code-block-letter-spacing)",fontWeight:"var(--markdown-code-block-font-weight)"}},tool:{collapsed:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},popup:{fontSize:"var(--text-code)",lineHeight:"var(--code-block-line-height)",letterSpacing:"var(--code-block-letter-spacing)",fontWeight:"var(--code-block-font-weight)"},inline:{fontSize:"var(--text-code)",lineHeight:"var(--code-inline-line-height)",letterSpacing:"var(--code-inline-letter-spacing)",fontWeight:"var(--code-inline-font-weight)"}}},To={padding:{collapsed:"0.375rem",popup:"0.75rem",popupContainer:"1rem"},backgroundOpacity:{muted:"30",mutedAlt:"50"},getCollapsedStyles:()=>({...pr.tool.collapsed,background:"transparent",backgroundColor:"transparent",margin:0,padding:To.padding.collapsed,borderRadius:0}),getPopupStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:To.padding.popup,borderRadius:"0.75rem"}),getPopupContainerStyles:()=>({...pr.tool.popup,background:"transparent",backgroundColor:"transparent",margin:0,padding:To.padding.popupContainer,borderRadius:"0.5rem",overflowX:"auto"}),getInlineStyles:()=>({...pr.tool.inline})},_e=zt()(Yt(As((s,r)=>({theme:"system",isMultiRunLauncherOpen:!1,multiRunLauncherPrefillPrompt:"",isSidebarOpen:!0,sidebarWidth:264,hasManuallyResizedLeftSidebar:!1,isSessionSwitcherOpen:!1,activeMainTab:"chat",pendingDiffFile:null,isMobile:!1,isKeyboardOpen:!1,isCommandPaletteOpen:!1,isHelpDialogOpen:!1,isAboutDialogOpen:!1,isSessionCreateDialogOpen:!1,isSettingsDialogOpen:!1,isModelSelectorOpen:!1,sidebarSection:"sessions",eventStreamStatus:"idle",eventStreamHint:null,showReasoningTraces:!1,autoDeleteEnabled:!1,autoDeleteAfterDays:30,autoDeleteLastRunAt:null,toolCallExpansion:"collapsed",fontSize:100,padding:100,inputBarOffset:0,favoriteModels:[],recentModels:[],diffLayoutPreference:"dynamic",diffFileLayout:{},diffWrapLines:!1,isTimelineDialogOpen:!1,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(sl);if(o===1){for(const[i]of a)n.style.removeProperty(Ul(i));return}for(const[i,l]of a){const d=parseFloat(l);Number.isFinite(d)&&n.style.setProperty(Ul(i),`${d*o}rem`)}},applyPadding:()=>{const{padding:t}=r(),n=document.documentElement,o=t/100;if(o===1){n.style.removeProperty("--padding-scale"),n.style.removeProperty("--line-height-tight"),n.style.removeProperty("--line-height-normal"),n.style.removeProperty("--line-height-relaxed"),n.style.removeProperty("--line-height-loose");return}const a=Math.sqrt(o);n.style.setProperty("--padding-scale",a.toString());const i=1+(o-1)*.15;n.style.setProperty("--line-height-tight",(1.25*i).toFixed(3)),n.style.setProperty("--line-height-normal",(1.5*i).toFixed(3)),n.style.setProperty("--line-height-relaxed",(1.625*i).toFixed(3)),n.style.setProperty("--line-height-loose",(2*i).toFixed(3))},setDiffLayoutPreference:t=>{s({diffLayoutPreference:t})},setDiffFileLayout:(t,n)=>{s(o=>({diffFileLayout:{...o.diffFileLayout,[t]:n}}))},setDiffWrapLines:t=>{s({diffWrapLines:t})},setInputBarOffset:t=>{s({inputBarOffset:t})},setKeyboardOpen:t=>{s({isKeyboardOpen:t})},toggleFavoriteModel:(t,n)=>{s(o=>o.favoriteModels.some(i=>i.providerID===t&&i.modelID===n)?{favoriteModels:o.favoriteModels.filter(i=>!(i.providerID===t&&i.modelID===n))}:{favoriteModels:[{providerID:t,modelID:n},...o.favoriteModels]})},isFavoriteModel:(t,n)=>{const{favoriteModels:o}=r();return o.some(a=>a.providerID===t&&a.modelID===n)},addRecentModel:(t,n)=>{s(o=>{const a=o.recentModels.filter(i=>!(i.providerID===t&&i.modelID===n));return{recentModels:[{providerID:t,modelID:n},...a].slice(0,5)}})},updateProportionalSidebarWidths:()=>{typeof window>"u"||s(t=>{const n={};return t.isSidebarOpen&&!t.hasManuallyResizedLeftSidebar&&(n.sidebarWidth=Math.floor(window.innerWidth*.2)),n})},applyTheme:()=>{const{theme:t}=r(),n=document.documentElement;if(n.classList.remove("light","dark"),t==="system"){const o=window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";n.classList.add(o)}else n.classList.add(t)},setMultiRunLauncherOpen:t=>{s(n=>({isMultiRunLauncherOpen:t,multiRunLauncherPrefillPrompt:t?n.multiRunLauncherPrefillPrompt:""}))},openMultiRunLauncher:()=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:"",isSessionSwitcherOpen:!1})},openMultiRunLauncherWithPrompt:t=>{s({isMultiRunLauncherOpen:!0,multiRunLauncherPrefillPrompt:t,isSessionSwitcherOpen:!1})},setTimelineDialogOpen:t=>{s({isTimelineDialogOpen:t})},setNativeNotificationsEnabled:t=>{s({nativeNotificationsEnabled:t})},setNotificationMode:t=>{s({notificationMode:t})}}),{name:"ui-store",storage:Es(()=>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,nativeNotificationsEnabled:s.nativeNotificationsEnabled,notificationMode:s.notificationMode})}),{name:"ui-store"}));async function lg(){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 cg(){return Zt()?"desktop":kn()?"web":null}const Vl={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null},ha=zt()((s,r)=>({...Vl,checkForUpdates:async()=>{const t=cg();if(t){s({checking:!0,error:null,runtimeType:t});try{let n=null;t==="desktop"?n=await sg():t==="web"&&(n=await lg()),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 rg(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 ng()}catch(o){s({error:o instanceof Error?o.message:"Failed to restart"})}},dismiss:()=>{s({available:!1,downloaded:!1,info:null})},reset:()=>{s(Vl)}})),dg="/api",ug=/^[a-zA-Z][a-zA-Z\d+\-.]*:\/\//,mg=s=>{const r=typeof s=="string"&&s.trim().length>0?s.trim():"/api";if(ug.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}},fg=()=>{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},co=s=>s.replace(/\\/g,"/"),Ra=()=>{if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s&&s.runtime?.isDesktop&&s.files?s.files:null};class pg{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=dg){const n=fg()||r;this.baseUrl=mg(n),this.client=Lf({baseUrl:this.baseUrl})}normalizeCandidatePath(r){if(typeof r!="string")return null;const t=r.trim();if(!t)return null;const n=t.replace(/\\/g,"/");return(n.length>1?n.replace(/\/+$/,""):n)||null}deriveHomeDirectory(r){const t=r.match(/^([A-Za-z]:)(?:\/|$)/);if(t){const a=t[1],l=r.slice(a.length+(r.charAt(a.length)==="/"?1:0)).split("/").filter(Boolean);return l.length>=2?{homeDirectory:`${a}/${l[0]}/${l[1]}`,username:l[1]}:l.length===1?{homeDirectory:`${a}/${l[0]}`,username:l[0]}:{homeDirectory:a,username:void 0}}const n=r.startsWith("/"),o=r.split("/").filter(Boolean);return o.length>=2&&(o[0]==="Users"||o[0]==="home")?{homeDirectory:`${n?"/":""}${o[0]}/${o[1]}`,username:o[1]}:n?o.length===0?{homeDirectory:"/",username:void 0}:{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:o.length>0?{homeDirectory:`/${o.join("/")}`,username:o[o.length-1]}:{homeDirectory:"/",username:void 0}}setDirectory(r){this.currentDirectory=r}getDirectory(){return this.currentDirectory}async withDirectory(r,t){if(r==null)return t();const n=this.currentDirectory;this.currentDirectory=r;try{return await t()}finally{this.currentDirectory=n}}getApiClient(){return this.client}async getSystemInfo(){const r=new Set,t=o=>{const a=this.normalizeCandidatePath(o);a&&r.add(a)};try{const a=(await this.client.path.get(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data;a&&(t(a.directory),t(a.worktree),t(a.state))}catch(o){console.debug("Failed to load path info:",o)}if(!r.size)try{const o=await this.client.project.current(this.currentDirectory?{directory:this.currentDirectory}:void 0);t(o.data?.worktree)}catch(o){console.debug("Failed to load project info:",o)}if(!r.size)try{(await this.listSessions()).forEach(a=>t(a.directory))}catch(o){console.debug("Failed to inspect sessions for system info:",o)}if(t(this.currentDirectory),typeof window<"u")try{t(window.localStorage.getItem("lastDirectory")),t(window.localStorage.getItem("homeDirectory"))}catch{}if(!r.size&&typeof process<"u"&&typeof process.cwd=="function"&&t(process.cwd()),!r.size)return{homeDirectory:"/",username:void 0};const[n]=Array.from(r);return this.deriveHomeDirectory(n)}async listSessions(){const r=await this.client.session.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);return Array.isArray(r.data)?r.data:[]}async createSession(r){const t=await this.client.session.create({...this.currentDirectory?{directory:this.currentDirectory}:{},parentID:r?.parentID,title:r?.title});if(!t.data)throw new Error("Failed to create session");return t.data}async getSession(r){const t=await this.client.session.get({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Session not found");return t.data}async deleteSession(r){return(await this.client.session.delete({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||!1}async updateSession(r,t){const n=await this.client.session.update({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},title:t});if(!n.data)throw new Error("Failed to update session");return n.data}async getSessionMessages(r){return(await this.client.session.messages({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}})).data||[]}async getSessionTodos(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/${encodeURIComponent(r)}/todo`);this.currentDirectory&&this.currentDirectory.length>0&&n.searchParams.set("directory",this.currentDirectory);const o=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!o.ok)return[];const a=await o.json().catch(()=>null);return!a||!Array.isArray(a)?[]:a}catch{return[]}}shouldNormalizeToTextPlain(r){if(!r)return!1;const t=r.toLowerCase();return t.startsWith("text/")&&t!=="text/plain"?!0:["application/json","application/xml","application/javascript","application/typescript","application/x-yaml","application/yaml","application/toml","application/x-sh","application/x-shellscript"].includes(t)}isHeicMime(r){if(!r)return!1;const t=r.toLowerCase();return t==="image/heic"||t==="image/heif"}async convertHeicToJpeg(r){try{const t=(await as(async()=>{const{default:f}=await import("./vendor-.bun-94fMDU1C.js").then(p=>p.h);return{default:f}},__vite__mapDeps([0,1]))).default,n=r.url.indexOf(",");if(n===-1)return r;const o=r.url.substring(n+1),a=atob(o),i=new Uint8Array(a.length);for(let f=0;f<a.length;f++)i[f]=a.charCodeAt(f);const l=new Blob([i],{type:r.mime}),d=await t({blob:l,toType:"image/jpeg",quality:.9}),u=await new Promise((f,p)=>{const g=new FileReader;g.onload=()=>f(g.result),g.onerror=p,g.readAsDataURL(d)});let m=r.filename;return m&&(m=m.replace(/\.heic$/i,".jpg").replace(/\.heif$/i,".jpg")),{mime:"image/jpeg",filename:m,url:u}}catch(t){return console.warn("Failed to convert HEIC to JPEG:",t),r}}async normalizeFilePart(r){if(this.isHeicMime(r.mime))return this.convertHeicToJpeg(r);if(!this.shouldNormalizeToTextPlain(r.mime))return r;let t=r.url;if(r.url.startsWith("data:")){const n=r.url.indexOf(",");if(n!==-1){const o=r.url.substring(5,n),a=r.url.substring(n);t=`data:${o.replace(/^[^;,]+/,"text/plain")}${a}`}}return{mime:"text/plain",filename:r.filename,url:t}}async sendMessage(r){const t=Date.now(),n=r.messageId??`temp_${t}_${Math.random().toString(36).substring(2,9)}`,o=[];if(r.prefaceText&&r.prefaceText.trim()&&o.push({type:"text",text:r.prefaceText}),r.text&&r.text.trim()){const a={type:"text",text:r.text};o.push(a)}if(r.files&&r.files.length>0)for(const a of r.files){const i=await this.normalizeFilePart(a),l={type:"file",mime:i.mime,filename:i.filename,url:i.url};o.push(l)}if(r.additionalParts&&r.additionalParts.length>0){for(const a of r.additionalParts)if(a.text&&a.text.trim()&&o.push({type:"text",text:a.text}),a.files&&a.files.length>0)for(const i of a.files){const l=await this.normalizeFilePart(i),d={type:"file",mime:l.mime,filename:l.filename,url:l.url};o.push(d)}}if(r.agentMentions&&r.agentMentions.length>0){const[a]=r.agentMentions;a?.name&&o.push({type:"agent",name:a.name,...a.source?{source:a.source}:{}})}if(o.length===0)throw new Error("Message must have at least one part (text or file)");return await this.client.session.prompt({sessionID:r.id,...this.currentDirectory?{directory:this.currentDirectory}:{},model:{providerID:r.providerID,modelID:r.modelID},agent:r.agent,variant:r.variant,parts:o}),n}async abortSession(r){return!!(await this.client.session.abort({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}},{throwOnError:!0})).data}async revertSession(r,t,n){const o=await this.client.session.revert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t,partID:n});if(!o.data)throw new Error("Failed to revert session");return o.data}async unrevertSession(r){const t=await this.client.session.unrevert({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{}});if(!t.data)throw new Error("Failed to unrevert session");return t.data}async forkSession(r,t){const n=await this.client.session.fork({sessionID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},messageID:t});if(!n.data)throw new Error("Failed to fork session");return n.data}async getSessionStatus(){return this.getSessionStatusForDirectory(this.currentDirectory??null)}async getSessionStatusForDirectory(r){try{const t=this.baseUrl.replace(/\/$/,""),n=new URL(`${t}/session/status`),o=typeof r=="string"?r.trim():"";o.length>0&&n.searchParams.set("directory",o);const a=await fetch(n.toString(),{method:"GET",headers:{Accept:"application/json"}});if(!a.ok)return{};const i=await a.json().catch(()=>null);return!i||typeof i!="object"?{}:i}catch{return{}}}async getGlobalSessionStatus(){return this.getSessionStatusForDirectory(null)}async listToolIds(r){try{const t=typeof r?.directory=="string"?r.directory.trim():this.currentDirectory?this.currentDirectory.trim():"";return((await this.client.tool.ids(t?{directory:t}:void 0)).data||[]).filter(a=>typeof a=="string"&&a!=="invalid")}catch{return[]}}async replyToPermission(r,t,n){return(await this.client.permission.reply({requestID:r,...this.currentDirectory?{directory:this.currentDirectory}:{},reply:t,...n?.message?{message:n.message}:{}})).data||!1}async listPendingPermissions(){try{return(await this.client.permission.list()).data||[]}catch{return[]}}async 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),i=[],l=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||l.has(m)||(l.add(m),i.push(u))}return i}async getConfig(){const r=await this.client.config.get();if(!r.data)throw new Error("Failed to get config");return r.data}async updateConfig(r){const t=`${this.baseUrl}/config`,n=await fetch(t,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!n.ok){const a=await n.text();throw console.error("[OpencodeClient] Failed to update config:",n.status,a),new Error(`Failed to update config: ${n.status} ${n.statusText}`)}return await n.json()}async updateConfigPartial(r){const t=await this.getConfig(),n=r(t);return await this.updateConfig(n)}async getProviders(){const r=await this.client.config.providers(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(!r.data)throw new Error("Failed to get providers");return r.data}async getApp(){return{version:"0.0.3",config:await this.getConfig()}}async initApp(){try{return await this.checkHealth()}catch{return!1}}async listAgents(){try{return(await this.client.app.agents(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]}catch{return[]}}parseSseBlock(r){if(!r)return null;const t=r.split(`
3
- `),n=[];let o;for(const i of t)if(i.startsWith("data:"))n.push(i.slice(5).replace(/^\s/,""));else if(i.startsWith("id:")){const l=i.slice(3).trim();l&&(o=l)}if(n.length===0)return null;const a=n.join(`
4
- `).trim();if(!a)return null;try{return{data:JSON.parse(a),id:o}}catch{return null}}normalizeRoutedSsePayload(r){if(!r||typeof r!="object")return null;const t=r,n=typeof t.directory=="string"?t.directory:typeof t.properties=="object"&&t.properties!==null?t.properties.directory:null,o=typeof n=="string"?this.normalizeCandidatePath(n)??n.trim():null;if(typeof t.type=="string")return{directory:o&&o.length>0?o:"global",payload:t};const a=t.payload;if(a&&typeof a=="object"){const i=a;if(typeof i.type=="string")return{directory:o&&o.length>0?o:"global",payload:i}}return null}emitGlobalSseEvent(r){for(const t of this.globalSseListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE listener error:",n)}}notifyGlobalSseOpen(){for(const r of this.globalSseOpenListeners)try{r()}catch(t){console.warn("[OpencodeClient] Global SSE open handler error:",t)}}notifyGlobalSseError(r){for(const t of this.globalSseErrorListeners)try{t(r)}catch(n){console.warn("[OpencodeClient] Global SSE error handler failed:",n)}}ensureGlobalSseStarted(){if(this.globalSseTask)return;const r=new AbortController;this.globalSseAbortController=r,this.globalSseTask=this.runGlobalSseLoop(r).catch(t=>{t?.name==="AbortError"||r.signal.aborted||console.error("[OpencodeClient] Global SSE task failed:",t)}).finally(()=>{this.globalSseAbortController===r&&(this.globalSseAbortController=null),this.globalSseTask=null,this.globalSseIsConnected=!1})}maybeStopGlobalSse(){this.globalSseListeners.size>0||(this.globalSseAbortController&&!this.globalSseAbortController.signal.aborted&&this.globalSseAbortController.abort(),this.globalSseAbortController=null)}async runGlobalSseLoop(r){const t=`${this.baseUrl.replace(/\/+$/,"")}/global/event`;let n=0;for(;!r.signal.aborted;){try{const a={Accept:"text/event-stream","Cache-Control":"no-cache"};this.globalSseLastEventId&&(a["Last-Event-ID"]=this.globalSseLastEventId);const i=await fetch(t,{method:"GET",headers:a,signal:r.signal});if(!i.ok||!i.body)throw new Error(`Global SSE connect failed with status ${i.status}`);n=0,this.globalSseIsConnected=!0,r.signal.aborted||this.notifyGlobalSseOpen();const l=i.body.getReader(),d=new TextDecoder;let u="";for(;;){const{done:f,value:p}=await l.read();if(f||r.signal.aborted)break;if(!p||p.length===0)continue;u+=d.decode(p,{stream:!0}).replace(/\r\n/g,`
5
- `);const g=u.split(`
6
-
7
- `);u=g.pop()??"";for(const w of g){const h=this.parseSseBlock(w);if(!h)continue;h.id&&(this.globalSseLastEventId=h.id);const j=this.normalizeRoutedSsePayload(h.data);j&&this.emitGlobalSseEvent(j)}}const m=u.trim();if(m&&!r.signal.aborted){const f=this.parseSseBlock(m);f?.id&&(this.globalSseLastEventId=f.id);const p=f?this.normalizeRoutedSsePayload(f.data):null;p&&this.emitGlobalSseEvent(p)}this.globalSseIsConnected=!1}catch(a){if(this.globalSseIsConnected=!1,a?.name==="AbortError"||r.signal.aborted)return;console.error("[OpencodeClient] Global SSE stream error (will retry):",a),this.notifyGlobalSseError(a)}if(r.signal.aborted)break;n+=1;const o=Math.min(3e3*Math.pow(2,n),3e4);await new Promise(a=>setTimeout(a,o))}}subscribeToGlobalEvents(r,t,n,o){const a=this.normalizeCandidatePath(o?.directory??null),i=l=>{a&&l.directory!==a||r(l)};return this.globalSseListeners.add(i),n&&(this.globalSseOpenListeners.add(n),this.globalSseIsConnected&&setTimeout(()=>{if(this.globalSseOpenListeners.has(n))try{n()}catch(l){console.warn("[OpencodeClient] Global SSE open handler error:",l)}},0)),t&&this.globalSseErrorListeners.add(t),this.ensureGlobalSseStarted(),()=>{this.globalSseListeners.delete(i),n&&this.globalSseOpenListeners.delete(n),t&&this.globalSseErrorListeners.delete(t),this.maybeStopGlobalSse()}}subscribeToEvents(r,t,n,o,a){const i=a?.key??"default",l=a?.scope??"directory",d=this.sseAbortControllers.get(i);d&&d.abort();const u=new AbortController;this.sseAbortControllers.set(i,u);let m;if(l==="global"){let p=null;const g=h=>{if(h.directory==="global")return h.payload;const j=h.payload,x=typeof j.properties=="object"&&j.properties!==null?j.properties:{};return x.directory===h.directory?h.payload:{...j,properties:{...x,directory:h.directory}}},w=()=>{if(p){try{p()}catch{}p=null}this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)};return u.signal.addEventListener("abort",w,{once:!0}),p=this.subscribeToGlobalEvents(h=>{u.signal.aborted||r(g(h))},t?h=>{u.signal.aborted||t(h)}:void 0,n?()=>{u.signal.aborted||n()}:void 0),()=>{w(),u.abort()}}const f=p=>{if(!p||typeof p!="object")return null;const g=p;if(typeof g.type=="string")return g;const w=g.payload;if(w&&typeof w=="object"){const h=w;if(typeof h.type=="string"){if(typeof g.directory=="string"&&g.directory.length>0){const x={...(typeof h.properties=="object"&&h.properties!==null?h.properties:null)??{},directory:g.directory};return{...h,properties:x}}return h}}return null};return console.log("[OpencodeClient] Starting SSE subscription..."),(async()=>{const p=typeof o=="string"&&o.trim().length>0?o.trim():this.currentDirectory;console.log("[OpencodeClient] Connecting to SSE with directory:",p??"default");const g=async w=>{try{const h=p?{directory:p}:void 0,j={signal:u.signal,sseDefaultRetryDelay:3e3,sseMaxRetryDelay:3e4,onSseError:y=>{y instanceof Error&&y.name==="AbortError"||(console.error("[OpencodeClient] SSE error:",y),t&&!u.signal.aborted&&t(y))},onSseEvent:y=>{if(u.signal.aborted)return;y.id&&typeof y.id=="string"&&(m=y.id);const b=y.data,N=f(b);N&&r(N)}};m&&(j.headers={...j.headers||{},"Last-Event-ID":m});const x=await this.client.event.subscribe(h,j);n&&!u.signal.aborted&&(console.log("[OpencodeClient] SSE connection opened"),n());for await(const y of x.stream)if(u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted");break}}catch(h){if(h?.name==="AbortError"||u.signal.aborted){console.log("[OpencodeClient] SSE stream aborted normally");return}console.error("[OpencodeClient] SSE stream error (will retry):",h),t&&t(h);const j=Math.min(3e3*Math.pow(2,w),3e4);await new Promise(x=>setTimeout(x,j)),u.signal.aborted||await g(w+1);return}if(!u.signal.aborted){const h=Math.min(3e3*Math.pow(2,w),3e4);await new Promise(j=>setTimeout(j,h)),await g(w+1)}};try{await g(0)}finally{console.log("[OpencodeClient] SSE subscription cleanup"),this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i)}})(),()=>{this.sseAbortControllers.get(i)===u&&this.sseAbortControllers.delete(i),u.abort()}}async readFile(r){try{const t=await fetch(`${this.baseUrl}/files/read`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r,directory:this.currentDirectory})});if(!t.ok)throw new Error(`Failed to read file: ${t.statusText}`);return await t.text()}catch{return`// Content of ${r}
8
- // This would be loaded from the server`}}async listFiles(r){try{const t=r||this.currentDirectory||"/",n=await fetch(`${this.baseUrl}/files/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({directory:t})});if(!n.ok)throw new Error(`Failed to list files: ${n.statusText}`);return await n.json()}catch{return[]}}async listCommands(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model}))}catch{return[]}}async listCommandsWithDetails(){try{return((await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0)).data||[]).map(t=>({name:t.name,description:t.description,agent:t.agent,model:t.model,template:t.template,subtask:t.subtask}))}catch{return[]}}async getCommandDetails(r){try{const t=await this.client.command.list(this.currentDirectory?{directory:this.currentDirectory}:void 0);if(t.data){const n=t.data.find(o=>o.name===r);if(n)return{name:n.name,template:n.template,description:n.description,agent:n.agent,model:n.model}}return null}catch{return null}}async checkHealth(){try{let r;const t=this.baseUrl.endsWith("/")?this.baseUrl.replace(/\/+$/,""):this.baseUrl;t==="/api"?r="/health":t.endsWith("/api")?r=`${t.slice(0,-4)}/health`:r=`${t}/health`;const n=await fetch(r);return!(!n.ok||(await n.json()).isOpenCodeReady===!1)}catch{return!1}}async createDirectory(r){const t=Ra();if(t?.createDirectory)try{return await t.createDirectory(r)}catch(a){const i=a instanceof Error?a.message:String(a);throw new Error(i||"Failed to create directory")}const n=await fetch(`${this.baseUrl}/fs/mkdir`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})});if(!n.ok){const a=await n.json().catch(()=>({error:"Failed to create directory"}));throw new Error(a.error||"Failed to create directory")}return await n.json()}async listLocalDirectory(r){const t=Ra();if(t)try{const n=await t.listDirectory(r||"");return!n||!Array.isArray(n.entries)?[]:n.entries.map(o=>({name:o.name,path:co(o.path),isDirectory:!!o.isDirectory,isFile:!o.isDirectory,isSymbolicLink:!1}))}catch(n){throw console.error("Failed to list directory contents:",n),n}try{const n=new URLSearchParams;r&&r.trim().length>0&&n.set("path",r);const o=n.toString(),a=await fetch(`${this.baseUrl}/fs/list${o?`?${o}`:""}`);if(!a.ok){const l=await a.json().catch(()=>({})),d=typeof l.error=="string"?l.error:"Failed to list directory";throw new Error(d)}const i=await a.json();return!i||!Array.isArray(i.entries)?[]:i.entries}catch(n){throw console.error("Failed to list directory contents:",n),n}}async searchFiles(r,t){const n=Ra(),o=typeof t?.directory=="string"&&t.directory.trim().length>0?t.directory.trim():this.currentDirectory,a=o?co(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=co(f.path),g=p.split("/").filter(Boolean).pop()||p,w=f.preview&&f.preview.length>0&&typeof f.preview[0]=="string"?co(f.preview[0]):a&&p.startsWith(a)&&p.slice(a.length).replace(/^\/+/,"")||g;return{name:g,path:p,relativePath:w,extension:g.includes(".")?g.split(".").pop()?.toLowerCase():void 0}}):[]}catch(m){throw console.error("Failed to search files:",m),m}const i=new URLSearchParams;o&&o.length>0&&i.set("directory",o),typeof r=="string"&&i.set("q",r),typeof t?.limit=="number"&&Number.isFinite(t.limit)&&i.set("limit",String(t.limit));const l=`${this.baseUrl}/fs/search${i.toString()?`?${i.toString()}`:""}`,d=await fetch(l,{method:"GET",headers:{Accept:"application/json"}});if(!d.ok){const m=await d.json().catch(()=>({})),f=typeof m.error=="string"?m.error:"Failed to search files";throw new Error(f)}const u=await d.json();return!u||!Array.isArray(u.files)?[]:u.files}async getFilesystemHome(){const r=await Cu();if(r)return r;try{const t=await fetch(`${this.baseUrl}/fs/home`,{method:"GET",headers:{Accept:"application/json"}});if(!t.ok){const o=await t.json().catch(()=>({})),a=typeof o.error=="string"&&o.error.length>0?o.error:"Failed to resolve home directory";throw new Error(a)}const n=await t.json();return n&&typeof n.home=="string"&&n.home.length>0?n.home:null}catch(t){return console.warn("Failed to resolve filesystem home directory:",t),null}}async setOpenCodeWorkingDirectory(r){if(!r||typeof r!="string"||!r.trim())return console.warn("[OpencodeClient] setOpenCodeWorkingDirectory: invalid path",r),null;const t=`${this.baseUrl}/opencode/directory`;console.log("[OpencodeClient] POST",t,"with path:",r);try{const n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path:r})}),o=await n.json().catch(()=>null);if(!n.ok){const a=o??{},i=typeof a.error=="string"&&a.error.length>0?a.error:"Failed to update OpenCode working directory";throw new Error(i)}return o&&typeof o=="object"?o:{success:!0,restarted:!1,path:r}}catch(n){throw console.warn("Failed to update OpenCode working directory:",n),n}}}const je=new pg,hg=Object.freeze(Object.defineProperty({__proto__:null,opencodeClient:je},Symbol.toStringTag,{value:"Module"})),Mi=new Set;function ga(s){return Mi.add(s),()=>{Mi.delete(s)}}function sr(s,r){const t=Array.isArray(s)?s:[s],n=Array.from(new Set(t));if(n.length===0)return;n.includes("all")&&n.splice(0,n.length,"all");const o={scopes:n,source:r?.source,timestamp:Date.now()};for(const a of Mi)try{const i=a(o);i instanceof Promise&&i.catch(l=>{console.error("[ConfigSync] Async listener failed:",l)})}catch(i){console.error("[ConfigSync] Listener threw:",i)}}function Zn(s,r){return s.scopes.includes("all")||s.scopes.includes(r)}const rl="Updating OpenCode configuration...";let rr=0,Ir=rl;const Di=new Set;function Yo(){const s={isUpdating:rr>0,message:Ir};Di.forEach(r=>r(s))}function Vs(s){rr+=1,rr===1?(Ir=s||rl,Yo()):s&&(Ir=s,Yo())}function Ds(){rr!==0&&(rr-=1,rr===0&&(Ir=rl,Yo()))}function gr(s){Ir===s&&rr>0||(Ir=s,rr>0&&Yo())}function gg(s){return Di.add(s),s({isUpdating:rr>0,message:Ir}),()=>{Di.delete(s)}}function xg(){return{isUpdating:rr>0,message:Ir}}const Zs=zt()(Yt(As((s,r)=>({queuedMessages:{},queueModeEnabled:!1,addToQueue:(t,n)=>{const a={id:`queued-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,content:n.content,attachments:n.attachments,createdAt:Date.now()};s(i=>{const l=i.queuedMessages[t]??[];return{queuedMessages:{...i.queuedMessages,[t]:[...l,a]}}})},removeFromQueue:(t,n)=>{s(o=>{const i=(o.queuedMessages[t]??[]).filter(l=>l.id!==n);if(i.length===0){const{[t]:l,...d}=o.queuedMessages;return{queuedMessages:d}}return{queuedMessages:{...o.queuedMessages,[t]:i}}})},popToInput:(t,n)=>{const i=(r().queuedMessages[t]??[]).find(l=>l.id===n);return i?(s(l=>{const u=(l.queuedMessages[t]??[]).filter(m=>m.id!==n);if(u.length===0){const{[t]:m,...f}=l.queuedMessages;return{queuedMessages:f}}return{queuedMessages:{...l.queuedMessages,[t]:u}}}),i):null},clearQueue:t=>{s(n=>{const{[t]:o,...a}=n.queuedMessages;return{queuedMessages:a}})},clearAllQueues:()=>{s({queuedMessages:{}})},setQueueMode:t=>{s({queueModeEnabled:t}),rs({queueModeEnabled:t})},getQueueForSession:t=>r().queuedMessages[t]??[]}),{name:"message-queue-store",storage:Es(()=>ds()),partialize:s=>({queuedMessages:s.queuedMessages,queueModeEnabled:s.queueModeEnabled})}),{name:"message-queue-store"})),Gl=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},yg=s=>!s||typeof s!="object"?null:{showReasoningTraces:s.showReasoningTraces},bg=s=>{const r=_e.getState();typeof s.showReasoningTraces=="boolean"&&r.setShowReasoningTraces(s.showReasoningTraces)},wg=async()=>{if(typeof window>"u")return null;if(Zt()){const r=window.opencodeAppearance;if(!r||typeof r.load!="function")return null;try{const t=await r.load();return Gl(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=yg(r);return Gl(t)}catch(r){return console.warn("Failed to parse stored appearance preferences:",r),null}};let Au=null;const ql=s=>{Au=s},vr=()=>Au,Fo=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"))},vg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set;for(const n of s){if(!n||typeof n!="object")continue;const o=n,a=typeof o.id=="string"?o.id.trim():"",i=typeof o.label=="string"?o.label.trim():"",l=typeof o.source=="string"?o.source.trim():"",d=typeof o.subpath=="string"?o.subpath.trim():"",u=typeof o.gitIdentityId=="string"?o.gitIdentityId.trim():"";!a||!i||!l||t.has(a)||(t.add(a),r.push({id:a,label:i,source:l,...d?{subpath:d}:{},...u?{gitIdentityId:u}:{}}))}return r},jg=s=>{if(!Array.isArray(s))return;const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=l==="/"?l:l.replace(/\\/g,"/").replace(/\/+$/,"");if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&m.branchPrefix.trim()&&(f.branchPrefix=m.branchPrefix.trim()),typeof m.baseBranch=="string"&&m.baseBranch.trim()&&(f.baseBranch=m.baseBranch.trim()),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r.length>0?r:void 0},Eu=()=>{const s=_e.persist;if(s&&typeof s=="object")return s},Iu=()=>vr()?.settings??null,Ro=s=>{const r=_e.getState(),t=Zs.getState();if(typeof s.showReasoningTraces=="boolean"&&s.showReasoningTraces!==r.showReasoningTraces&&r.setShowReasoningTraces(s.showReasoningTraces),typeof s.autoDeleteEnabled=="boolean"&&s.autoDeleteEnabled!==r.autoDeleteEnabled&&r.setAutoDeleteEnabled(s.autoDeleteEnabled),typeof s.autoDeleteAfterDays=="number"&&Number.isFinite(s.autoDeleteAfterDays)){const n=Math.max(1,Math.min(365,s.autoDeleteAfterDays));n!==r.autoDeleteAfterDays&&r.setAutoDeleteAfterDays(n)}typeof s.queueModeEnabled=="boolean"&&s.queueModeEnabled!==t.queueModeEnabled&&t.setQueueMode(s.queueModeEnabled)},Kl=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=jg(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=vg(r.skillCatalogs);return o&&(t.skillCatalogs=o),t},Sg=async()=>{const s=Iu();if(s)try{const r=await s.load();return Kl(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 Kl(t)}catch(r){return console.warn("Failed to load shared settings from server:",r),null}},Pu=async()=>{if(typeof window>"u")return;const s=Eu(),r=t=>{Fo(t);const n=()=>Ro(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=Zt()?await sn():await Sg();t&&r(t)}catch(t){console.warn("Failed to synchronise settings:",t)}},rs=async s=>{if(typeof window>"u")return;if(Zt()){try{const t=await Jh(s);t&&(Fo(t),Ro(t))}catch(t){console.warn("Failed to update desktop settings:",t)}return}const r=Iu();if(r)try{const t=await r.save(s);t&&(Fo(t),Ro(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&&(Fo(n),Ro(n))}catch(t){console.warn("Failed to update shared settings via API:",t)}},Tu=async()=>{if(typeof window>"u")return;const s=Eu();try{const r=await wg();if(!r)return;const t=()=>bg(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)}},kg=3e4,Ng=40,Cg=60,Mg=(s,r,t)=>{const n=s.trim(),o=r.trim().toLowerCase();return`${n}::${o}::${t}`},nl=zt()(Yt((s,r)=>({cache:{},cacheKeys:[],inFlight:{},async searchFiles(t,n,o=Cg){if(!t||t.trim().length===0)return[];const a=t.trim(),i=typeof n=="string"?n.trim():"",l=Mg(a,i,o),d=Date.now(),u=r().cache[l];if(u&&d-u.timestamp<kg)return u.files;const m=r().inFlight[l];if(m)return m;const f=je.searchFiles(i,{directory:a,limit:o}).then(p=>(s(g=>{const w={...g.cache,[l]:{files:p,timestamp:Date.now()}},h=g.cacheKeys.filter(j=>j!==l);for(h.push(l);h.length>Ng;){const j=h.shift();j&&delete w[j]}return{cache:w,cacheKeys:h}}),p)).finally(()=>{s(p=>{const g={...p.inFlight};return delete g[l],{inFlight:g}})});return s(p=>({inFlight:{...p.inFlight,[l]:f}})),f},invalidateDirectory(t){if(!t||t.trim().length===0){s({cache:{},cacheKeys:[],inFlight:{}});return}const o=`${t.trim()}::`;s(a=>{const i={...a.cache},l=a.cacheKeys.filter(m=>m.startsWith(o)?(delete i[m],!1):!0),d=Object.entries(a.inFlight).filter(([m])=>!m.startsWith(o)),u=Object.fromEntries(d);return{cache:i,cacheKeys:l,inFlight:u}})}}),{name:"file-search-store"})),Qt=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}};var Dg={};let Ws=null;const zs=ds(),Yl=zs.getItem("lastDirectory"),Ag=typeof Yl=="string"&&Yl.length>0,uo=s=>{try{nl.getState().invalidateDirectory(s)}catch(r){console.warn("Failed to invalidate file search cache:",r)}},Eg=s=>{const r=s.trim();if(!r)return r;const t=r.replace(/\\/g,"/");return t.length>1?t.replace(/\/+$/,""):t},Ig=(s,r)=>{const t=s.trim();return t.startsWith("~")?t==="~"?r||t:(t.startsWith("~/")||t.startsWith("~\\"))&&r?`${r}${t.slice(1)}`:t:t},_o=(s,r)=>{const t=Ig(s,r);return Eg(t)},Qo=()=>{if(typeof window<"u"){const r=zs.getItem("homeDirectory")||Ws||null,t=zs.getItem("lastDirectory");if(t)return _o(t,r);if(Ws)return Ws;const n=typeof window.__OPENCHAMBER_HOME__=="string"&&window.__OPENCHAMBER_HOME__.length>0?window.__OPENCHAMBER_HOME__:window.opencodeDesktop&&typeof window.opencodeDesktop.homeDirectory=="string"?window.opencodeDesktop.homeDirectory:null;if(n&&n.length>0)return Ws=n,zs.setItem("homeDirectory",n),n;if(r)return Ws=r,r}const s=typeof process<"u"&&Dg?.HOME;return s||process?.cwd?.()||"/"},Pg=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},Tg=s=>(Ws=s,typeof window<"u"&&zs.setItem("homeDirectory",s),rs({homeDirectory:s}),s),Fu=async()=>{const s=n=>{const o=Pg(n);return o?Tg(o):null};try{const n=await je.getFilesystemHome(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain filesystem home directory:",n)}try{const n=await je.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 Cu(),o=s(n);if(o)return o}catch(n){console.warn("Failed to obtain desktop-integrated home directory:",n)}const r=Qo(),t=s(r);return t||r},Gr=Qo();Gr&&je.setDirectory(Gr);const Fg=!!(Gr&&Gr!=="/"),mt=zt()(Yt((s,r)=>({currentDirectory:Gr,directoryHistory:[Gr],historyIndex:0,homeDirectory:Gr,hasPersistedDirectory:Ag,isHomeReady:Fg,isSwitchingDirectory:!1,setDirectory:(t,n)=>{const o=Ws||r().homeDirectory||zs.getItem("homeDirectory"),a=_o(t,o);Qt()&&console.log("[DirectoryStore] setDirectory called with path:",a),je.setDirectory(a),uo(),s(i=>{const l=[...i.directoryHistory.slice(0,i.historyIndex+1),a];return zs.setItem("lastDirectory",a),rs({lastDirectory:a}),{currentDirectory:a,directoryHistory:l,historyIndex:l.length-1,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1}})},goBack:()=>{const t=r();if(t.historyIndex>0){const n=t.historyIndex-1,o=t.directoryHistory[n];je.setDirectory(o),uo(),zs.setItem("lastDirectory",o),rs({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];je.setDirectory(o),uo(),zs.setItem("lastDirectory",o),rs({lastDirectory:o}),s({currentDirectory:o,historyIndex:n,hasPersistedDirectory:!0,isHomeReady:!0,isSwitchingDirectory:!1})}},goToParent:()=>{const{currentDirectory:t,setDirectory:n}=r(),o=Ws||r().homeDirectory||Qo();if(t===o||t==="/")return;const a=t.endsWith("/")?t.slice(0,-1):t,i=a.lastIndexOf("/");if(i===-1){const l=Ws||Qo();n(l)}else n(i===0?"/":a.substring(0,i))},goHome:async()=>{const t=Ws||r().homeDirectory||await Fu();r().setDirectory(t)},synchronizeHomeDirectory:t=>{const n=r(),o=t;Ws=o;const a=n.homeDirectory!==o,i=zs.getItem("lastDirectory"),l=typeof i=="string"&&i.length>0,d=!l&&(n.currentDirectory==="/"||n.currentDirectory===n.homeDirectory||!n.currentDirectory);if(!a&&!d){n.isHomeReady||s({isHomeReady:!0});return}const u=typeof o=="string"&&o!==""&&o!=="/",m=n.currentDirectory?_o(n.currentDirectory,o):n.currentDirectory,f=n.directoryHistory.map(h=>_o(h,o)),p=f.some((h,j)=>h!==n.directoryHistory[j]),g=!!(m&&m!==n.currentDirectory),w={homeDirectory:o,hasPersistedDirectory:l,isHomeReady:u};if(d?(w.currentDirectory=o,w.directoryHistory=[o],w.historyIndex=0,w.isSwitchingDirectory=!1):(g||p)&&(w.currentDirectory=m,w.directoryHistory=f,w.historyIndex=Math.min(n.historyIndex,f.length-1),w.isSwitchingDirectory=!1),s(()=>w),(d||g)&&u){const h=d?o:m;je.setDirectory(h),uo(),zs.setItem("lastDirectory",h),rs({lastDirectory:h})}rs({homeDirectory:o})}}),{name:"directory-store"}));typeof window<"u"&&Fu().then(s=>{mt.getState().synchronizeHomeDirectory(s)});const bn=ds(),Ru="projects",Ai="activeProjectId",Rg=(s,r)=>{const t=s.trim();return!t.startsWith("~")||!r?t:t==="~"?r:t.startsWith("~/")||t.startsWith("~\\")?`${r}${t.slice(1)}`:t},xa=s=>{const r=s.trim();if(!r)return"";const t=bn.getItem("homeDirectory")||mt.getState().homeDirectory||"",o=Rg(r,t).replace(/\\/g,"/");return o==="/"?"/":o.length>1?o.replace(/\/+$/,""):o},_u=s=>{const r=xa(s);if(!r||r==="/")return"Root";const t=r.split("/").filter(Boolean);return t[t.length-1]||r},_g=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`proj_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Ou=s=>{if(!Array.isArray(s))return[];const r=[],t=new Set,n=new Set;for(const o of s){if(!o||typeof o!="object")continue;const a=o,i=typeof a.id=="string"?a.id.trim():"",l=typeof a.path=="string"?a.path.trim():"";if(!i||!l)continue;const d=xa(l);if(!d||t.has(i)||n.has(d))continue;t.add(i),n.add(d);const u={id:i,path:d};if(typeof a.label=="string"&&a.label.trim().length>0&&(u.label=a.label.trim()),typeof a.addedAt=="number"&&Number.isFinite(a.addedAt)&&a.addedAt>=0&&(u.addedAt=a.addedAt),typeof a.lastOpenedAt=="number"&&Number.isFinite(a.lastOpenedAt)&&a.lastOpenedAt>=0&&(u.lastOpenedAt=a.lastOpenedAt),a.worktreeDefaults&&typeof a.worktreeDefaults=="object"){const m=a.worktreeDefaults,f={};typeof m.branchPrefix=="string"&&(f.branchPrefix=m.branchPrefix),typeof m.baseBranch=="string"&&(f.baseBranch=m.baseBranch),typeof m.autoCreateWorktree=="boolean"&&(f.autoCreateWorktree=m.autoCreateWorktree),Object.keys(f).length>0&&(u.worktreeDefaults=f)}r.push(u)}return r},Og=()=>{try{const s=bn.getItem(Ru);return s?Ou(JSON.parse(s)):[]}catch{return[]}},$g=()=>{try{const s=bn.getItem(Ai);if(typeof s=="string"&&s.trim().length>0)return s.trim()}catch{return null}return null},ol=(s,r)=>{try{bn.setItem(Ru,JSON.stringify(s))}catch{}try{r?bn.setItem(Ai,r):bn.removeItem(Ai)}catch{}},ln=(s,r)=>{ol(s,r),rs({projects:s,activeProjectId:r??void 0})},Lg=Og(),Bg=()=>{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=xa(r);if(!t)return null;const n=`vscode:${t}`,o={id:n,path:t,label:_u(t),addedAt:Date.now(),lastOpenedAt:Date.now()};return Qt()&&console.log("[OpenChamber][VSCode][projects] Using workspace fallback project",o),{projects:[o],activeProjectId:n}},Ls=Bg(),al=Ls?.projects??Lg,$u=Ls?.activeProjectId??$g()??al[0]?.id??null;Ls&&ol(al,$u);const Ft=zt()(Yt((s,r)=>({projects:al,activeProjectId:$u,validateProjectPath:t=>{if(typeof t!="string"||t.trim().length===0)return{ok:!1,reason:"Provide a directory path."};const n=xa(t);return n?{ok:!0,normalizedPath:n}:{ok:!1,reason:"Directory path cannot be empty."}},addProject:(t,n)=>{if(Ls)return null;const{validateProjectPath:o}=r(),a=o(t);if(!a.ok||!a.normalizedPath)return null;const i=a.normalizedPath,l=r().projects.find(w=>w.path===i);if(l)return r().setActiveProject(l.id),l;const d=Date.now(),u=n?.label?.trim()||_u(i),m=n?.id?.trim(),p={id:m&&!r().projects.some(w=>w.id===m)?m:_g(),path:i,label:u,addedAt:d,lastOpenedAt:d},g=[...r().projects,p];return s({projects:g}),Qt()&&console.info("[ProjectsStore] Added project",p),r().setActiveProject(p.id),p},removeProject:t=>{if(Ls)return;const n=r(),o=n.projects.filter(i=>i.id!==t);let a=n.activeProjectId;if(n.activeProjectId===t&&(a=o[0]?.id??null),s({projects:o,activeProjectId:a}),ln(o,a),a){const i=o.find(l=>l.id===a);i&&(je.setDirectory(i.path),mt.getState().setDirectory(i.path,{showOverlay:!1}))}else mt.getState().goHome()},setActiveProject:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t)return;const a=n.find(d=>d.id===t);if(!a)return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),ln(l,t),je.setDirectory(a.path),mt.getState().setDirectory(a.path,{showOverlay:!1})},setActiveProjectIdOnly:t=>{if(Ls)return;const{projects:n,activeProjectId:o}=r();if(o===t||!n.find(d=>d.id===t))return;const i=Date.now(),l=n.map(d=>d.id===t?{...d,lastOpenedAt:i}:d);s({projects:l,activeProjectId:t}),ln(l,t)},renameProject:(t,n)=>{if(Ls)return;const o=n.trim();if(!o)return;const{projects:a,activeProjectId:i}=r(),l=a.map(d=>d.id===t?{...d,label:o}:d);s({projects:l}),ln(l,i)},reorderProjects:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r();if(t<0||t>=o.length||n<0||n>=o.length||t===n)return;const i=[...o],[l]=i.splice(t,1);i.splice(n,0,l),s({projects:i}),ln(i,a)},synchronizeFromSettings:t=>{if(Ls)return;const n=Ou(t.projects??[]),o=typeof t.activeProjectId=="string"&&t.activeProjectId.trim()?t.activeProjectId.trim():null,a=r(),i=JSON.stringify(a.projects)!==JSON.stringify(n),l=a.activeProjectId!==o;if(!(!i&&!l)&&(s({projects:n,activeProjectId:o}),ol(n,o),o)){const d=n.find(u=>u.id===o);d&&(je.setDirectory(d.path),mt.getState().setDirectory(d.path,{showOverlay:!1}))}},getActiveProject:()=>{const{projects:t,activeProjectId:n}=r();return n?t.find(o=>o.id===n)??null:null},updateWorktreeDefaults:(t,n)=>{if(Ls)return;const{projects:o,activeProjectId:a}=r(),i=o.find(u=>u.id===t);if(!i)return;const l={...i.worktreeDefaults};n.branchPrefix!==void 0&&(n.branchPrefix.trim()?l.branchPrefix=n.branchPrefix.trim():delete l.branchPrefix),n.baseBranch!==void 0&&(n.baseBranch.trim()?l.baseBranch=n.baseBranch.trim():delete l.baseBranch),n.autoCreateWorktree!==void 0&&(l.autoCreateWorktree=n.autoCreateWorktree);const d=o.map(u=>u.id===t?{...u,worktreeDefaults:Object.keys(l).length>0?l:void 0}:u);s({projects:d}),ln(d,a)}}),{name:"projects-store"}));typeof window<"u"&&window.addEventListener("openchamber:settings-synced",s=>{const r=s.detail;r&&typeof r=="object"&&Ft.getState().synchronizeFromSettings(r)});const zg=new Set(["init","review"]),hn=s=>zg.has(s.name),Hn="useCommandsStore",Ei=s=>new Promise(r=>setTimeout(r,s)),mo=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=je.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[CommandsStore] Error resolving config directory:",s)}return null},Wg=2e4,Ql=300,Xl=4,Hg=800,Ug=200,Vg=2e3,Rr=zt()(Yt(As((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=mo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await je.withDirectory(a,()=>je.listCommandsWithDetails()),d=await Promise.all(l.map(async u=>{try{const m=await fetch(`/api/config/commands/${encodeURIComponent(u.name)}${i}`,{headers:{"Cache-Control":"no-cache",...a?{"x-opencode-directory":a}:{}}});if(m.ok){const f=await m.json();let p=f.scope;if(!p&&f.sources){const g=f.sources;p=(g.md?.exists?g.md.scope:void 0)??(g.json?.exists?g.json.scope:void 0)??g.md?.scope??g.json?.scope}return p==="project"||p==="user"?{...u,scope:p}:{...u,scope:void 0}}}catch(m){console.warn(`[CommandsStore] Failed to fetch config for command ${u.name}:`,m)}return u}));return JSON.stringify(t)!==JSON.stringify(d)?s({commands:d,isLoading:!1}):s({isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load commands:",n),s({commands:t,isLoading:!1}),!1},createCommand:async t=>{Vs("Creating command configuration…");let n=!1;try{console.log("[CommandsStore] Creating command:",t.name);const o={template:t.template||""};t.description&&(o.description=t.description),t.agent&&(o.agent=t.agent),t.model&&(o.model=t.model),t.subtask!==void 0&&(o.subtask=t.subtask),t.scope&&(o.scope=t.scope),console.log("[CommandsStore] Command config to save:",o);const a=mo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/commands/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create command";throw new Error(f)}if(console.log("[CommandsStore] Command created successfully"),d?.requiresReload??!0)return n=!0,await _a({message:d?.message,delayMs:d?.reloadDelayMs}),!0;const m=await r().loadCommands();return m&&sr("commands",{source:Hn}),m}catch(o){return console.error("[CommandsStore] Failed to create command:",o),!1}finally{n||Ds()}},updateCommand:async(t,n)=>{Vs("Updating command configuration…");let o=!1;try{console.log("[CommandsStore] Updating command:",t),console.log("[CommandsStore] Config received:",n);const a={};n.description!==void 0&&(a.description=n.description),n.agent!==void 0&&(a.agent=n.agent),n.model!==void 0&&(a.model=n.model),n.template!==void 0&&(a.template=n.template),n.subtask!==void 0&&(a.subtask=n.subtask),console.log("[CommandsStore] Command config to update:",a);const i=mo(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/commands/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update command";throw new Error(p)}if(console.log("[CommandsStore] Command updated successfully"),u?.requiresReload??!0)return o=!0,await _a({message:u?.message,delayMs:u?.reloadDelayMs}),!0;const f=await r().loadCommands();return f&&sr("commands",{source:Hn}),f}catch(a){return console.error("[CommandsStore] Failed to update command:",a),!1}finally{o||Ds()}},deleteCommand:async t=>{Vs("Deleting command configuration…");let n=!1;try{const o=mo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/commands/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete command";throw new Error(m)}if(console.log("[CommandsStore] Command deleted successfully"),l?.requiresReload??!0)return n=!0,await _a({message:l?.message,delayMs:l?.reloadDelayMs}),!0;const u=await r().loadCommands();return u&&sr("commands",{source:Hn}),r().selectedCommandName===t&&s({selectedCommandName:null}),u}catch(o){return console.error("Failed to delete command:",o),!1}finally{n||Ds()}},getCommandByName:t=>{const{commands:n}=r();return n.find(o=>o.name===t)}}),{name:"commands-store",storage:Es(()=>ds()),partialize:s=>({selectedCommandName:s.selectedCommandName})}),{name:"commands-store"}));typeof window<"u"&&(window.__zustand_commands_store__=Rr);async function Gg(s){const r=typeof s=="number"&&s>0?Math.min(s,Ql):0;r>0&&await Ei(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Wg;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await je.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=Xl&&a<1200?Ql:Math.min(Hg+Math.max(0,n-Xl)*Ug,Vg);await Ei(i)}throw o||new Error("OpenCode did not become ready in time")}async function _a(s={}){const{message:r,delayMs:t}=s;try{gr(r||"Refreshing commands…")}catch{}try{await Gg(t),gr("Refreshing commands…"),await Rr.getState().loadCommands(),sr("commands",{source:Hn})}catch(n){console.error("[CommandsStore] Failed to refresh configuration after OpenCode restart:",n),gr("OpenCode refresh failed. Please retry refreshing configuration manually."),await Ei(1500)}finally{Ds()}}let Jl=null;Jl||(Jl=ga(s=>{if(s.source!==Hn&&Zn(s,"commands")){const{loadCommands:r}=Rr.getState();r()}}));const Sr=()=>{const s=je.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},Oo="useSkillsStore",Hs=zt()(Yt(As((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=Sr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills${i}`);if(!l.ok)throw new Error(`Failed to list skills: ${l.status}`);const m=((await l.json()).skills||[]).map(f=>({name:f.name,path:f.path,scope:f.scope??"user",source:f.source??"opencode",description:f.sources?.md?.description||""}));return s({skills:m,isLoading:!1}),!0}catch(a){n=a;const i=200*(o+1);await new Promise(l=>setTimeout(l,i))}return console.error("Failed to load skills:",n),s({skills:t,isLoading:!1}),!1},getSkillDetail:async t=>{try{const n=Sr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`);return a.ok?await a.json():null}catch{return null}},createSkill:async t=>{Vs("Creating skill...");try{const n={name:t.name,description:t.description};t.instructions&&(n.instructions=t.instructions),t.scope&&(n.scope=t.scope),t.supportingFiles&&(n.supportingFiles=t.supportingFiles);const o=Sr(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t.name)}${a}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),l=await i.json().catch(()=>null);if(!i.ok){const u=l?.error||"Failed to create skill";throw new Error(u)}const d=await r().loadSkills();return d&&sr("skills",{source:Oo}),d}catch{return!1}finally{Ds()}},updateSkill:async(t,n)=>{Vs("Updating skill...");try{const o={};n.description!==void 0&&(o.description=n.description),n.instructions!==void 0&&(o.instructions=n.instructions),n.supportingFiles!==void 0&&(o.supportingFiles=n.supportingFiles);const a=Sr(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/skills/${encodeURIComponent(t)}${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const m=d?.error||"Failed to update skill";throw new Error(m)}const u=await r().loadSkills();return u&&sr("skills",{source:Oo}),u}catch{return!1}finally{Ds()}},deleteSkill:async t=>{Vs("Deleting skill...");try{const n=Sr(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/${encodeURIComponent(t)}${o}`,{method:"DELETE"}),i=await a.json().catch(()=>null);if(!a.ok){const d=i?.error||"Failed to delete skill";throw new Error(d)}const l=await r().loadSkills();return l&&sr("skills",{source:Oo}),r().selectedSkillName===t&&s({selectedSkillName:null}),l}catch{return!1}finally{Ds()}},getSkillByName:t=>{const{skills:n}=r();return n.find(o=>o.name===t)},readSupportingFile:async(t,n)=>{try{const o=Sr(),a=o?`&directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}?${a.slice(1)}`);return i.ok?(await i.json()).content??null:null}catch{return null}},writeSupportingFile:async(t,n,o)=>{try{const a=Sr(),i=a?`?directory=${encodeURIComponent(a)}`:"";return(await fetch(`/api/config/skills/${encodeURIComponent(t)}/files/${encodeURIComponent(n)}${i}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({content:o})})).ok}catch{return!1}},deleteSupportingFile:async(t,n)=>{try{const o=Sr(),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:Es(()=>ds()),partialize:s=>({selectedSkillName:s.selectedSkillName})}),{name:"skills-store"}));typeof window<"u"&&(window.__zustand_skills_store__=Hs);let Zl=null;Zl||(Zl=ga(s=>{if(s.source!==Oo&&Zn(s,"skills")){const{loadSkills:r}=Hs.getState();r()}}));const Oa=()=>{const s=je.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},ao=zt()(Yt((s,r)=>({sources:[],itemsBySource:{},selectedSourceId:null,isLoadingCatalog:!1,isScanning:!1,isInstalling:!1,lastCatalogError:null,lastScanError:null,lastInstallError:null,scanResults:null,setSelectedSource:t=>s({selectedSourceId:t}),loadCatalog:async t=>{s({isLoadingCatalog:!0,lastCatalogError:null});const n={sources:r().sources,itemsBySource:r().itemsBySource};let o=null;try{for(let a=0;a<3;a++)try{const i=Oa(),l=t?.refresh?"&refresh=true":"",d=i?`?directory=${encodeURIComponent(i)}${l}`:l?"?refresh=true":"",u=await fetch(`/api/config/skills/catalog${d}`,{method:"GET",headers:{Accept:"application/json"}}),m=await u.json().catch(()=>null);if(!u.ok||!m?.ok){o=m?.error||{kind:"unknown",message:`Failed to load catalog (${u.status})`};const h=200*(a+1);await new Promise(j=>setTimeout(j,h));continue}const f=m.sources||[],p=m.itemsBySource||{},g=r().selectedSourceId,w=g&&f.some(h=>h.id===g)?g:f[0]?.id??null;return s({sources:f,itemsBySource:p,selectedSourceId:w}),!0}catch(i){o={kind:"unknown",message:i instanceof Error?i.message:String(i)};const l=200*(a+1);await new Promise(d=>setTimeout(d,l))}return s({sources:n.sources,itemsBySource:n.itemsBySource,lastCatalogError:o||{kind:"unknown",message:"Failed to load catalog"}}),!1}finally{s({isLoadingCatalog:!1})}},scanRepo:async t=>{s({isScanning:!0,lastScanError:null,scanResults:null});try{const n=Oa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/scan${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!a.ok||!i){const l=i?.error||{kind:"unknown",message:"Failed to scan repository"};return s({lastScanError:l}),{ok:!1,error:l}}return i.ok?(s({scanResults:i.items||[]}),i):(s({lastScanError:i.error||{kind:"unknown",message:"Failed to scan repository"}}),i)}finally{s({isScanning:!1})}},installSkills:async t=>{s({isInstalling:!0,lastInstallError:null});try{const n=Oa(),o=n?`?directory=${encodeURIComponent(n)}`:"",a=await fetch(`/api/config/skills/install${o}`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(t)}),i=await a.json().catch(()=>null);if(!i){const l={kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}if(!a.ok||!i.ok){const l=i.error||{kind:"unknown",message:"Failed to install skills"};return s({lastInstallError:l}),{ok:!1,error:l}}return Hs.getState().loadSkills(),i}catch(n){const o={kind:"unknown",message:n instanceof Error?n.message:String(n)};return s({lastInstallError:o}),{ok:!1,error:o}}finally{s({isInstalling:!1})}}}),{name:"skills-catalog-store"})),qg=()=>{const s=je.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},fo=()=>{try{const r=Ft.getState().getActiveProject?.();if(r?.path?.trim())return r.path.trim();const t=je.getDirectory();if(t?.trim())return t.trim()}catch(s){console.warn("[AgentsStore] Error resolving config directory:",s)}return null},Hr=s=>{const r=s;return r.native===!0||r.builtIn===!0},Lu=s=>{const r=s;return r.hidden===!0||r.options?.hidden===!0},Bu=s=>s.filter(r=>!Lu(r)),$o="useAgentsStore",Xo=s=>new Promise(r=>setTimeout(r,s)),Kg=2e4,ec=300,tc=4,Yg=800,Qg=200,Xg=2e3,_r=zt()(Yt(As((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=fo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await je.withDirectory(o,()=>je.listAgents()),l=await Promise.all(i.map(async d=>{try{const u=await fetch(`/api/config/agents/${encodeURIComponent(d.name)}${a}`,{headers:{"Cache-Control":"no-cache",...o?{"x-opencode-directory":o}:{}}});if(u.ok){const m=await u.json();let f=m.scope;if(!f&&m.sources){const p=m.sources;f=(p.md?.exists?p.md.scope:void 0)??(p.json?.exists?p.json.scope:void 0)??p.md?.scope??p.json?.scope}return f==="project"||f==="user"?{...d,scope:f}:{...d,scope:void 0}}}catch(u){console.warn(`[AgentsStore] Failed to fetch config for agent ${d.name}:`,u)}return d}));return JSON.stringify(t)!==JSON.stringify(l)?s({agents:l,isLoading:!1}):s({isLoading:!1}),!0}catch{}return s({isLoading:!1}),!1},createAgent:async t=>{Vs("Creating agent configuration…");let n=!1;try{console.log("[AgentsStore] Creating agent:",t.name);const o={mode:t.mode||"subagent"};t.description&&(o.description=t.description),t.model&&(o.model=t.model),t.temperature!==void 0&&(o.temperature=t.temperature),t.top_p!==void 0&&(o.top_p=t.top_p),t.prompt&&(o.prompt=t.prompt),t.permission&&(o.permission=t.permission),t.disable!==void 0&&(o.disable=t.disable),t.scope&&(o.scope=t.scope),console.log("[AgentsStore] Agent config to save:",o);const a=fo(),i=a?`?directory=${encodeURIComponent(a)}`:"",l=await fetch(`/api/config/agents/${encodeURIComponent(t.name)}${i}`,{method:"POST",headers:{"Content-Type":"application/json",...a?{"x-opencode-directory":a}:{}},body:JSON.stringify(o)}),d=await l.json().catch(()=>null);if(!l.ok){const f=d?.error||"Failed to create agent";throw new Error(f)}if(d?.requiresReload??!0)return n=!0,await Un({message:d?.message,delayMs:d?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const m=await r().loadAgents();return m&&sr("agents",{source:$o}),m}catch(o){return console.error("Failed to create agent:",o),!1}finally{n||Ds()}},updateAgent:async(t,n)=>{Vs("Updating agent configuration…");let o=!1;try{const a={};n.mode!==void 0&&(a.mode=n.mode),n.description!==void 0&&(a.description=n.description),n.model!==void 0&&(a.model=n.model),n.temperature!==void 0&&(a.temperature=n.temperature),n.top_p!==void 0&&(a.top_p=n.top_p),n.prompt!==void 0&&(a.prompt=n.prompt),n.permission!==void 0&&(a.permission=n.permission),n.disable!==void 0&&(a.disable=n.disable);const i=fo(),l=i?`?directory=${encodeURIComponent(i)}`:"",d=await fetch(`/api/config/agents/${encodeURIComponent(t)}${l}`,{method:"PATCH",headers:{"Content-Type":"application/json",...i?{"x-opencode-directory":i}:{}},body:JSON.stringify(a)}),u=await d.json().catch(()=>null);if(!d.ok){const p=u?.error||"Failed to update agent";throw new Error(p)}if(u?.requiresReload??!0)return o=!0,await Un({message:u?.message,delayMs:u?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const f=await r().loadAgents();return f&&sr("agents",{source:$o}),f}catch(a){throw console.error("Failed to update agent:",a),a}finally{o||Ds()}},deleteAgent:async t=>{Vs("Deleting agent configuration…");let n=!1;try{const o=fo(),a=o?`?directory=${encodeURIComponent(o)}`:"",i=await fetch(`/api/config/agents/${encodeURIComponent(t)}${a}`,{method:"DELETE",headers:o?{"x-opencode-directory":o}:void 0}),l=await i.json().catch(()=>null);if(!i.ok){const m=l?.error||"Failed to delete agent";throw new Error(m)}if(l?.requiresReload??!0)return n=!0,await Un({message:l?.message,delayMs:l?.reloadDelayMs,scopes:["agents"],mode:"active"}),!0;const u=await r().loadAgents();return u&&sr("agents",{source:$o}),r().selectedAgentName===t&&s({selectedAgentName:null}),u}catch{return!1}finally{n||Ds()}},getAgentByName:t=>{const{agents:n}=r();return n.find(o=>o.name===t)},getVisibleAgents:()=>{const{agents:t}=r();return Bu(t)}}),{name:"agents-store",storage:Es(()=>ds()),partialize:s=>({selectedAgentName:s.selectedAgentName})}),{name:"agents-store"}));typeof window<"u"&&(window.__zustand_agents_store__=_r);async function Jg(s){const r=typeof s=="number"&&s>0?Math.min(s,ec):0;r>0&&await Xo(r);const t=Date.now();let n=0,o=null;for(;Date.now()-t<Kg;){n+=1,gr(`Waiting for OpenCode… (attempt ${n})`);try{if(await je.checkHealth())return;o=new Error("OpenCode health check reported not ready")}catch(l){o=l}const a=Date.now()-t,i=n<=tc&&a<1200?ec:Math.min(Yg+Math.max(0,n-tc)*Qg,Xg);await Xo(i)}throw o||new Error("OpenCode did not become ready in time")}const Zg=s=>{if(!s||s.length===0)return["all"];const r=Array.from(new Set(s));return r.includes("all")?["all"]:r};async function ex(s={}){const{message:r,delayMs:t}=s,n=Zg(s.scopes),o=s.mode??(n.includes("all")?"projects":"active");try{gr(r||"Refreshing configuration…")}catch{}try{await Jg(t);const a=rt.getState(),i=_r.getState(),l=Rr.getState(),d=Hs.getState(),u=ao.getState(),m=n.includes("all")||n.includes("providers"),f=n.includes("all")||n.includes("agents"),p=n.includes("all")||n.includes("agents"),g=n.includes("all")||n.includes("commands"),w=n.includes("all")||n.includes("skills"),h=qg(),j=o==="projects"?Ft.getState().projects:[],x=Array.from(new Set([...h?[h]:[],...j.map(N=>N.path).filter(Boolean)]));n.includes("all")&&o==="projects"&&rt.setState({directoryScoped:{}});const y=[];for(const N of x)m&&y.push(a.loadProviders({directory:N}).then(()=>{})),f&&y.push(a.loadAgents({directory:N}).then(()=>{}));const b=[];p&&b.push(i.loadAgents().then(()=>{})),g&&b.push(l.loadCommands().then(()=>{})),w&&(b.push(d.loadSkills().then(()=>{})),b.push(u.loadCatalog().then(()=>{}))),gr("Refreshing configuration…"),await Promise.all([...y,...b])}catch{gr("OpenCode refresh failed. Please retry."),await Xo(1500)}finally{Ds()}}async function Un(s){await ex(s)}async function Vn(s){Vs(s?.message||"Reloading OpenCode configuration…");try{const r=await fetch("/api/config/reload",{method:"POST",headers:{"Content-Type":"application/json"}}),t=await r.json().catch(()=>null);if(!r.ok){const o=t?.error||"Failed to reload configuration";throw new Error(o)}const n={...s,scopes:s?.scopes??["all"],mode:s?.mode??"projects"};t?.requiresReload?await Un({...n,message:t.message,delayMs:t.reloadDelayMs}):await Un(n)}catch(r){throw console.error("[reloadOpenCodeConfiguration] Failed:",r),gr("Failed to reload configuration. Please try again."),await Xo(2e3),Ds(),r}}let sc=null;sc||(sc=ga(s=>{if(s.source!==$o&&Zn(s,"agents")){const{loadAgents:r}=_r.getState();r()}}));const tx="https://models.dev/api.json",sx="/api/openchamber/models-metadata",rc="opencode",nc="big-pickle",rx=async()=>{try{if(Zt()){const l=await sn();return{defaultModel:l?.defaultModel,defaultVariant:l?.defaultVariant,defaultAgent:l?.defaultAgent,autoCreateWorktree:l?.autoCreateWorktree,commitMessageModel:l?.commitMessageModel}}const s=vr()?.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():"",i=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:i.length>0?i:void 0}}catch{return{}}},po=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]}},nx=s=>s?.toLowerCase?.()??"",ox=s=>s==="primary"||s==="all"||s===void 0||s===null,eo=s=>typeof s=="object"&&s!==null,Jo=s=>Array.isArray(s)&&s.every(r=>typeof r=="string"),ax=s=>{if(!eo(s))return!1;const r=s;if(r.modalities){const{input:t,output:n}=r.modalities;if(t&&!Jo(t)||n&&!Jo(n))return!1}return!0},ix=s=>{if(!eo(s))return!1;const r=s;return r.models===void 0||eo(r.models)},zu=(s,r)=>{const t=nx(s);return!t||!r?"":`${t}/${r}`},lx=s=>{const r=new Map;if(!eo(s))return r;for(const[t,n]of Object.entries(s)){if(!ix(n))continue;const o=typeof n.id=="string"&&n.id.length>0?n.id:t,a=n.models;if(!(!a||!eo(a)))for(const[i,l]of Object.entries(a)){if(!ax(l))continue;const d=typeof i=="string"&&i.length>0?i:l.id;if(!d||typeof d!="string"||d.length===0)continue;const u={id:typeof l.id=="string"&&l.id.length>0?l.id:d,providerId:o,name:typeof l.name=="string"?l.name:void 0,tool_call:typeof l.tool_call=="boolean"?l.tool_call:void 0,reasoning:typeof l.reasoning=="boolean"?l.reasoning:void 0,temperature:typeof l.temperature=="boolean"?l.temperature:void 0,attachment:typeof l.attachment=="boolean"?l.attachment:void 0,modalities:l.modalities?{input:Jo(l.modalities.input)?l.modalities.input:void 0,output:Jo(l.modalities.output)?l.modalities.output:void 0}:void 0,cost:l.cost,limit:l.limit,knowledge:typeof l.knowledge=="string"?l.knowledge:void 0,release_date:typeof l.release_date=="string"?l.release_date:void 0,last_updated:typeof l.last_updated=="string"?l.last_updated:void 0},m=zu(o,d);m&&r.set(m,u)}}return r},cx=async()=>{if(typeof fetch!="function")return new Map;const s=[sx,tx];for(const r of s){const t=typeof AbortController<"u"?new AbortController:void 0,n=t?setTimeout(()=>t.abort(),8e3):void 0;try{const o=/^https?:\/\//i.test(r),a={signal:t?.signal,headers:{Accept:"application/json"},cache:"no-store"};o?a.mode="cors":a.credentials="same-origin";const i=await fetch(r,a);if(!i.ok)throw new Error(`Metadata request to ${r} returned status ${i.status}`);const l=await i.json();return lx(l)}catch(o){o?.name==="AbortError"?console.warn(`Model metadata request aborted (${r})`):console.warn(`Failed to fetch model metadata from ${r}:`,o)}finally{n&&clearTimeout(n)}}return new Map};let $a=null;const dx=(s,r)=>{s().size>0||$a||($a=cx().then(n=>(n.size>0&&r(n),n)).catch(()=>new Map).finally(()=>{$a=null}))},ux=s=>new Promise(r=>setTimeout(r,s)),il="__global__",wn=s=>{const r=typeof s=="string"?s.trim():"";return r.length>0?r:il},cn=s=>s===il?null:s,mx=()=>{if(typeof window>"u")return il;const s=je.getDirectory()??mt.getState().currentDirectory;return wn(s)},rt=zt()(Yt(As((s,r)=>({activeDirectoryKey:mx(),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=wn(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:cn(n)}),await r().loadAgents({directory:cn(n)}))},loadProviders:async t=>{const n=wn(t?.directory??cn(r().activeDirectoryKey)),o=r().directoryScoped[n],a=o?.providers??(r().activeDirectoryKey===n?r().providers:[]),i=o?.defaultProviders??(r().activeDirectoryKey===n?r().defaultProviders:{});let l=null;for(let d=0;d<3;d++)try{dx(()=>r().modelsMetadata,g=>s({modelsMetadata:g}));const u=await je.withDirectory(cn(n),()=>je.getProviders()),m=Array.isArray(u?.providers)?u.providers:[],f=u?.default||{},p=m.map(g=>{const w=g.models??{},h=Object.keys(w).map(j=>w[j]);return{...g,models:h}});s(g=>{const h={...g.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:p,defaultProviders:f},j={directoryScoped:{...g.directoryScoped,[n]:h}};if(g.activeDirectoryKey===n&&(j.providers=p,j.defaultProviders=f,!g.currentProviderId&&!g.currentModelId&&g.settingsDefaultModel)){const x=po(g.settingsDefaultModel);if(x){const y=p.find(b=>b.id===x.providerId);if(y?.models.some(b=>b.id===x.modelId)){const b=y.models.find(v=>v.id===x.modelId),N=g.settingsDefaultVariant&&b?.variants?.[g.settingsDefaultVariant]?g.settingsDefaultVariant:void 0;j.currentProviderId=x.providerId,j.currentModelId=x.modelId,j.currentVariant=N,j.selectedProviderId=x.providerId,h.currentProviderId=x.providerId,h.currentModelId=x.modelId,h.currentVariant=N,h.selectedProviderId=x.providerId}}}return j});return}catch(u){l=u;const m=200*(d+1);await new Promise(f=>setTimeout(f,m))}console.error("Failed to load providers:",l),s(d=>{const m={...d.directoryScoped[n]??{providers:[],agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:a,defaultProviders:i},f={directoryScoped:{...d.directoryScoped,[n]:m}};if(d.activeDirectoryKey===n&&(f.providers=a,f.defaultProviders=i,!d.currentProviderId&&!d.currentModelId&&d.settingsDefaultModel)){const p=po(d.settingsDefaultModel);if(p){const g=a.find(w=>w.id===p.providerId);if(g?.models.some(w=>w.id===p.modelId)){const w=g.models.find(j=>j.id===p.modelId),h=d.settingsDefaultVariant&&w?.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(l=>l.id===t);if(!o)return;const i=o.models[0]?.id||"";s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentVariant:l.currentVariant,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentProviderId:t,currentModelId:i,selectedProviderId:t};return{currentProviderId:t,currentModelId:i,selectedProviderId:t,directoryScoped:{...l.directoryScoped,[d]:m}}})},setModel:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentModelId:t};return{currentModelId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},setCurrentVariant:t=>{s(n=>{if(n.currentVariant===t)return n;const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentVariant:n.currentVariant,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},currentVariant:t};return{currentVariant:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},getCurrentModelVariants:()=>{const n=r().getCurrentModel()?.variants;return n?Object.keys(n):[]},cycleCurrentVariant:()=>{const t=r().getCurrentModelVariants();if(t.length===0)return;const n=r().currentVariant;if(!n){r().setCurrentVariant(t[0]);return}const o=t.indexOf(n);if(o===-1||o===t.length-1){r().setCurrentVariant(void 0);return}r().setCurrentVariant(t[o+1])},setSelectedProvider:t=>{s(n=>{const o=n.activeDirectoryKey,i={...n.directoryScoped[o]??{providers:n.providers,agents:n.agents,currentProviderId:n.currentProviderId,currentModelId:n.currentModelId,currentAgentName:n.currentAgentName,selectedProviderId:n.selectedProviderId,agentModelSelections:n.agentModelSelections,defaultProviders:n.defaultProviders},selectedProviderId:t};return{selectedProviderId:t,directoryScoped:{...n.directoryScoped,[o]:i}}})},saveAgentModelSelection:(t,n,o)=>{s(a=>{const i=a.activeDirectoryKey,l={...a.agentModelSelections,[t]:{providerId:n,modelId:o}},u={...a.directoryScoped[i]??{providers:a.providers,agents:a.agents,currentProviderId:a.currentProviderId,currentModelId:a.currentModelId,currentAgentName:a.currentAgentName,selectedProviderId:a.selectedProviderId,agentModelSelections:a.agentModelSelections,defaultProviders:a.defaultProviders},agentModelSelections:l};return{agentModelSelections:l,directoryScoped:{...a.directoryScoped,[i]:u}}})},getAgentModelSelection:t=>{const{agentModelSelections:n}=r();return n[t]||null},loadAgents:async t=>{const n=wn(t?.directory??cn(r().activeDirectoryKey)),a=r().directoryScoped[n]?.agents??(r().activeDirectoryKey===n?r().agents:[]);let i=null;for(let l=0;l<3;l++)try{const[d,u]=await Promise.all([je.withDirectory(cn(n),()=>je.listAgents()),rx()]),m=Array.isArray(d)?d:[],f=r().activeDirectoryKey===n?r().providers:r().directoryScoped[n]?.providers??[];if(s(v=>{const D={...v.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:{...v.directoryScoped,[n]:D}};return v.activeDirectoryKey===n&&(C.agents=m),C}),m.length===0)return s(v=>{const D={...v.directoryScoped[n]??{providers:f,agents:[],currentProviderId:"",currentModelId:"",currentVariant:void 0,currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:f,agents:[],currentAgentName:void 0},C={directoryScoped:{...v.directoryScoped,[n]:D}};return v.activeDirectoryKey===n&&(C.currentAgentName=void 0),C}),!0;const p=(v,k)=>{const D=f.find(C=>C.id===v);return D?D.models.some(C=>C.id===k):!1},g=m.filter(v=>ox(v.mode));let j=g.find(v=>v.name==="build")||g[0]||m[0];const x={};if(u.defaultAgent){const v=m.find(k=>k.name===u.defaultAgent);v?j=v:x.defaultAgent=""}let y,b,N;if(u.defaultModel){const v=po(u.defaultModel);if(v&&p(v.providerId,v.modelId)){if(y=v.providerId,b=v.modelId,u.defaultVariant){const C=f.find(M=>M.id===v.providerId)?.models.find(M=>M.id===v.modelId)?.variants;C&&Object.prototype.hasOwnProperty.call(C,u.defaultVariant)?N=u.defaultVariant:x.defaultVariant=""}}else x.defaultModel=""}if(!y&&j?.model?.providerID&&j?.model?.modelID&&p(j.model.providerID,j.model.modelID)&&(y=j.model.providerID,b=j.model.modelID),!y)if(p(rc,nc))y=rc,b=nc;else{const v=f[0];v&&v.models[0]&&(y=v.id,b=v.models[0].id)}return s(v=>{const k=v.directoryScoped[n]??{providers:f,agents:m,currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},D={...k,providers:f,agents:m,currentAgentName:j.name,currentProviderId:y??k.currentProviderId,currentModelId:b??k.currentModelId,currentVariant:N},C={directoryScoped:{...v.directoryScoped,[n]:D}};return v.activeDirectoryKey===n&&(C.currentAgentName=j.name,y&&b&&(C.currentProviderId=y,C.currentModelId=b,C.currentVariant=N)),C}),Object.keys(x).length>0&&(s({settingsDefaultModel:x.defaultModel!==void 0?void 0:r().settingsDefaultModel,settingsDefaultVariant:x.defaultVariant!==void 0?void 0:r().settingsDefaultVariant,settingsDefaultAgent:x.defaultAgent!==void 0?void 0:r().settingsDefaultAgent}),rs(x).catch(()=>{})),!0}catch(d){i=d;const u=200*(l+1);await new Promise(m=>setTimeout(m,u))}return console.error("Failed to load agents:",i),s(l=>{const d=l.activeDirectoryKey===n?l.providers:l.directoryScoped[n]?.providers??[],m={...l.directoryScoped[n]??{providers:d,agents:[],currentProviderId:"",currentModelId:"",currentAgentName:void 0,selectedProviderId:"",agentModelSelections:{},defaultProviders:{}},providers:d,agents:a},f={directoryScoped:{...l.directoryScoped,[n]:m}};return l.activeDirectoryKey===n&&(f.agents=a),f}),!1},setAgent:t=>{const{agents:n,providers:o,settingsDefaultModel:a,settingsDefaultVariant:i}=r();if(s(l=>{const d=l.activeDirectoryKey,m={...l.directoryScoped[d]??{providers:l.providers,agents:l.agents,currentProviderId:l.currentProviderId,currentModelId:l.currentModelId,currentAgentName:l.currentAgentName,selectedProviderId:l.selectedProviderId,agentModelSelections:l.agentModelSelections,defaultProviders:l.defaultProviders},currentAgentName:t};return{currentAgentName:t,directoryScoped:{...l.directoryScoped,[d]:m}}}),t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const d=l.getState(),{currentSessionId:u,isOpenChamberCreatedSession:m,initializeNewOpenChamberSession:f,getAgentModelForSession:p}=d;u&&l.setState(g=>{const w=new Map(g.currentAgentContext);return w.set(u,t),{currentAgentContext:w}}),u&&m(u)&&(p(u,t)||f(u,n))}}if(t&&typeof window<"u"){const l=window.__zustand_session_store__;if(l){const{currentSessionId:u,getAgentModelForSession:m}=l.getState();if(u&&m(u,t))return}if(a){const u=po(a);if(u&&o.find(f=>f.id===u.providerId)?.models.some(f=>f.id===u.modelId)){s(f=>{const p=f.activeDirectoryKey,g=f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentVariant:f.currentVariant,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders};let w;if(i){const y=o.find(b=>b.id===u.providerId)?.models.find(b=>b.id===u.modelId)?.variants;y&&Object.prototype.hasOwnProperty.call(y,i)&&(w=i)}const h={...g,currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:w};return{currentProviderId:u.providerId,currentModelId:u.modelId,currentVariant:w,directoryScoped:{...f.directoryScoped,[p]:h}}});return}}const d=n.find(u=>u.name===t);if(d?.model?.providerID&&d?.model?.modelID){const u=o.find(m=>m.id===d.model.providerID);u&&u.models.find(f=>f.id===d.model.modelID)&&s(f=>{const p=f.activeDirectoryKey,w={...f.directoryScoped[p]??{providers:f.providers,agents:f.agents,currentProviderId:f.currentProviderId,currentModelId:f.currentModelId,currentAgentName:f.currentAgentName,selectedProviderId:f.selectedProviderId,agentModelSelections:f.agentModelSelections,defaultProviders:f.defaultProviders},currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID};return{currentProviderId:d.model.providerID,currentModelId:d.model.modelID,selectedProviderId:d.model.providerID,directoryScoped:{...f.directoryScoped,[p]:w}}})}}},setSettingsDefaultModel:t=>{s({settingsDefaultModel:t})},setSettingsDefaultVariant:t=>{s({settingsDefaultVariant:t})},setSettingsDefaultAgent:t=>{s({settingsDefaultAgent:t})},setSettingsAutoCreateWorktree:t=>{s({settingsAutoCreateWorktree:t})},setSettingsCommitMessageModel:t=>{s({settingsCommitMessageModel:t})},checkConnection:async()=>{let n=0,o=null;for(;n<5;)try{const a=await je.checkHealth();return s({isConnected:a}),a}catch(a){o=a,n+=1;const i=400*n;await ux(i)}return o&&console.warn("[ConfigStore] Failed to reach OpenCode after retrying:",o),s({isConnected:!1}),!1},initializeApp:async()=>{try{const t=Qt();t&&console.log("Starting app initialization...");const n=await r().checkConnection();if(t&&console.log("Connection check result:",n),!n){t&&console.log("Server not connected"),s({isConnected:!1});return}t&&console.log("Initializing app..."),await je.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=zu(t,n);if(!o)return;const{modelsMetadata:a}=r();return a.get(o)},getVisibleAgents:()=>{const{agents:t}=r();return Bu(t)}}),{name:"config-store",storage:Es(()=>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__=rt);let oc=null;oc||(oc=ga(async s=>{const r=[];if(Zn(s,"agents")){const{loadAgents:t}=rt.getState();r.push(t().then(()=>{}))}if(Zn(s,"providers")){const{loadProviders:t}=rt.getState();r.push(t())}r.length>0&&await Promise.all(r)}));let ac=null;typeof window<"u"&&!ac&&(ac=mt.subscribe((s,r)=>{const t=wn(s.currentDirectory),n=wn(r.currentDirectory);t!==n&&rt.getState().activateDirectory(s.currentDirectory)}));const us={MAX_SESSIONS:3,VIEWPORT_MESSAGES:120,STREAMING_BUFFER:1/0,BACKGROUND_STREAMING_BUFFER:120,ZOMBIE_TIMEOUT:600*1e3},fx=180,xs=()=>typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.git?window.__OPENCHAMBER_RUNTIME_APIS__.git:null;async function rn(s){const r=xs();return r?r.checkIsGitRepository(s):Rh(s)}async function px(s){const r=xs();return r?r.getGitStatus(s):Oh(s)}async function ll(s){const r=xs();return r?r.getGitBranches(s):Yh(s)}async function hx(s,r){const t=xs();return t?t.deleteGitBranch(s,r):Lh(s,r)}async function gx(s,r){const t=xs();return t?t.deleteRemoteBranch(s,r):Bh(s,r)}async function xx(s){const r=xs();return r?r.listGitWorktrees(s):_h(s)}async function yx(s,r){const t=xs();return t?t.addGitWorktree(s,r):zh(s,r)}async function Wu(s,r){const t=xs();return t?t.removeGitWorktree(s,r):$h(s,r)}async function bx(s){const r=xs();return r?r.ensureOpenChamberIgnored(s):Kh(s)}async function wx(){const s=xs();return s?s.getGitIdentities():qh()}async function vx(s){const r=xs();return r?r.createGitIdentity(s):Uh(s)}async function jx(s,r){const t=xs();return t?t.updateGitIdentity(s,r):Hh(s,r)}async function Sx(s){const r=xs();return r?r.deleteGitIdentity(s):Wh(s)}async function kx(){const s=xs();return s?.discoverGitCredentials?s.discoverGitCredentials():Vh()}async function Nx(){const s=xs();return s?.getGlobalGitIdentity?s.getGlobalGitIdentity():Gh()}const Cx="openchamber.json",Hu=".openchamber";function Uu(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const Mx=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Ii=(s,r)=>{const t=Mx(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Vu=s=>Ii(Ii(s,Hu),Cx);async function Gu(s){const r=Vu(s);try{const t=Uu();if(t?.readFile)try{const i=await t.readFile(r);if(!i.content.trim())return null;const l=JSON.parse(i.content);return!l||typeof l!="object"?null:l}catch{return null}const n=await fetch(`${Ku()}/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 Dx(s,r){const t=Vu(s),n=Ii(s,Hu);try{await je.createDirectory(n);const o=Uu();if(o?.writeFile)try{return(await o.writeFile(t,JSON.stringify(r,null,2))).success}catch(i){return console.error("Failed to write openchamber config via runtime API:",i),!1}return(await fetch(`${Ku()}/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 Ax(s,r){const n={...await Gu(s)||{},...r};return Dx(s,n)}async function io(s){return(await Gu(s))?.["setup-worktree"]??[]}async function qu(s,r){const t=r.filter(n=>n.trim().length>0);return Ax(s,{"setup-worktree":t})}function Ex(s,r){return s.replace(/\$ROOT_WORKTREE_PATH/g,r.rootWorktreePath).replace(/\$\{ROOT_WORKTREE_PATH\}/g,r.rootWorktreePath)}function Ku(){const s="/api";return s.startsWith("/"),s}const Ix=".openchamber",ic="/api";function Px(){if(typeof window>"u")return null;const s=window.__OPENCHAMBER_RUNTIME_APIS__;return s?.files?s.files:null}const wr=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},lc=(s,r)=>{const t=wr(s),n=r.replace(/\\/g,"/").replace(/^\/+/,"").replace(/\/+$/,"");return!t||t==="/"?`/${n}`:`${t}/${n}`},Yu=s=>s?s.startsWith("refs/heads/")?s.substring(11):s.startsWith("heads/")?s.substring(6):s.startsWith("refs/")?s.substring(5):s:"",Tx=async s=>{try{await je.createDirectory(s)}catch(r){if(r instanceof Error&&/exist/i.test(r.message))return;throw r}};async function Fx(s,r){const t=wr(s),n=lc(t,Ix);return await Tx(n),lc(n,r)}async function Qu(s){const{projectDirectory:r,worktreeSlug:t,branch:n,createBranch:o,startPoint:a}=s,i=wr(r),l=await Fx(i,t),d={path:l,branch:n,createBranch:!!o,startPoint:a?.trim()||void 0};return await yx(i,d),{path:l,branch:n,label:Yu(n),projectDirectory:i,relativePath:l.startsWith(`${i}/`)?l.slice(i.length+1):l}}async function Rx(s){const{projectDirectory:r,path:t,force:n}=s,o=wr(r);await Wu(o,{path:t,force:n})}async function Xu(s){const{projectDirectory:r,path:t,branch:n,force:o,deleteRemote:a,remote:i}=s,l=wr(r),d=n.startsWith("refs/heads/")?n.substring(11):n;if(await Wu(l,{path:t,force:o}),d&&(await hx(l,{branch:d,force:!0}),a))try{await gx(l,{branch:d,remote:i})}catch(u){console.warn("Failed to delete remote branch during worktree archive:",u)}}async function Nn(s){const r=wr(s);return xx(r)}async function cl(s){const r=wr(s),t=await px(r);return{isDirty:!t.isClean,ahead:t.ahead,behind:t.behind,upstream:t.tracking}}function Cn(s,r){const t=wr(s),n=wr(r.worktree);return{path:n,branch:r.branch??"",label:Yu(r.branch??""),projectDirectory:t,relativePath:n.startsWith(`${t}/`)?n.slice(t.length+1):n}}async function Ju(s,r,t){const n=t??await io(r);if(n.length===0)return{success:!0,results:[]};const o=n.map(a=>Ex(a,{rootWorktreePath:r}));console.log("[worktreeService] Running setup commands:",{worktreePath:s,projectDirectory:r,commands:o});try{const a=Px();if(a?.execCommands){console.log("[worktreeService] Using runtime API for exec");try{const d=await a.execCommands(o,s);return console.log("[worktreeService] Runtime exec result:",d),d}catch(d){return console.error("[worktreeService] Runtime exec error:",d),{success:!1,results:o.map(u=>({command:u,success:!1,error:d instanceof Error?d.message:"Unknown error"}))}}}console.log("[worktreeService] Using web API for exec");const i=await fetch(`${ic}/fs/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({commands:o,cwd:s,background:!0})}),l=await i.json().catch(()=>null);if(i.status===202&&l&&typeof l.jobId=="string"){const d=l.jobId,u=800,m=Math.max(5*6e4,o.length*6e4),f=Date.now();for(;Date.now()-f<m;){await new Promise(h=>setTimeout(h,u));const p=await fetch(`${ic}/fs/exec/${d}`,{method:"GET"}),g=await p.json().catch(()=>null);if(!p.ok)return{success:!1,results:o.map(h=>({command:h,success:!1,error:g&&g.error||"Failed to poll exec job"}))};if(g?.status==="done"){const h=Array.isArray(g?.results)?g.results:[];return{success:g?.success===!0,results:h}}}return{success:!1,results:o.map(p=>({command:p,success:!1,error:"Setup commands timed out"}))}}if(!i.ok){const d=l&&l.error||"Request failed";return console.error("[worktreeService] Web exec failed:",l),{success:!1,results:o.map(u=>({command:u,success:!1,error:d}))}}return console.log("[worktreeService] Web exec result:",l),l}catch(a){return console.error("[worktreeService] Exec exception:",a),{success:!1,results:o.map(i=>({command:i,success:!1,error:a instanceof Error?a.message:"Unknown error"}))}}}const Zu=ds(),em="oc.sessionSelectionByDirectory",La=".openchamber",_x=()=>{try{const s=Zu.getItem(em);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 Lo=null;const dl=()=>(Lo||(Lo=_x()),Lo),tm=s=>{Lo=s;try{Zu.setItem(em,JSON.stringify(s))}catch{}},sm=s=>{if(!s)return null;const t=dl()[s];return typeof t=="string"?t:null},cr=(s,r)=>{if(!s)return;const t={...dl()};r?t[s]=r:delete t[s],tm(t)},Ox=(s,r)=>{if(!s)return;const t=sm(s);if(!t)return;if(!new Set(r).has(t)){const o={...dl()};delete o[s],tm(o)}},cc=async(s,r)=>{const t=s.status??await cl(s.path).catch(()=>{});await Xu({projectDirectory:s.projectDirectory,path:s.path,branch:s.branch,force:!!t?.isDirty,deleteRemote:!!r?.deleteRemoteBranch,remote:r?.remoteName})},jt=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},dc=()=>{if(typeof window>"u")return null;const s=window.__VSCODE_CONFIG__,r=typeof s?.workspaceFolder=="string"?s.workspaceFolder:null;return jt(r)},$x=()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,ho=(...s)=>{Qt()&&$x()&&console.log("[OpenChamber][VSCode][sessions]",...s)},kr=s=>{const r=new Map;return s.forEach(t=>{if(!t||typeof t.id!="string"||t.id.length===0)return;const n=r.get(t.id);if(!n){r.set(t.id,t);return}const o=n.time?.updated??0;(t.time?.updated??0)>o&&r.set(t.id,t)}),Array.from(r.values())},_s=s=>{const r=new Map;s.forEach(t=>{const n=jt(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,kr(n));return r},dn=(s,r)=>{const t=s.find(n=>n.id===r);return t?jt(t.directory??null):null},Lx=async(s,r,t)=>{const n=jt(r);if(!n||s.length===0)return null;const o=s.map(u=>({id:u.id,directory:jt(u.directory)})).filter(u=>!!u.directory);if(o.length===0)return null;let a;try{a=await Nn(n)}catch(u){return console.debug("Failed to hydrate worktree metadata from git worktree list:",u),null}if(!Array.isArray(a)||a.length===0){let u=!1;const m=new Map(t);return o.forEach(({id:f})=>{m.delete(f)&&(u=!0)}),u?m:null}const i=new Map;a.forEach(u=>{const m=Cn(n,u),f=jt(m.path)??m.path;f!==n&&i.set(f,m)});let l=!1;const d=new Map(t);return o.forEach(({id:u,directory:m})=>{const f=i.get(m);if(!f){d.delete(u)&&(l=!0);return}const p=d.get(u);(!p||p.path!==f.path||p.branch!==f.branch||p.label!==f.label)&&(d.set(u,f),l=!0)}),l?d:null},lt=zt()(Yt(As((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=mt.getState(),n=Ft.getState(),o=je.getApiClient(),a=dc(),i=!!a;ho("loadSessions:start",{workspace:a,currentDirectory:t.currentDirectory,clientDirectory:je.getDirectory(),projectsCount:n.projects.length,activeProjectId:n.activeProjectId});const l=new Map,d=async L=>{const Z=jt(L)??L,q=Z,$=l.get(q);if($)return $;try{const H=await o.path.get({directory:L}),K=jt(H.data?.directory??null)??Z;return l.set(q,K),K}catch{return l.set(q,Z),Z}},u=(L,Z,q)=>{const $=jt(Z);if(!$)return L;const U=q?.includeDescendants===!0?`${$}/`:null,K=q?.includeMissingDirectory===!0;return L.filter(se=>{const Y=jt(se.directory??null);return Y?!!(Y===$||U&&Y.startsWith(U)):K})},m=(L,Z,q)=>{const $=jt(Z);if(!$)return L;const H=jt(q??null);if(!H||H===$)return L.map(se=>jt(se.directory??null)?se:{...se,directory:$});const U=H==="/"?"/":`${H}/`,K=$==="/"?"/":`${$}/`;return L.map(se=>{const Y=jt(se.directory??null);if(!Y)return{...se,directory:$};if(Y===H)return{...se,directory:$};if(U!=="/"&&Y.startsWith(U)){const re=Y.slice(U.length);return{...se,directory:`${K}${re}`}}return se})},f=async L=>{const Z=jt(L);if(!Z)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(Z),$=async()=>{const Y=await o.session.list({directory:Z});return Array.isArray(Y.data)?Y.data:[]};let H=[],U=null,K=!1;try{H=await $()}catch(Y){console.debug("Failed to list sessions for directory:",Z,Y),U=Y,H=[]}if(H.length===0){K=!0;try{const Y=await o.session.list(void 0),re=Array.isArray(Y.data)?Y.data:[];H=u(re,q,{includeDescendants:i,includeMissingDirectory:!1})}catch(Y){throw console.debug("Failed to list sessions (global fallback):",Y),U||Y}}const se=u(H,q,{includeDescendants:i,includeMissingDirectory:!K});return ho("fetchSessionsForDirectory",{requestedDirectory:Z,canonicalDirectory:q,fetched:H.length,filtered:se.length}),m(se,Z,q)},p=jt(t.currentDirectory??je.getDirectory()??null),g=n.projects.find(L=>L.id===n.activeProjectId)??null,w=jt(g?.path??null),h=w??p??null,j=n.projects.length>0?n.projects:h?[{id:"legacy",path:h}]:[];if(j.length===0){s({sessions:[],sessionsByDirectory:new Map,currentSessionId:null,lastLoadedDirectory:null,isLoading:!1,worktreeMetadata:new Map,availableWorktrees:[],availableWorktreesByProject:new Map});return}const x=await Promise.all(j.map(async L=>{const Z=jt(L.path);if(!Z)return{projectId:L.id,projectPath:null,sessions:[],discoveredWorktrees:[],validPaths:new Set};const q=await rn(Z).catch(()=>!1),$=await f(Z||null);ho("projectSessions",{projectId:L.id,projectPath:Z,isGitRepo:q,parentSessions:$.length});const H=[];let U=[];const K=new Set;if(K.add(Z),q){const Y=`${Z}/${La}`;try{const re=new Set;(await je.listLocalDirectory(Z)).some(B=>B.isDirectory&&B.name===La)&&(await je.listLocalDirectory(Y)).filter(F=>F.isDirectory).forEach(F=>{const z=/^([A-Za-z]:)?\//.test(F.path)?F.path:`${Y}/${F.name}`,Q=jt(z)??z;re.add(Q)});const E=await Nn(Z);Array.isArray(E)&&(U=E.map(B=>Cn(Z,B)).filter(B=>B.path.includes(`/${La}/`)),U.forEach(B=>re.add(B.path))),re.forEach(B=>{const F=jt(B)??B;K.add(F)}),re.size>0&&(await Promise.allSettled(Array.from(re).map(F=>f(F)))).forEach(F=>{F.status==="fulfilled"&&Array.isArray(F.value)&&H.push(...F.value)})}catch{U=[]}}const se=kr([...$,...H]);return{projectId:L.id,projectPath:Z,sessions:se,discoveredWorktrees:U,validPaths:K}})),y=new Map;x.forEach(L=>{L.projectPath&&L.validPaths.forEach(Z=>{const q=jt(Z)??Z,$=L.sessions.filter(H=>(jt(H.directory??null)??q)===q);y.set(q,kr($))})});const b=kr(Array.from(y.values()).flat()),N=r();let v=N.worktreeMetadata;for(const L of x)if(L.projectPath)try{const Z=await Lx(L.sessions,L.projectPath,v);Z&&(v=Z)}catch(Z){console.debug("Failed to refresh worktree metadata during session load:",Z)}const k=new Map;x.forEach(L=>{L.projectPath&&k.set(L.projectPath,L.discoveredWorktrees)});const D=new Set;x.forEach(L=>{L.validPaths.forEach(Z=>{const q=jt(Z)??Z;q&&D.add(q)})});const C=p??w??null,M=C&&D.has(C)?C:w??C,S=M?y.get(M)??[]:b,A=new Set(b.map(L=>L.id));for(const[L,Z]of y.entries())Ox(L,Z.map(q=>q.id));const I=(M??null)!==(N.lastLoadedDirectory??null);let _=N.currentSessionId;if((!_||!A.has(_)||I)&&(_=S[0]?.id??b[0]?.id??null),M){const L=sm(M);L&&A.has(L)&&(_=L)}const T=(()=>{if(!_)return M??null;const L=v.get(_)?.path;if(L)return jt(L)??L;const Z=dn(b,_);return Z||(M??null)})();try{je.setDirectory(T??void 0)}catch(L){console.warn("Failed to sync OpenCode directory after session load:",L)}const P=w?x.find(L=>L.projectPath===w)?.discoveredWorktrees??[]:[];s({sessions:b,sessionsByDirectory:y,currentSessionId:_,lastLoadedDirectory:M??null,isLoading:!1,worktreeMetadata:v,availableWorktrees:P,availableWorktreesByProject:k}),M&&cr(M,_),T&&T!==M&&cr(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=mt.getState(),i=jt(a.currentDirectory),l=dc(),d=l??jt(n??je.getDirectory()??i);ho("createSession:start",{title:t,parentID:o,targetDirectory:d,vscodeWorkspaceDirectory:l});const u=`temp_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,m=r(),f=new Set(m.sessions.map(h=>h.id)),p={id:u,title:t||"New session",parentID:o??void 0,directory:d??null,projectID:m.sessions[0]?.projectID??"",version:"0.0.0",time:{created:Date.now(),updated:Date.now()},summary:void 0,share:void 0};if(s(h=>{const j=[p,...h.sessions],x=new Map(h.sessionsByDirectory);if(d){const y=x.get(d)??[];x.set(d,kr([p,...y]))}return{sessions:j,sessionsByDirectory:x,currentSessionId:u,webUICreatedSessions:new Set([...h.webUICreatedSessions,u]),isLoading:!1}}),d)try{je.setDirectory(d)}catch(h){console.warn("Failed to sync OpenCode directory after session creation:",h)}const g=h=>{const j=d??null,x=j?{...h,directory:j}:h;s(y=>{const b=y.sessions.map(v=>v.id===u?x:v),N=new Map(y.sessionsByDirectory);if(d){const k=(N.get(d)??[]).map(D=>D.id===u?x:D);N.set(d,kr(k))}return{sessions:b,sessionsByDirectory:_s(b),currentSessionId:x.id,webUICreatedSessions:new Set([...Array.from(y.webUICreatedSessions).filter(v=>v!==u),x.id])}}),cr(d??null,x.id)},w=async()=>{const h=je.getApiClient(),j=20;for(let x=0;x<j;x+=1){try{const y=await h.session.list(d?{directory:d}:void 0),N=(Array.isArray(y.data)?y.data:[]).find(v=>!(f.has(v.id)||t&&v.title&&v.title!==t));if(N)return N}catch(y){console.debug("Session poll attempt failed:",y)}await new Promise(y=>setTimeout(y,2e3))}return null};try{const h=()=>je.createSession({title:t,parentID:o??void 0});let j=null;try{j=d?await je.withDirectory(d,h):await h()}catch(x){console.warn("Direct session create failed or timed out, falling back to polling:",x)}return j||(j=await w()),j?(g(j),j):(s(x=>({sessions:x.sessions.filter(y=>y.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(x.webUICreatedSessions).filter(y=>y!==u)),isLoading:!1,error:"Failed to create session"})),null)}catch(h){return s(j=>({sessions:j.sessions.filter(x=>x.id!==u),currentSessionId:m.currentSessionId,webUICreatedSessions:new Set(Array.from(j.webUICreatedSessions).filter(x=>x!==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=dn(r().sessions,t),i=o?.path??a;let l=null;try{o&&n?.archiveWorktree&&(await cc(o,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),l=o);const d=()=>je.deleteSession(t);if(!(i?await je.withDirectory(i,d):await d()))return s(p=>{const g={isLoading:!1,error:"Failed to delete session"};if(l){const w=new Map(p.worktreeMetadata);w.delete(t),g.worktreeMetadata=w}return g}),!1;let m=null;s(p=>{const g=p.sessions.filter(x=>x.id!==t);m=p.currentSessionId===t?null:p.currentSessionId;const w=new Map(p.worktreeMetadata);w.delete(t);const h=n?.archiveWorktree&&o?p.availableWorktrees.filter(x=>jt(x.path)!==jt(o.path)):p.availableWorktrees,j=new Map(p.availableWorktreesByProject);if(n?.archiveWorktree&&o){const x=jt(o.projectDirectory)??o.projectDirectory,y=j.get(x)??[];j.set(x,y.filter(b=>jt(b.path)!==jt(o.path)))}return{sessions:g,sessionsByDirectory:_s(g),currentSessionId:m,isLoading:!1,worktreeMetadata:w,availableWorktrees:h,availableWorktreesByProject:j}});const f=i??je.getDirectory()??null;return cr(f,m),!0}catch(d){const u=d instanceof Error?d.message:"Failed to delete session";return s(l?m=>{const f=new Map(m.worktreeMetadata);return f.delete(t),{worktreeMetadata:f,error:u,isLoading:!1}}:{error:u,isLoading:!1}),!1}},deleteSessions:async(t,n)=>{const o=Array.from(new Set(t.filter(j=>typeof j=="string"&&j.length>0)));if(o.length===0)return{deletedIds:[],failedIds:[]};const a=n?.silent===!0;a||s({isLoading:!0,error:null});const i=[],l=[],d=new Set,u=[],m=new Set;for(const j of o)try{const x=r().worktreeMetadata.get(j),y=dn(r().sessions,j),b=x?.path??y;x&&n?.archiveWorktree&&!m.has(x.path)&&(await cc(x,{deleteRemoteBranch:n?.deleteRemoteBranch,remoteName:n?.remoteName}),d.add(j),u.push({path:x.path,projectDirectory:x.projectDirectory}),m.add(x.path));const N=()=>je.deleteSession(j);(b?await je.withDirectory(b,N):await N())?(i.push(j),x?.path&&!u.some(k=>k.path===x.path)&&u.push({path:x.path,projectDirectory:x.projectDirectory})):l.push(j)}catch{l.push(j)}const f=mt.getState();u.forEach(({path:j,projectDirectory:x})=>{f.currentDirectory===j&&f.setDirectory(x,{showOverlay:!1})});const p=new Set(i),g=l.length>0?l.length===o.length?"Failed to delete sessions":"Failed to delete some sessions":null;let w=null;s(j=>{const x=j.sessions.filter(k=>!p.has(k.id));j.currentSessionId&&p.has(j.currentSessionId)?w=null:w=j.currentSessionId;const y=new Map(j.worktreeMetadata);for(const k of p)y.delete(k);for(const k of d)y.delete(k);const b=new Set(u.map(k=>jt(k.path)).filter(k=>!!k)),N=b.size>0?j.availableWorktrees.filter(k=>!b.has(jt(k.path)??k.path)):j.availableWorktrees,v=new Map(j.availableWorktreesByProject);return u.length>0&&u.reduce((D,C)=>{const M=jt(C.projectDirectory)??C.projectDirectory,S=jt(C.path)??C.path;return D.has(M)||D.set(M,new Set),D.get(M)?.add(S),D},new Map).forEach((D,C)=>{const S=(v.get(C)??[]).filter(A=>!D.has(jt(A.path)??A.path));v.set(C,S)}),{sessions:x,sessionsByDirectory:_s(x),currentSessionId:w,...a?{}:{isLoading:!1,error:g},worktreeMetadata:y,availableWorktrees:N,availableWorktreesByProject:v}});const h=je.getDirectory()??null;return cr(h,w),{deletedIds:i,failedIds:l}},updateSessionTitle:async(t,n)=>{try{const o=dn(r().sessions,t),a=r().worktreeMetadata.get(t),i=()=>je.updateSession(t,n),l=a?.path??o,d=l?await je.withDirectory(l,i):await i();s(u=>{const m=u.sessions.map(f=>f.id===t?d:f);return{sessions:m,sessionsByDirectory:_s(m)}})}catch(o){s({error:o instanceof Error?o.message:"Failed to update session title"})}},shareSession:async t=>{try{const n=dn(r().sessions,t),o=je.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??je.getDirectory();return o.session.share({sessionID:t,...u?{directory:u}:{}})},d=i?await je.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to share session"}),null}},unshareSession:async t=>{try{const n=dn(r().sessions,t),o=je.getApiClient(),i=r().worktreeMetadata.get(t)?.path??n,l=async()=>{const u=n??je.getDirectory();return o.session.unshare({sessionID:t,...u?{directory:u}:{}})},d=i?await je.withDirectory(i,l):await l();return d.data?(s(u=>{const m=u.sessions.map(f=>f.id===t?d.data:f);return{sessions:m,sessionsByDirectory:_s(m)}}),d.data):null}catch(n){return s({error:n instanceof Error?n.message:"Failed to unshare session"}),null}},setCurrentSession:t=>{s({currentSessionId:t,error:null});const n=je.getDirectory()??null;cr(n,t)},clearError:()=>{s({error:null})},getSessionsByDirectory:t=>{const n=jt(t)??t,{sessionsByDirectory:o,sessions:a}=r(),i=o.get(n);return i||a.filter(l=>(jt(l.directory??null)??n)===n)},getDirectoryForSession:t=>{if(!t)return null;const n=r().worktreeMetadata.get(t);if(n?.path)return jt(n.path)??n.path;const o=r().sessions.find(i=>i.id===t);return jt(o?.directory??null)},applySessionMetadata:(t,n)=>{!t||!n||s(o=>{const a=o.sessions.findIndex(g=>g.id===t);if(a===-1)return o;const i=o.sessions[a],l=n.time?{...i.time,...n.time}:i.time,d=n.summary===void 0?i.summary:n.summary||void 0,u=n.share===void 0?i.share:n.share||void 0,m={...i,...n,time:l,summary:d,share:u},f=m.title!==i.title||m.parentID!==i.parentID||m.directory!==i.directory||m.version!==i.version||m.projectID!==i.projectID||JSON.stringify(m.time)!==JSON.stringify(i.time)||JSON.stringify(m.summary??null)!==JSON.stringify(i.summary??null)||JSON.stringify(m.share??null)!==JSON.stringify(i.share??null),p=[...o.sessions];return p[a]=f?m:i,{sessions:p,sessionsByDirectory:_s(p)}})},isOpenChamberCreatedSession:t=>{const{webUICreatedSessions:n}=r();return n.has(t)},markSessionAsOpenChamberCreated:t=>{s(n=>{const o=new Set(n.webUICreatedSessions);return o.add(t),{webUICreatedSessions:o}})},initializeNewOpenChamberSession:t=>{const{markSessionAsOpenChamberCreated:n}=r();n(t)},setWorktreeMetadata:(t,n)=>{t&&s(o=>{const a=new Map(o.worktreeMetadata);return n?a.set(t,n):a.delete(t),{worktreeMetadata:a}})},getWorktreeMetadata:t=>{if(t)return r().worktreeMetadata.get(t)},setSessionDirectory:(t,n)=>{if(!t)return;const o=r().sessions,a=o.findIndex(u=>u.id===t);if(a===-1)return;const l=o[a].directory??null,d=n??void 0;l!==(d??null)&&(s(u=>{const m=[...u.sessions],f={...m[a]};return d!==void 0?f.directory=d:delete f.directory,m[a]=f,{sessions:m,sessionsByDirectory:_s(m)}}),l&&cr(l,null),n&&cr(n,t))},updateSession:t=>{s(n=>{const a=n.sessions.findIndex(l=>l.id===t.id)===-1?[t,...n.sessions]:n.sessions.map(l=>l.id===t.id?t:l),i=kr(a);return{sessions:i,sessionsByDirectory:_s(i)}})},removeSessionFromStore:t=>{t&&s(n=>{const o=n.sessions.find(u=>u.id===t),a=jt(o?.directory??null),i=n.sessions.filter(u=>u.id!==t);if(i.length===n.sessions.length)return n;const l=new Map(n.worktreeMetadata);l.delete(t);const d=n.currentSessionId===t?null:n.currentSessionId;return a&&cr(a,null),{sessions:i,sessionsByDirectory:_s(i),currentSessionId:d,worktreeMetadata:l}})}}),{name:"session-store",storage:Es(()=>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:[],i=Array.isArray(s.worktreeMetadata)?s.worktreeMetadata:[],l=Array.isArray(s.availableWorktrees)?s.availableWorktrees:r.availableWorktrees,d=Array.isArray(s.availableWorktreesByProject)?s.availableWorktreesByProject:[],u=new Map(d),m=typeof s.lastLoadedDirectory=="string"?s.lastLoadedDirectory:r.lastLoadedDirectory??null,f=kr(n);return{...r,...s,sessions:f,sessionsByDirectory:_s(f),currentSessionId:o,webUICreatedSessions:new Set(a),worktreeMetadata:new Map(i),availableWorktrees:l,availableWorktreesByProject:u.size>0?u:r.availableWorktreesByProject,lastLoadedDirectory:m}}}),{name:"session-store"})),rm="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.",Bx="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: ",Ba=s=>typeof s=="string"&&s.trim()===rm.trim(),za=(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},Rn=(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},uc=new Map,nm=s=>{const r=uc.get(s);r&&(clearTimeout(r),uc.delete(s))},Lr=s=>{for(const r of s)nm(r)},to=s=>{if(!s)return"";if(typeof s=="string")return s;if(Array.isArray(s))return s.map(r=>to(r)).join("");if(typeof s=="object"){if(typeof s.text=="string")return s.text;if(Array.isArray(s.content))return s.content.map(r=>to(r)).join("")}return""},Gn=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:Gn(n)).join("");const t=to(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||to(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=to(s.delta);o?t.text=o:a?t.text=n?`${n}${a}`:a:n?t.text=n:t.text="",delete t.delta}return t},mc=10*1024*1024,zx=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"}},Wx=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"}},Hx=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},Ux=s=>{const r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";let t="";for(let n=0;n<s.length;n+=3){const o=s[n]??0,a=s[n+1],i=s[n+2],l=o<<16|(a??0)<<8|(i??0);t+=r[l>>18&63],t+=r[l>>12&63],t+=typeof a=="number"?r[l>>6&63]:"=",t+=typeof i=="number"?r[l&63]:"="}return t},er=zt()(Yt(As((s,r)=>({attachedFiles:[],addAttachedFile:async t=>{const{attachedFiles:n}=r();if(n.some(w=>w.filename===t.name&&w.size===t.size)){console.log(`File "${t.name}" is already attached`);return}const a=mc;if(t.size>a)throw new Error(`File "${t.name}" is too large. Maximum size is 10MB.`);const i=["text/","application/json","application/xml","application/pdf","image/","video/","audio/","application/javascript","application/typescript","application/x-python","application/x-ruby","application/x-sh","application/yaml","application/octet-stream"],l=Wx(t);!i.some(w=>l.startsWith(w)||l===w||l==="")&&l!==""&&console.warn(`File type "${l}" might not be supported`);const u=new FileReader,m=await new Promise((w,h)=>{u.onload=()=>w(u.result),u.onerror=h,u.readAsDataURL(t)}),f=m.startsWith("data:")?m.replace(/^data:[^;]*/,`data:${l}`):m,p=w=>{const h=w.replace(/\\/g,"/").split("/");return h[h.length-1]||w},g={id:`file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:t,dataUrl:f,mimeType:l,filename:p(t.name),size:t.size,source:"local"};s(w=>({attachedFiles:[...w.attachedFiles,g]}))},addServerFile:async(t,n,o)=>{const{attachedFiles:a}=r();if(a.some(x=>x.serverPath===t&&x.source==="server")){console.log(`Server file "${n}" is already attached`);return}let l=o,d,u;if(!l)try{const x=je.getApiClient(),y=t.lastIndexOf("/"),b=y>0?t.substring(0,y):"/",N=y>0?t.substring(y+1):t,v=await x.file.read({path:N,directory:b});v.data&&"content"in v.data?(l=v.data.content,d=v.data.encoding??void 0,u=v.data.mimeType??void 0):l=""}catch(x){console.error("Failed to read server file:",x),l=`[File: ${n}]`}const m=u||zx(n),f=m&&m.trim().length>0?m:"application/octet-stream",p=(()=>{if(d==="base64")return l||"";const y=new TextEncoder().encode(l||"");return Ux(y)})(),g=d==="base64"?Hx(p):new TextEncoder().encode(l||"").length;if(g>mc)throw new Error(`File "${n}" is too large. Maximum size is 10MB.`);const w=new File([],n,{type:f}),h=`data:${f};base64,${p}`,j={id:`server-file-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,file:w,dataUrl:h,mimeType:f,filename:n,size:g,source:"server",serverPath:t};s(x=>({attachedFiles:[...x.attachedFiles,j]}))},removeAttachedFile:t=>{s(n=>({attachedFiles:n.attachedFiles.filter(o=>o.id!==t)}))},clearAttachedFiles:()=>{s({attachedFiles:[]})}}),{name:"file-store",storage:Es(()=>ds()),partialize:s=>({attachedFiles:s.attachedFiles})}),{name:"file-store"})),Vx=new Set(["edit","multiedit","str_replace","str_replace_based_edit_tool","write"]),Gx=s=>s?Vx.has(s.toLowerCase()):!1,qx=()=>{if(!(typeof window>"u"))return window.__zustand_config_store__},Kx=s=>{if(s)try{const r=qx();if(r?.getState)return r.getState().agents?.find?.(n=>n.name===s)}catch{}},Yx=(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"},Bo=s=>{const r=Kx(s);return r?Yx(r.permission,"edit"):"ask"},fc=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},Wa=s=>{const r=s.info.tokens;if(typeof r=="number")return r;if(r&&typeof r=="object")return fc(r);const t=s.parts.find(n=>typeof n.tokens<"u");return!t||typeof t.tokens>"u"?0:typeof t.tokens=="number"?t.tokens:fc(t.tokens)},Ha=(s,r,t)=>{const n=Number.isFinite(r)?Math.max(r,0):0,o=Number.isFinite(t)&&t>0,a=o?Math.max(t,0):0,i=Math.min(o?a:32e3,32e3),l=Math.min(i,n),d=n>0?Math.max(n-l,1):0,u=d>0?s/d*100:0;return{percentage:Math.min(u,100),contextLimit:n,outputLimit:a,thresholdLimit:d||1,normalizedOutput:l}},On=["ask","allow","full"],St=zt()(Yt(As((s,r)=>({sessionModelSelections:new Map,sessionAgentSelections:new Map,sessionAgentModelSelections:new Map,sessionAgentModelVariantSelections:new Map,currentAgentContext:new Map,sessionContextUsage:new Map,sessionAgentEditModes:new Map,hasHydrated:typeof window>"u",saveSessionModelSelection:(t,n,o)=>{s(a=>{const i=new Map(a.sessionModelSelections);return i.set(t,{providerId:n,modelId:o}),{sessionModelSelections:i}})},getSessionModelSelection:t=>{const{sessionModelSelections:n}=r();return n.get(t)||null},saveSessionAgentSelection:(t,n)=>{s(o=>{const a=new Map(o.sessionAgentSelections);return a.set(t,n),{sessionAgentSelections:a}})},getSessionAgentSelection:t=>{const{sessionAgentSelections:n}=r();return n.get(t)||null},saveAgentModelForSession:(t,n,o,a)=>{s(i=>{const l=new Map(i.sessionAgentModelSelections);let d=l.get(t);return d?d=new Map(d):d=new Map,d.set(n,{providerId:o,modelId:a}),l.set(t,d),{sessionAgentModelSelections:l}})},getAgentModelForSession:(t,n)=>{const{sessionAgentModelSelections:o}=r(),a=o.get(t);return a&&a.get(n)||null},saveAgentModelVariantForSession:(t,n,o,a,i)=>{s(l=>{const d=new Map(l.sessionAgentModelVariantSelections);let u=d.get(t);u?u=new Map(u):u=new Map;let m=u.get(n);m?m=new Map(m):m=new Map;const f=`${o}/${a}`;return i===void 0?(m.delete(f),m.size===0?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,m),d.set(t,u))):(m.set(f,i),u.set(n,m),d.set(t,u)),{sessionAgentModelVariantSelections:d}})},getAgentModelVariantForSession:(t,n,o,a)=>{const{sessionAgentModelVariantSelections:i}=r(),l=i.get(t);if(!l)return;const d=l.get(n);if(d)return d.get(`${o}/${a}`)},analyzeAndSaveExternalSessionChoices:async(t,n,o)=>{const{saveAgentModelForSession:a,saveAgentModelVariantForSession:i}=r(),l=new Map,d=(p,g)=>{if("mode"in p&&p.mode&&typeof p.mode=="string"&&n.find(x=>x.name===p.mode))return p.mode;if(p.providerID&&p.modelID){const j=n.find(x=>x.model?.providerID===p.providerID&&x.model?.modelID===p.modelID);if(j)return j.name}const{currentAgentContext:w}=r(),h=w.get(t);if(h&&n.find(j=>j.name===h))return h;if(g>0&&p.providerID&&p.modelID){const x=(o.get(t)||[]).filter(y=>y.info.role==="assistant").sort((y,b)=>y.info.time.created-b.info.time.created);for(let y=g-1;y>=0;y--){const N=x[y].info;if(N.providerID===p.providerID&&N.modelID===p.modelID){if(N.mode&&typeof N.mode=="string"&&n.find(D=>D.name===N.mode))return N.mode;const v=n.find(k=>k.model?.providerID===N.providerID&&k.model?.modelID===N.modelID);if(v)return v.name}}}return p.providerID&&p.modelID&&n.find(x=>x.name==="build")?"build":null},u=o.get(t)||[],m=u.filter(p=>p.info.role==="assistant"||p.info.role==="user").sort((p,g)=>p.info.time.created-g.info.time.created),f=u.filter(p=>p.info.role==="assistant").sort((p,g)=>p.info.time.created-g.info.time.created);for(let p=0;p<m.length;p++){const g=m[p],{info:w}=g,h=w;if(h.providerID&&h.modelID){const j=d(h,f.indexOf(g));if(j&&n.find(x=>x.name===j)){const x=typeof h.variant=="string"&&h.variant.trim().length>0?h.variant:void 0;x&&i(t,j,h.providerID,h.modelID,x);const y={providerId:h.providerID,modelId:h.modelID,timestamp:w.time.created},b=l.get(j);(!b||y.timestamp>b.timestamp)&&l.set(j,y)}}}for(const[p,g]of l)a(t,p,g.providerId,g.modelId);return l},getContextUsage:(t,n,o,a)=>{if(!t)return null;const i=Ha(0,n,o),l=i.contextLimit,d=i.normalizedOutput??0,u=i.thresholdLimit;if(l===0||u===0)return null;const f=(a.get(t)||[]).filter(b=>b.info.role==="assistant");if(f.length===0)return null;const p=f[f.length-1],g=p.info.id,w=b=>{const N=()=>{s(v=>{const k=v.sessionContextUsage.get(t);if(k&&k.totalTokens===b.totalTokens&&k.percentage===b.percentage&&k.contextLimit===b.contextLimit&&(k.outputLimit??0)===(b.outputLimit??0)&&(k.normalizedOutput??0)===(b.normalizedOutput??0)&&k.thresholdLimit===b.thresholdLimit&&k.lastMessageId===b.lastMessageId)return v;const D=new Map(v.sessionContextUsage);return D.set(t,b),{sessionContextUsage:D}})};typeof queueMicrotask=="function"?queueMicrotask(N):typeof window<"u"?window.setTimeout(N,0):setTimeout(N,0)},h=r().sessionContextUsage.get(t);if(h&&h.lastMessageId===g){const b=h.normalizedOutput??h.outputLimit??0,N=h.contextLimit!==l||b!==d||h.thresholdLimit!==u;if(N&&h.totalTokens>0){const v=h.totalTokens/u*100,k={totalTokens:h.totalTokens,percentage:Math.min(v,100),contextLimit:l,outputLimit:i.outputLimit,normalizedOutput:d,thresholdLimit:u,lastMessageId:g};return w(k),k}if(!N&&h.totalTokens>0)return h}const j=Wa(p);if(j===0)return h||null;const x=Ha(j,n,o),y={totalTokens:j,percentage:x.percentage,contextLimit:x.contextLimit,outputLimit:x.outputLimit,normalizedOutput:x.normalizedOutput,thresholdLimit:x.thresholdLimit,lastMessageId:g};return w(y),y},updateSessionContextUsage:(t,n,o,a)=>{const l=(a.get(t)||[]).filter(f=>f.info.role==="assistant");if(l.length===0)return;const d=l[l.length-1],u=Wa(d);if(u===0)return;const m=Ha(u,n,o);s(f=>{const p=new Map(f.sessionContextUsage);return p.set(t,{totalTokens:u,percentage:m.percentage,contextLimit:m.contextLimit,outputLimit:m.outputLimit,normalizedOutput:m.normalizedOutput,thresholdLimit:m.thresholdLimit,lastMessageId:d.info.id}),{sessionContextUsage:p}})},initializeSessionContextUsage:(t,n,o,a)=>{const l=r().sessionContextUsage.get(t);(!l||l.totalTokens===0)&&r().updateSessionContextUsage(t,n,o,a)},pollForTokenUpdates:(t,n,o,a=10)=>{let i=0;const l=()=>{i++;const u=(o.get(t)||[]).find(m=>m.info.id===n);if(u&&u.info.role==="assistant"&&Wa(u)>0){r().updateSessionContextUsage(t,0,0,o);return}i<a&&setTimeout(l,1e3)};setTimeout(l,2e3)},getCurrentAgent:t=>{const{currentAgentContext:n}=r();return n.get(t)},getSessionAgentEditMode:(t,n,o=Bo(n))=>!t||!n?o:r().sessionAgentEditModes.get(t)?.get(n)??o,setSessionAgentEditMode:(t,n,o,a=Bo(n))=>{if(!t||!n)return;const i=a??"ask";i==="deny"||o==="deny"||On.includes(o)&&s(l=>{const d=new Map(l.sessionAgentEditModes),u=new Map(d.get(t)??new Map);return o===i?(u.delete(n),u.size===0?d.delete(t):d.set(t,u)):(u.set(n,o),d.set(t,u)),{sessionAgentEditModes:d}})},toggleSessionAgentEditMode:(t,n,o=Bo(n))=>{if(!t||!n)return;const a=o??"ask";if(a==="deny")return;const i=r().getSessionAgentEditMode(t,n,a),l=On.indexOf(i),d=On.indexOf(a),m=((l>=0?l:d>=0?d:0)+1)%On.length,f=On[m];r().setSessionAgentEditMode(t,n,f,a)}}),{name:"context-store",storage:Es(()=>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,i])=>{t.set(a,new Map(i))});const n=new Map;s?.sessionAgentModelVariantSelections&&s.sessionAgentModelVariantSelections.forEach(([a,i])=>{const l=new Map;i.forEach(([d,u])=>{l.set(d,new Map(u))}),n.set(a,l)});const o=new Map;return s?.sessionAgentEditModes&&s.sessionAgentEditModes.forEach(([a,i])=>{o.set(a,new Map(i))}),{...r,...s,sessionModelSelections:new Map(s?.sessionModelSelections||[]),sessionAgentSelections:new Map(s?.sessionAgentSelections||[]),sessionAgentModelSelections:t,sessionAgentModelVariantSelections:n,currentAgentContext:new Map(s?.currentAgentContext||[]),sessionContextUsage:new Map(s?.sessionContextUsage||[]),sessionAgentEditModes:o,hasHydrated:!0}}}),{name:"context-store"})),pc=(s,r)=>{const t=new Map(s);return t.delete(r),t};let Ua=[],Va=null;const Qx=50,Xx=3e4,Br=new Map,go=new Map,un=new Map,Jx=10,Zo=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<Jx?null:n},xo=(s,r)=>{const t=Zo(s),n=Zo(r);return!t||!n||t.length!==n.length?!0:t>n},Zx=()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}},gn=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),ea=s=>s?.finish==="stop",hc=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??""}`}}},gc=new Set,ta=(s=[],r=[])=>{if(!r.length)return[...s];const t=[...s],n=new Set(s.map(hc).filter(o=>!!o));return r.forEach(o=>{if(!o)return;const a=hc(o);a&&n.has(a)||(t.push(o),a&&n.add(a))}),t},ey=(s,r)=>{const t=Array.isArray(s.parts)?s.parts:[],n=Array.isArray(r.parts)?r.parts:[],o=gn(t),a=gn(n),i=ea(s.info),l=ea(r.info);let d=n;return i&&o>=a?d=ta(t,n):l&&a>=o?d=ta(n,t):o>=a&&(d=t),{...r,info:{...s.info,...r.info},parts:d}},Ga=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]=ey(r[a],n)}return r},ty=(s,r)=>{let t=r,n=r?Zo(r):null;for(const o of s){const a=o?.info?.id,i=Zo(a);!a||!i||(!n||i>n)&&(n=i,t=a)}return t},Ys=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return t?o.set(r,t):o.delete(r),o},mn=(s,r,t)=>{if(s.get(r)===t)return s;const o=new Map(s);return o.set(r,t),o},yo=(s,r)=>{const t=new Map(s);let n=!1;for(const o of r)t.delete(o)&&(n=!0);return n?t:s},sy=(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},xc=(s,r,t)=>s.streamingMessageIds.get(r)===t?!0:s.messageSessionIndex.get(t)===r&&s.messageStreamStates.has(t),ry=async s=>{if(s)try{return lt.getState().getDirectoryForSession(s)??void 0}catch(r){console.warn("Failed to resolve session directory override:",r);return}},yc=s=>{if(!s)return null;try{return lt.getState().sessions.find(n=>n.id===s)?.revert?.messageID??null}catch{return null}},bc=(s,r)=>{if(!r)return s;const t=s.findIndex(n=>n.info.id===r);return t===-1?s:s.slice(0,t)},qa=async(s,r)=>{const t=await ry(s);return t?je.withDirectory(t,r):r()},yt=zt()(Yt(As((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 qa(t,()=>je.getSessionMessages(t)),a=yc(t),i=bc(o,a),l=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,u=(l?i.filter(m=>{const f=m?.info?.id;return f?xo(f,l):!0}):i).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])),w=u.map(M=>{const S={...M.info,clientRole:M.info?.clientRole??M.info.role,userMessageMarker:M.info.role==="user"?!0:M.info?.userMessageMarker},A=(Array.isArray(M.parts)?M.parts:[]).map(_=>{if(_?.type==="text"){const T=_.text??_.content??"";if(Ba(T))return{..._,synthetic:!0}}return _}),I=S?.id?g.get(S.id):void 0;if(I&&I.info.role==="assistant"){const _=Array.isArray(I.parts)?I.parts:[],T=gn(_),P=gn(A);if(ea(I.info)&&T>P){const Z=ta(_,A);return{...M,info:S,parts:Z}}}return{...M,info:S,parts:A}}),h=Ga(w),j=new Set(p.map(M=>M.info.id)),x=new Set(h.map(M=>M.info.id)),y=[];j.forEach(M=>{x.has(M)||y.push(M)}),f.set(t,h);const b=new Map(m.sessionMemoryState),N=m.sessionMemoryState.get(t);b.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 v={messages:f,sessionMemoryState:b};Lr(y);const k=Rn(m.messageStreamStates,y);if(k!==m.messageStreamStates&&(v.messageStreamStates=k),y.length>0){const M=m.streamingMessageIds.get(t);M&&y.includes(M)&&(v.streamingMessageIds=Ys(v.streamingMessageIds??m.streamingMessageIds,t,null))}if(y.length>0){const M=yo(v.messageSessionIndex??m.messageSessionIndex,y);M!==(v.messageSessionIndex??m.messageSessionIndex)&&(v.messageSessionIndex=M)}if(y.length>0){const M=new Map(m.pendingAssistantParts);let S=!1;y.forEach(A=>{M.delete(A)&&(S=!0)}),S&&(v.pendingAssistantParts=M)}const D=v.messageSessionIndex??m.messageSessionIndex;let C=D;return h.forEach(M=>{const S=M?.info?.id;typeof S=="string"&&S.length>0&&(C=mn(C,S,t))}),C!==D&&(v.messageSessionIndex=C),v})},sendMessage:async(t,n,o,a,i,l,d,u,m)=>{if(!i)throw new Error("No session selected");const f=i;r().sessionAbortFlags.has(f)&&s(p=>{const g=new Map(p.sessionAbortFlags);return g.delete(f),{sessionAbortFlags:g}}),await qa(f,async()=>{try{let p=t;if(t.startsWith("/")){const w=t.indexOf(" "),h=w===-1?t.substring(1):t.substring(1,w),j=w===-1?"":t.substring(w+1).trim(),x=je.getApiClient(),y=je.getDirectory();if(h==="init"){const b=`msg_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;await x.session.init({sessionID:f,...y?{directory:y}:{},messageID:b,providerID:n,modelID:o});return}if(h==="summarize"){await x.session.summarize({sessionID:f,...y?{directory:y}:{},providerID:n,modelID:o});return}try{const b=await je.getCommandDetails(h);b?.template?p=b.template.replace(/\$ARGUMENTS/g,j):p=t}catch(b){console.error("Command template resolution failed:",b),p=t}}s({lastUsedProvider:{providerID:n,modelID:o}}),s(w=>{const h=w.sessionMemoryState.get(f)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},j=un.get(f);j&&(clearTimeout(j),un.delete(f));const x=new Map(w.sessionMemoryState);return x.set(f,{...h,isStreaming:!0,streamStartTime:Date.now(),streamingCooldownUntil:void 0}),{sessionMemoryState:x}});try{const w=new AbortController;s(x=>{const y=new Map(x.abortControllers);return y.set(f,w),{abortControllers:y}});const h=(l??[]).map(x=>({type:"file",mime:x.mimeType,filename:x.filename,url:x.dataUrl}));s(x=>{const y=new Set(x.pendingAssistantHeaderSessions);y.add(f);const b=new Map(x.pendingUserMessageMetaBySession);return b.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:y,pendingUserMessageMetaBySession:b}});const j=u?.map(x=>({text:x.text,files:x.attachments?.map(y=>({type:"file",mime:y.mimeType,filename:y.filename,url:y.dataUrl}))}));if(await je.sendMessage({id:f,providerID:n,modelID:o,text:p,agent:a,variant:m,files:h.length>0?h:void 0,additionalParts:j,agentMentions:d?[{name:d}]:void 0}),h.length>0)try{er.getState().clearAttachedFiles()}catch(x){console.error("Failed to clear attached files after send",x)}s(x=>{const y=new Map(x.abortControllers);return y.delete(f),{abortControllers:y}})}catch(w){let h="Network error while sending message. The message may still be processing.";if(w.name==="AbortError")h="Request timed out. The message may still be processing.";else if(w.message?.includes("504")||w.message?.includes("Gateway")){h="Gateway timeout - your message is being processed. Please wait for response.",s(j=>{const x=new Map(j.abortControllers);return x.delete(f),{abortControllers:x}});return}else w.message&&(h=w.message);throw s(j=>{const x=new Map(j.abortControllers);x.delete(f);const y=new Set(j.pendingAssistantHeaderSessions);y.delete(f);const b=new Map(j.pendingUserMessageMetaBySession);return b.delete(f),{abortControllers:x,pendingAssistantHeaderSessions:y,pendingUserMessageMetaBySession:b}}),new Error(h)}}catch(p){let g="Network error while sending message. The message may still be processing.";throw p.name==="AbortError"?g="Request timed out. The message may still be processing.":p.response?.status===401?g="Session not found or unauthorized. Please refresh the page.":p.response?.status===502?g="OpenCode is restarting. Please wait a moment and try again.":p.message?.includes("504")||p.message?.includes("Gateway")?g="Gateway timeout - your message is being processed. Please wait for response.":p.message&&(g=p.message),s(w=>{const h=new Map(w.abortControllers);h.delete(f);const j=new Set(w.pendingAssistantHeaderSessions);j.delete(f);const x=new Map(w.pendingUserMessageMetaBySession);return x.delete(f),{abortControllers:h,pendingAssistantHeaderSessions:j,pendingUserMessageMetaBySession:x}}),new Error(g)}})},abortCurrentOperation:async t=>{if(!t)return;const n=r(),{abortControllers:o,messages:a}=n;o.get(t)?.abort();const l=sy(n,t);if(l.size===0){const u=t?a.get(t)??[]:[];let m=null;for(let f=u.length-1;f>=0;f-=1){const p=u[f];if(!p||p.info.role!=="assistant")continue;if(m||(m=p.info.id),(p.parts??[]).some(w=>w.type==="reasoning"||w.type==="tool"||w.type==="step-start")){l.add(p.info.id);break}}l.size===0&&m&&l.add(m)}for(const u of l){const m=Br.get(u);m&&(clearTimeout(m),Br.delete(u),go.delete(u))}l.size>0&&Lr(l);const d=Date.now();s(u=>{const m=Rn(u.messageStreamStates,l),f=u.messages.get(t)??[];let p=!1,g=u.messages;if(f.length>0&&l.size>0){const x=f.map(y=>{if(!l.has(y.info.id)&&l.size>0)return y;const b=(y.parts??[]).map(N=>{if(N.type==="reasoning"){const v=N,k={...v.time??{}};return typeof k.end!="number"&&(k.end=d),{...v,time:k}}if(N.type==="tool"){const v=N,k={...v.state??{}};return(k.status==="running"||k.status==="pending")&&(k.status="aborted"),{...v,state:k}}return N.type==="step-start"?{...N,type:"step-finish",aborted:!0}:N});return p=!0,{...y,info:{...y.info,abortedAt:d,streaming:!1,status:"aborted"},parts:b}});p&&(g=new Map(u.messages),g.set(t,x))}const w=u.sessionMemoryState.get(t);let h=u.sessionMemoryState;if(w){const x=new Map(u.sessionMemoryState);x.set(t,{...w,isStreaming:!1,streamStartTime:void 0,isZombie:!1}),h=x}const j=new Map(u.sessionAbortFlags);return j.set(t,{timestamp:d,acknowledged:!1}),{messageStreamStates:m,sessionMemoryState:h,sessionAbortFlags:j,abortControllers:(()=>{const x=new Map(u.abortControllers);return x.delete(t),x})(),streamingMessageIds:Ys(u.streamingMessageIds,t,null),...p?{messages:g}:{}}}),je.abortSession(t).catch(u=>{console.warn("Abort request failed:",u)})},_addStreamingPartImmediate:(t,n,o,a,i)=>{const l=r();if(gc.has(n))return;const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!xo(n,d)){window.__messageTracker?.(n,"ignored_trimmed_stream_part");return}const u=l.messages.get(t)||[],m=u.find(g=>g.info.id===n),f=a==="user"||m?.info.role==="user"?"user":a||m?.info.role||"assistant",p=r().sessionMemoryState.get(t);if(p?.streamStartTime&&Date.now()-p.streamStartTime>us.ZOMBIE_TIMEOUT){p.isZombie||s(w=>{const h=new Map(w.sessionMemoryState);return h.set(t,{...p,isZombie:!0}),{sessionMemoryState:h}}),setTimeout(()=>{r().completeStreamingMessage(t,n)},0),window.__messageTracker?.(n,"skipped_zombie_stream");return}s(g=>{const h=[...g.messages.get(t)||[]],j={},x=mn(g.messageSessionIndex,n,t);x!==g.messageSessionIndex&&(j.messageSessionIndex=x);const y=M=>{if(!((f==="assistant"||f==="user")&&g.sessionAbortFlags.has(t)))return M;const A=new Map(g.sessionAbortFlags);return A.delete(t),{...M,sessionAbortFlags:A}},b=M=>{const S=M||"",A=go.get(n);if(S&&A===S){const T=r();if(xc(T,t,n)){const P=Br.get(n);P&&(clearTimeout(P),Br.delete(n)),setTimeout(()=>{const L=r();typeof L.forceCompleteMessage=="function"&&L.forceCompleteMessage(t,n,"timeout"),L.completeStreamingMessage(t,n)},100)}}go.set(n,S);const I=Br.get(n);I&&clearTimeout(I);const _=setTimeout(()=>{const T=r();typeof T.forceCompleteMessage=="function"&&T.forceCompleteMessage(t,n,"timeout"),xc(T,t,n)&&T.completeStreamingMessage(t,n),Br.delete(n),go.delete(n)},8e3);Br.set(n,_)},N=t!==i,v=g.sessionMemoryState.get(t);if(N&&v?.isStreaming){h.length>=us.BACKGROUND_STREAMING_BUFFER&&h.shift();const M=new Map(g.sessionMemoryState);M.set(t,{...v,backgroundMessageCount:(v.backgroundMessageCount||0)+1}),g.sessionMemoryState=M}if(f==="assistant"){const M=g.sessionMemoryState.get(t);if(M){const S=Date.now(),A=new Map(g.sessionMemoryState);A.set(t,{...M,isStreaming:!0,streamStartTime:M.streamStartTime??S,lastAccessedAt:S,isZombie:!1}),g.sessionMemoryState=A}}const k=Gn(o);if(Ba(k)&&(o.synthetic=!0),Zx()&&f==="assistant")try{console.info("[STREAM-TRACE] part",{messageId:n,role:f,type:o?.type||"text",textLen:k.length,snapshotParts:u.length})}catch{}const D=j.streamingMessageIds??g.streamingMessageIds;if(f==="assistant"){const M=Ys(D,t,n);M!==D&&(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 A=_n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`user_part_type:${A.type||"unknown"}`);const I={...M};S!==-1?I.parts=I.parts.map((P,L)=>L===S?A:P):I.parts=[...I.parts,A];const _=[...h];_[C]=I;const T=new Map(g.messages);return T.set(t,_),y({messages:T})}if(f==="assistant"&&C!==-1){const M=h[C],S=M.parts.findIndex(L=>L.id===o.id),A=_n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const I={...M};S!==-1?I.parts=I.parts.map((L,Z)=>Z===S?A:L):I.parts=[...I.parts,A];const _=[...h];_[C]=I;const T=new Map(g.messages);T.set(t,_),j.messageStreamStates=za(g.messageStreamStates,n);const P=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);return P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set")),A.type==="text"?b(A.text||""):b(""),y({messages:T,...j})}if(C===-1){if(f==="user"){if(o.synthetic===!0)return window.__messageTracker?.(n,"skipped_synthetic_new_user_part"),g;const V=_n(o);window.__messageTracker?.(n,`new_user_part_type:${V.type||"unknown"}`);const ae=g.pendingUserMessageMetaBySession.get(t),E=St.getState(),B=ae?.mode??E.getSessionAgentSelection(t)??E.getCurrentAgent(t),F=typeof B=="string"&&B.trim().length>0?B.trim():void 0,O=ae?.providerID??(g.lastUsedProvider?.providerID||void 0),z=ae?.modelID??(g.lastUsedProvider?.modelID||void 0);ae&&(j.pendingUserMessageMetaBySession=pc(g.pendingUserMessageMetaBySession,t));const Q={info:{id:n,sessionID:t,role:"user",clientRole:"user",userMessageMarker:!0,...F?{mode:F}:{},...O?{providerID:O}:{},...z?{modelID:z}:{},time:{created:Date.now()}},parts:[V]},me=[...h,Q];me.sort((he,Pe)=>{const ve=he.info?.time?.created||0,Be=Pe.info?.time?.created||0;return ve-Be});const Se=new Map(g.messages);return Se.set(t,me),y({messages:Se})}if(o?.type==="text"){const V=Gn(o).trim();if(V.length>0){const ae=[...h].reverse().find(E=>E.info.role==="user");if(ae){const E=ae.parts.map(B=>Gn(B)).join("").trim();if(E.length>0&&E===V)return gc.add(n),window.__messageTracker?.(n,"ignored_assistant_echo"),g}}}const M=_n(o);window.__messageTracker?.(n,`part_type:${M.type||"unknown"}`),M.type==="text"?b(M.text||""):b("");const S=g.pendingAssistantParts.get(n),A=S?[...S.parts]:[],I=A.findIndex(V=>V.id===M.id);I!==-1?A[I]=M:A.push(M);const _=new Map(g.pendingAssistantParts);_.set(n,{sessionId:t,parts:A});const T=g.lastUsedProvider?.providerID||"",P=g.lastUsedProvider?.modelID||"",L=Date.now(),Z=je.getDirectory()??"/",q=St.getState(),$=q.getSessionAgentSelection(t)??q.getCurrentAgent(t),H=typeof $=="string"&&$.trim().length>0?$.trim():void 0,U=g.pendingAssistantHeaderSessions.has(t);if(U){const V=new Set(g.pendingAssistantHeaderSessions);V.delete(t),j.pendingAssistantHeaderSessions=V}const se={info:f==="user"?{id:n,sessionID:t,role:"user",time:{created:L},agent:H||"default",model:{providerID:T,modelID:P},clientRole:f,animationSettled:void 0,streaming:void 0}:{id:n,sessionID:t,role:"assistant",time:{created:L},parentID:n,modelID:P,providerID:T,mode:H||"default",...U?{openchamberHeaderAnchor:!0}:{},path:{cwd:Z,root:Z},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},clientRole:f,animationSettled:!1,streaming:!0},parts:A},Y=[...h,se],re=new Map(g.messages);if(re.set(t,Y),f==="assistant"){j.messageStreamStates=za(g.messageStreamStates,n);const V=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);V!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=V,window.__messageTracker?.(n,"streamingId_set"))}return y({messages:re,pendingAssistantParts:_,...j})}else{const M=h[C],S=M.parts.findIndex(P=>P.id===o.id),A=_n(o,S!==-1?M.parts[S]:void 0);window.__messageTracker?.(n,`part_type:${A.type||"unknown"}`);const I={...M};S!==-1?I.parts=I.parts.map((P,L)=>L===S?A:P):I.parts=[...I.parts,A];const _=[...h];_[C]=I;const T=new Map(g.messages);if(T.set(t,_),I.info.role==="assistant"){j.messageStreamStates=za(g.messageStreamStates,n);const P=Ys(j.streamingMessageIds??g.streamingMessageIds,t,n);P!==(j.streamingMessageIds??g.streamingMessageIds)&&(j.streamingMessageIds=P,window.__messageTracker?.(n,"streamingId_set"))}return A.type==="text"?b(A.text||""):b(""),y({messages:T,...j})}})},addStreamingPart:(t,n,o,a,i)=>{if(a!=="user"){r()._addStreamingPartImmediate(t,n,o,a,i);return}Ua.push({sessionId:t,messageId:n,part:o,role:a,currentSessionId:i}),Va||(Va=setTimeout(()=>{const l=[...Ua];Ua=[],Va=null;const d=r();for(const u of l)d._addStreamingPartImmediate(u.sessionId,u.messageId,u.part,u.role,u.currentSessionId)},Qx))},forceCompleteMessage:(t,n,o="timeout")=>{const a=i=>{if(t)return t;for(const[l,d]of i.messages.entries())if(d.some(u=>u.info.id===n))return l;return null};s(i=>{const l=a(i);if(!l)return i;const d=i.messages.get(l)??[],u=d.findIndex(v=>v.info.id===n);if(u===-1)return i;const m=d[u];if(!m)return i;const f=Date.now(),p=m.info,g=typeof p?.time?.completed=="number"&&p.time.completed>0;let w=!1;const h={...p};g||(h.time={...p.time??{},completed:f},w=!0),h.status!=="completed"&&(h.status="completed",w=!0),h.streaming&&(h.streaming=!1,w=!0);let j=!1;const x=m.parts.map(v=>{if(!v)return v;if(v.type==="tool"){const k=v.state;if(!k)return v;const D=k.status,C=D==="running"||D==="pending"||D==="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,{...v,state:S}}return v}if(v.type==="reasoning"){const k=v.time;return!k||typeof k.end!="number"?(j=!0,{...v,time:{...k??{},end:f}}):v}if(v.type==="text"){const k=v.time;return k&&typeof k.end!="number"?(j=!0,{...v,time:{...k,end:f}}):v}return v});if(!w&&!j)return i;window.__messageTracker?.(n,`force_complete:${o}`);const y={...m,info:h,parts:j?x:m.parts},b=[...d];b[u]=y;const N=new Map(i.messages);return N.set(l,b),{messages:N}})},markMessageStreamSettled:t=>{s(n=>{nm(t);const o=new Map(n.messageStreamStates);o.delete(t);let a=n.messages,i=!1;return n.messages.forEach((d,u)=>{if(i)return;const m=d.findIndex(h=>h.info.id===t);if(m===-1)return;const f=d[m];if(f.info?.animationSettled)return;const p={...f,info:{...f.info,animationSettled:!0}},g=[...d];g[m]=p;const w=new Map(n.messages);w.set(u,g),a=w,i=!0}),{messageStreamStates:o,...i?{messages:a}:{}}}),Lr([t])},updateMessageInfo:(t,n,o)=>{s(l=>{const d=l.sessionMemoryState.get(t)?.trimmedHeadMaxId;if(d&&!xo(n,d))return window.__messageTracker?.(n,"ignored_trimmed_update"),l;const m=[...l.messages.get(t)??[]],f=m.findIndex(C=>C.info.id===n),p=l.pendingAssistantParts.get(n),g=(C=[],M=[])=>{if(!M.length)return C;const S=[...C];return M.forEach(A=>{const I=S.findIndex(_=>_.id===A.id);I===-1?S.push(A):S[I]=A}),S},w=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 Z=m[0]?.info,q=typeof Z?.time?.created=="number"?Z.time.created:null,$=typeof Z?.id=="string"?Z.id:null,H=o,U=typeof H?.time?.created=="number"?H.time.created:null,K=typeof H?.id=="string"?H.id:n;let se=!1;if(U!==null&&q!==null&&(se=U<q),!se&&K&&$&&(se=K.localeCompare($)<0),se)return window.__messageTracker?.(n,"skipped_evicted_message_update"),l}const C=w(o);if(C&&C.role==="user"){const L=p?.parts??[],Z=l.pendingUserMessageMetaBySession.get(t),q={info:{...C,userMessageMarker:!0,clientRole:"user",...Z?.mode?{mode:Z.mode}:{},...Z?.providerID?{providerID:Z.providerID}:{},...Z?.modelID?{modelID:Z.modelID}:{}},parts:L.length>0?[...L]:[]},$=new Map(l.messages),H=[...m,q];H.sort((se,Y)=>{const re=se.info?.time?.created||0,V=Y.info?.time?.created||0;return re-V}),$.set(t,H);const U={messages:$,...Z?{pendingUserMessageMetaBySession:pc(l.pendingUserMessageMetaBySession,t)}:{}},K=mn(U.messageSessionIndex??l.messageSessionIndex,n,t);if(K!==(U.messageSessionIndex??l.messageSessionIndex)&&(U.messageSessionIndex=K),p){const se=new Map(l.pendingAssistantParts);se.delete(n),U.pendingAssistantParts=se}return U}if(!C||C.role!=="assistant")return l;const M=p?.parts??[],S=l.pendingAssistantHeaderSessions.has(t),A={info:{...C,animationSettled:C?.animationSettled??!1,...S?{openchamberHeaderAnchor:!0}:{}},parts:M.length>0?[...M]:[]},I=new Map(l.messages),_=[...m,A];I.set(t,_);const T={messages:I,...S?{pendingAssistantHeaderSessions:(()=>{const L=new Set(l.pendingAssistantHeaderSessions);return L.delete(t),L})()}:{}},P=mn(T.messageSessionIndex??l.messageSessionIndex,n,t);if(P!==(T.messageSessionIndex??l.messageSessionIndex)&&(T.messageSessionIndex=P),p){const L=new Map(l.pendingAssistantParts);L.delete(n),T.pendingAssistantParts=L}return T}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=l.pendingUserMessageMetaBySession.get(t);M&&!C.mode&&M.mode&&(C.mode=M.mode);const S={...h,info:C},A=new Map(l.messages),I=[...m];if(I[f]=S,A.set(t,I),M){const _=new Map(l.pendingUserMessageMetaBySession);return _.delete(t),{messages:A,pendingUserMessageMetaBySession:_}}return{messages:A}}const y={...h.info,...o};o.role&&o.role!==h.info.role&&(y.role=h.info.role),y.clientRole=y.clientRole??h.info.clientRole??h.info.role,y.clientRole==="user"&&(y.userMessageMarker=!0);const b=p?.parts?g(h.parts,p.parts):h.parts,N={...h,info:y,parts:b},v=new Map(l.messages),k=[...m];k[f]=N,v.set(t,k);const D={messages:v};if(p){const C=new Map(l.pendingAssistantParts);C.delete(n),D.pendingAssistantParts=C}return D});const a=o?.finish,i=o?.role;typeof a=="string"&&i!=="user"&&setTimeout(()=>{r().completeStreamingMessage(t,n)},0)},completeStreamingMessage:(t,n)=>{const o=r();window.__messageTracker?.(n,`completion_called_current:${o.streamingMessageIds.get(t)??"none"}`),typeof o.forceCompleteMessage=="function"&&o.forceCompleteMessage(t,n,"cooldown");const a=o.streamingMessageIds.get(t)===n;a?window.__messageTracker?.(n,"streamingId_cleared"):window.__messageTracker?.(n,"streamingId_NOT_cleared_different_id");const i={};if(a&&(i.streamingMessageIds=Ys(o.streamingMessageIds,t,null),i.abortControllers=(()=>{const d=new Map(o.abortControllers);return d.delete(t),d})()),o.messageStreamStates.has(n)){const d=new Map(o.messageStreamStates);d.delete(n),i.messageStreamStates=d}Object.keys(i).length>0&&s(i),o.pendingAssistantParts.has(n)&&s(d=>{if(!d.pendingAssistantParts.has(n))return d;const u=new Map(d.pendingAssistantParts);return u.delete(n),{pendingAssistantParts:u}}),Lr([n]);let l=!1;if(s(d=>{const u=d.sessionMemoryState.get(t);if(!u||!u.isStreaming)return d;const m=new Map(d.sessionMemoryState),f=Date.now(),p={...u,isStreaming:!1,streamStartTime:void 0,isZombie:!1,lastAccessedAt:f,streamingCooldownUntil:f+2e3};return m.set(t,p),l=!0,{sessionMemoryState:m}}),l){const d=un.get(t);d&&(clearTimeout(d),un.delete(t));const u=setTimeout(()=>{s(m=>{const f=m.sessionMemoryState.get(t);if(!f||f.isStreaming)return m;const p=new Map(m.sessionMemoryState),{streamingCooldownUntil:g,...w}=f;return p.set(t,w),{sessionMemoryState:p}}),un.delete(t)},2e3);un.set(t,u)}},syncMessages:(t,n)=>{const o=yc(t),a=bc(n,o),i=r().sessionMemoryState.get(t)?.trimmedHeadMaxId,l=i?a.filter(d=>{const u=d?.info?.id;return u?xo(u,i):!0}):a;s(d=>{const u=new Map(d.messages),m=d.messages.get(t)||[],f=new Map(m.filter(v=>typeof v.info?.id=="string").map(v=>[v.info.id,v])),p=l.map(v=>{const k={...v.info,clientRole:v.info?.clientRole??v.info.role,userMessageMarker:v.info.role==="user"?!0:v.info?.userMessageMarker,animationSettled:v.info.role==="assistant"?v.info?.animationSettled??!0:v.info?.animationSettled},D=(Array.isArray(v.parts)?v.parts:[]).map(S=>{if(S?.type==="text"){const A=S.text??S.content??"";if(Ba(A))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:[],A=gn(S),I=gn(D);if(ea(M.info)&&A>I){const T=ta(S,D);return{...v,info:k,parts:T}}}return{...v,info:k,parts:D}}),g=Ga(p),w=new Set(m.map(v=>v.info.id)),h=new Set(g.map(v=>v.info.id)),j=[];w.forEach(v=>{h.has(v)||j.push(v)}),u.set(t,g);const x={messages:u,isSyncing:!0};Lr(j);const y=Rn(d.messageStreamStates,j);if(y!==d.messageStreamStates&&(x.messageStreamStates=y),j.length>0){const v=d.streamingMessageIds.get(t);v&&j.includes(v)&&(x.streamingMessageIds=Ys(x.streamingMessageIds??d.streamingMessageIds,t,null))}if(j.length>0){const v=yo(x.messageSessionIndex??d.messageSessionIndex,j);v!==(x.messageSessionIndex??d.messageSessionIndex)&&(x.messageSessionIndex=v)}if(j.length>0){const v=new Map(d.pendingAssistantParts);let k=!1;j.forEach(D=>{v.delete(D)&&(k=!0)}),k&&(x.pendingAssistantParts=v)}const b=x.messageSessionIndex??d.messageSessionIndex;let N=b;return g.forEach(v=>{const k=v?.info?.id;typeof k=="string"&&k.length>0&&(N=mn(N,k,t))}),N!==b&&(x.messageSessionIndex=N),x}),setTimeout(()=>{s({isSyncing:!1})},100)},updateSessionCompaction:(t,n)=>{s(o=>{const a=new Map(o.sessionCompactionUntil);if(!n||n<=0)return a.has(t)?(a.delete(t),{sessionCompactionUntil:a}):o;const i=n+Xx;return a.get(t)===i?o:(a.set(t,i),{sessionCompactionUntil:a})})},acknowledgeSessionAbort:t=>{t&&s(n=>{const o=n.sessionAbortFlags.get(t);if(!o||o.acknowledged)return n;const a=new Map(n.sessionAbortFlags);return a.set(t,{...o,acknowledged:!0}),{sessionAbortFlags:a}})},updateViewportAnchor:(t,n)=>{s(o=>{const a=o.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},i=new Map(o.sessionMemoryState);return i.set(t,{...a,viewportAnchor:n}),{sessionMemoryState:i}})},updateActiveTurnAnchor:(t,n,o)=>{s(a=>{const i=a.sessionMemoryState.get(t)||{viewportAnchor:0,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0},l=new Map(a.sessionMemoryState);return l.set(t,{...i,activeTurnAnchorId:n??void 0,activeTurnSpacerHeight:o}),{sessionMemoryState:l}})},getActiveTurnAnchor:t=>{const n=r().sessionMemoryState.get(t);return n?{anchorId:n.activeTurnAnchorId??null,spacerHeight:n.activeTurnSpacerHeight??0}:null},trimToViewportWindow:(t,n=us.VIEWPORT_MESSAGES,o)=>{const a=r(),i=a.messages.get(t);if(!i||i.length<=n)return;const l=a.sessionMemoryState.get(t)||{viewportAnchor:i.length-1,isStreaming:!1,lastAccessedAt:Date.now(),backgroundMessageCount:0};if(l.isStreaming&&t===o)return;const d=l.viewportAnchor||i.length-1;let u=Math.max(0,d-Math.floor(n/2));const m=Math.min(i.length,u+n);m===i.length&&m-u<n&&(u=Math.max(0,m-n));const f=i.slice(u,m),p=i.slice(0,u),g=new Set(f.map(h=>h.info.id)),w=i.filter(h=>!g.has(h.info.id)).map(h=>h.info.id);s(h=>{const j=new Map(h.messages);j.set(t,f);const x=new Map(h.sessionMemoryState),y={...l,viewportAnchor:d-u,trimmedHeadMaxId:ty(p,l.trimmedHeadMaxId)};x.set(t,y);const b={messages:j,sessionMemoryState:x};Lr(w);const N=Rn(h.messageStreamStates,w);if(N!==h.messageStreamStates&&(b.messageStreamStates=N),w.length>0){const D=h.streamingMessageIds.get(t);D&&w.includes(D)&&(b.streamingMessageIds=Ys(b.streamingMessageIds??h.streamingMessageIds,t,null))}if(w.length>0){const D=yo(b.messageSessionIndex??h.messageSessionIndex,w);D!==(b.messageSessionIndex??h.messageSessionIndex)&&(b.messageSessionIndex=D)}const v=b.messageSessionIndex??h.messageSessionIndex;let k=v;return f.forEach(D=>{const C=D?.info?.id;typeof C=="string"&&C.length>0&&(k=mn(k,C,t))}),k!==v&&(b.messageSessionIndex=k),b})},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 i=a.filter(([d,u])=>d!==t&&!u.isStreaming);if(i.length===0)return;i.sort((d,u)=>d[1].lastAccessedAt-u[1].lastAccessedAt);const l=i[0][0];s(d=>{const m=(d.messages.get(l)||[]).map(N=>N.info.id),f=new Map(d.messages),p=new Map(d.sessionMemoryState);f.delete(l),p.delete(l);const g={messages:f,sessionMemoryState:p},w=new Map(d.pendingAssistantParts);let h=!1;w.forEach((N,v)=>{N.sessionId===l&&(w.delete(v),h=!0)}),h&&(g.pendingAssistantParts=w);const j=new Map(d.sessionCompactionUntil);j.delete(l)&&(g.sessionCompactionUntil=j),Lr(m);const x=Rn(d.messageStreamStates,m);x!==d.messageStreamStates&&(g.messageStreamStates=x);const y=yo(g.messageSessionIndex??d.messageSessionIndex,m);y!==(g.messageSessionIndex??d.messageSessionIndex)&&(g.messageSessionIndex=y);const b=Ys(d.streamingMessageIds,l,null);if(b!==d.streamingMessageIds&&(g.streamingMessageIds=b),d.abortControllers.has(l)){const N=new Map(d.abortControllers);N.delete(l),g.abortControllers=N}return g})},loadMoreMessages:async(t,n="up")=>{const o=r(),a=o.messages.get(t),i=o.sessionMemoryState.get(t);if(!a||!i||i.totalAvailableMessages&&a.length>=i.totalAvailableMessages)return;const l=await qa(t,()=>je.getSessionMessages(t));if(n==="up"&&a.length>0){const d=a[0],u=l.findIndex(m=>m.info.id===d.info.id);if(u>0){const m=Math.min(us.VIEWPORT_MESSAGES,u),f=l.slice(u-m,u);s(p=>{const g=[...f,...a],w=Ga(g),h=new Map(p.messages);h.set(t,w);const j=Math.max(0,w.length-a.length),x=new Map(p.sessionMemoryState);return x.set(t,{...i,viewportAnchor:i.viewportAnchor+j,hasMoreAbove:u-m>0,totalAvailableMessages:l.length}),{messages:h,sessionMemoryState:x}})}else u===0&&s(m=>{const f=new Map(m.sessionMemoryState);return f.set(t,{...i,hasMoreAbove:!1}),{sessionMemoryState:f}})}},getLastMessageModel:t=>{const{messages:n}=r(),o=n.get(t);if(!o||o.length===0)return null;for(let a=o.length-1;a>=0;a--){const i=o[a];if(i.info.role==="assistant"&&"providerID"in i.info&&"modelID"in i.info)return{providerID:i.info.providerID,modelID:i.info.modelID}}return null}}),{name:"message-store",storage:Es(()=>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"})),ny=s=>typeof s=="object"&&s!==null,oy=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},ay=async(s,r)=>{try{const n=lt.getState().getDirectoryForSession(s);if(n)return je.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for permission handling:",t)}return r()},so=zt()(Yt(As((s,r)=>({permissions:new Map,addPermission:(t,n)=>{const o=t.sessionID;if(!o||r().permissions.get(o)?.some(f=>f.id===t.id))return;const i=t.permission?.toLowerCase?.()??null;let l=n?.currentAgentContext?.get(o);if(l||(l=n?.sessionAgentSelections?.get(o)??void 0),!l&&typeof window<"u"){const f=window.__zustand_config_store__;f?.getState&&(l=f.getState().currentAgentName??void 0)}const d=Bo(l),u=n?.getSessionAgentEditMode?.(o,l)??d;if(u==="full"||u==="allow"&&Gx(i)){r().respondToPermission(o,t.id,"once").catch(()=>{});return}s(f=>{const p=f.permissions.get(o)||[],g=new Map(f.permissions);return g.set(o,[...p,t]),{permissions:g}})},respondToPermission:async(t,n,o)=>{await ay(t,()=>je.replyToPermission(n,o)),o==="reject"&&await yt.getState().abortCurrentOperation(t),s(a=>{const l=(a.permissions.get(t)||[]).filter(u=>u.id!==n),d=new Map(a.permissions);return d.set(t,l),{permissions:d}})}}),{name:"permission-store",storage:Es(()=>ds()),partialize:s=>({permissions:Array.from(s.permissions.entries())}),merge:(s,r)=>{if(!ny(s))return r;const t=oy(s.permissions);return{...r,permissions:new Map(t)}}}),{name:"permission-store"})),iy=s=>typeof s=="object"&&s!==null,ly=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},wc=async(s,r)=>{try{const n=lt.getState().getDirectoryForSession(s);if(n)return je.withDirectory(n,r)}catch(t){console.warn("Failed to resolve session directory for question handling:",t)}return r()},xn=zt()(Yt(As((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 i=a.questions.get(n)||[],l=new Map(a.questions);return l.set(n,[...i,t]),{questions:l}})},dismissQuestion:(t,n)=>{!t||!n||s(o=>{const i=(o.questions.get(t)||[]).filter(d=>d.id!==n),l=new Map(o.questions);return l.set(t,i),{questions:l}})},respondToQuestion:async(t,n,o)=>{await wc(t,()=>je.replyToQuestion(n,o)),r().dismissQuestion(t,n)},rejectQuestion:async(t,n)=>{await wc(t,()=>je.rejectQuestion(n)),r().dismissQuestion(t,n)}}),{name:"question-store",storage:Es(()=>ds()),partialize:s=>({questions:Array.from(s.questions.entries())}),merge:(s,r)=>{if(!iy(s))return r;const t=ly(s.questions);return{...r,questions:new Map(t)}}}),{name:"question-store"})),ul=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},vc=(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},ue=zt()(Yt((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)=>St.getState().getSessionAgentEditMode(t,n,o),toggleSessionAgentEditMode:(t,n,o)=>St.getState().toggleSessionAgentEditMode(t,n,o),setSessionAgentEditMode:(t,n,o,a)=>St.getState().setSessionAgentEditMode(t,n,o,a),loadSessions:()=>lt.getState().loadSessions(),openNewSessionDraft:t=>{let n=null;t?.directoryOverride!==void 0?n=t.directoryOverride:n=Ft.getState().getActiveProject()?.path??null,s({newSessionDraft:{open:!0,directoryOverride:n,parentID:t?.parentID??null,title:t?.title},currentSessionId:null,error:null});try{const o=rt.getState(),a=o.getVisibleAgents();let i;if(o.settingsDefaultAgent){const l=a.find(d=>d.name===o.settingsDefaultAgent);l&&(i=l.name)}i||(i=a.find(l=>l.name==="build")?.name||a[0]?.name),i&&o.setAgent(i)}catch{}},closeNewSessionDraft:()=>{const t=lt.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 lt.getState().createSession(t,n,o);return a?.id&&await r().setCurrentSession(a.id),a},createSessionFromAssistantMessage:async t=>{if(!t)return;const n=yt.getState(),{messages:o,lastUsedProvider:a}=n;let i,l;if(o.forEach((x,y)=>{const b=x.find(N=>N.info?.id===t);b&&!i&&(i=b,l=y)}),!i||i.info.role!=="assistant")return;const d=ul(i.parts);if(!d.trim())return;const u=lt.getState(),m=vc(u.sessions,l??null,u.getWorktreeMetadata),f=await r().createSession(void 0,m??null,null);if(!f)return;const{currentProviderId:p,currentModelId:g,currentAgentName:w}=rt.getState(),h=p||a?.providerID,j=g||a?.modelID;!h||!j||await je.sendMessage({id:f.id,providerID:h,modelID:j,text:d,prefaceText:rm,agent:w??void 0})},deleteSession:(t,n)=>lt.getState().deleteSession(t,n),deleteSessions:(t,n)=>lt.getState().deleteSessions(t,n),updateSessionTitle:(t,n)=>lt.getState().updateSessionTitle(t,n),shareSession:t=>lt.getState().shareSession(t),unshareSession:t=>lt.getState().unshareSession(t),setCurrentSession:async t=>{t&&r().closeNewSessionDraft();const n=lt.getState().currentSessionId,o=vc(lt.getState().sessions,t,lt.getState().getWorktreeMetadata),a=je.getDirectory()??mt.getState().currentDirectory??null,i=o??a;try{je.setDirectory(i??void 0)}catch(l){console.warn("Failed to set OpenCode directory for session switch:",l)}if(n&&n!==t&&!r().sessionMemoryState.get(n)?.isStreaming){const d=r().messages.get(n)||[];d.length>0&&r().updateViewportAnchor(n,d.length-1),r().trimToViewportWindow(n,us.VIEWPORT_MESSAGES)}lt.getState().setCurrentSession(t),t&&(r().messages.get(t)||await r().loadMessages(t),r().trimToViewportWindow(t,fx)),r().evictLeastRecentlyUsed()},loadMessages:t=>yt.getState().loadMessages(t),sendMessage:async(t,n,o,a,i,l,d,u)=>{const m=r().newSessionDraft,f=typeof a=="string"&&a.trim().length>0?a.trim():void 0,p=y=>{s(b=>{const N=new Map(b.sessionActivityPhase??new Map);return N.set(y,"busy"),{sessionActivityPhase:N}})},g=y=>{s(b=>{const N=new Map(b.sessionActivityPhase??new Map);return N.set(y,"idle"),{sessionActivityPhase:N}})};if(m?.open){const y=await lt.getState().createSession(m.title,m.directoryOverride??null,m.parentID??null);if(!y?.id)throw new Error("Failed to create session");const b=rt.getState(),N=b.currentAgentName,v=f??N,k=b.currentProviderId,D=b.currentModelId;if(k&&D)try{St.getState().saveSessionModelSelection(y.id,k,D)}catch{}if(v){try{St.getState().saveSessionAgentSelection(y.id,v)}catch{}if(k&&D){try{St.getState().saveAgentModelForSession(y.id,v,k,D)}catch{}if(u!==void 0)try{St.getState().saveAgentModelVariantForSession(y.id,v,k,D,u)}catch{}}}try{lt.getState().initializeNewOpenChamberSession(y.id,b.agents)}catch{}r().closeNewSessionDraft(),p(y.id);try{return await yt.getState().sendMessage(t,n,o,v,y.id,i,l,d,u)}catch(C){throw g(y.id),C}}const w=lt.getState().currentSessionId,h=w?St.getState().getSessionAgentSelection(w):null,j=rt.getState().currentAgentName,x=f||h||j||void 0;if(w&&x){try{St.getState().saveSessionAgentSelection(w,x)}catch{}if(u!==void 0)try{St.getState().saveAgentModelVariantForSession(w,x,n,o,u)}catch{}}w&&p(w);try{return await yt.getState().sendMessage(t,n,o,x,w||void 0,i,l,d,u)}catch(y){throw w&&g(w),y}},abortCurrentOperation:()=>{const t=lt.getState().currentSessionId;return yt.getState().abortCurrentOperation(t||void 0)},armAbortPrompt:(t=3e3)=>{const n=lt.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&&yt.getState().acknowledgeSessionAbort(t)},addStreamingPart:(t,n,o,a)=>{const l=lt.getState().currentSessionId||t;return yt.getState().addStreamingPart(t,n,o,a,l)},completeStreamingMessage:(t,n)=>yt.getState().completeStreamingMessage(t,n),markMessageStreamSettled:t=>yt.getState().markMessageStreamSettled(t),updateMessageInfo:(t,n,o)=>yt.getState().updateMessageInfo(t,n,o),updateSessionCompaction:(t,n)=>yt.getState().updateSessionCompaction(t,n??null),addPermission:t=>{const n={currentAgentContext:St.getState().currentAgentContext,sessionAgentSelections:St.getState().sessionAgentSelections,getSessionAgentEditMode:St.getState().getSessionAgentEditMode};return so.getState().addPermission(t,n)},respondToPermission:(t,n,o)=>so.getState().respondToPermission(t,n,o),addQuestion:t=>xn.getState().addQuestion(t),dismissQuestion:(t,n)=>xn.getState().dismissQuestion(t,n),respondToQuestion:(t,n,o)=>xn.getState().respondToQuestion(t,n,o),rejectQuestion:(t,n)=>xn.getState().rejectQuestion(t,n),clearError:()=>lt.getState().clearError(),getSessionsByDirectory:t=>lt.getState().getSessionsByDirectory(t),getDirectoryForSession:t=>lt.getState().getDirectoryForSession(t),getLastMessageModel:t=>yt.getState().getLastMessageModel(t),getCurrentAgent:t=>St.getState().getCurrentAgent(t),syncMessages:(t,n)=>yt.getState().syncMessages(t,n),applySessionMetadata:(t,n)=>lt.getState().applySessionMetadata(t,n),addAttachedFile:t=>er.getState().addAttachedFile(t),addServerFile:(t,n,o)=>er.getState().addServerFile(t,n,o),removeAttachedFile:t=>er.getState().removeAttachedFile(t),clearAttachedFiles:()=>er.getState().clearAttachedFiles(),updateViewportAnchor:(t,n)=>yt.getState().updateViewportAnchor(t,n),updateActiveTurnAnchor:(t,n,o)=>yt.getState().updateActiveTurnAnchor(t,n,o),getActiveTurnAnchor:t=>yt.getState().getActiveTurnAnchor(t),trimToViewportWindow:(t,n)=>{const o=lt.getState().currentSessionId;return yt.getState().trimToViewportWindow(t,n,o||void 0)},evictLeastRecentlyUsed:()=>{const t=lt.getState().currentSessionId;return yt.getState().evictLeastRecentlyUsed(t||void 0)},loadMoreMessages:(t,n)=>yt.getState().loadMoreMessages(t,n),saveSessionModelSelection:(t,n,o)=>St.getState().saveSessionModelSelection(t,n,o),getSessionModelSelection:t=>St.getState().getSessionModelSelection(t),saveSessionAgentSelection:(t,n)=>St.getState().saveSessionAgentSelection(t,n),getSessionAgentSelection:t=>St.getState().getSessionAgentSelection(t),saveAgentModelForSession:(t,n,o,a)=>St.getState().saveAgentModelForSession(t,n,o,a),getAgentModelForSession:(t,n)=>St.getState().getAgentModelForSession(t,n),saveAgentModelVariantForSession:(t,n,o,a,i)=>St.getState().saveAgentModelVariantForSession(t,n,o,a,i),getAgentModelVariantForSession:(t,n,o,a)=>St.getState().getAgentModelVariantForSession(t,n,o,a),analyzeAndSaveExternalSessionChoices:(t,n)=>{const o=yt.getState().messages;return St.getState().analyzeAndSaveExternalSessionChoices(t,n,o)},isOpenChamberCreatedSession:t=>lt.getState().isOpenChamberCreatedSession(t),markSessionAsOpenChamberCreated:t=>lt.getState().markSessionAsOpenChamberCreated(t),initializeNewOpenChamberSession:(t,n)=>lt.getState().initializeNewOpenChamberSession(t,n),setWorktreeMetadata:(t,n)=>lt.getState().setWorktreeMetadata(t,n),setSessionDirectory:(t,n)=>lt.getState().setSessionDirectory(t,n),getWorktreeMetadata:t=>lt.getState().getWorktreeMetadata(t),getContextUsage:(t,n)=>{if(r().newSessionDraft?.open)return null;const o=lt.getState().currentSessionId;if(!o)return null;const a=yt.getState().messages;return St.getState().getContextUsage(o,t,n,a)},updateSessionContextUsage:(t,n,o)=>{const a=yt.getState().messages;return St.getState().updateSessionContextUsage(t,n,o,a)},initializeSessionContextUsage:(t,n,o)=>{const a=yt.getState().messages;return St.getState().initializeSessionContextUsage(t,n,o,a)},debugSessionMessages:async t=>{const n=yt.getState().messages.get(t)||[],o=lt.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=yt.getState().messages;return St.getState().pollForTokenUpdates(t,n,a,o)},updateSession:t=>lt.getState().updateSession(t),removeSessionFromStore:t=>lt.getState().removeSessionFromStore(t),revertToMessage:async(t,n)=>{const a=(yt.getState().messages.get(t)||[]).find(m=>m.info.id===n);let i="";a&&a.info.role==="user"&&(i=a.parts.filter(f=>f.type==="text").map(f=>{const p=f;return p.text||p.content||""}).join(`
11
- `).trim());const l=await je.revertSession(t,n);lt.getState().updateSession(l);const d=yt.getState().messages.get(t)||[],u=l.revert?.messageID;if(u){const m=d.findIndex(f=>f.info.id===u);if(m!==-1){const f=d.slice(0,m);yt.getState().syncMessages(t,f)}}i&&s({pendingInputText:i})},handleSlashUndo:async t=>{const o=(r().messages.get(t)||[]).filter(p=>p.info.role==="user"),i=r().sessions.find(p=>p.id===t);if(o.length===0)return;const l=i?.revert?.messageID;let d;if(l){const p=o.findIndex(g=>g.info.id===l);d=o[p+1]}else d=o[o.length-1];if(!d)return;const u=d.parts.find(p=>p.type==="text"),m=typeof u=="object"&&u&&"text"in u?String(u.text).slice(0,50)+(String(u.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,d.info.id);const{toast:f}=await as(async()=>{const{toast:p}=await import("./vendor-.bun-94fMDU1C.js").then(g=>g.cv);return{toast:p}},__vite__mapDeps([0,1]));f.success(`Undid to: ${m}`)},handleSlashRedo:async t=>{const a=r().sessions.find(m=>m.id===t)?.revert?.messageID;if(!a)return;const l=(r().messages.get(t)||[]).filter(m=>m.info.role==="user"),d=l.findIndex(m=>m.info.id===a),u=l[d-1];if(u){const m=u.parts.find(g=>g.type==="text"),f=typeof m=="object"&&m&&"text"in m?String(m.text).slice(0,50)+(String(m.text).length>50?"...":""):"[No text]";await r().revertToMessage(t,u.info.id);const{toast:p}=await as(async()=>{const{toast:g}=await import("./vendor-.bun-94fMDU1C.js").then(w=>w.cv);return{toast:g}},__vite__mapDeps([0,1]));p.success(`Redid to: ${f}`)}else{const m=await je.unrevertSession(t);await lt.getState().updateSession(m),await r().loadMessages(t);const{toast:f}=await as(async()=>{const{toast:p}=await import("./vendor-.bun-94fMDU1C.js").then(g=>g.cv);return{toast:p}},__vite__mapDeps([0,1]));f.success("Restored all messages")}},forkFromMessage:async(t,n)=>{const a=r().sessions.find(i=>i.id===t);if(a)try{const i=await je.forkSession(t,n);if(!i||!i.id){const{toast:f}=await as(async()=>{const{toast:p}=await import("./vendor-.bun-94fMDU1C.js").then(g=>g.cv);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-94fMDU1C.js").then(g=>g.cv);return{toast:p}},__vite__mapDeps([0,1]));f.error("Message not found");return}let u="";for(const f of d.parts)f.type==="text"&&!f.synthetic&&!f.ignored&&(u+=f.text||"");r().setCurrentSession(i.id),u&&s({pendingInputText:u}),await r().loadMessages(i.id);const{toast:m}=await as(async()=>{const{toast:f}=await import("./vendor-.bun-94fMDU1C.js").then(p=>p.cv);return{toast:f}},__vite__mapDeps([0,1]));m.success(`Forked from ${a.title}`)}catch(i){console.error("Failed to fork session:",i);const{toast:l}=await as(async()=>{const{toast:d}=await import("./vendor-.bun-94fMDU1C.js").then(u=>u.cv);return{toast:d}},__vite__mapDeps([0,1]));l.error("Failed to fork session")}},setPendingInputText:t=>{s({pendingInputText:t})},consumePendingInputText:()=>{const t=r().pendingInputText;return t!==null&&s({pendingInputText:null}),t}}),{name:"composed-session-store"}));lt.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=ue.getState().newSessionDraft?.open;ue.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})});yt.subscribe((s,r)=>{if(s.messages===r.messages&&s.sessionMemoryState===r.sessionMemoryState&&s.messageStreamStates===r.messageStreamStates&&s.sessionCompactionUntil===r.sessionCompactionUntil&&s.sessionAbortFlags===r.sessionAbortFlags&&s.streamingMessageIds===r.streamingMessageIds&&s.abortControllers===r.abortControllers&&s.lastUsedProvider===r.lastUsedProvider&&s.isSyncing===r.isSyncing)return;const t=new Map;s.messages.forEach((n,o)=>{if(!(!Array.isArray(n)||n.length===0))for(let a=n.length-1;a>=0;a-=1){const i=n[a];if(!i||!i.info)continue;const l=i.info;if(l.role==="user"){const d=l.summary?.title;if(typeof d=="string"){const u=d.trim();if(u.length>0){const m=l.time&&typeof l.time.created=="number"?l.time.created:null;t.set(o,{title:u,createdAt:m});break}}}}}),ue.setState({messages:s.messages,sessionMemoryState:s.sessionMemoryState,messageStreamStates:s.messageStreamStates,sessionCompactionUntil:s.sessionCompactionUntil,sessionAbortFlags:s.sessionAbortFlags,streamingMessageIds:s.streamingMessageIds,abortControllers:s.abortControllers,lastUsedProvider:s.lastUsedProvider,isSyncing:s.isSyncing,userSummaryTitles:t})});er.subscribe((s,r)=>{s.attachedFiles!==r.attachedFiles&&ue.setState({attachedFiles:s.attachedFiles})});St.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||ue.setState({sessionModelSelections:s.sessionModelSelections,sessionAgentSelections:s.sessionAgentSelections,sessionAgentModelSelections:s.sessionAgentModelSelections,currentAgentContext:s.currentAgentContext,sessionContextUsage:s.sessionContextUsage,sessionAgentEditModes:s.sessionAgentEditModes})});so.subscribe((s,r)=>{s.permissions!==r.permissions&&ue.setState({permissions:s.permissions})});xn.subscribe((s,r)=>{s.questions!==r.questions&&ue.setState({questions:s.questions})});mt.subscribe((s,r)=>{const t=qn(s.currentDirectory??null),n=qn(r.currentDirectory??null);if(t===n)return;const o=ue.getState().newSessionDraft;if(!o?.open)return;const a=qn(o.directoryOverride);a&&a!==n||ue.setState(i=>({newSessionDraft:{...i.newSessionDraft,directoryOverride:t,parentID:null}}))});const cy=ue.getState().newSessionDraft?.open;ue.setState({sessions:lt.getState().sessions,currentSessionId:cy?null:lt.getState().currentSessionId,lastLoadedDirectory:lt.getState().lastLoadedDirectory,isLoading:lt.getState().isLoading,error:lt.getState().error,webUICreatedSessions:lt.getState().webUICreatedSessions,worktreeMetadata:lt.getState().worktreeMetadata,availableWorktrees:lt.getState().availableWorktrees,availableWorktreesByProject:lt.getState().availableWorktreesByProject,messages:yt.getState().messages,sessionMemoryState:yt.getState().sessionMemoryState,messageStreamStates:yt.getState().messageStreamStates,sessionCompactionUntil:yt.getState().sessionCompactionUntil,sessionAbortFlags:yt.getState().sessionAbortFlags,streamingMessageIds:yt.getState().streamingMessageIds,abortControllers:yt.getState().abortControllers,lastUsedProvider:yt.getState().lastUsedProvider,isSyncing:yt.getState().isSyncing,permissions:so.getState().permissions,questions:xn.getState().questions,attachedFiles:er.getState().attachedFiles,sessionModelSelections:St.getState().sessionModelSelections,sessionAgentSelections:St.getState().sessionAgentSelections,sessionAgentModelSelections:St.getState().sessionAgentModelSelections,currentAgentContext:St.getState().currentAgentContext,sessionContextUsage:St.getState().sessionContextUsage,sessionAgentEditModes:St.getState().sessionAgentEditModes,abortPromptSessionId:null,abortPromptExpiresAt:null});typeof window<"u"&&(window.__zustand_session_store__=ue);const ml=({containerRef:s,minThumbSize:r=32,hideDelayMs:t=1e3,className:n,disableHorizontal:o=!1})=>{const[a,i]=c.useState(!1),[l,d]=c.useState({length:0,offset:0}),[u,m]=c.useState({length:0,offset:0}),f=c.useRef(null),p=c.useRef(null),g=c.useRef(!1),w=c.useRef({pointerX:0,pointerY:0,scrollTop:0,scrollLeft:0}),h=c.useRef(null),j=c.useCallback(()=>{const M=s.current;if(!M)return;const{scrollHeight:S,clientHeight:A,scrollTop:I,scrollWidth:_,clientWidth:T,scrollLeft:P}=M,L=8;if(S>A){const Z=Math.max(A-L*2,0),q=A/S*Z,$=Math.max(r,Math.min(Z,q)),H=Math.max(Z-$,0),U=Math.max(S-A,1),K=I/U*H;d({length:$,offset:K})}else d({length:0,offset:0});if(!o&&_>T){const Z=Math.max(T-L*2,0),q=T/_*Z,$=Math.max(r,Math.min(Z,q)),H=Math.max(Z-$,0),U=Math.max(_-T,1),K=P/U*H;m({length:$,offset:K})}else m({length:0,offset:0})},[s,r,o]),x=c.useCallback(()=>{f.current&&clearTimeout(f.current),f.current=setTimeout(()=>i(!1),t)},[t]),y=c.useCallback(()=>{p.current&&cancelAnimationFrame(p.current),p.current=requestAnimationFrame(()=>{j(),i(!0),x()})},[x,j]);c.useEffect(()=>{const M=s.current;if(!M)return;j(),i(!0),x(),M.addEventListener("scroll",y,{passive:!0});const S=typeof ResizeObserver<"u"?new ResizeObserver(()=>j()):null;S?.observe(M);const A=typeof MutationObserver<"u"?new MutationObserver(()=>j()):null;return A?.observe(M,{childList:!0,subtree:!0,characterData:!0}),()=>{M.removeEventListener("scroll",y),S?.disconnect(),A?.disconnect(),f.current&&clearTimeout(f.current),p.current&&cancelAnimationFrame(p.current)}},[s,y,x,j]);const b=(M,S)=>{const A=s.current;A&&(g.current=!0,w.current={pointerX:M.clientX,pointerY:M.clientY,scrollTop:A.scrollTop,scrollLeft:A.scrollLeft},h.current=S,i(!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 A=h.current;if(A==="vertical"){const{pointerY:I,scrollTop:_}=w.current,T=M.clientY-I,P=S.clientHeight,L=Math.max(P-l.length,1),Z=Math.max(S.scrollHeight-S.clientHeight,1),q=T/L*Z;S.scrollTop=_+q}else if(A==="horizontal"){const{pointerX:I,scrollLeft:_}=w.current,T=M.clientX-I,P=S.clientWidth,L=Math.max(P-u.length,1),Z=Math.max(S.scrollWidth-S.clientWidth,1),q=T/L*Z;S.scrollLeft=_+q}},v=M=>{g.current&&(g.current=!1,M.currentTarget.releasePointerCapture(M.pointerId),x())},k=l.length>0,D=u.length>0;if(!k&&!D)return null;const C=8;return e.jsxs("div",{className:R("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:`${l.length}px`,top:`${C+l.offset}px`,right:`${C/2}px`},onPointerDown:M=>b(M,"vertical"),onPointerMove:N,onPointerUp:v,onPointerCancel:v}),D&&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=>b(M,"horizontal"),onPointerMove:N,onPointerUp:v,onPointerCancel:v})]})},ft=c.forwardRef(({className:s,outerClassName:r,children:t,style:n,minThumbSize:o,hideDelayMs:a,as:i="div",scrollbarClassName:l,disableHorizontal:d=!1,fillContainer:u=!0,keyboardAvoid:m=!1,...f},p)=>{const g=c.useRef(null);return c.useImperativeHandle(p,()=>g.current,[]),e.jsxs("div",{className:R("relative flex flex-col min-h-0 w-full overflow-hidden overscroll-none",r),"data-keyboard-avoid":m?"true":void 0,children:[e.jsx(i,{ref:g,className:R("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(ml,{containerRef:g,minThumbSize:o,hideDelayMs:a,className:l,disableHorizontal:d})]})});ft.displayName="ScrollableOverlay";const jc="mobile-overlay-root",dy=()=>{if(typeof document>"u")return null;let s=document.getElementById(jc);return s||(s=document.createElement("div"),s.id=jc,document.body.appendChild(s)),s},vs=({open:s,title:r,onClose:t,children:n,footer:o,className:a,contentMaxHeightClassName:i,renderHeader:l})=>{const d=c.useRef(null);if(typeof document<"u"&&!d.current&&(d.current=dy()),c.useEffect(()=>{if(!s)return;const f=document.body.style.overflow;document.body.style.overflow="hidden";const p=g=>{g.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>{document.body.style.overflow=f,document.removeEventListener("keydown",p)}},[s,t]),!s||!d.current)return null;const u=i??"max-h-[min(70vh,520px)]",m=e.jsx("div",{className:"fixed inset-0 z-50 flex flex-col bg-background/40 backdrop-blur-sm",role:"dialog","aria-modal":"true",onClick:t,children:e.jsxs("div",{className:R("mt-auto w-full rounded-t-xl border border-border/50 bg-background shadow-none pwa-overlay-panel","mx-auto max-w-lg",a),"data-keyboard-avoid":"true",onClick:f=>f.stopPropagation(),children:[(()=>{const f=e.jsx("button",{type:"button",onClick:t,className:"flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:bg-accent",children:e.jsx(Ht,{className:"h-4 w-4"})});return l?l(f):e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b border-border/40",children:[e.jsx("h2",{className:"typography-ui-label font-semibold text-foreground",children:r}),f]})})(),e.jsx(ft,{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 Bf.createPortal(m,d.current)},Pi=({totalTokens:s,percentage:r,contextLimit:t,outputLimit:n,size:o="default",isMobile:a=!1})=>{const[i,l]=c.useState(!1),d=c.useRef(void 0),u=j=>j>=1e6?`${(j/1e6).toFixed(1)}M`:j>=1e3?`${(j/1e3).toFixed(1)}K`:j.toFixed(1).replace(/\.0$/,""),m=j=>j>=90?"text-status-error":j>=75?"text-status-warning":"text-status-success",f=typeof n=="number"?Math.max(n,0):0,p=[`Used tokens: ${u(s)}`,`Context limit: ${u(t)}`,`Output limit: ${u(f)}`],g=c.useCallback(()=>{d.current&&clearTimeout(d.current),d.current=setTimeout(()=>{l(!0)},500)},[]),w=c.useCallback(()=>{d.current&&clearTimeout(d.current)},[]);c.useEffect(()=>()=>{d.current&&clearTimeout(d.current)},[]);const h=e.jsxs("div",{className:R("app-region-no-drag flex items-center gap-1.5 text-muted-foreground/60 select-none",o==="compact"?"typography-micro":"typography-meta"),"aria-label":"Context usage",onTouchStart:a?g:void 0,onTouchEnd:a?w:void 0,children:[e.jsx(zf,{className:"h-4 w-4 flex-shrink-0"}),e.jsxs("span",{className:R(m(r),"font-medium"),children:[Math.min(r,999).toFixed(1),"%"]})]});return a?e.jsxs(e.Fragment,{children:[h,e.jsx(vs,{open:i,onClose:()=>l(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(s)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:u(f)})]}),e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:R("typography-meta font-semibold",m(r)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:h}),e.jsx(nt,{children:e.jsx("div",{className:"space-y-0.5",children:p.map(j=>e.jsx("p",{className:"typography-micro leading-tight",children:j},j))})})]})},$n={xs:0,sm:640,md:768,lg:1024,xl:1280,"2xl":1536},om=(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 Ka(){const s=window.innerWidth,r=typeof window.matchMedia=="function",t=r?window.matchMedia("(pointer: coarse)"):null,n=r?window.matchMedia("(hover: none)"):null,o=t?.matches??!1,a=n?.matches??!1,i=typeof navigator<"u"?navigator.maxTouchPoints??0:0,l=typeof window<"u"&&typeof window.opencodeDesktop<"u",d=o||a||i>0,u=s>$n.md&&s<=$n.lg,m=s<=$n.md;let f=d&&m,p=d&&!f&&u,g=!d||s>$n.lg,w="desktop";l?(f=!1,p=!1,g=!0,w="desktop"):f?w="mobile":p?w="tablet":(g=!0,w="desktop"),om(l,w,d);let h="xs";for(const[j,x]of Object.entries($n))s>=x&&(h=j);return{isMobile:f,isTablet:p,isDesktop:g,deviceType:w,screenWidth:s,breakpoint:h,hasTouchInput:d}}function _t(){const[s,r]=c.useState(()=>typeof window>"u"?{isMobile:!1,isTablet:!1,isDesktop:!0,deviceType:"desktop",screenWidth:1024,breakpoint:"lg",hasTouchInput:!1}:Ka());return c.useEffect(()=>{if(typeof window>"u")return;const t=()=>{r(Ka())};return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)},[]),c.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const t=window.matchMedia("(pointer: coarse)"),n=window.matchMedia("(hover: none)"),o=()=>{r(Ka())},a=[],i=l=>{l&&(typeof l.addEventListener=="function"?(l.addEventListener("change",o),a.push(()=>l.removeEventListener("change",o))):typeof l.addListener=="function"&&(l.addListener(o),a.push(()=>l.removeListener(o))))};return i(t),i(n),()=>{a.forEach(l=>l())}},[]),c.useEffect(()=>{if(typeof window>"u")return;const t=typeof window.opencodeDesktop<"u",n=typeof window.matchMedia=="function",o=n?window.matchMedia("(pointer: coarse)"):null,a=n?window.matchMedia("(hover: none)"):null,i=o?.matches??!1,l=a?.matches??!1,d=typeof navigator<"u"?navigator.maxTouchPoints??0:0,u=i||l||d>0;om(t,s.deviceType,u)},[s.deviceType,s.hasTouchInput]),s}const bo=5e3,uy=1e4,my=5e3,fy=1e4,py=25,hy=4,Sc=15e3,Qs=()=>({isGitRepo:null,status:null,branches:null,log:null,identity:null,diffCache:new Map,lastStatusFetch:0,lastStatusChange:0,lastLogFetch:0,logMaxCount:25}),gy=(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},xy=(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!!gy(s.diffStats,r.diffStats)},yy=(s,r)=>{const t=new Set;if(!r)return t;const n=s?.files??[],o=r.files??[],a=new Map(n.map(f=>[f.path,f])),i=new Map(o.map(f=>[f.path,f])),l=new Set([...a.keys(),...i.keys()]);for(const f of l){const p=a.get(f),g=i.get(f);if(!p||!g){t.add(f);continue}if(p.index!==g.index||p.working_dir!==g.working_dir){t.add(f);continue}}const d=s?.diffStats??{},u=r.diffStats??{},m=new Set([...Object.keys(d),...Object.keys(u)]);for(const f of m){const p=d[f],g=u[f];if(!p||!g){t.add(f);continue}(p.insertions!==g.insertions||p.deletions!==g.deletions)&&t.add(f)}return t},Xt=zt()(Yt((s,r)=>({directories:new Map,activeDirectory:null,isLoadingStatus:!1,isLoadingLog:!1,isLoadingBranches:!1,isLoadingIdentity:!1,pollIntervalId:null,currentPollInterval:bo,setActiveDirectory:t=>{const{activeDirectory:n,directories:o}=r();if(n!==t)if(t&&!o.has(t)){const a=new Map(o);a.set(t,Qs()),s({activeDirectory:t,directories:a})}else s({activeDirectory:t})},getDirectoryState:t=>r().directories.get(t)??null,fetchStatus:async(t,n,o={})=>{const{silent:a=!1}=o,{directories:i}=r();let l=i.get(t);l||(l=Qs()),a||s({isLoadingStatus:!0});let d=!1;try{if(!await n.checkIsGitRepository(t)){const f=new Map(i);return f.set(t,{...l,isGitRepo:!1,status:null,lastStatusFetch:Date.now()}),s({directories:f,isLoadingStatus:!1}),!1}const m=await n.getGitStatus(t);if(xy(l.status,m)){d=!0;const f=new Map(r().directories),p=f.get(t)??Qs(),g=yy(p.status,m),w=new Set((p.status?.files??[]).map(y=>y.path)),h=new Set((m.files??[]).map(y=>y.path)),j=new Map(p.diffCache);for(const y of w)h.has(y)||j.delete(y);for(const y of g)j.delete(y);const x=g.size>0;f.set(t,{...p,isGitRepo:!0,status:m,diffCache:j,lastStatusFetch:Date.now(),lastStatusChange:x?Date.now():p.lastStatusChange}),s({directories:f})}else{const f=new Map(r().directories),p=f.get(t)??Qs();f.set(t,{...p,isGitRepo:!0,lastStatusFetch:Date.now(),lastStatusChange:p.lastStatusChange}),s({directories:f})}}catch(u){console.error("Failed to fetch git status:",u)}finally{a||s({isLoadingStatus:!1})}return d},fetchBranches:async(t,n)=>{s({isLoadingBranches:!0});try{const o=await n.getGitBranches(t),a=new Map(r().directories),i=a.get(t)??Qs();a.set(t,{...i,branches:o}),s({directories:a})}catch(o){console.error("Failed to fetch git branches:",o)}finally{s({isLoadingBranches:!1})}},fetchLog:async(t,n,o)=>{const{directories:a}=r(),i=a.get(t),l=o??i?.logMaxCount??25;s({isLoadingLog:!0});try{const d=await n.getGitLog(t,{maxCount:l}),u=new Map(r().directories),m=u.get(t)??Qs();u.set(t,{...m,log:d,lastLogFetch:Date.now(),logMaxCount:l}),s({directories:u})}catch(d){console.error("Failed to fetch git log:",d)}finally{s({isLoadingLog:!1})}},fetchIdentity:async(t,n)=>{s({isLoadingIdentity:!0});try{const o=await n.getCurrentGitIdentity(t),a=new Map(r().directories),i=a.get(t)??Qs();a.set(t,{...i,identity:o}),s({directories:a})}catch(o){console.error("Failed to fetch git identity:",o)}finally{s({isLoadingIdentity:!1})}},fetchAll:async(t,n,o={})=>{const{directories:a}=r();let i=a.get(t);if(!i){i=Qs();const f=new Map(a);f.set(t,i),s({directories:f})}const{force:l=!1}=o,d=Date.now();await r().fetchStatus(t,n);const u=r().directories.get(t);if(!u?.isGitRepo)return;await r().fetchBranches(t,n);const m=d-(u.lastLogFetch||0);(l||m>fy||!u.log)&&await r().fetchLog(t,n),await r().fetchIdentity(t,n),r().fetchAllDiffs(t,n)},getDiff:(t,n)=>r().directories.get(t)?.diffCache.get(n)??null,setDiff:(t,n,o)=>{const a=new Map(r().directories),i=a.get(t)??Qs(),l=new Map(i.diffCache);l.set(n,{...o,fetchedAt:Date.now()}),a.set(t,{...i,diffCache:l}),s({directories:a})},clearDiffCache:t=>{const n=new Map(r().directories),o=n.get(t);o&&(n.set(t,{...o,diffCache:new Map}),s({directories:n}))},fetchAllDiffs:async(t,n)=>{const o=r().directories.get(t);if(!o?.status?.files||o.status.files.length===0)return;const l=o.status.files.filter(y=>!o.diffCache.has(y.path)).slice(0,py);if(l.length===0)return;let d=0;const u=[],m=()=>{const y=d;return d+=1,y<l.length?l[y]:null},f=async y=>{const b=n.getGitFileDiff(t,{path:y}),N=new Promise((k,D)=>{setTimeout(()=>D(new Error(`Timed out after ${Sc}ms`)),Sc)}),v=await Promise.race([b,N]);return{path:y,diff:{original:v.original??"",modified:v.modified??""}}},p=async()=>{for(;;){const y=m();if(!y)return;try{u.push(await f(y.path))}catch{}}},g=Math.min(hy,l.length);await Promise.allSettled(Array.from({length:g},()=>p()));const w=new Map(r().directories),h=w.get(t);if(!h)return;const j=new Map(h.diffCache),x=Date.now();u.forEach(y=>{j.set(y.path,{...y.diff,fetchedAt:x})}),w.set(t,{...h,diffCache:j}),s({directories:w})},setLogMaxCount:(t,n)=>{const o=new Map(r().directories),a=o.get(t)??Qs();o.set(t,{...a,logMaxCount:n}),s({directories:o})},startPolling:t=>{const{pollIntervalId:n}=r();if(n)return;const o=()=>{const{currentPollInterval:a}=r();return setTimeout(async()=>{if(typeof document<"u"&&document.hidden){s({pollIntervalId:o()});return}const{activeDirectory:l}=r();if(!l){s({pollIntervalId:o()});return}if(await r().fetchStatus(l,t,{silent:!0}))await r().fetchLog(l,t),r().fetchAllDiffs(l,t),s({currentPollInterval:bo});else{const m=Math.min(a+my,uy);s({currentPollInterval:m})}const{pollIntervalId:u}=r();u!==null&&s({pollIntervalId:o()})},a)};s({pollIntervalId:o(),currentPollInterval:bo})},stopPolling:()=>{const{pollIntervalId:t}=r();t&&(clearTimeout(t),s({pollIntervalId:null,currentPollInterval:bo}))},refresh:async(t,n={})=>{const{activeDirectory:o}=r();o&&await r().fetchAll(o,t,n)}}),{name:"git-store"})),am=s=>Xt(r=>s?r.directories.get(s)?.status??null:null),im=s=>Xt(r=>s?r.directories.get(s)?.branches??null:null),by=s=>Xt(r=>s?r.directories.get(s)?.log??null:null),wy=s=>Xt(r=>s?r.directories.get(s)?.identity??null:null),fl=s=>Xt(r=>s?r.directories.get(s)?.isGitRepo??null:null),vy=s=>Xt(r=>s?r.directories.get(s)?.status?.files?.length??0:0);function Vt({...s}){return e.jsx(Wf,{"data-slot":"dropdown-menu",...s})}function Gt({...s}){return e.jsx(Hf,{"data-slot":"dropdown-menu-trigger",...s})}function qt({className:s,sideOffset:r=4,...t}){return e.jsx(Uf,{children:e.jsx(Vf,{"data-slot":"dropdown-menu-content",sideOffset:r,className:R("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 Dt({className:s,inset:r,variant:t="default",...n}){return e.jsx(Yf,{"data-slot":"dropdown-menu-item","data-inset":r,"data-variant":t,className:R("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 lm({...s}){return e.jsx(Gf,{"data-slot":"dropdown-menu-radio-group",...s})}function cm({className:s,children:r,...t}){return e.jsxs(qf,{"data-slot":"dropdown-menu-radio-item",className:R("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(Kf,{children:e.jsx(Pt,{className:"size-3"})})}),r]})}function Ur({className:s,inset:r,...t}){return e.jsx(Xf,{"data-slot":"dropdown-menu-label","data-inset":r,className:R("px-2 py-1 typography-ui-label font-medium data-[inset]:pl-8",s),...t})}function Ms({className:s,...r}){return e.jsx(Qf,{"data-slot":"dropdown-menu-separator",className:R("bg-border -mx-1 my-0.5 h-px",s),...r})}const jy={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 pl(s){return jy[s]||{displayName:s.charAt(0).toUpperCase()+s.slice(1).replace(/-/g," "),category:"system",outputLanguage:"text",inputFields:[]}}function Sy(s,r,t){const n=pl(s);if(n.outputLanguage==="auto"){if(t?.filePath||t?.file_path||t?.sourcePath){const o=t.filePath||t.file_path||t.sourcePath,a=nn(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 nn(s){const r=s.split(".").pop()?.toLowerCase();return{js:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",mjs:"javascript",cjs:"javascript",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",jsonc:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",kt:"kotlin",swift:"swift",c:"c",cpp:"cpp",cc:"cpp",h:"c",hpp:"cpp",cs:"csharp",php:"php",dart:"dart",r:"r",lua:"lua",vim:"vim",sh:"bash",bash:"bash",zsh:"bash",fish:"bash",ps1:"powershell",md:"markdown",mdx:"markdown",rst:"text",txt:"text",dockerfile:"dockerfile",makefile:"makefile",gitignore:"text",env:"text",conf:"text",cfg:"text",ini:"ini",sql:"sql",diff:"diff",patch:"diff"}[r||""]||null}const ky=["png","jpg","jpeg","gif","svg","webp","ico","bmp","avif"];function dm(s){const r=s.split(".").pop()?.toLowerCase();return ky.includes(r||"")}function Ny(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 Cy(s,r){if(!s)return"";const t=n=>{const o=s[n];return typeof o=="string"?o:typeof o=="number"?String(o):null};if(r==="bash"){const n=t("command");if(n)return n}if(r==="task"){const n=t("prompt");if(n)return n;const o=t("description");if(o)return o}if((r==="edit"||r==="multiedit")&&typeof s=="object"){const n=t("filePath")||t("file_path")||t("path");if(n)return`File path: ${n}`}if(r==="write"&&typeof s=="object"){const n=t("content");if(n)return n}return typeof s=="object"?Object.entries(s).filter(([,o])=>o!=null&&o!=="").map(([o,a])=>{const i=o.replace(/([A-Z])/g," $1").replace(/_/g," ").toLowerCase().replace(/^./,d=>d.toUpperCase());let l=a;return typeof a=="object"?l=JSON.stringify(a,null,2):typeof a=="boolean"&&(l=a?"Yes":"No"),`${i}: ${l}`}).join(`
12
- `):String(s)}const hl=c.createContext(null),Pn=()=>{const s=c.useContext(hl);if(!s)throw new Error("Runtime APIs are not available. Did you forget to wrap the app in <RuntimeAPIProvider>?");return s},um=s=>{const r=Pn();return s(r)},My=()=>um(s=>s.runtime.isDesktop),mm=()=>um(s=>s.runtime.isVSCode),Dy=Jf("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 Ce({className:s,variant:r,size:t,asChild:n=!1,...o}){const a=n?iu:"button";return e.jsx(a,{"data-slot":"button",className:R(Dy({variant:r,size:t,className:s})),...o})}const Ay=({mode:s,onModeChange:r,className:t})=>{const n=c.useCallback(o=>{o.stopPropagation(),r(s==="side-by-side"?"unified":"side-by-side")},[s,r]);return e.jsx(Ce,{size:"sm",variant:"ghost",className:R("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(Zf,{className:"h-3 w-3"}):e.jsx(ep,{className:"h-3 w-3"})})},gl=De.createContext(void 0);function on(){const s=De.useContext(gl);if(!s)throw new Error("useThemeSystem must be used within a ThemeSystemProvider");return s}function ya(){return De.useContext(gl)}const Ey="Flexoki",Iy="dark",Py={"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"},Ty=[{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"}}],Fy={name:Ey,type:Iy,colors:Py,tokenColors:Ty},Ry="Flexoki",_y="light",Oy={"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"},$y=[{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"}}],Ly={name:Ry,type:_y,colors:Oy,tokenColors:$y},xl="flexoki-dark",yl="flexoki-light",By=Fy,zy=Ly;function fm(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 pm(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 bl=pm(By,xl,"dark"),wl=pm(zy,yl,"light");fm(bl,xl);fm(wl,yl);const Mn={dark:xl,light:yl},kc=[wl,bl];let Nc=!1;function hm(){Nc||($l(Mn.dark,async()=>bl),$l(Mn.light,async()=>wl),Nc=!0)}const Wy=`
13
- :host {
14
- font-family: var(--font-mono);
15
- font-size: var(--text-code);
16
- }
17
-
18
- :host, pre, [data-diffs], [data-code] {
19
- transform: translateZ(0);
20
- -webkit-transform: translateZ(0);
21
- -webkit-backface-visibility: hidden;
22
- backface-visibility: hidden;
23
- }
24
-
25
- pre, [data-code] {
26
- font-family: var(--font-mono);
27
- font-size: var(--text-code);
28
- }
29
-
30
- [data-code] {
31
- -webkit-overflow-scrolling: touch;
32
- }
33
- /* Reduce hunk separator height */
34
- [data-separator-content] {
35
- height: 24px !important;
36
- }
37
- [data-expand-button] {
38
- height: 24px !important;
39
- width: 24px !important;
40
- }
41
- [data-separator-multi-button] {
42
- row-gap: 0 !important;
43
- }
44
- [data-expand-up] {
45
- height: 12px !important;
46
- min-height: 12px !important;
47
- max-height: 12px !important;
48
- margin: 0 !important;
49
- margin-top: 3px !important;
50
- padding: 0 !important;
51
- border-radius: 4px 4px 0 0 !important;
52
- }
53
- [data-expand-down] {
54
- height: 12px !important;
55
- min-height: 12px !important;
56
- max-height: 12px !important;
57
- margin: 0 !important;
58
- margin-top: -3px !important;
59
- padding: 0 !important;
60
- border-radius: 0 0 4px 4px !important;
61
- }
62
- `;function Hy(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 Cc=({original:s,modified:r,language:t,fileName:n="file",renderSideBySide:o,wrapLines:a=!1})=>{const l=ya()?.currentTheme?.metadata?.variant==="dark";hm();const d=De.useRef(null),u=De.useMemo(()=>{const f=Hy(n,s,r);if(d.current?.key===f)return d.current.fileDiff;const p={name:n,contents:s,cacheKey:`old-${f}`},g={name:n,contents:r,cacheKey:`new-${f}`},w=wi(p,g);return d.current={key:f,fileDiff:w},w},[n,s,r,t]),m=De.useMemo(()=>({theme:{dark:Mn.dark,light:Mn.light},themeType:l?"dark":"light",diffStyle:o?"split":"unified",diffIndicators:"none",hunkSeparators:"line-info",lineDiffType:"word-alt",overflow:a?"wrap":"scroll",disableFileHeader:!0,enableLineSelection:!1,enableHoverUtility:!1,unsafeCSS:Wy}),[l,o,a]);return typeof window>"u"?null:e.jsx(ft,{outerClassName:"pierre-diff-wrapper size-full",disableHorizontal:!1,children:e.jsx(tp,{fileDiff:u,options:m})})},Uy=1100,Vy=s=>{const{index:r,working_dir:t}=s;return r==="A"||t==="A"||r==="?"||t==="?"},Mc=(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]})},Gy=c.memo(({changedFiles:s,selectedFile:r,selectedFileEntry:t,onSelectFile:n,isMobile:o})=>{const a=c.useCallback(i=>{if(!o)return i;const l=i.lastIndexOf("/");return l>=0?i.slice(l+1):i},[o]);return s.length===0?null:e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{className:"flex h-8 items-center gap-2 rounded-lg border border-input bg-transparent px-2 typography-ui-label text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring",children:[t?e.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(t.path)}),Mc(t.insertions,t.deletions)]}):e.jsx("span",{className:"text-muted-foreground",children:"Select file"}),e.jsx(It,{className:"size-4 opacity-50"})]})}),e.jsx(qt,{className:"max-h-[70vh] min-w-[320px] overflow-y-auto",children:e.jsx(lm,{value:r??"",onValueChange:n,children:s.map(i=>e.jsx(cm,{value:i.path,children:e.jsxs("div",{className:"flex w-full min-w-0 items-center gap-3",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",children:a(i.path)}),e.jsx("span",{className:"ml-auto",children:Mc(i.insertions,i.deletions)})]})},i.path))})})]})}),qy=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n})=>{const o=r.original.length>0,a=r.modified.length>0;if(!t)return e.jsx("div",{className:"absolute inset-0 hidden"});const i=n?"flex flex-row gap-6 items-start justify-center h-full":"flex flex-col gap-4 items-center",l=n?"flex flex-col items-center gap-2 flex-1 min-w-0 h-full":"flex flex-col items-center gap-2";return e.jsx("div",{className:"absolute inset-0 overflow-auto p-4",style:{contain:"size layout"},children:e.jsxs("div",{className:i,children:[o&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Original"}),e.jsx("img",{src:r.original,alt:`Original: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]}),a&&e.jsxs("div",{className:l,children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:o?"Modified":"New"}),e.jsx("img",{src:r.modified,alt:`Modified: ${s}`,className:n?"max-w-full max-h-[calc(100%-2rem)] object-contain":"max-w-full object-contain",style:{imageRendering:"auto"}})]})]})})}),Ky=c.memo(({filePath:s,diff:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=c.useMemo(()=>nn(s)||"text",[s]);return dm(s)?e.jsx(qy,{filePath:s,diff:r,isVisible:t,renderSideBySide:n}):t?e.jsx("div",{className:"absolute inset-0",style:{contain:"size layout"},children:e.jsx(Cc,{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(Cc,{original:r.original,modified:r.modified,language:a,fileName:s,renderSideBySide:n,wrapLines:o})})}),Yy=c.memo(({directory:s,filePath:r,isVisible:t,renderSideBySide:n,wrapLines:o})=>{const a=Xt(c.useCallback(l=>l.directories.get(s)?.diffCache.get(r)??null,[s,r])),i=c.useMemo(()=>a?{original:a.original,modified:a.modified}:null,[a]);return i?e.jsx(Ky,{filePath:r,diff:i,isVisible:t,renderSideBySide:n,wrapLines:o}):null}),Qy=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ue(),{currentDirectory:n}=mt(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},Xy=()=>{const{git:s}=Pn(),r=Qy(),{screenWidth:t,isMobile:n}=_t(),o=fl(r??null),a=am(r??null),i=Xt($=>$.isLoadingStatus),{setActiveDirectory:l,fetchStatus:d,setDiff:u}=Xt(),[m,f]=c.useState(null),[p,g]=c.useState(0),[w,h]=c.useState(null),j=c.useRef(null),x=_e($=>$.pendingDiffFile),y=_e($=>$.setPendingDiffFile),b=_e($=>$.diffLayoutPreference),N=_e($=>$.diffFileLayout),v=_e($=>$.setDiffFileLayout),k=_e($=>$.diffWrapLines),D=_e($=>$.setDiffWrapLines),C=n||k,M=c.useMemo(()=>{if(!a?.files)return[];const $=a.diffStats??{};return a.files.map(H=>({...H,insertions:$[H.path]?.insertions??0,deletions:$[H.path]?.deletions??0,isNew:Vy(H)})).sort((H,U)=>H.path.localeCompare(U.path))},[a]),S=c.useMemo(()=>m?M.find($=>$.path===m)??null:null,[M,m]),A=c.useMemo(()=>{if(!S)return null;const $=N[S.path];if($)return $;if(b==="inline")return"inline";if(b==="side-by-side")return"side-by-side";const H=t<Uy;return S.isNew||H?"inline":"side-by-side"},[S,N,b,t]);c.useEffect(()=>{r&&(l(r),Xt.getState().directories.get(r)?.status||d(r,s))},[r,l,d,s]),c.useEffect(()=>{x&&(f(x),y(null))},[x,y]),c.useEffect(()=>{!m&&!x&&M.length>0&&f(M[0].path)},[M,m,x]),c.useEffect(()=>{m&&M.length>0&&(M.some(H=>H.path===m)||f(M[0]?.path??null))},[M,m]);const I=c.useCallback($=>{f($)},[]),_=(A??"side-by-side")==="side-by-side",T=Xt(c.useCallback($=>!r||!m?null:$.directories.get(r)?.diffCache.get(m)??null,[r,m])),P=!!T,L=!!m&&!P;c.useEffect(()=>{if(h(null),!r||!m){j.current=null;return}if(T){j.current=null;return}const $=`${r}::${m}::${p}`;if(j.current===$)return;j.current=$;let H=!1;return(async()=>{try{const U=s.getGitFileDiff(r,{path:m}),K=15e3,se=new Promise((re,V)=>{setTimeout(()=>V(new Error(`Timed out after ${K}ms`)),K)}),Y=await Promise.race([U,se]);if(H)return;u(r,m,{original:Y.original??"",modified:Y.modified??""})}catch(U){if(H)return;const K=U instanceof Error?U.message:String(U);h(K)}})(),()=>{H=!0,j.current===$&&(j.current=null)}},[r,m,T,s,u,p]);const Z=()=>!r||M.length===0?null:M.map($=>e.jsx(Yy,{directory:r,filePath:$.path,isVisible:$.path===m,renderSideBySide:_,wrapLines:C},$.path)),q=()=>r?i&&!a?e.jsxs("div",{className:"flex flex-1 items-center justify-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading repository status…"]}):o===!1?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Not a git repository. Use the Git tab to initialize or change directories."}):M.length===0?e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Working tree clean — no changes to display"}):e.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden px-3 py-3 relative",children:[Z(),L&&!P&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center gap-2 text-sm text-muted-foreground",children:w?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),e.jsx("div",{className:"typography-meta text-muted-foreground max-w-[32rem] text-center",children:w}),e.jsx("button",{type:"button",className:"typography-ui-label text-primary hover:underline",onClick:()=>{h(null),g($=>$+1)},children:"Retry"})]}):e.jsxs(e.Fragment,{children:[e.jsx(cs,{size:16,className:"animate-spin"}),"Loading diff…"]})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center text-sm text-muted-foreground",children:"Select a session directory to view diffs"});return e.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-3 px-3 py-2 bg-background",children:[!n&&e.jsxs("div",{className:"flex items-center gap-1 rounded-md px-2 py-1 text-muted-foreground shrink-0",children:[e.jsx(Ki,{size:16}),e.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:i&&!a?"Loading changes…":`${M.length} ${M.length===1?"file":"files"} changed`})]}),e.jsx(Gy,{changedFiles:M,selectedFile:m,selectedFileEntry:S,onSelectFile:I,isMobile:n||t<=768}),e.jsx("div",{className:"flex-1"}),S&&e.jsx("button",{type:"button",onClick:()=>D(!k),className:`flex items-center justify-center size-5 rounded-sm transition-opacity ${C?"text-foreground opacity-100":"text-muted-foreground opacity-60 hover:opacity-100"}`,title:C?"Disable line wrap":"Enable line wrap",children:e.jsx(sp,{className:"size-4"})}),S&&A&&e.jsx(Ay,{mode:A==="side-by-side"?"side-by-side":"unified",onModeChange:$=>{if(!S)return;const H=$==="side-by-side"?"side-by-side":"inline";v(S.path,H)}})]}),q()]})},Jy=()=>{const{git:s}=Pn(),{currentSessionId:r,sessions:t,worktreeMetadata:n}=ue(),{currentDirectory:o}=mt(),a=r?n.get(r)??void 0:void 0,l=t.find(p=>p.id===r)?.directory,d=a?.path??l??o??void 0,{setActiveDirectory:u,fetchStatus:m}=Xt(),f=vy(d??null);return c.useEffect(()=>{d&&(u(d),Xt.getState().directories.get(d)?.status||m(d,s))},[d,u,m,s]),f},sa=De.forwardRef(({className:s,...r},t)=>e.jsx(lu,{className:R("peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",s),...r,ref:t,children:e.jsx(rp,{className:R("pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0")})}));sa.displayName=lu.displayName;const Zy={},zo=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},Dc=s=>zo(s)??"__global__",eb=s=>{const r=Object.entries(s??{}),t=r.filter(([,i])=>i?.status==="connected").length,n=r.length,o=r.some(([,i])=>i?.status==="failed"),a=r.some(([,i])=>i?.status==="needs_auth"||i?.status==="needs_client_registration");return{connected:t,total:n,hasFailed:o,hasAuthRequired:a}},zn=zt()(Yt((s,r)=>({byDirectory:{},loadingKeys:{},lastErrorKeys:{},getStatusForDirectory:t=>{const n=Dc(t??mt.getState().currentDirectory);return r().byDirectory[n]??Zy},refresh:async t=>{const n=zo(t?.directory??mt.getState().currentDirectory),o=Dc(n);t?.silent||s(a=>({loadingKeys:{...a.loadingKeys,[o]:!0},lastErrorKeys:{...a.lastErrorKeys,[o]:null}}));try{const l=(await je.getApiClient().mcp.status(n?{directory:n}:void 0)).data??{};s(d=>({byDirectory:{...d.byDirectory,[o]:l},loadingKeys:{...d.loadingKeys,[o]:!1},lastErrorKeys:{...d.lastErrorKeys,[o]:null}}))}catch(a){const i=a instanceof Error?a.message:"Failed to load MCP status";s(l=>({loadingKeys:{...l.loadingKeys,[o]:!1},lastErrorKeys:{...l.lastErrorKeys,[o]:i}}))}},connect:async(t,n)=>{const o=zo(n??mt.getState().currentDirectory);await je.getApiClient().mcp.connect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})},disconnect:async(t,n)=>{const o=zo(n??mt.getState().currentDirectory);await je.getApiClient().mcp.disconnect({name:t,...o?{directory:o}:{}},{throwOnError:!0}),await r().refresh({directory:o,silent:!0})}})));function tb(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 sb=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}},rb=s=>{switch(s?.status){case"connected":return"success";case"failed":return"error";case"needs_auth":case"needs_client_registration":return"warning";default:return"default"}},Ti=({headerIconButtonClass:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(!1),{isMobile:i}=_t(),d=mt(C=>C.currentDirectory)??null,u=zn(C=>C.getStatusForDirectory(d)),m=zn(C=>C.refresh),f=zn(C=>C.connect),p=zn(C=>C.disconnect),g=c.useCallback(C=>{C||(a.current=!0,o(!1),setTimeout(()=>{a.current=!1},200)),t(C)},[]),w=c.useCallback(C=>{a.current||o(C)},[]),[h,j]=c.useState(!1),[x,y]=c.useState(null);c.useEffect(()=>{m({directory:d,silent:!0})},[m,d]),c.useEffect(()=>{r&&m({directory:d,silent:!0})},[r,m,d]);const b=c.useMemo(()=>eb(u),[u]),N=c.useMemo(()=>Object.keys(u).sort((C,M)=>C.localeCompare(M)),[u]),v=c.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=rb(M),A=M?.status==="connected",I=x===C,_=sb(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:[i?e.jsx("span",{className:R("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":_}):e.jsxs(at,{delayDuration:300,children:[e.jsx(it,{asChild:!0,children:e.jsx("span",{className:R("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":_})}),e.jsx(nt,{side:"left",children:e.jsx("p",{children:_})})]}),e.jsx("span",{className:"typography-ui-label truncate",children:C})]})}),e.jsx(sa,{checked:A,disabled:I,className:"data-[state=checked]:bg-status-info",onCheckedChange:async T=>{y(C);try{T?await f(C,d):await p(C,d)}finally{y(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."})]}),D=e.jsxs("button",{type:"button","aria-label":"MCP servers",className:R(s,"relative"),onClick:i?()=>t(!0):void 0,children:[e.jsx(tb,{className:"h-[1.0625rem] w-[1.0625rem]"}),b.total>0&&e.jsx("span",{className:R("absolute top-1.5 right-1.5 h-1.5 w-1.5 rounded-full",b.hasFailed?"bg-status-error":b.hasAuthRequired?"bg-status-warning":b.connected>0?"bg-status-success":"bg-muted-foreground/40"),"aria-label":"MCP status"})]});return i?e.jsxs(e.Fragment,{children:[D,e.jsxs(vs,{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:v,"aria-label":"Refresh",children:e.jsx(Ar,{className:R("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(Vt,{open:r,onOpenChange:g,children:[e.jsxs(at,{delayDuration:1e3,open:r?!1:n,onOpenChange:w,children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:D})}),e.jsx(nt,{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:v,"aria-label":"Refresh",children:e.jsx(Ar,{className:R("h-4 w-4",h&&"animate-spin")})})]}),e.jsx(Ms,{}),e.jsx("div",{className:"max-h-64 overflow-y-auto py-1",children:k()}),d&&e.jsxs(e.Fragment,{children:[e.jsx(Ms,{}),e.jsx("div",{className:"px-2 py-1",children:e.jsx("span",{className:"typography-meta text-muted-foreground truncate block",children:d.split("/").pop()||d})})]})]})]})},nb=()=>{const s=_e(d=>d.setSessionSwitcherOpen),r=_e(d=>d.toggleSidebar),{isMobile:t}=_t(),[n,o]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),a=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const d=typeof window.opencodeDesktop<"u";o(d)},[]);const i=c.useCallback(()=>{t?s(!0):r()},[t,s,r]),l="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground";return t||!n||!a?null:e.jsx("div",{className:"fixed top-[0.375rem] left-[5.25rem] z-[9999]",style:{pointerEvents:"auto","--padding-scale":"1"},children:e.jsx("button",{type:"button",onClick:i,"aria-label":"Open sessions",className:l,children:e.jsx(da,{className:"h-5 w-5"})})})},Ac=()=>{const s=_e(U=>U.setSessionSwitcherOpen),r=_e(U=>U.toggleSidebar),t=_e(U=>U.setSettingsDialogOpen),n=_e(U=>U.toggleCommandPalette),o=_e(U=>U.toggleHelpDialog),a=_e(U=>U.isSidebarOpen),i=_e(U=>U.sidebarWidth),l=_e(U=>U.activeMainTab),d=_e(U=>U.setActiveMainTab),{getCurrentModel:u}=rt(),m=ue(U=>U.getContextUsage),{isMobile:f}=_t(),p=Jy(),g=ha(U=>U.available),w=c.useRef(null),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);De.useEffect(()=>{if(typeof window>"u")return;const U=typeof window.opencodeDesktop<"u";j(U)},[]);const y=u(),b=y&&typeof y.limit=="object"&&y.limit!==null?y.limit:null,N=b&&typeof b.context=="number"?b.context:0,v=b&&typeof b.output=="number"?b.output:0,k=m(N,v),D=_e(U=>U.isSessionSwitcherOpen),C=c.useCallback(()=>{if(typeof document>"u")return;const U=document.activeElement;if(!U)return;const K=U.tagName;(K==="INPUT"||K==="TEXTAREA"||K==="SELECT"||U.isContentEditable)&&U.blur()},[]),M=c.useCallback(()=>{if(f){C(),s(!D);return}r()},[C,f,D,s,r]),S=c.useCallback(()=>{f&&C(),s(!1),t(!0)},[C,f,s,t]),A="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground",I=c.useMemo(()=>h&&x?a?"pl-0":"pl-[8.0rem]":"pl-3",[h,x,a]),_=c.useCallback(()=>{if(typeof document>"u")return;const U=w.current?.getBoundingClientRect().height;U&&document.documentElement.style.setProperty("--oc-header-height",`${U}px`)},[]);De.useEffect(()=>{if(typeof window>"u")return;_();const U=w.current;if(!U||typeof ResizeObserver>"u")return()=>{};const K=new ResizeObserver(()=>{_()});return K.observe(U),window.addEventListener("resize",_),window.addEventListener("orientationchange",_),()=>{K.disconnect(),window.removeEventListener("resize",_),window.removeEventListener("orientationchange",_)}},[_]),De.useEffect(()=>{_()},[_,f]);const T=c.useCallback(async U=>{if(!U.target.closest("button, a, input, select, textarea")&&U.button===0&&h)try{const{getCurrentWindow:K}=await as(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-94fMDU1C.js").then(re=>re.cw);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await K().startDragging()}catch(K){console.error("Failed to start window dragging:",K)}},[h]),P=c.useCallback(async U=>{if(U.button===0&&h)try{const{getCurrentWindow:K}=await as(async()=>{const{getCurrentWindow:Y}=await import("./vendor-.bun-94fMDU1C.js").then(re=>re.cw);return{getCurrentWindow:Y}},__vite__mapDeps([0,1]));await K().startDragging()}catch(K){console.error("Failed to start window dragging:",K)}},[h]),L=c.useMemo(()=>[{id:"chat",label:"Chat",icon:np},{id:"diff",label:"Diff",icon:nr,badge:!f&&p>0?p:void 0},{id:"terminal",label:"Terminal",icon:Pr},{id:"git",label:"Git",icon:$t,showDot:f&&p>0}],[p,f]);De.useEffect(()=>{const U=K=>{if(Cs(K)&&!K.shiftKey&&!K.altKey){const se=parseInt(K.key,10);se>=1&&se<=L.length&&(K.preventDefault(),d(L[se-1].id))}};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[L,d]);const Z=(U,K)=>{const se=l===U.id,Y=U.icon,re=U.id==="chat",V=U.id==="git";return e.jsxs(c.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>d(U.id),onMouseDown:se?P:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",se?"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",se?"text-foreground":"text-muted-foreground",se&&"after:absolute after:bottom-[-1px] after:left-0 after:right-0 after:h-[2px] after:bg-background",se&&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&&x&&a)&&"border-l",V&&"border-r",re&&!f&&"min-w-[165px] max-[1024px]:min-w-0"),style:{...se&&re&&a?{"--sidebar-w":h&&x?`${i}px`:"64px"}:{},...re&&!(h&&x&&a)||V?{borderColor:"var(--interactive-border)"}:{}},"aria-label":U.label,"aria-selected":se,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:U.label})]}),re&&!f&&k&&k.totalTokens>0&&e.jsx("span",{className:"ml-1",children:e.jsx(Pi,{totalTokens:k.totalTokens,percentage:k.percentage,contextLimit:k.contextLimit,outputLimit:k.outputLimit??0,size:"compact"})}),U.badge!==void 0&&U.badge>0&&e.jsx("span",{className:"text-xs font-semibold text-primary",children:U.badge})]}),!K&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},U.id)},q=()=>e.jsxs("div",{onMouseDown:T,className:R("app-region-drag relative flex h-12 select-none items-center",I),role:"tablist","aria-label":"Main navigation",children:[!(h&&x)&&e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",onClick:M,"aria-label":"Open sessions",className:`${A} mr-2.5`,children:e.jsx(da,{className:"h-5 w-5"})})}),e.jsx("div",{className:"flex h-full items-center",children:L.map((U,K)=>Z(U,K===L.length-1))}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex items-center gap-1 pr-3",children:[e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:n,"aria-label":"Open command palette",className:A,children:e.jsx(en,{className:"h-5 w-5"})})}),e.jsx(nt,{children:e.jsxs("p",{children:["Command Palette (",Jt(),"+K)"]})})]}),e.jsx(Ti,{headerIconButtonClass:A}),e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:o,"aria-label":"Keyboard shortcuts",className:A,children:e.jsx(Qr,{className:"h-5 w-5"})})}),e.jsx(nt,{children:e.jsxs("p",{children:["Keyboard Shortcuts (",Jt(),"+.)"]})})]})]})]}),$=()=>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(op,{className:"h-5 w-5"})}),k&&k.totalTokens>0&&l==="chat"&&e.jsx(Pi,{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:L.map(U=>{const K=l===U.id,se=U.icon;return e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>{f&&C(),d(U.id)},"aria-label":U.label,"aria-selected":K,role:"tab",className:R(A,"relative",K&&"text-foreground"),children:[e.jsx(se,{className:"h-5 w-5"}),U.badge!==void 0&&U.badge>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:U.badge}),U.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(nt,{children:e.jsx("p",{children:U.label})})]},U.id)})}),e.jsx(Ti,{headerIconButtonClass:A}),e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:S,"aria-label":"Open settings",className:R(A,"relative"),children:[e.jsx(Yr,{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(nt,{children:e.jsx("p",{children:g?"Settings (Update available)":"Settings"})})]})]})]}),H=R("header-safe-area border-b relative z-10",h?"bg-background":"bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80");return e.jsx("header",{ref:w,className:H,style:{borderColor:"var(--interactive-border)","--padding-scale":"1"},children:f?$():q()})};function vl({className:s,...r}){return e.jsx("div",{"data-slot":"card",className:R("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-none",s),...r})}function gm({className:s,...r}){return e.jsx("div",{"data-slot":"card-header",className:R("@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 xm({className:s,...r}){return e.jsx("div",{"data-slot":"card-title",className:R("leading-none font-semibold",s),...r})}function ym({className:s,...r}){return e.jsx("div",{"data-slot":"card-content",className:R("px-6",s),...r})}class ls extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?this.props.fallback?this.props.fallback:e.jsx("div",{className:"p-4 flex items-center justify-center min-h-screen",children:e.jsxs(vl,{className:"w-full max-w-md",children:[e.jsx(gm,{className:"text-center",children:e.jsxs(xm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(vi,{className:"h-5 w-5"}),"Something went wrong"]})}),e.jsxs(ym,{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(Ce,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ps,{className:"h-4 w-4 mr-2"}),"Try again"]})})]})]})}):this.props.children}}let wo=0;function ms({...s}){return e.jsx(ap,{"data-slot":"dialog",...s})}function ob({...s}){return e.jsx(cp,{"data-slot":"dialog-portal",...s})}const bm=De.forwardRef(({className:s,...r},t)=>(De.useEffect(()=>(wo+=1,document.documentElement.classList.add("oc-dialog-open"),()=>{wo=Math.max(0,wo-1),wo===0&&document.documentElement.classList.remove("oc-dialog-open")}),[]),e.jsx(cu,{ref:t,"data-slot":"dialog-overlay",className:R("fixed inset-0 z-50 bg-black/50 backdrop-blur-md",s),...r})));bm.displayName=cu.displayName;function fs({className:s,children:r,showCloseButton:t=!0,keyboardAvoid:n=!1,...o}){return e.jsxs(ob,{"data-slot":"dialog-portal",children:[e.jsx(bm,{className:"rounded-none"}),e.jsxs(ip,{"data-slot":"dialog-content","data-keyboard-avoid":n?"true":void 0,className:R("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(lp,{"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:R("flex flex-col gap-2 text-center sm:text-left",s),...r})}function Ks({className:s,...r}){return e.jsx("div",{"data-slot":"dialog-footer",className:R("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(dp,{"data-slot":"dialog-title",className:R("typography-markdown leading-none font-semibold text-foreground",s),...r})}function Ns({className:s,...r}){return e.jsx(up,{"data-slot":"dialog-description",className:R("text-muted-foreground typography-ui-label",s),...r})}const Ec="https://github.com/btriapitsyn/openchamber/releases";async function ab(){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 ib(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 Fi=({open:s,onOpenChange:r,info:t,downloading:n,downloaded:o,progress:a,error:i,onDownload:l,onRestart:d,runtimeType:u="desktop"})=>{const[m,f]=De.useState(!1),[p,g]=De.useState("idle"),[w,h]=De.useState(null),j=t?.version?`${Ec}/tag/v${t.version}`:Ec,x=a?.total?Math.round(a.downloaded/a.total*100):0,y=u==="web",b=t?.updateCommand||"openchamber update";De.useEffect(()=>{s||(g("idle"),h(null))},[s]);const N=async()=>{try{await navigator.clipboard.writeText(b),f(!0),setTimeout(()=>f(!1),2e3)}catch{}},v=De.useCallback(async()=>{g("updating"),h(null);const D=await ab();if(!D.success){g("error"),h(D.error||"Update failed");return}g("restarting"),await new Promise(M=>setTimeout(M,2e3)),g("reconnecting"),await ib()?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})]}),y&&k&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Io,{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(ft,{className:"max-h-48 rounded-md border border-border bg-muted/30 p-3",fillContainer:!1,children:e.jsx("div",{className:"text-sm text-muted-foreground whitespace-pre-wrap pr-3",children:t.body.split(/^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}\s*/gm).filter(Boolean).map((D,C)=>/^\d+\.\d+\.\d+$/.test(D.trim())?e.jsxs("span",{className:"font-semibold text-foreground",children:["v",D.trim(),`
63
- `]},C):D.replace(/^- /gm,"• ").trim()+`
64
-
65
- `)})}),y&&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(fp,{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:b}),e.jsx("button",{onClick:N,className:R("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(Pt,{className:"h-4 w-4"}):e.jsx(pp,{className:"h-4 w-4"})})]})]}),!y&&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:[x,"%"]})]}),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:`${x}%`}})})]}),(i||w)&&e.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:e.jsx("p",{className:"text-sm text-destructive",children:i||w})}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",className:R("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(Go,{className:"h-4 w-4"}),"GitHub"]}),!y&&!o&&!n&&e.jsxs("button",{onClick:l,className:R("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(Er,{className:"h-4 w-4"}),"Download Update"]}),!y&&n&&e.jsxs("button",{disabled:!0,className:R("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(Io,{className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!y&&o&&e.jsxs("button",{onClick:d,className:R("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(Ps,{className:"h-4 w-4"}),"Restart to Update"]}),y&&!k&&e.jsxs("button",{onClick:v,className:R("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(Er,{className:"h-4 w-4"}),"Update Now"]}),y&&k&&e.jsxs("button",{disabled:!0,className:R("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(Io,{className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Ic=264,Pc=200,Tc=500,lb=40,Fc="openchamber:check-for-updates",cb=({isOpen:s,isMobile:r,children:t})=>{const{sidebarWidth:n,setSidebarWidth:o,setSettingsDialogOpen:a,setAboutDialogOpen:i}=_e(),[l,d]=c.useState(!1),u=c.useRef(0),m=c.useRef(n||Ic),[f,p]=c.useState(!1),g=ha(),w=c.useRef(!1),h=g.checkForUpdates,{available:j,downloaded:x,checking:y}=g,[b,N]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),v=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const S=typeof window.opencodeDesktop<"u";N(S)},[]),c.useEffect(()=>{if(typeof window>"u")return;const S=()=>{typeof window.opencodeDesktop<"u"&&(w.current=!0,h())};return window.addEventListener(Fc,S),()=>{window.removeEventListener(Fc,S)}},[h]),c.useEffect(()=>{w.current&&(y||(j||x?p(!0):te.success("No updates available",{description:"You are running the latest version."}),w.current=!1))},[j,x,y]),c.useEffect(()=>{if(r||!l)return;const S=I=>{const _=I.clientX-u.current,T=Math.min(Tc,Math.max(Pc,m.current+_));o(T)},A=()=>{d(!1)};return window.addEventListener("pointermove",S),window.addEventListener("pointerup",A,{once:!0}),()=>{window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",A)}},[r,l,o]),c.useEffect(()=>{r&&l&&d(!1)},[r,l]);const k=c.useCallback(async S=>{if(S.button===0&&b)try{const{getCurrentWindow:A}=await as(async()=>{const{getCurrentWindow:_}=await import("./vendor-.bun-94fMDU1C.js").then(T=>T.cw);return{getCurrentWindow:_}},__vite__mapDeps([0,1]));await A().startDragging()}catch(A){console.error("Failed to start window dragging from sidebar:",A)}},[b]);if(r)return null;const D=s?Math.min(Tc,Math.max(Pc,n||Ic)):0,C=b&&v,M=S=>{s&&(d(!0),u.current=S.clientX,m.current=D,S.preventDefault())};return e.jsxs("aside",{className:R("relative flex h-full overflow-hidden border-r",b?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":"bg-sidebar",l?"transition-none":"",!s&&"border-r-0"),style:{width:`${D}px`,minWidth:`${D}px`,maxWidth:`${D}px`,pointerEvents:s?void 0:"none",borderColor:"var(--interactive-border)",overflowX:"clip"},"aria-hidden":!s||D===0,children:[s&&e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",l?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:M,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:R("relative z-10 flex h-full flex-col transition-opacity duration-200 ease-in-out",!s&&"pointer-events-none select-none opacity-0"),style:{width:`${D}px`,overflowX:"hidden"},"aria-hidden":!s,children:[C&&e.jsx("div",{className:"flex-shrink-0 select-none",style:{height:`${lb}px`},onMouseDown:k,"aria-hidden":!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{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:R("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(Yr,{className:"h-4 w-4"}),e.jsx("span",{children:"Settings"})]}),j||x?e.jsxs("button",{onClick:()=>p(!0),className:R("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(Er,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Update"})]}):!b&&e.jsxs(at,{children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{onClick:()=>i(!0),className:R("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(ss,{className:"h-4 w-4"})})}),e.jsx(nt,{side:"top",children:"About OpenChamber"})]})]})}),e.jsx(Fi,{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 wm({className:s,...r}){return e.jsx(tn,{"data-slot":"command",className:R("bg-background text-foreground flex h-full w-full flex-col overflow-hidden rounded-xl",s),...r})}function db({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(Ns,{children:r})]}),e.jsx(fs,{className:R("overflow-hidden p-0 transform-gpu will-change-transform",n),showCloseButton:o,children:e.jsx(wm,{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 vm({className:s,...r}){return e.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-8 items-center gap-2 border-b px-3",children:[e.jsx(yr,{className:"size-4 shrink-0 opacity-50"}),e.jsx(tn.Input,{"data-slot":"command-input",className:R("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 jm({className:s,children:r,scrollbarClassName:t,disableHorizontal:n,...o}){return e.jsx(ft,{as:tn.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:R("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 Sm({...s}){return e.jsx(tn.Empty,{"data-slot":"command-empty",className:"py-6 text-center typography-ui-label",...s})}function vn({className:s,...r}){return e.jsx(tn.Group,{"data-slot":"command-group",className:R("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 ra({className:s,...r}){return e.jsx(tn.Separator,{"data-slot":"command-separator",className:R("bg-border -mx-1 h-px",s),...r})}function os({className:s,...r}){return e.jsx(tn.Item,{"data-slot":"command-item",className:R("data-[selected=true]:bg-muted hover:bg-muted [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-lg px-2 py-1.5 typography-meta outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",s),...r})}function dr({className:s,...r}){const t=a=>{const i=a.trim().toLowerCase();return i==="ctrl"||i==="control"?e.jsx("span",{className:"text-xs font-medium",children:"ctrl"}):i==="cmd"||i==="⌘"||i==="command"||i==="meta"?e.jsx(en,{className:"size-3.5"}):i==="shift"||i==="⇧"?e.jsx(no,{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:R("text-muted-foreground ml-auto flex items-center gap-1 typography-meta",s),...r,children:o.length>0?o.map((a,i)=>e.jsxs(De.Fragment,{children:[i>0&&e.jsx("span",{className:"opacity-60 text-xs",children:"+"}),t(a)]},`${a}-${i}`)):r.children})}const Rc=["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"],_c=["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 ub(){const s=Rc[Math.floor(Math.random()*Rc.length)],r=_c[Math.floor(Math.random()*_c.length)];return`${s}-${r}`}function Oc(s){const r=ub();return s&&s.trim()?`${s.trim().replace(/\/+$/,"")}/${r}`:r}async function mb(s,r,t=10){let n;try{const o=await ll(s);n=new Set(o?.all??[])}catch{return Oc(r)}for(let o=0;o<t;o++){const a=Oc(r);if(!n.has(a))return a}return null}const fb=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120);let Ya=!1;async function ba(){if(Ya)return null;const s=Ft.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 rn(r)}catch{}if(!t)return te.error("Not a Git repository",{description:"Worktrees can only be created in Git repositories."}),null;Ya=!0,Vs("Creating new worktree session...");try{const n=s.worktreeDefaults,o=n?.branchPrefix,a=n?.baseBranch,i=await mb(r,o);if(!i)return te.error("Failed to generate branch name",{description:"Could not generate a unique branch name. Please try again."}),null;const l=fb(i),u=await Qu({projectDirectory:r,worktreeSlug:l,branch:i,createBranch:!0,startPoint:a&&a!=="HEAD"?a:void 0}),m=await cl(u.path).catch(()=>{}),f=m?{...u,status:m}:u,p=ue.getState(),g=await p.createSession(void 0,u.path);if(!g)return await Rx({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 w=rt.getState(),h=w.agents;p.initializeNewOpenChamberSession(g.id,h),p.setSessionDirectory(g.id,u.path),p.setWorktreeMetadata(g.id,f);try{const y=w.getVisibleAgents();let b;if(w.settingsDefaultAgent){const N=y.find(v=>v.name===w.settingsDefaultAgent);N&&(b=N.name)}if(b||(b=y.find(N=>N.name==="build")?.name||y[0]?.name),b){w.setAgent(b),St.getState().saveSessionAgentSelection(g.id,b);const N=w.settingsDefaultModel;if(N){const v=N.split("/");if(v.length===2){const[k,D]=v;if(w.getModelMetadata(k,D)){St.getState().saveSessionModelSelection(g.id,k,D),St.getState().saveAgentModelForSession(g.id,b,k,D);const M=w.settingsDefaultVariant;if(M){const I=w.providers.find(_=>_.id===k)?.models.find(_=>_.id===D)?.variants;I&&Object.prototype.hasOwnProperty.call(I,M)&&(w.setCurrentVariant(M),St.getState().saveAgentModelVariantForSession(g.id,b,k,D,M))}}}}}}catch{}mt.getState().setDirectory(u.path,{showOverlay:!1});try{await p.loadSessions()}catch{}const x=(await io(r)).filter(y=>y.trim().length>0);return x.length>0?(te.success("Worktree created",{description:`Branch: ${i}. Running ${x.length} setup command${x.length===1?"":"s"}...`}),Ju(u.path,r,x).then(y=>{if(y.success)te.success("Setup commands completed",{description:`All ${y.results.length} command${y.results.length===1?"":"s"} succeeded.`});else{const b=y.results.filter(v=>!v.success),N=y.results.filter(v=>v.success);te.error("Setup commands failed",{description:`${b.length} of ${y.results.length} command${y.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: ${i}`}),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{Ds(),Ya=!1}}const pb=()=>{const{isCommandPaletteOpen:s,setCommandPaletteOpen:r,setHelpDialogOpen:t,setActiveMainTab:n,setSettingsDialogOpen:o,setSessionSwitcherOpen:a,setTimelineDialogOpen:i,toggleSidebar:l}=_e(),{openNewSessionDraft:d,setCurrentSession:u,getSessionsByDirectory:m}=ue(),f=rt(P=>P.settingsAutoCreateWorktree),{currentDirectory:p}=mt(),{themeMode:g,setThemeMode:w}=on(),h=()=>{r(!1)},j=async()=>{n("chat"),a(!1),d(),h()},x=P=>{u(P),h()},y=P=>{w(P),h()},b=()=>{t(!0),h()},N=()=>{h(),ba()},{isMobile:v}=_t(),k=()=>{if(v){const{isSessionSwitcherOpen:P}=_e.getState();a(!P)}else l();h()},D=()=>{n("diff"),h()},C=()=>{n("git"),h()},M=()=>{n("terminal"),h()},S=()=>{o(!0),h()},A=()=>{Vn(),h()},I=()=>{i(!0),h()},_=m(p??""),T=c.useMemo(()=>_.slice(0,5),[_]);return e.jsxs(db,{open:s,onOpenChange:r,children:[e.jsx(vm,{placeholder:"Type a command or search..."}),e.jsxs(jm,{children:[e.jsx(Sm,{children:"No results found."}),e.jsxs(vn,{heading:"Actions",children:[e.jsxs(os,{onSelect:k,children:[e.jsx(da,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Session List"}),e.jsxs(dr,{children:[Jt()," + L"]})]}),e.jsxs(os,{onSelect:j,children:[e.jsx(Kt,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session"}),e.jsx(dr,{children:f?`Shift + ${Jt()} + N`:`${Jt()} + N`})]}),e.jsxs(os,{onSelect:N,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"New Session with Worktree"}),e.jsx(dr,{children:f?`${Jt()} + N`:`Shift + ${Jt()} + N`})]}),e.jsxs(os,{onSelect:b,children:[e.jsx(Qr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Keyboard Shortcuts"}),e.jsxs(dr,{children:[Jt()," + ."]})]}),e.jsxs(os,{onSelect:D,children:[e.jsx(nr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Diff Panel"}),e.jsxs(dr,{children:[Jt()," + 2"]})]}),e.jsxs(os,{onSelect:M,children:[e.jsx(Pr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Terminal"}),e.jsxs(dr,{children:[Jt()," + 3"]})]}),e.jsxs(os,{onSelect:C,children:[e.jsx($t,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Git Panel"}),e.jsxs(dr,{children:[Jt()," + 4"]})]}),e.jsxs(os,{onSelect:I,children:[e.jsx(or,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Timeline"}),e.jsxs(dr,{children:[Jt()," + T"]})]}),e.jsxs(os,{onSelect:S,children:[e.jsx(Yr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Open Settings"}),e.jsxs(dr,{children:[Jt()," + ,"]})]}),e.jsxs(os,{onSelect:A,children:[e.jsx(Ps,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]})]}),e.jsx(ra,{}),e.jsxs(vn,{heading:"Theme",children:[e.jsxs(os,{onSelect:()=>y("light"),children:[e.jsx(hp,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Light Theme"}),g==="light"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(os,{onSelect:()=>y("dark"),children:[e.jsx(gp,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"Dark Theme"}),g==="dark"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]}),e.jsxs(os,{onSelect:()=>y("system"),children:[e.jsx(du,{className:"mr-2 h-4 w-4"}),e.jsx("span",{children:"System Theme"}),g==="system"&&e.jsx(Pt,{className:"ml-auto h-4 w-4"})]})]}),T.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(ra,{}),e.jsx(vn,{heading:"Recent Sessions",children:T.map(P=>e.jsxs(os,{onSelect:()=>x(P.id),children:[e.jsx(Yi,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"truncate",children:P.title||"Untitled Session"})]},P.id))})]})]})]})},hb=(s,r)=>{const t=s.trim().toLowerCase();return t==="ctrl"||t==="control"?e.jsx(ua,{className:"h-3.5 w-3.5"},`ctrl-${r}`):t==="⌘"||t==="cmd"||t==="command"||t==="meta"?e.jsx(en,{className:"h-3.5 w-3.5"},`cmd-${r}`):e.jsx("span",{className:"text-xs font-medium",children:s.trim()},`key-${r}`)},gb=s=>{const r=s.split("+").map(t=>t.trim()).filter(Boolean);return r.length===0?s.trim():r.map((t,n)=>e.jsxs(c.Fragment,{children:[n>0&&e.jsx("span",{className:"text-muted-foreground text-[10px]",children:"+"}),hb(t,n)]},`${t}-${n}`))},xb=()=>{const{isHelpDialogOpen:s,setHelpDialogOpen:r}=_e(),t=rt(a=>a.settingsAutoCreateWorktree),n=Jt(),o=[{category:"Navigation & Commands",items:[{keys:[`${n} + K`],description:"Open Command Palette",icon:en},{keys:[`${n} + .`],description:"Show Keyboard Shortcuts (this dialog)",icon:Qr},{keys:[`${n} + L`],description:"Toggle Session Sidebar",icon:da},{keys:["Shift + Tab"],description:"Cycle Agent (chat input)",icon:Xr},{keys:[`Shift + ${n} + M`],description:"Open Model Selector",icon:uu},{keys:[`Shift + ${n} + T`],description:"Cycle Thinking Variant",icon:ar}]},{category:"Session Management",items:[{keys:[`${n} + N`],description:t?"Create New Session in Worktree":"Create New Session",icon:t?$t:Kt},{keys:[`Shift + ${n} + N`],description:t?"Create New Session":"Create New Session in Worktree",icon:t?Kt:$t},{keys:[`${n} + I`],description:"Focus Chat Input",icon:mu},{keys:["Esc + Esc"],description:"Abort active run (double press)",icon:Sn}]},{category:"Interface",items:[{keys:[`${n} + /`],description:"Cycle Theme (Light → Dark → System)",icon:xp},{keys:[`${n} + 2`],description:"Open Diff Panel",icon:nr},{keys:[`${n} + 3`],description:"Open Terminal",icon:Pr},{keys:[`${n} + 4`],description:"Open Git Panel",icon:$t},{keys:[`${n} + T`],description:"Open Timeline",icon:or},{keys:[`${n} + ,`],description:"Open Settings",icon:Yr}]}];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(Yr,{className:"h-5 w-5"}),"Keyboard Shortcuts"]}),e.jsx(Ns,{children:"Use these keyboard shortcuts to navigate OpenChamber efficiently"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:[e.jsx("div",{className:"space-y-4",children:o.map(a=>e.jsxs("div",{children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:a.category}),e.jsx("div",{className:"space-y-1",children:a.items.map((i,l)=>e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[i.icon&&e.jsx(i.icon,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:i.description})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(i.keys)?i.keys:i.keys.split(" / ")).map((d,u)=>e.jsxs(c.Fragment,{children:[u>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:gb(d)})]},`${d}-${u}`))})]},l))})]},a.category))}),e.jsx("div",{className:"mt-4 p-2 bg-muted/30 rounded-xl",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Qr,{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"})]})]})]})})]})]})})},Qa=new Set,Xa=new Set,Ja=new Set,Dn={onDeleteRequest(s){return Qa.add(s),()=>{Qa.delete(s)}},requestDelete(s){!s.sessions.length&&s.mode!=="worktree"||Qa.forEach(r=>r(s))},onCreateRequest(s){return Xa.add(s),()=>{Xa.delete(s)}},requestCreate(s){const r=s??{};Xa.forEach(t=>t(r))},onDirectoryRequest(s){return Ja.add(s),()=>{Ja.delete(s)}},requestDirectoryDialog(){Ja.forEach(s=>s())}};function km(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 $c="oc.sessions.projectCollapse",Lc="oc.sessions.expandedParents",Bc=s=>{const r=new Date(s),t=new Date,n=(i,l)=>i.getFullYear()===l.getFullYear()&&i.getMonth()===l.getMonth()&&i.getDate()===l.getDate(),o=new Date(t);return o.setDate(t.getDate()-1),n(r,t)?"Today":n(r,o)?"Yesterday":r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}).replace(",","")},Xs=s=>{if(!s)return null;const r=s.replace(/\\/g,"/").replace(/\/+$/,"");return r.length===0?"/":r},zc=s=>s.replace(/[-_]/g," ").replace(/\b\w/g,r=>r.toUpperCase()),yb=({id:s,projectLabel:r,projectDescription:t,isCollapsed:n,isActiveProject:o,isRepo:a,isHovered:i,isDesktopRuntime:l,isStuck:d,hideDirectoryControls:u,mobileVariant:m,onToggle:f,onHoverChange:p,onNewSession:g,onOpenMultiRunLauncher:w,onClose:h,sentinelRef:j,children:x})=>{const{attributes:y,listeners:b,setNodeRef:N,isDragging:v}=Ep({id:s});return e.jsxs("div",{ref:N,className:R("relative",v&&"opacity-40"),children:[l&&e.jsx("div",{ref:j,"data-project-id":s,className:"absolute top-0 h-px w-full pointer-events-none","aria-hidden":"true"}),e.jsx("div",{className:R("sticky top-0 z-10 pt-2 pb-1.5 w-full text-left cursor-pointer group/project border-b",!l&&"bg-sidebar"),style:{backgroundColor:l?d?"var(--sidebar-stuck-bg)":"transparent":void 0,borderColor:i?"var(--color-border)":n?"color-mix(in srgb, var(--color-border) 35%, transparent)":"var(--color-border)"},onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:e.jsxs("div",{className:"relative flex items-center gap-1 px-1",...y,children:[e.jsxs(at,{delayDuration:1500,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:f,...b,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:R("typography-ui font-semibold truncate",o?"text-primary":"text-foreground group-hover/project:text-foreground"),children:r})})}),e.jsx(nt,{side:"right",sideOffset:8,children:t})]}),e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(qt,{align:"end",className:"min-w-[180px]",children:[a&&!u&&e.jsxs(Dt,{onClick:w,children:[e.jsx(km,{className:"mr-1.5 h-4 w-4"}),"New Multi-Run"]}),e.jsxs(Dt,{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(Kt,{className:"h-4 w-4"})})]})}),x]})},bb=({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:R("typography-ui font-semibold truncate",r?"text-primary":"text-foreground"),children:s}),e.jsx("span",{className:"inline-flex h-6 w-6 items-center justify-center text-muted-foreground ml-auto",children:e.jsx(Kt,{className:"h-4 w-4"})})]})}),Ri=({mobileVariant:s=!1,onSessionSelected:r,allowReselect:t=!1,hideDirectoryControls:n=!1,showOnlyMainWorkspace:o=!1})=>{const[a,i]=c.useState(null),[l,d]=c.useState(""),[u,m]=c.useState(null),f=c.useRef(null),[p,g]=c.useState(new Set),[w,h]=c.useState(()=>new Map),j=c.useRef(new Set),x=c.useMemo(()=>ds(),[]),[y,b]=c.useState(new Set),[N,v]=c.useState(new Map),[k,D]=c.useState(new Set),[C,M]=c.useState(null),[S,A]=c.useState(null),[I,_]=c.useState(new Set),T=c.useRef(new Map),P=c.useRef(0),L=mt(X=>X.homeDirectory),Z=mt(X=>X.currentDirectory),q=mt(X=>X.setDirectory),$=Ft(X=>X.projects),H=Ft(X=>X.activeProjectId),U=Ft(X=>X.addProject),K=Ft(X=>X.removeProject),se=Ft(X=>X.setActiveProject),Y=Ft(X=>X.setActiveProjectIdOnly),re=Ft(X=>X.reorderProjects),V=_e(X=>X.setActiveMainTab),ae=_e(X=>X.setSessionSwitcherOpen),E=_e(X=>X.openMultiRunLauncher),B=rt(X=>X.settingsAutoCreateWorktree),F=ue(X=>X.sessions),O=ue(X=>X.sessionsByDirectory),z=ue(X=>X.currentSessionId),Q=ue(X=>X.setCurrentSession),me=ue(X=>X.updateSessionTitle),Se=ue(X=>X.shareSession),he=ue(X=>X.unshareSession),Pe=ue(X=>X.sessionMemoryState),ve=ue(X=>X.sessionActivityPhase),Be=ue(X=>X.permissions),W=ue(X=>X.worktreeMetadata),G=ue(X=>X.availableWorktreesByProject),ee=ue(X=>X.getSessionsByDirectory),fe=ue(X=>X.openNewSessionDraft),[de,Ae]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),Ne=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{try{const X=x.getItem(Lc);if(X){const pe=JSON.parse(X);Array.isArray(pe)&&g(new Set(pe.filter(Le=>typeof Le=="string")))}const xe=x.getItem($c);if(xe){const pe=JSON.parse(xe);Array.isArray(pe)&&b(new Set(pe.filter(Le=>typeof Le=="string")))}}catch{}},[x]),c.useEffect(()=>{typeof window>"u"||Ae(typeof window.opencodeDesktop<"u")},[]);const Oe=c.useMemo(()=>[...F].sort((X,xe)=>(xe.time?.updated||0)-(X.time?.updated||0)),[F]);c.useEffect(()=>{let X=!1;const xe=$.map(pe=>({id:pe.id,path:Xs(pe.path)})).filter(pe=>!!pe.path);return v(new Map),xe.length===0?()=>{X=!0}:(xe.forEach(pe=>{rn(pe.path).then(Le=>{X||v(Ee=>{const Ke=new Map(Ee);return Ke.set(pe.id,Le),Ke})}).catch(()=>{X||v(Le=>{const Ee=new Map(Le);return Ee.set(pe.id,null),Ee})})}),()=>{X=!0})},[$]);const ce=c.useMemo(()=>{const X=new Map;return Oe.forEach(xe=>{const pe=xe.parentID;pe&&X.set(xe.id,pe)}),X},[Oe]),dt=c.useMemo(()=>{const X=new Map;return Oe.forEach(xe=>{const pe=xe.parentID;if(!pe)return;const Le=X.get(pe)??[];Le.push(xe),X.set(pe,Le)}),X.forEach(xe=>xe.sort((pe,Le)=>(Le.time?.updated||0)-(pe.time?.updated||0))),X},[Oe]);c.useEffect(()=>{z&&g(X=>{const xe=new Set(X);let pe=ce.get(z)||null,Le=!1;for(;pe;)xe.has(pe)||(xe.add(pe),Le=!0),pe=ce.get(pe)||null;return Le?xe:X})},[z,ce]),c.useEffect(()=>{const X=new Set;Oe.forEach(xe=>{const pe=Xs(xe.directory??null);pe&&X.add(pe)}),$.forEach(xe=>{const pe=Xs(xe.path);pe&&X.add(pe)}),X.forEach(xe=>{const pe=w.get(xe);pe&&pe!=="unknown"||j.current.has(xe)||(j.current.add(xe),je.listLocalDirectory(xe).then(()=>{h(Le=>{const Ee=new Map(Le);return Ee.get(xe)==="exists"?Le:(Ee.set(xe,"exists"),Ee)})}).catch(()=>{h(Le=>{const Ee=new Map(Le);return Ee.get(xe)==="missing"?Le:(Ee.set(xe,"missing"),Ee)})}).finally(()=>{j.current.delete(xe)}))})},[Oe,$,w]),c.useEffect(()=>()=>{f.current&&clearTimeout(f.current)},[]);const kt=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."})]}),we=c.useCallback((X,xe,pe,Le)=>{if(!pe){if(Le&&Le!==H&&Y(Le),xe&&xe!==Z&&q(xe,{showOverlay:!1}),s&&(V("chat"),ae(!1)),!t&&X===z){r?.(X);return}Q(X),r?.(X)}},[H,t,Z,z,s,r,V,Y,Q,q,ae]),ne=c.useCallback(async()=>{a&&l.trim()&&(await me(a,l.trim()),i(null),d(""))},[a,l,me]),Qe=c.useCallback(()=>{i(null),d("")},[]),ge=c.useCallback(async X=>{const xe=await Se(X.id);xe&&xe.share?.url?te.success("Session shared",{description:"You can copy the link from the menu."}):te.error("Unable to share session")},[Se]),ye=c.useCallback((X,xe)=>{navigator.clipboard.writeText(X).then(()=>{m(xe),f.current&&clearTimeout(f.current),f.current=window.setTimeout(()=>{m(null),f.current=null},2e3)}).catch(()=>{te.error("Failed to copy URL")})},[]),qe=c.useCallback(async X=>{await he(X)?te.success("Session unshared"):te.error("Unable to unshare session")},[he]),Ze=c.useCallback(X=>{const xe=[],pe=Le=>{(dt.get(Le)??[]).forEach(Ke=>{xe.push(Ke),pe(Ke.id)})};return pe(X),xe},[dt]),We=ue(X=>X.deleteSession),Re=ue(X=>X.deleteSessions),Xe=c.useCallback(async X=>{const xe=Ze(X.id),pe=W.get(X.id);if(pe){const Le=pe.path,Ee=[],Ke=new Set;F.forEach(pt=>{const ut=W.get(pt.id);ut&&ut.path===Le&&!Ke.has(pt.id)&&(Ee.push(pt),Ke.add(pt.id),Ze(pt.id).forEach(xt=>{Ke.has(xt.id)||(Ee.push(xt),Ke.add(xt.id))}))}),Dn.requestDelete({sessions:Ee,mode:"worktree",worktree:pe});return}if(xe.length===0)await We(X.id)?te.success("Session deleted"):te.error("Failed to delete session");else{const Le=[X.id,...xe.map(pt=>pt.id)],{deletedIds:Ee,failedIds:Ke}=await Re(Le);Ee.length>0&&te.success(`Deleted ${Ee.length} session${Ee.length===1?"":"s"}`),Ke.length>0&&te.error(`Failed to delete ${Ke.length} session${Ke.length===1?"":"s"}`)}},[Ze,We,Re,W,F]),Ct=c.useCallback(()=>{de&&window.opencodeDesktop?.requestDirectoryAccess?window.opencodeDesktop.requestDirectoryAccess("").then(X=>{X.success&&X.path?U(X.path,{id:X.projectId})||te.error("Failed to add project",{description:"Please select a valid directory."}):X.error&&X.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:X.error})}).catch(X=>{console.error("Desktop: Error selecting directory:",X),te.error("Failed to select directory")}):Dn.requestDirectoryDialog()},[U,de]),ct=c.useCallback(X=>{g(xe=>{const pe=new Set(xe);pe.has(X)?pe.delete(X):pe.add(X);try{x.setItem(Lc,JSON.stringify(Array.from(pe)))}catch{}return pe})},[x]),At=c.useCallback(X=>{const xe=dt.get(X.id)??[];return{session:X,children:xe.map(pe=>At(pe)),worktree:W.get(X.id)??null}},[dt,W]),Mt=c.useCallback((X,xe,pe)=>{const Le=Xs(xe??null),Ee=[...X].sort((ze,Ye)=>(Ye.time?.updated||0)-(ze.time?.updated||0)),Ke=new Map(Ee.map(ze=>[ze.id,ze])),pt=new Map;Ee.forEach(ze=>{const Ye=ze.parentID;if(!Ye)return;const wt=pt.get(Ye)??[];wt.push(ze),pt.set(Ye,wt)}),pt.forEach(ze=>ze.sort((Ye,wt)=>(wt.time?.updated||0)-(Ye.time?.updated||0)));const ut=new Map;pe.forEach(ze=>{if(ze.path){const Ye=Xs(ze.path)??ze.path;ut.set(Ye,ze)}});const Tt=ze=>{const Ye=Xs(ze.directory??null),wt=W.get(ze.id)??null;if(wt)return wt;if(Ye){const Rt=ut.get(Ye)??null;if(Rt&&Ye!==Le)return Rt}return null},xt=ze=>{const Ye=pt.get(ze.id)??[];return{session:ze,children:Ye.map(wt=>xt(wt)),worktree:Tt(ze)}},tt=Ee.filter(ze=>{const Ye=ze.parentID;return Ye?!Ke.has(Ye):!0}).map(ze=>xt(ze));return[{id:"all",label:"All sessions",description:Le?Vr(Le,L):null,isMain:!0,worktree:null,directory:Le,sessions:tt}]},[L,W]),ke=c.useCallback(X=>{D(xe=>{const pe=new Set(xe);return pe.has(X)?pe.delete(X):pe.add(X),pe})},[]),$e=c.useCallback(X=>{P.current=Date.now()+150,b(xe=>{const pe=new Set(xe);pe.has(X)?pe.delete(X):pe.add(X);try{x.setItem($c,JSON.stringify(Array.from(pe)))}catch{}return pe})},[x]),Fe=c.useMemo(()=>$.map(X=>({...X,normalizedPath:Xs(X.path)})).filter(X=>!!X.normalizedPath),[$]),ot=c.useCallback(X=>{const xe=Ne?[]:G.get(X.normalizedPath)??[],pe=[X.normalizedPath,...xe.map(Ke=>Xs(Ke.path)??Ke.path).filter(Ke=>!!Ke)],Le=new Set,Ee=[];return pe.forEach(Ke=>{(O.get(Ke)??ee(Ke)).forEach(ut=>{Le.has(ut.id)||(Le.add(ut.id),Ee.push(ut))})}),Ee},[G,ee,O,Ne]),Lt=c.useMemo(()=>Fe.map(X=>{const xe=ot(X),pe=G.get(X.normalizedPath)??[],Le=Mt(xe,X.normalizedPath,pe);return{project:X,groups:Le}}),[Fe,ot,Mt,G]);c.useEffect(()=>{if(!de)return;const X=new IntersectionObserver(xe=>{xe.forEach(pe=>{const Le=pe.target.dataset.projectId;Le&&_(Ee=>{const Ke=new Set(Ee);return pe.isIntersecting?Ke.delete(Le):Ke.add(Le),Ke})})},{threshold:0});return T.current.forEach(xe=>{xe&&X.observe(xe)}),()=>X.disconnect()},[de,Lt]);const es=c.useCallback((X,xe=0,pe,Le)=>{const Ee=X.session,Ke=Xs(Ee.directory??null)??Xs(pe??null),ut=(Ke?w.get(Ke):null)==="missing",Tt=Pe.get(Ee.id),xt=z===Ee.id,Me=Ee.title||"Untitled Session",tt=X.children.length>0,ze=p.has(Ee.id),Ye=Ee.summary?.additions,wt=Ee.summary?.deletions,Rt=typeof Ye=="number"||typeof wt=="number";if(a===Ee.id)return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1","dark:bg-accent/80 bg-primary/12",xe>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:Ot=>{Ot.preventDefault(),ne()},children:[e.jsx("input",{value:l,onChange:Ot=>d(Ot.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:Ot=>{Ot.key==="Escape"&&Qe()}}),e.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",children:e.jsx(Pt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:Qe,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:[tt?e.jsx("span",{className:"inline-flex items-center justify-center flex-shrink-0",children:ze?e.jsx(It,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Bc(Ee.time?.created||Date.now())}),Ee.share?e.jsx(Ia,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,Rt&&((Ye??0)!==0||(wt??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,Ye??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,wt??0)]})]}):null,tt?e.jsxs("span",{className:"truncate",children:[X.children.length," ",X.children.length===1?"task":"tasks"]}):null]})]})},Ee.id);const ns=ve?.get(Ee.id)??"idle",ts=ns==="busy"||ns==="cooldown",ps=Be.get(Ee.id)?.length??0,lr=Tt&&Tt.isZombie?e.jsx(vi,{className:"h-4 w-4 text-warning"}):null;return e.jsxs(c.Fragment,{children:[e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1",xt?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6",ut?"opacity-75":"",xe>0&&"pl-[20px]"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{type:"button",disabled:ut,onClick:()=>we(Ee.id,Ke,ut,Le),className:R("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:R("truncate typography-ui-label font-normal text-foreground",ts&&"animate-pulse [animation-duration:1.8s]"),children:Me}),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(yp,{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:[tt?e.jsx("span",{role:"button",tabIndex:0,onClick:Ot=>{Ot.stopPropagation(),ct(Ee.id)},onKeyDown:Ot=>{(Ot.key==="Enter"||Ot.key===" ")&&(Ot.preventDefault(),Ot.stopPropagation(),ct(Ee.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":ze?"Collapse subsessions":"Expand subsessions",children:ze?e.jsx(It,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}):null,e.jsx("span",{className:"flex-shrink-0",children:Bc(Ee.time?.created||Date.now())}),Ee.share?e.jsx(Ia,{className:"h-3 w-3 text-[color:var(--status-info)] flex-shrink-0"}):null,X.worktree?e.jsxs(at,{delayDuration:700,children:[e.jsx(it,{asChild:!0,children:e.jsx("span",{className:"flex-shrink-0",children:e.jsx($t,{className:"h-3 w-3 text-[color:var(--status-info)]"})})}),e.jsx(nt,{side:"top",className:"text-xs",children:X.worktree.branch||X.worktree.label||"Worktree"})]}):null,Rt&&((Ye??0)!==0||(wt??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,Ye??0)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,wt??0)]})]}):null,tt?e.jsxs("span",{className:"truncate",children:[X.children.length," ",X.children.length===1?"task":"tasks"]}):null,ut?e.jsxs("span",{className:"inline-flex items-center gap-0.5 text-warning flex-shrink-0",children:[e.jsx(vi,{className:"h-3 w-3"}),"Missing"]}):null]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 self-stretch",children:[lr,e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("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:Ot=>Ot.stopPropagation(),onKeyDown:Ot=>Ot.stopPropagation(),children:e.jsx(Tr,{className:s?"h-4 w-4":"h-3.5 w-3.5"})})}),e.jsxs(qt,{align:"end",className:"min-w-[180px]",children:[e.jsxs(Dt,{onClick:()=>{i(Ee.id),d(Me)},className:"[&>svg]:mr-1",children:[e.jsx(mr,{className:"mr-1 h-4 w-4"}),"Rename"]}),Ee.share?e.jsxs(e.Fragment,{children:[e.jsx(Dt,{onClick:()=>{Ee.share?.url&&ye(Ee.share.url,Ee.id)},className:"[&>svg]:mr-1",children:u===Ee.id?e.jsxs(e.Fragment,{children:[e.jsx(Pt,{className:"mr-1 h-4 w-4",style:{color:"var(--status-success)"}}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{className:"mr-1 h-4 w-4"}),"Copy link"]})}),e.jsxs(Dt,{onClick:()=>qe(Ee.id),className:"[&>svg]:mr-1",children:[e.jsx(bp,{className:"mr-1 h-4 w-4"}),"Unshare"]})]}):e.jsxs(Dt,{onClick:()=>ge(Ee),className:"[&>svg]:mr-1",children:[e.jsx(Ia,{className:"mr-1 h-4 w-4"}),"Share"]}),X.worktree?e.jsxs(Dt,{onClick:()=>{Le&&Le!==H&&se(Le),V("chat"),s&&ae(!1),fe({directoryOverride:X.worktree?.path??null})},className:"[&>svg]:mr-1",children:[e.jsx($t,{className:"mr-1 h-4 w-4"}),"New session in worktree"]}):null,e.jsxs(Dt,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>Xe(Ee),children:[e.jsx(qs,{className:"mr-1 h-4 w-4"}),"Remove"]})]})]})]})]})}),tt&&ze?X.children.map(Ot=>es(Ot,xe+1,Ke??pe,Le)):null]},Ee.id)},[w,Pe,ve,Be,z,p,a,l,ne,Qe,ct,we,ge,ye,qe,Xe,u,s,H,se,V,ae,fe]),Wt=c.useCallback((X,xe,pe)=>{const Le=k.has(xe),Ee=n?10:5,Ke=X.sessions.length,pt=Le?X.sessions:X.sessions.slice(0,Ee),ut=Ke-pt.length;return e.jsxs(e.Fragment,{children:[pt.map(Tt=>es(Tt,0,X.directory,pe)),Ke===0?e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions in this workspace yet."}):null,ut>0&&!Le?e.jsxs("button",{type:"button",onClick:()=>ke(xe),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 ",ut," more ",ut===1?"session":"sessions"]}):null,Le&&Ke>Ee?e.jsx("button",{type:"button",onClick:()=>ke(xe),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,es,ke]),He=wp(Ll(Ap,{activationConstraint:{distance:8}}),Ll(Dp,{coordinateGetter:Mp})),et=c.useCallback(X=>{A(X.active.id)},[]),gt=c.useCallback(X=>{const{active:xe,over:pe}=X;if(A(null),!pe||xe.id===pe.id)return;const Le=Fe.findIndex(Ke=>Ke.id===xe.id),Ee=Fe.findIndex(Ke=>Ke.id===pe.id);Le!==-1&&Ee!==-1&&re(Le,Ee)},[Fe,re]),Je=c.useCallback(()=>{A(null)},[]),bt=c.useMemo(()=>{if(!S)return null;const X=Lt.find(pe=>pe.project.id===S);if(!X)return null;const xe=X.project;return{id:xe.id,label:zc(xe.label?.trim()||Wl(xe.normalizedPath,L)||xe.normalizedPath),isActive:xe.id===H}},[S,Lt,L,H]);return e.jsxs("div",{className:R("flex h-full flex-col text-foreground overflow-x-hidden",s?"":de?"bg-transparent":"bg-sidebar"),children:[!n&&e.jsx("div",{className:"h-8 select-none pl-3.5 pr-2 flex-shrink-0",children:e.jsxs("div",{className:"flex h-full items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[e.jsx("p",{className:"typography-ui-label font-medium text-muted-foreground",children:"Projects"}),e.jsx("span",{className:"typography-micro text-muted-foreground/50",children:$.length})]}),e.jsx("button",{type:"button",onClick:Ct,className:R("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",!de&&"bg-sidebar/60 hover:bg-sidebar"),"aria-label":"Add project",title:"Add project",children:e.jsx(vp,{className:"h-4.5 w-4.5"})})]})}),e.jsx(ft,{outerClassName:"flex-1 min-h-0",className:R("space-y-1 pb-1 pl-2.5 pr-1",""),children:Lt.length===0?kt:o?e.jsx("div",{className:"space-y-[0.6rem] py-1",children:(()=>{const X=Lt.find(Le=>Le.project.id===H)??Lt[0];if(!X)return kt;const xe=X.groups.find(Le=>Le.isMain&&Le.sessions.length>0)??X.groups.find(Le=>Le.sessions.length>0)??X.groups.find(Le=>Le.isMain)??X.groups[0];if(!xe)return e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."});const pe=`${X.project.id}:${xe.id}`;return Wt(xe,pe,X.project.id)})()}):e.jsxs(jp,{sensors:He,collisionDetection:Sp,onDragStart:et,onDragEnd:gt,onDragCancel:Je,children:[e.jsx(kp,{items:Fe.map(X=>X.id),strategy:Np,children:Lt.map(X=>{const xe=X.project,pe=xe.id,Le=zc(xe.label?.trim()||Wl(xe.normalizedPath,L)||xe.normalizedPath),Ee=Vr(xe.normalizedPath,L),Ke=y.has(pe),pt=pe===H,ut=N.get(pe),Tt=C===pe;return e.jsx(yb,{id:pe,projectLabel:Le,projectDescription:Ee,isCollapsed:Ke,isActiveProject:pt,isRepo:!!ut,isHovered:Tt,isDesktopRuntime:de,isStuck:I.has(pe),hideDirectoryControls:n,mobileVariant:s,onToggle:()=>$e(pe),onHoverChange:xt=>M(xt?pe:null),onNewSession:()=>{pe!==H&&se(pe),V("chat"),s&&ae(!1),B&&ut?ba():fe({directoryOverride:xe.normalizedPath})},onOpenMultiRunLauncher:()=>{pe!==H&&se(pe),E()},onClose:()=>K(pe),sentinelRef:xt=>{T.current.set(pe,xt)},children:Ke?null:e.jsx("div",{className:"space-y-[0.6rem] py-1 pl-1",children:X.groups[0]?Wt(X.groups[0],`${pe}:all`,pe):e.jsx("div",{className:"py-1 text-left typography-micro text-muted-foreground",children:"No sessions yet."})})},pe)})}),e.jsx(Cp,{children:bt?e.jsx(bb,{projectLabel:bt.label,isActiveProject:bt.isActive}):null})]})})]})};function ht({className:s,type:r,...t}){return e.jsx("input",{type:r,"data-slot":"input",className:R("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 wa=()=>{const[s,r]=De.useState(!1);De.useEffect(()=>{r(Zt())},[]);const t=De.useCallback(async a=>s?await Zh(a):{success:!0,path:a},[s]),n=De.useCallback(async a=>s?await eg(a):{success:!0},[s]),o=De.useCallback(async a=>s?await tg(a):{success:!0},[s]);return{isDesktop:s,requestAccess:t,startAccessing:n,stopAccessing:o}},Wc=({currentPath:s,onSelectPath:r,triggerClassName:t,variant:n="dropdown",className:o,selectionBehavior:a="immediate",onDoubleClickPath:i,showHidden:l=!1,rootDirectory:d=null,isRootReady:u,alwaysShowActions:m=!1})=>{const f=c.useMemo(()=>Zt(),[]),{isMobile:p}=_t(),[g,w]=c.useState([]),[h,j]=c.useState(new Set),[x,y]=c.useState(!0),[b,N]=c.useState(!1),[v,k]=c.useState(""),[D,C]=c.useState(new Set),[M,S]=c.useState(null),[A,I]=c.useState(""),[_,T]=c.useState(!0),P=c.useRef(null),{requestAccess:L,startAccessing:Z,isDesktop:q}=wa(),$=c.useRef(l),H=c.useCallback(W=>{if(!W)return W;if(W==="/"||W.length===0)return"/";let G=W;for(;G.length>1&&G.endsWith("/");)G=G.slice(0,-1);return G.length===0?"/":G},[]),U=c.useMemo(()=>{if(!v)return null;const W=v.replace(/\\/g,"/");return H(W)},[v,H]),K=c.useMemo(()=>{if(typeof d=="string"&&d.length>0){const W=d.replace(/\\/g,"/"),G=H(W);if(G&&G!=="/")return G}return U&&U!=="/"?U:null},[d,U,H]),se=c.useMemo(()=>typeof u=="boolean"?!!(u&&K):!!K,[u,K]);c.useEffect(()=>{se||(y(!0),w([]))},[se]);const Y=c.useCallback(W=>{if(!W||!se||!K)return!1;const G=W.replace(/\\/g,"/"),ee=H(G)??G;if(ee===K)return!0;const fe=`${K}/`;return ee.startsWith(fe)},[se,K,H]),re=async W=>{if(se){if(a==="deferred"){r(W);return}if(q){const G=await L(W);G.success&&G.path?(await Z(G.path),r(G.path)):(console.error("Failed to get directory access:",G.error),r(W))}else r(W)}};c.useEffect(()=>{let W=!1;const G=de=>{if(!de)return!1;const Ae=H(de.replace(/\\/g,"/"));return!Ae||Ae==="/"?!1:(k(typeof Ae=="string"?Ae:de.replace(/\\/g,"/")),!0)};return d&&G(d)||(async()=>{try{const de=await je.getFilesystemHome();if(!W&&G(de))return}catch(de){console.warn("Failed to resolve filesystem home directory:",de)}try{const de=await je.getSystemInfo();if(!W&&G(de?.homeDirectory))return}catch(de){console.warn("Failed to resolve home directory from system info:",de)}})(),()=>{W=!0}},[d,H]),c.useEffect(()=>{let W=!1;const G=Ae=>{if(W)return;const Ne=Ae.filter(Oe=>typeof Oe=="string"&&Oe.length>0).map(Oe=>{const ce=Oe.replace(/\\/g,"/");return H(ce)??ce});C(new Set(Ne))},ee=()=>{try{const Ae=localStorage.getItem("pinnedDirectories");if(!Ae)return;const Ne=JSON.parse(Ae);Array.isArray(Ne)&&G(Ne)}catch(Ae){console.warn("Failed to load pinned directories from local storage:",Ae)}},fe=async()=>{try{let Ae=[];if(f){const Ne=await sn();Ae=Array.isArray(Ne?.pinnedDirectories)?Ne.pinnedDirectories:[]}else{const Ne=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});if(Ne.ok){const Oe=await Ne.json();Ae=Array.isArray(Oe?.pinnedDirectories)?Oe.pinnedDirectories:[]}}if(W)return;G(Ae)}catch(Ae){console.warn("Failed to load pinned directories:",Ae)}};ee();const de=Ae=>{const Ne=Ae.detail;Ne&&Array.isArray(Ne.pinnedDirectories)&&G(Ne.pinnedDirectories)};return window.addEventListener("openchamber:settings-synced",de),fe(),()=>{W=!0,window.removeEventListener("openchamber:settings-synced",de)}},[f,H]);const V=c.useRef(!0);c.useEffect(()=>{if(V.current){V.current=!1;return}const W={pinnedDirectories:Array.from(D)};rs(W)},[D]),c.useEffect(()=>{K&&C(W=>{const G=Array.from(W).map(ee=>H(ee.replace(/\\/g,"/"))??ee).filter(ee=>Y(ee));return new Set(G)})},[K,Y,H]),c.useEffect(()=>{$.current!==l&&($.current=l)},[l]);const ae=W=>{C(G=>{if(!Y(W))return G;const ee=H(W.replace(/\\/g,"/"))??W.replace(/\\/g,"/"),fe=new Set(G);return fe.has(ee)?fe.delete(ee):fe.add(ee),fe})},E=c.useMemo(()=>Array.from(D).map(W=>H(W.replace(/\\/g,"/"))??W).filter(W=>Y(W)).map(W=>({path:W,name:W.split("/").pop()||W})).sort((W,G)=>W.name.localeCompare(G.name)),[D,Y,H]),B=c.useCallback(async W=>{const G=Ne=>l||!Ne.startsWith("."),ee=K;if(!se||!ee)return[];const fe=W&&W.length>0?W:ee,de=fe?fe.replace(/\\/g,"/"):null,Ae=de?H(de)??de:null;if(Ae){const Ne=`${ee}/`;if(!(Ae===ee||Ae.startsWith(Ne)))return[]}try{return(await je.listLocalDirectory(W)).filter(Oe=>{if(!Oe.isDirectory||!G(Oe.name))return!1;const ce=Oe.path.replace(/\\/g,"/"),dt=H(ce)??ce,kt=dt===ee?ee:`${ee}/`;return dt===ee||dt.startsWith(kt)}).map(Oe=>({name:Oe.name,path:Oe.path.replace(/\\/g,"/"),isDirectory:!0})).sort((Oe,ce)=>Oe.name.localeCompare(ce.name))}catch{try{const Oe=await je.getApiClient().file.list({path:".",directory:W});return Oe.data?Oe.data.filter(ce=>{if(ce.type!=="directory"||!ce.name||!G(ce.name))return!1;const dt=String(ce.absolute||ce.path||ce.name).replace(/\\/g,"/"),kt=H(dt)??dt,we=kt===ee?ee:`${ee}/`;return kt===ee||kt.startsWith(we)}).map(ce=>({name:ce.name||"",path:String(ce.absolute||ce.path||ce.name).replace(/\\/g,"/"),isDirectory:!0})).filter(ce=>ce.name!=="").sort((ce,dt)=>ce.name.localeCompare(dt.name)):[]}catch{return[]}}},[l,K,H,se]),F=c.useRef(!1),O=c.useCallback(async()=>{if(!se||!K){y(!0),w([]);return}F.current||y(!0);try{const W=await B(K);w(W),F.current=!0}catch{}finally{y(!1)}},[se,K,B]);c.useEffect(()=>{se&&(n==="inline"||b)&&O()},[n,b,se,O]);const z=async W=>{if(!se)return;const G=h.has(W.path),ee=new Set(h);if(G){ee.delete(W.path),j(ee);return}ee.add(W.path),j(ee);const fe=await B(W.path),de=Ae=>Ae.map(Ne=>Ne.path===W.path?{...Ne,children:fe}:Ne.children?{...Ne,children:de(Ne.children)}:Ne);w(Ae=>de(Ae))};c.useEffect(()=>{M&&P.current&&(P.current.focus(),P.current.select())},[M]);const Q=(W,G=[])=>{const ee="new_directory",fe=G.map(Oe=>Oe.name);if(!fe.includes(ee))return ee;let de=1;const Ae=new RegExp(`^${ee}(\\d+)$`);for(const Oe of fe){const ce=Oe.match(Ae);if(ce){const dt=parseInt(ce[1],10);dt>de&&(de=dt)}}let Ne=2;for(;fe.includes(`${ee}${Ne}`);)Ne++;return`${ee}${Math.max(Ne,de+1)}`},me=async W=>{if(se){if(h.has(W.path)){const G=Q(W.path,W.children);I(G)}else{const G=new Set(h);if(G.add(W.path),j(G),W.children){const ee=Q(W.path,W.children);I(ee)}else{const ee=await B(W.path),fe=Ae=>Ae.map(Ne=>Ne.path===W.path?{...Ne,children:ee}:Ne.children?{...Ne,children:fe(Ne.children)}:Ne);w(Ae=>fe(Ae));const de=Q(W.path,ee);I(de)}}S(W.path)}},Se=async()=>{if(!M||!se)return;const W=A.trim()||"new_directory",G=`${M}/${W}`;try{await je.createDirectory(G);const ee=await B(M),fe=de=>de.map(Ae=>Ae.path===M?{...Ae,children:ee}:Ae.children?{...Ae,children:fe(Ae.children)}:Ae);w(de=>fe(de)),S(null),I("")}catch(ee){console.error("Failed to create directory:",ee)}},he=()=>{S(null),I("")},Pe=(W,G=0)=>{const ee=h.has(W.path),fe=W.isDirectory,de=D.has(W.path),Ae=s===W.path,Ne=n==="inline",Oe=e.jsxs(e.Fragment,{children:[fe&&e.jsx("button",{onClick:ce=>{ce.stopPropagation(),z(W)},className:R("hover:bg-accent rounded","p-0.5"),children:ee?e.jsx(It,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"})}),!fe&&e.jsx("div",{className:p?"w-4.5":"w-4"}),e.jsxs("button",{onClick:ce=>{ce.stopPropagation(),re(W.path),n==="dropdown"&&a==="immediate"&&N(!1)},onDoubleClick:ce=>{ce.stopPropagation(),i&&i(W.path)},className:R("flex items-center flex-1 text-left focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/60 rounded","gap-1.5",Ne&&Ae?"text-primary":"text-foreground"),children:[e.jsx(ur,{className:R("text-muted-foreground flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",Ne&&Ae&&"text-primary")}),e.jsx("span",{className:R("font-medium truncate","typography-ui-label",Ne&&Ae?"text-primary":"text-foreground"),children:W.name})]}),e.jsx("button",{onClick:ce=>{ce.stopPropagation(),me(W)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:"Create new directory",children:e.jsx(Kt,{className:R("text-muted-foreground",p?"h-3.5 w-3.5":"h-3 w-3")})}),e.jsx("button",{onClick:ce=>{ce.stopPropagation(),ae(W.path)},className:R("hover:bg-accent rounded transition-opacity",p?"p-1.5":"p-1",m?"opacity-60":"opacity-0 group-hover:opacity-100"),title:de?"Unpin directory":"Pin directory",children:de?e.jsx(Pa,{className:R("text-primary",p?"h-3.5 w-3.5":"h-3 w-3")}):e.jsx(Ip,{className:R("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:R("group flex items-center gap-1 rounded-lg mx-1 text-left transition-colors",p?"px-1.5 py-1":"px-2 py-1.5",Ae?"bg-primary/10 text-primary":"hover:bg-accent/50 text-foreground"),style:{paddingLeft:`${G*(p?12:14)+(p?4:6)}px`},children:Oe}),ee&&e.jsxs(e.Fragment,{children:[M===W.path&&e.jsxs("div",{className:"flex items-center gap-1 mx-1 px-2 py-1.5",style:{paddingLeft:`${(G+1)*14+6}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:P,value:A,onChange:ce=>I(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"?(ce.preventDefault(),ce.stopPropagation(),Se()):ce.key==="Escape"&&(ce.preventDefault(),ce.stopPropagation(),he())},onBlur:Se,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),Se()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Pt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),W.children&&W.children.map(ce=>Pe(ce,G+1))]})]},W.path):e.jsxs("div",{children:[e.jsxs(Dt,{className:R("flex items-center gap-1 cursor-pointer group",s===W.path&&"bg-accent"),style:{paddingLeft:`${G*12+8}px`},onSelect:ce=>{ce.preventDefault()},children:[fe&&e.jsx("button",{onClick:ce=>{ce.stopPropagation(),z(W)},className:"p-0.5 hover:bg-accent rounded",children:ee?e.jsx(It,{className:"h-3 w-3"}):e.jsx(Us,{className:"h-3 w-3"})}),!fe&&e.jsx("div",{className:"w-4"}),Oe]}),ee&&e.jsxs("div",{children:[M===W.path&&e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5",style:{paddingLeft:`${(G+1)*12+8}px`},children:[e.jsx("div",{className:"w-4"}),e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:P,value:A,onChange:ce=>I(ce.target.value),onKeyDown:ce=>{ce.key==="Enter"?(ce.preventDefault(),ce.stopPropagation(),Se()):ce.key==="Escape"&&(ce.preventDefault(),ce.stopPropagation(),he())},onBlur:Se,className:"h-6 typography-meta flex-1 selection:bg-muted selection:text-muted-foreground",placeholder:"new_directory"}),e.jsx("button",{onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),Se()},className:"p-1 hover:bg-accent rounded",title:"Create directory",children:e.jsx(Pt,{className:"h-3 w-3 text-green-600"})}),e.jsx("button",{onClick:ce=>{ce.preventDefault(),ce.stopPropagation(),he()},className:"p-1 hover:bg-accent rounded",title:"Cancel",children:e.jsx(Ht,{className:"h-3 w-3 text-muted-foreground"})})]}),W.children&&W.children.map(ce=>Pe(ce,G+1))]})]},W.path)},ve=(W,G)=>{if(n==="inline"){const ee=s===G;return e.jsxs("div",{className:R("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(G),onDoubleClick:fe=>{fe.stopPropagation(),i&&i(G)},className:R("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(ur,{className:R("flex-shrink-0",p?"h-4 w-4":"h-3.5 w-3.5",ee?"text-primary":"text-muted-foreground")}),e.jsx("span",{className:R("typography-ui-label font-medium truncate flex-shrink-0",ee?"text-primary":"text-foreground"),children:W}),e.jsx("span",{className:"typography-meta text-muted-foreground/60 truncate",children:Vr(G,v)})]}),e.jsx("button",{onClick:()=>ae(G),className:R("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(Pa,{className:R("text-primary","h-3.5 w-3.5")})})]},G)}return e.jsxs(Dt,{onSelect:ee=>{ee.preventDefault(),re(G),a==="immediate"&&N(!1)},className:R("flex items-start gap-2 cursor-pointer group py-2",s===G&&"bg-accent"),children:[e.jsx(ur,{className:"h-3.5 w-3.5 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"typography-ui-label font-medium",children:W}),e.jsx("div",{className:"typography-meta text-muted-foreground",children:Vr(G,v)})]}),e.jsx("button",{onClick:ee=>{ee.stopPropagation(),ee.preventDefault(),ae(G)},className:"p-1 opacity-0 group-hover:opacity-100 hover:bg-accent rounded transition-opacity",title:"Unpin directory",children:e.jsx(Pa,{className:"h-3 w-3 text-primary"})})]},G)},Be=e.jsx(e.Fragment,{children:se?e.jsxs(e.Fragment,{children:[E.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:()=>T(W=>!W),className:R("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:[_?e.jsx(It,{className:p?"h-3.5 w-3.5":"h-3 w-3"}):e.jsx(Us,{className:p?"h-3.5 w-3.5":"h-3 w-3"}),e.jsx("span",{children:"Pinned"}),e.jsx("span",{className:"ml-auto typography-micro text-muted-foreground/60 normal-case tracking-normal",children:E.length})]}),_&&E.map(({name:W,path:G})=>ve(W,G)),n==="dropdown"&&e.jsx(Ms,{}),n==="inline"&&_&&e.jsx("div",{className:"mx-3 my-2 border-t border-border/40"})]}),e.jsx("div",{className:R("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"}),x?e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"Loading..."}):g.map(W=>Pe(W)),!x&&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:R("overflow-hidden flex flex-col",o),children:e.jsx(ft,{outerClassName:"flex-1 min-h-0",className:"w-full py-1",children:Be})}):e.jsxs(Vt,{open:b,onOpenChange:N,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",className:R("w-full h-8 px-2.5 justify-between items-center rounded-lg border border-transparent bg-sidebar-accent/40 text-foreground/90 hover:bg-sidebar-accent/60 typography-meta",t),"aria-label":"Select working directory",children:[e.jsxs("span",{className:"flex items-center gap-1.5 min-w-0 flex-1",children:[e.jsx(ur,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",title:s,children:Vr(s,v)})]}),e.jsx(It,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsx(qt,{align:"start",className:"w-[350px]",children:e.jsx(ft,{outerClassName:"h-full",className:"w-full",children:Be})})]})},jl=(s,r=200)=>{const[t,n]=De.useState(s);return De.useEffect(()=>{const o=window.setTimeout(()=>{n(s)},r);return()=>{window.clearTimeout(o)}},[s,r]),t},Nm=c.forwardRef(({inputValue:s,homeDirectory:r,onSelectSuggestion:t,visible:n,onClose:o,showHidden:a},i)=>{const[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(0),g=c.useRef(null),w=c.useRef([]),h=c.useCallback((v,k)=>{const D=v.trim().toLowerCase();if(!D)return 0;const C=k.toLowerCase();let M=0,S=-1,A=0;for(let I=0;I<D.length;I+=1){const _=D[I];if(!_||_===" ")continue;const T=C.indexOf(_,S+1);if(T===-1)return null;const P=T-S-1;if(P===0?A+=1:A=0,M+=10,M+=Math.max(0,18-T),M-=Math.max(0,P),T===0)M+=12;else{const L=C[T-1];(L==="/"||L==="_"||L==="-"||L==="."||L===" ")&&(M+=10)}M+=A>0?12:0,S=T}return M+=Math.max(0,24-Math.round(C.length/3)),M},[]),j=c.useCallback(v=>v.startsWith("~")&&r?v.replace(/^~/,r):v,[r]),x=c.useCallback(v=>{const k=j(v);if(k.endsWith("/"))return k;const D=k.lastIndexOf("/");return D===-1?"":D===0?"/":k.substring(0,D+1)},[j]),y=c.useCallback(v=>{const k=j(v);if(k.endsWith("/"))return"";const D=k.lastIndexOf("/");return D===-1?k:k.substring(D+1)},[j]),b=jl(s,150);c.useEffect(()=>{if(!n||!b){d([]);return}const v=x(b),k=y(b).toLowerCase();if(!v){d([]);return}let D=!1;return m(!0),je.listLocalDirectory(v).then(C=>{if(D)return;const M=C.filter(A=>!(!A.isDirectory||!a&&A.name.startsWith("."))),S=k?M.map(A=>{const I=h(k,A.name);return I!==null?{entry:A,score:I}:null}).filter(A=>A!==null).sort((A,I)=>I.score-A.score||A.entry.name.localeCompare(I.entry.name)).map(A=>A.entry):M.sort((A,I)=>A.name.localeCompare(I.name));d(S.slice(0,10)),p(0)}).catch(()=>{D||d([])}).finally(()=>{D||m(!1)}),()=>{D=!0}},[n,b,x,y,a,h]),c.useEffect(()=>{w.current[f]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[f]),c.useEffect(()=>{if(!n)return;const v=k=>{const D=k.target;!D||!g.current||g.current.contains(D)||o()};return document.addEventListener("pointerdown",v,!0),()=>{document.removeEventListener("pointerdown",v,!0)}},[n,o]);const N=c.useCallback(v=>{const k=v.path.endsWith("/")?v.path:v.path+"/";t(k)},[t]);return c.useImperativeHandle(i,()=>({handleKeyDown:v=>{if(!n||l.length===0)return!1;const k=l.length;if(v.key==="Tab"){if(v.preventDefault(),v.shiftKey)p(D=>(D-1+k)%k);else if(k===1){const D=l[0];D&&N(D)}else p(D=>(D+1)%k);return!0}if(v.key==="ArrowDown")return v.preventDefault(),p(D=>(D+1)%k),!0;if(v.key==="ArrowUp")return v.preventDefault(),p(D=>(D-1+k)%k),!0;if(v.key==="Enter"){v.preventDefault();const D=(f%k+k)%k,C=l[D];return C&&N(C),o(),!0}return v.key==="Escape"?(v.preventDefault(),o(),!0):!1}}),[n,l,f,N,o]),!n||l.length===0&&!u?null:e.jsxs("div",{ref:g,className:"absolute z-[100] w-full max-h-48 bg-background border border-border rounded-lg shadow-lg top-full mt-1 left-0 flex flex-col overflow-hidden",children:[u?e.jsx("div",{className:"flex items-center justify-center py-3",children:e.jsx(Ar,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"overflow-y-auto py-1",children:l.map((v,k)=>{const D=f===k;return e.jsxs("div",{ref:C=>{w.current[k]=C},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label",D&&"bg-muted"),onClick:()=>{N(v),o()},onMouseEnter:()=>p(k),children:[e.jsx(ir,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"truncate",children:v.name})]},v.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"})]})});Nm.displayName="DirectoryAutocomplete";const Hc="directoryTreeShowHidden",wb=({open:s,onOpenChange:r})=>{const{currentDirectory:t,homeDirectory:n,isHomeReady:o}=mt(),{addProject:a,getActiveProject:i}=Ft(),[l,d]=c.useState(null),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(!1),[h,j]=c.useState(()=>{if(typeof window>"u")return!1;try{const V=window.localStorage.getItem(Hc);if(V==="true")return!0;if(V==="false")return!1}catch{}return!1}),{isDesktop:x,requestAccess:y,startAccessing:b}=wa(),{isMobile:N}=_t(),[v,k]=c.useState(!1),D=c.useRef(null),C=c.useCallback(V=>V?Vr(V,n):"",[n]);c.useEffect(()=>{if(s){p(!1),w(!1),k(!1);const ae=i()?.path||t||n||"";d(ae),m(C(ae))}},[s,t,n,C,i]),c.useEffect(()=>{!s||f||l||n&&o&&(d(n),p(!0),m("~"))},[s,f,l,n,o]),c.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Hc,h?"true":"false")}catch{}},[h]);const M=c.useCallback(()=>{r(!1)},[r]),S=c.useCallback(async V=>{if(!(!V||g)){w(!0);try{let ae=V,E;if(x){const F=await y(V);if(!F.success){te.error("Unable to access directory",{description:F.error||"Desktop denied directory access."});return}ae=F.path??V,E=F.projectId;const O=await b(ae);if(!O.success){te.error("Failed to open directory",{description:O.error||"Desktop could not grant file access."});return}}if(!a(ae,{id:E})){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{w(!1)}}},[a,M,x,y,b,g]),A=c.useCallback(async()=>{const V=u.trim()||l;V&&await S(V)},[S,u,l]),I=c.useCallback(V=>{d(V),p(!0),m(C(V))},[C]),_=c.useCallback(async V=>{d(V),p(!0),m(C(V)),await S(V)},[S,C]),T=c.useCallback(V=>{const ae=V.target.value;if(m(ae),p(!0),k(ae.startsWith("/")||ae.startsWith("~")),ae.startsWith("/")||ae.startsWith("~")){const E=ae.startsWith("~")&&n?ae.replace(/^~/,n):ae;d(E)}},[n]),P=c.useCallback(V=>{D.current?.handleKeyDown(V)||V.key==="Enter"&&(V.preventDefault(),A())},[A]),L=c.useCallback(V=>{d(V),p(!0),m(C(V))},[C]),Z=c.useCallback(()=>{k(!1)},[]),q=c.useCallback(()=>{j(V=>!V)},[]),$=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(Qi,{className:"h-4 w-4 text-primary"}):e.jsx(Xi,{className:"h-4 w-4"}),"Show hidden"]}),H=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(Ns,{className:"flex-1",children:"Choose a folder to add as a project."}),$]})]}),U=e.jsxs("div",{className:"relative",children:[e.jsx(ht,{value:u,onChange:T,onKeyDown:P,placeholder:"Enter path or select from tree...",className:"font-mono typography-meta",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),e.jsx(Nm,{ref:D,inputValue:u,homeDirectory:n,onSelectSuggestion:L,visible:v,onClose:Z,showHidden:h})]}),K=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(Wc,{variant:"inline",currentPath:l??t,onSelectPath:I,onDoubleClickPath:_,className:"flex-1 min-h-0 sm:min-h-[280px] sm:max-h-[380px]",selectionBehavior:"deferred",showHidden:h,rootDirectory:o?n:null,isRootReady:o})}),se=e.jsxs("div",{className:"flex flex-col gap-3 h-full",children:[e.jsx("div",{className:"flex-shrink-0",children:U}),e.jsx("div",{className:"flex-shrink-0 flex items-center justify-end",children:$}),e.jsx("div",{className:"flex-1 min-h-0 rounded-xl border border-border/40 bg-sidebar/70 overflow-hidden flex flex-col",children:e.jsx(Wc,{variant:"inline",currentPath:l??t,onSelectPath:I,onDoubleClickPath:_,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:[U,K]}),re=()=>e.jsxs(e.Fragment,{children:[e.jsx(Ce,{variant:"ghost",onClick:M,disabled:g,className:"flex-1 sm:flex-none sm:w-auto",children:"Cancel"}),e.jsx(Ce,{onClick:A,disabled:g||!f||!l&&!u.trim(),className:"flex-1 sm:flex-none sm:w-auto sm:min-w-[140px]",children:g?"Adding...":"Add Project"})]});return N?e.jsx(vs,{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:se}):e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:R("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:V=>{V.preventDefault()},children:[H,Y,e.jsx(Ks,{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()})]})})},vo=s=>s?e.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:s}):void 0,vb=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},jb=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=c.useRef(new Set),[a,i]=c.useState(null),[l,d]=c.useState([]),[u,m]=c.useState(!1),[f,p]=c.useState(!1),{deleteSession:g,deleteSessions:w,loadSessions:h,getWorktreeMetadata:j}=ue(),{currentDirectory:x,homeDirectory:y,isHomeReady:b}=mt(),{projects:N,addProject:v,activeProjectId:k}=Ft(),{requestAccess:D,startAccessing:C}=wa(),{isMobile:M,isTablet:S,hasTouchInput:A}=_t(),I=M||S||A,_=c.useMemo(()=>{const F=(k?N.find(O=>O.id===k)??null:null)?.path??x;return vb(F)},[k,x,N]),T=c.useMemo(()=>(a?.worktree?.status?.isDirty??!1)||l.some(B=>B.metadata.status?.isDirty),[a?.worktree?.status?.isDirty,l]),P=c.useMemo(()=>{const B=a?.worktree;return B&&typeof B.branch=="string"&&B.branch.trim().length>0?!0:l.length>0&&l.every(({metadata:F})=>typeof F.branch=="string"&&F.branch.trim().length>0)},[a?.worktree,l]),L=a?.mode==="worktree",Z=L,q=f||!L||!P;c.useEffect(()=>{_&&(o.current.has(_)||bx(_).then(()=>o.current.add(_)).catch(B=>{console.warn("Failed to ensure .openchamber directory is ignored:",B),o.current.delete(_)}))},[_]),c.useEffect(()=>{h()},[h,x]);const $=c.useMemo(()=>N.map(B=>`${B.id}:${B.path}`).join("|"),[N]),H=c.useRef($);c.useEffect(()=>{$!==H.current&&(H.current=$,h())},[h,$]),c.useEffect(()=>{if(!(t||!b||N.length>0)){if(n(!0),Zt()){D("").then(async B=>{if(!B.success||!B.path){B.error&&B.error!=="Directory selection cancelled"&&te.error("Failed to select directory",{description:B.error});return}const F=await C(B.path);if(!F.success){te.error("Failed to open directory",{description:F.error||"Desktop could not grant file access."});return}v(B.path,{id:B.projectId})||te.error("Failed to add project",{description:"Please select a valid directory path."})}).catch(B=>{console.error("Desktop: Error selecting directory:",B),te.error("Failed to select directory")});return}r(!0)}},[v,t,b,N.length,D,C]);const U=c.useCallback(B=>{i({sessions:B.sessions,dateLabel:B.dateLabel,mode:B.mode??"session",worktree:B.worktree??null})},[]),K=c.useCallback(()=>{i(null),d([]),m(!1),p(!1)},[]);c.useEffect(()=>Dn.onDeleteRequest(B=>{U(B)}),[U]),c.useEffect(()=>Dn.onDirectoryRequest(()=>{r(!0)}),[]),c.useEffect(()=>{if(!a){d([]),m(!1);return}const B=a.sessions.map(O=>{const z=j(O.id);return z?{session:O,metadata:z}:null}).filter(O=>!!O);if(d(B),m(!1),B.length===0)return;let F=!1;return(async()=>{const O=await Promise.all(B.map(async({metadata:z})=>{if(z.status&&typeof z.status.isDirty=="boolean")return z.status;try{return await cl(z.path)}catch{return z.status}})).catch(z=>(console.warn("Failed to inspect worktree status before deletion:",z),B.map(({metadata:Q})=>Q.status)));F||!Array.isArray(O)||d(z=>z.map((Q,me)=>({session:Q.session,metadata:{...Q.metadata,status:O[me]??Q.metadata.status}})))})(),()=>{F=!0}},[a,j]),c.useEffect(()=>{P||m(!1)},[P]);const se=c.useCallback(async()=>{if(a){p(!0);try{const B=Z,F=B&&u;if(a.sessions.length===0&&L&&a.worktree){const O=u&&P;await Xu({projectDirectory:_,path:a.worktree.path,branch:a.worktree.branch,force:!0,deleteRemote:O});const z=O?"Worktree and remote branch removed.":"Worktree removed.";te.success("Worktree removed",{description:vo(z)}),K(),h();return}if(a.sessions.length===1){const O=a.sessions[0];if(!await g(O.id,{archiveWorktree:B,deleteRemoteBranch:F})){te.error("Failed to delete session"),p(!1);return}const Q=B?F?"Worktree and remote branch removed.":"Attached worktree archived.":void 0;te.success("Session deleted",{description:vo(Q)})}else{const O=a.sessions.map(me=>me.id),{deletedIds:z,failedIds:Q}=await w(O,{archiveWorktree:B,deleteRemoteBranch:F});if(z.length>0){const me=B?F?"Archived worktrees and removed remote branches.":"Attached worktrees archived.":void 0,he=[Q.length>0?`${Q.length} session${Q.length===1?"":"s"} could not be deleted.`:a.dateLabel?`Removed all sessions from ${a.dateLabel}.`:void 0,me].filter(Boolean).join(" ");te.success(`Deleted ${z.length} session${z.length===1?"":"s"}`,{description:vo(he||void 0)})}if(Q.length>0&&(te.error(`Failed to delete ${Q.length} session${Q.length===1?"":"s"}`,{description:vo("Please try again in a moment.")}),z.length===0)){p(!1);return}}K()}finally{p(!1)}}},[a,u,g,w,K,Z,L,P,_,h]),Y=a?.worktree??l[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}`:""}.`:"",V=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:[L&&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(B=>e.jsx("li",{className:"typography-micro text-muted-foreground/80",children:B.title||"Untitled Session"},B.id)),a.sessions.length>5&&e.jsxs("li",{className:"typography-micro text-muted-foreground/70",children:["+",a.sessions.length-5," more"]})]})]}),L?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?Vr(Y.path,y):"Worktree path unavailable."}),T&&e.jsx("p",{className:"typography-micro text-warning",children:"Uncommitted changes will be discarded."}),P?e.jsxs("button",{type:"button",onClick:()=>{q||m(B=>!B)},disabled:q,className:R("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(Qi,{className:"size-4 text-primary"}):e.jsx(Xi,{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(Ce,{variant:"ghost",onClick:K,disabled:f,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:se,disabled:f,children:f?"Deleting…":L?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions"})]}),E=L?"Delete worktree":a?.sessions.length===1?"Delete session":"Delete sessions";return e.jsxs(e.Fragment,{children:[I?e.jsx(vs,{open:!!a,onClose:()=>{f||K()},title:E,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}),V]})}):e.jsx(ms,{open:!!a,onOpenChange:B=>{if(!B){if(f)return;K()}},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:E}),re&&e.jsx(Ns,{children:re})]}),V,e.jsx(Ks,{className:"mt-2 gap-2 pt-1 pb-1",children:ae})]})}),e.jsx(wb,{open:s,onOpenChange:r})]})};function Sb(){return new Worker(Pp,{type:"module"})}const kb=["typescript","javascript","tsx","jsx","json","html","css","markdown","yaml","python","rust","go","bash"];function Nb(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 Uc(s){if(typeof window>"u")return()=>{};const r=window.setTimeout(()=>s(void 0),0);return()=>window.clearTimeout(r)}const Cb=({children:s})=>{const r=Fp(),t=Xt(l=>l.activeDirectory),n=Xt(l=>t?l.directories.get(t)?.lastStatusChange??0:0),o=Xt(l=>t?l.directories.get(t)?.diffCache.size??0:0),a=De.useRef(!1),i=De.useRef(new Map);return De.useEffect(()=>{if(!r||a.current)return;a.current=!0;const l={name:"warmup.ts",contents:"const x = 1;",lang:"typescript",cacheKey:"warmup-file"},d=wi(l,{...l,contents:"const x = 2;",cacheKey:"warmup-file-2"}),u={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(u,d)},[r]),De.useEffect(()=>{if(!r||!t||!n||o===0)return;const l=Xt.getState().directories.get(t);if(!l||l.diffCache.size===0||(i.current.get(t)??0)>=l.lastStatusChange)return;i.current.set(t,l.lastStatusChange);let u=!1,m=null;const f=Array.from(l.diffCache.entries());let p=0;const g=w=>{if(u)return;const h=Date.now();for(;p<f.length&&!(w&&w.timeRemaining()<8||!w&&Date.now()-h>8);){const[j,x]=f[p];p+=1,nn(j);const y=Nb(j,x.original,x.modified),b={name:j,contents:x.original,cacheKey:`old-${y}`},N={name:j,contents:x.modified,cacheKey:`new-${y}`},v=wi(b,N),k={onHighlightSuccess:()=>{},onHighlightError:()=>{}};r.highlightDiffAST(k,v)}p<f.length&&(m=Uc(g))};return g(void 0),p<f.length&&(m=Uc(g)),()=>{u=!0,m?.()}},[r,t,n,o]),e.jsx(e.Fragment,{children:s})},Mb=({children:s})=>{const t=ya()?.currentTheme?.metadata?.variant==="dark";hm();const n=De.useMemo(()=>({theme:{dark:Mn.dark,light:Mn.light},themeType:t?"dark":"light",langs:kb}),[t]);return e.jsx(Tp,{poolOptions:{workerFactory:Sb,poolSize:4,totalASTLRUCacheSize:200},highlighterOptions:n,children:e.jsx(Cb,{children:s})})},Ts=De.forwardRef(({className:s,...r},t)=>e.jsx(ft,{as:"textarea",ref:t,disableHorizontal:!0,fillContainer:!1,outerClassName:"w-full",className:R("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}));Ts.displayName="Textarea";const va=Rp,Sl=({className:s,...r})=>e.jsx(_p,{className:R("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}),ja=({className:s,...r})=>e.jsx(Op,{className:R("overflow-hidden data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down",s),...r}),_i=s=>s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").substring(0,50),Db=(s,r)=>{const t=_i(s),n=_i(r);return`${t}-${n}`.substring(0,60)},Vc=(s,r)=>`${s}/${r}`,Ab=s=>s.trim().replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,120),Eb=()=>{const s=Ft.getState(),r=s.activeProjectId,t=r?s.projects.find(l=>l.id===r)?.path:void 0;if(typeof t=="string"&&t.trim().length>0)return t;const n=mt.getState().currentDirectory??null;if(!n)return null;const o=n.replace(/\\/g,"/").replace(/\/+$/,"")||n,i=o.indexOf("/.openchamber/");return i>0?o.slice(0,i):o.endsWith("/.openchamber")?o.slice(0,o.length-13):o},Kn=zt()(Yt(s=>({isLoading:!1,error:null,createMultiRun:async r=>{const t=r.name.trim(),n=r.prompt.trim(),{models:o,agent:a,files:i,setupCommands:l}=r;if(!t)return s({error:"Group name is required"}),null;if(!n)return s({error:"Prompt is required"}),null;if(o.length<1)return s({error:"Select at least 1 model"}),null;if(o.length>5)return s({error:"Maximum 5 models allowed"}),null;s({isLoading:!0,error:null});try{const d=Eb();if(!d)return s({error:"No directory selected",isLoading:!1}),null;if(!await rn(d))return s({error:"Not in a git repository",isLoading:!1}),null;const m=_i(t),f=typeof r.worktreeBaseBranch=="string"&&r.worktreeBaseBranch.trim().length>0?r.worktreeBaseBranch.trim():"HEAD",p=f!=="HEAD"?f:void 0,g=[],w=l?.filter(v=>v.trim().length>0)??[],h=new Map;for(const v of o){const k=`${v.providerID}:${v.modelID}`;h.set(k,(h.get(k)||0)+1)}const j=new Map;for(const v of o){const k=`${v.providerID}:${v.modelID}`,D=h.get(k)||1,C=(j.get(k)||0)+1;j.set(k,C);const M=Db(v.providerID,v.modelID),S=D>1?Vc(m,`${M}/${C}`):Vc(m,M);if(!S)return s({error:"Branch name is required for worktree creation",isLoading:!1}),null;const A=Ab(S);if(!A)return s({error:`Invalid branch name: ${S}`,isLoading:!1}),null;try{const I=await Qu({projectDirectory:d,worktreeSlug:A,branch:S,createBranch:!0,startPoint:p}),_=D>1?`${m}/${v.providerID}/${v.modelID}/${C}`:`${m}/${v.providerID}/${v.modelID}`,T=await je.withDirectory(I.path,()=>je.createSession({title:_}));lt.getState().setWorktreeMetadata(T.id,I),g.push({sessionId:T.id,worktreePath:I.path,providerID:v.providerID,modelID:v.modelID,variant:v.variant})}catch(I){console.warn("[MultiRun] Failed to create session:",I)}}const x=l?.filter(v=>v.trim().length>0)??[];x.length>0&&qu(d,x).catch(()=>{console.warn("[MultiRun] Failed to save worktree setup commands")});const y=g.map(v=>v.sessionId),b=g[0]?.sessionId??null;if(y.length===0)return s({error:"Failed to create any sessions",isLoading:!1}),null;const N=i?.map(v=>({type:"file",mime:v.mime,filename:v.filename,url:v.url}));try{await lt.getState().loadSessions()}catch{}if(w.length>0)for(const v of g)Ju(v.worktreePath,d,w).then(k=>{if(!k.success){const D=k.results.filter(C=>!C.success);console.warn(`[MultiRun] Setup commands failed for ${v.worktreePath}:`,D)}}).catch(k=>{console.warn(`[MultiRun] Setup commands error for ${v.worktreePath}:`,k)});return(async()=>{try{await Promise.allSettled(g.map(async v=>{try{await je.withDirectory(v.worktreePath,()=>je.sendMessage({id:v.sessionId,providerID:v.providerID,modelID:v.modelID,variant:v.variant,text:n,agent:a,files:N}))}catch(k){console.warn("[MultiRun] Failed to start run:",k)}}))}catch(v){console.warn("[MultiRun] Failed to start runs:",v)}})(),s({isLoading:!1}),{groupSlug:m,sessionIds:y,firstSessionId:b}}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 js({...s}){return e.jsx($p,{"data-slot":"select",...s})}function qr({...s}){return e.jsx(Vp,{"data-slot":"select-group",...s})}function Jr({...s}){return e.jsx(zp,{"data-slot":"select-value",...s})}function Ss({className:s,size:r="default",children:t,...n}){return e.jsxs(Lp,{"data-slot":"select-trigger","data-size":r,className:R("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(Bp,{asChild:!0,children:e.jsx(It,{className:"size-4 opacity-50"})})]})}function ks({className:s,children:r,position:t="popper",fitContent:n=!1,...o}){return e.jsx(Wp,{children:e.jsx(Hp,{"data-slot":"select-content",className:R("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(ft,{as:Up,outerClassName:R("max-h-[var(--radix-select-content-available-height)]",n?"w-max":"w-full"),className:R("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 jn({className:s,...r}){return e.jsx(Gp,{"data-slot":"select-label",className:R("text-muted-foreground px-2 py-1.5 typography-meta",s),...r})}function Bt({className:s,children:r,...t}){return e.jsxs(qp,{"data-slot":"select-item",className:R("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(Kp,{children:e.jsx(Pt,{className:"size-4"})})}),e.jsx(Yp,{children:r})]})}function na({className:s,...r}){return e.jsx(Qp,{"data-slot":"select-separator",className:R("bg-border pointer-events-none -mx-1 my-1 h-px",s),...r})}const Ib="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",Pb=Object.assign({"../assets/provider-logos/gocode.svg":Ib}),Oi=new Map;for(const[s,r]of Object.entries(Pb)){const t=s.match(/provider-logos\/([^/]+)\.svg$/i);t?.[1]&&r&&Oi.set(t[1].toLowerCase(),r)}function Cm(s){const r=s?.toLowerCase()??null,t=r?Oi.has(r):!1,n=r?Oi.get(r)??null:null,[o,a]=De.useState(t?"local":"remote");De.useEffect(()=>{a(t?"local":"remote")},[t,r]);const i=De.useCallback(()=>{a(l=>l==="local"&&t?"remote":"none")},[t]);return r?o==="local"&&n?{src:n,onError:i,hasLogo:!0}:o==="remote"?{src:`https://models.dev/logos/${r}.svg`,onError:i,hasLogo:!0}:{src:null,onError:i,hasLogo:!1}:{src:null,onError:i,hasLogo:!1}}const is=({providerId:s,alt:r,className:t,onError:n})=>{const{src:o,onError:a,hasLogo:i}=Cm(s),l=c.useCallback(()=>{a(),n?.()},[a,n]);return!i||!o?null:e.jsx("img",{src:o,alt:r||`${s} logo`,className:R("dark:invert",t),onError:l})},kl=s=>s.nativeEvent.isComposing||s.nativeEvent.keyCode===229,Nl=()=>{const{providers:s}=rt(),{favoriteModels:r,recentModels:t}=_e(),n=c.useMemo(()=>r.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null),[r,s]),o=c.useMemo(()=>t.map(({providerID:a,modelID:i})=>{const l=s.find(m=>m.id===a);if(!l)return null;const u=(Array.isArray(l.models)?l.models:[]).find(m=>m.id===i);return u?{provider:l,model:u,providerID:a,modelID:i}:null}).filter(a=>a!==null).filter(({providerID:a,modelID:i})=>!r.some(l=>l.providerID===a&&l.modelID===i)),[t,s,r]);return{favoriteModelsList:n,recentModelsList:o}},Mm="h-7",oa=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,Tb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Fb=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=Tb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Rb=({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:R("flex items-center gap-1.5 px-2 rounded-md bg-accent/50 border border-border/30",Mm),children:[e.jsx(is,{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"})})]})},Dm=({selectedModels:s,onAdd:r,onRemove:t,onUpdate:n,minModels:o,addButtonLabel:a="Add model",showChips:i=!0,maxModels:l})=>{const{providers:d,modelsMetadata:u}=rt(),{favoriteModelsList:m,recentModelsList:f}=Nl(),[p,g]=c.useState(!1),[w,h]=c.useState(""),[j,x]=c.useState(0),[y,b]=c.useState(null),N=c.useRef(null),v=c.useRef(null),k=c.useRef(null),D=c.useRef([]),C=c.useMemo(()=>{const q=new Map;for(const $ of s){const H=`${$.providerID}:${$.modelID}`;q.set(H,(q.get(H)||0)+1)}return q},[s]),M=c.useCallback(q=>s.filter(H=>H.providerID===q.providerID&&H.modelID===q.modelID).findIndex(H=>H.instanceId===q.instanceId)+1,[s]),S=(q,$)=>{const H=`${q}/${$}`;return u.get(H)},A=q=>{const $=q?.name||q?.id||"",H=String($);return H.length>40?H.substring(0,37)+"...":H},I=c.useCallback((q,$)=>{if(!w.trim())return!0;const H=w.toLowerCase();return q.toLowerCase().includes(H)||$.toLowerCase().includes(H)},[w]),_=c.useMemo(()=>m.filter(({model:q,providerID:$})=>{const U=d.find(se=>se.id===$)?.name||$,K=A(q);return I(K,U)}),[m,d,I]),T=c.useMemo(()=>f.filter(({model:q,providerID:$})=>{const U=d.find(se=>se.id===$)?.name||$,K=A(q);return I(K,U)}),[f,d,I]),P=c.useMemo(()=>d.map(q=>{const H=(Array.isArray(q.models)?q.models:[]).filter(U=>{const K=A(U);return I(K,q.name||q.id||"")});return{...q,models:H}}).filter(q=>q.models.length>0),[d,I]),L=_.length>0||T.length>0||P.length>0;c.useEffect(()=>{if(p&&k.current){const $=k.current.getBoundingClientRect().top-100;b(Math.max(150,Math.min(400,$)))}},[p]),c.useEffect(()=>{p&&N.current&&N.current.focus()},[p]),c.useEffect(()=>{if(!p)return;const q=$=>{v.current&&!v.current.contains($.target)&&(g(!1),h(""),x(0))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[p]),c.useEffect(()=>{x(0)},[w]);const Z=(q,$,H,U,K,se)=>{const Y=`${$}:${H}`,re=C.get(Y)||0,V=S($,H),ae=Fb(V?.limit?.context);return e.jsxs("button",{ref:E=>{D.current[K]=E},type:"button",onClick:()=>{r({providerID:$,modelID:H,displayName:q.name||H,instanceId:oa()})},onMouseEnter:()=>x(K),className:R("w-full text-left px-2 py-1.5 rounded-md typography-meta transition-colors flex items-center gap-2",se?"bg-accent":"hover:bg-accent/50"),children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-1 min-w-0",children:[e.jsx("span",{className:"font-medium truncate",children:A(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]})]},`${U}-${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:v,children:[e.jsxs(Ce,{ref:k,type:"button",variant:"outline",size:"sm",className:Mm,onClick:()=>g(!p),children:[e.jsx(Kt,{className:"h-3.5 w-3.5 mr-1"}),a]}),p&&(()=>{const q=[];_.forEach(({model:K,providerID:se,modelID:Y})=>{q.push({model:K,providerID:se,modelID:Y,section:"fav"})}),T.forEach(({model:K,providerID:se,modelID:Y})=>{q.push({model:K,providerID:se,modelID:Y,section:"recent"})}),P.forEach(K=>{K.models.forEach(se=>{q.push({model:se,providerID:K.id,modelID:se.id,section:"provider"})})});const $=q.length,H=K=>{if(!kl(K))if(K.key==="ArrowDown"){K.preventDefault(),K.stopPropagation();const se=(j+1)%Math.max(1,$);x(se),setTimeout(()=>{D.current[se]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(K.key==="ArrowUp"){K.preventDefault(),K.stopPropagation();const se=(j-1+Math.max(1,$))%Math.max(1,$);x(se),setTimeout(()=>{D.current[se]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(K.key==="Enter"){K.preventDefault(),K.stopPropagation();const se=q[j];se&&r({providerID:se.providerID,modelID:se.modelID,displayName:se.model.name||se.modelID,instanceId:oa()})}else K.key==="Escape"&&(K.preventDefault(),K.stopPropagation(),g(!1),h(""),x(0))};let U=0;return e.jsxs("div",{className:"absolute bottom-full left-0 mb-1 z-50 border border-border/30 rounded-xl overflow-hidden bg-background shadow-lg w-[min(380px,calc(100vw-2rem))] flex flex-col",children:[e.jsx("div",{className:"p-2 border-b border-border/40",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{ref:N,type:"text",placeholder:"Search models",value:w,onChange:K=>h(K.target.value),onKeyDown:H,className:"h-8 pl-8 typography-meta"})]})}),e.jsx(ft,{outerClassName:"flex-1",style:{maxHeight:y?`${y}px`:"300px"},children:e.jsxs("div",{className:"p-1",children:[!L&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),_.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),_.map(({model:K,providerID:se,modelID:Y})=>{const re=U++;return Z(K,se,Y,"fav",re,j===re)})]}),T.length>0&&e.jsxs(e.Fragment,{children:[_.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),e.jsxs("div",{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),T.map(({model:K,providerID:se,modelID:Y})=>{const re=U++;return Z(K,se,Y,"recent",re,j===re)})]}),(_.length>0||T.length>0)&&P.length>0&&e.jsx("div",{className:"h-px bg-border/40 my-1"}),P.map((K,se)=>e.jsxs(c.Fragment,{children:[se>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(is,{providerId:K.id,className:"h-4 w-4 flex-shrink-0"}),K.name]}),K.models.map(Y=>{const re=U++;return Z(Y,K.id,Y.id,"provider",re,j===re)})]},K.id))]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t border-border/40 typography-micro text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})})()]}),i&&s.length>0&&e.jsx("div",{className:"flex flex-col gap-2 w-full",children:s.map((q,$)=>{const H=`${q.providerID}:${q.modelID}`,U=C.get(H)||1,K=M(q),Y=d.find(B=>B.id===q.providerID)?.models.find(B=>B.id===q.modelID),re=Y?.variants?Object.keys(Y.variants):[],V=re.length>0,ae="__default__",E=q.variant??ae;return e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Rb,{model:q,instanceIndex:K,totalSameModel:U,onRemove:()=>t($)}),V&&e.jsxs(js,{value:E,onValueChange:B=>{if(!n)return;n($,{...q,variant:B===ae?void 0:B})},children:[e.jsxs(Ss,{size:"chip",className:"px-2 gap-1.5 rounded-md bg-accent/50 border-border/30 hover:bg-accent/60 typography-meta font-medium text-foreground",children:[e.jsx(ar,{className:R("h-3.5 w-3.5 flex-shrink-0",E===ae?"text-muted-foreground":"text-[color:var(--status-info)]")}),e.jsx(Jr,{placeholder:"Thinking"})]}),e.jsxs(ks,{fitContent:!0,children:[e.jsx(Bt,{value:ae,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),re.map(B=>e.jsx(Bt,{value:B,className:"pr-2 [&>span:first-child]:hidden",children:B},B))]})]})]},q.instanceId)})})]}),o!==void 0&&s.length<o&&e.jsxs("p",{className:"typography-micro text-muted-foreground",children:["Select from ",o," ",l!==void 0?`to ${l} models`:"","."]})]})};function Cl(s){const[r,t]=c.useState([{value:"HEAD",label:"Current (HEAD)",group:"special"}]),[n,o]=c.useState(!1),[a,i]=c.useState(null);return c.useEffect(()=>{let l=!1;if(!s){i(null),o(!1),t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}return o(!0),i(null),(async()=>{try{const d=await rn(s);if(l)return;if(i(d),!d){t([{value:"HEAD",label:"Current (HEAD)",group:"special"}]);return}const u=await ll(s).catch(()=>null);if(l)return;const m=[],f=u?.current?`Current (HEAD: ${u.current})`:"Current (HEAD)";m.push({value:"HEAD",label:f,group:"special"}),u&&(u.all.filter(w=>!w.startsWith("remotes/")).sort((w,h)=>w.localeCompare(h)).forEach(w=>{m.push({value:w,label:w,group:"local"})}),u.all.filter(w=>w.startsWith("remotes/")).map(w=>w.replace(/^remotes\//,"")).sort((w,h)=>w.localeCompare(h)).forEach(w=>{m.push({value:w,label:w,group:"remote"})})),t(m)}finally{l||o(!1)}})(),()=>{l=!0}},[s]),{branches:r,isLoading:n,isGitRepository:a}}const Am=({directory:s,value:r,onChange:t,className:n,disabled:o,id:a})=>{const{branches:i,isLoading:l,isGitRepository:d}=Cl(s),u=c.useMemo(()=>i.find(f=>f.value===r)?.label??null,[i,r]);c.useEffect(()=>{!i.some(p=>p.value===r)&&i.length>0&&t("HEAD")},[i,r,t]);const m=o||!d||l;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(js,{value:r,onValueChange:t,disabled:m,children:[e.jsx(Ss,{id:a,size:"lg",className:n??"max-w-full typography-meta text-foreground",children:u?e.jsx(Jr,{children:u}):e.jsx(Jr,{placeholder:l?"Loading branches…":"Select a branch"})}),e.jsxs(ks,{fitContent:!0,children:[e.jsxs(qr,{children:[e.jsx(jn,{children:"Default"}),i.filter(f=>f.group==="special").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]}),i.some(f=>f.group==="local")?e.jsxs(e.Fragment,{children:[e.jsx(na,{}),e.jsxs(qr,{children:[e.jsx(jn,{children:"Local branches"}),i.filter(f=>f.group==="local").map(f=>e.jsx(Bt,{value:f.value,className:"w-auto whitespace-nowrap",children:f.label},f.value))]})]}):null,i.some(f=>f.group==="remote")?e.jsxs(e.Fragment,{children:[e.jsx(na,{}),e.jsxs(qr,{children:[e.jsx(jn,{children:"Remote branches"}),i.filter(f=>f.group==="remote").map(f=>e.jsx(Bt,{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."})]})},Em=({value:s,onChange:r,className:t,disabled:n,id:o})=>{const a=rt(f=>f.getVisibleAgents),i=rt(f=>f.loadAgents),l=rt(f=>f.currentAgentName),d=a(),u=c.useMemo(()=>d.filter(f=>f.mode!=="subagent"),[d]);c.useEffect(()=>{i()},[i]),c.useEffect(()=>{if(n)return;const f=s.trim();if(f.length>0&&u.some(w=>w.name===f))return;const p=typeof l=="string"&&l.trim().length>0?l.trim():null;if(p&&u.some(w=>w.name===p)){r(p);return}const g=u[0]?.name;g&&r(g)},[l,n,r,u,s]);const m=s.trim().length>0?s:void 0;return e.jsxs(js,{value:m,onValueChange:r,disabled:n,children:[e.jsx(Ss,{id:o,size:"lg",className:t??"max-w-full typography-meta text-foreground",children:e.jsx(Jr,{placeholder:"Select an agent"})}),e.jsx(ks,{fitContent:!0,children:u.length>0&&e.jsx(qr,{children:u.map(f=>e.jsx(Bt,{value:f.name,className:"w-auto whitespace-nowrap",children:f.name},f.name))})})]})},_b=10*1024*1024,Gc=5,qc=({initialPrompt:s,onCreated:r,onCancel:t})=>{const[n,o]=c.useState(""),[a,i]=c.useState(()=>s??""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,w]=c.useState(!1),[h,j]=c.useState([]),[x,y]=c.useState(!1),[b,N]=c.useState(!1),v=c.useRef(null),k=mt(F=>F.currentDirectory??null),D=c.useMemo(()=>{if(typeof window>"u")return null;const F=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof F=="string"&&F.trim().length>0?F.trim():null},[]),C=Ft(F=>F.activeProjectId),M=Ft(F=>F.projects),S=c.useMemo(()=>{if(C){const me=M.find(Se=>Se.id===C);if(me?.path)return me.path}const F=k??D;if(!F)return null;const O=F.replace(/\\/g,"/").replace(/\/+$/,"")||F,Q=O.indexOf("/.openchamber/");return Q>0?O.slice(0,Q):O.endsWith("/.openchamber")?O.slice(0,O.length-13):O},[C,M,k,D]),A=_e(F=>F.isSidebarOpen),[I,_]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),T=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]);c.useEffect(()=>{if(typeof window>"u")return;const F=typeof window.opencodeDesktop<"u";_(F)},[]);const P=c.useMemo(()=>I&&T?A?"pl-0":"pl-[8.0rem]":"pl-3",[I,T,A]),[L,Z]=c.useState("HEAD"),{isLoading:q,isGitRepository:$}=Cl(k),H=Kn(F=>F.createMultiRun),U=Kn(F=>F.error),K=Kn(F=>F.clearError);c.useEffect(()=>{typeof s=="string"&&s.trim().length>0&&i(F=>F.trim().length>0?F:s)},[s]),c.useEffect(()=>{if(!S)return;let F=!1;return N(!0),(async()=>{try{const O=await io(S);F||j(O)}catch{}finally{F||N(!1)}})(),()=>{F=!0}},[S]);const se=F=>{l.length>=Gc||(d(O=>[...O,F]),K())},Y=F=>{d(O=>O.filter((z,Q)=>Q!==F)),K()},re=c.useCallback((F,O)=>{d(z=>z.map((Q,me)=>me===F?O:Q))},[]),V=async F=>{const O=F.target.files;if(!O)return;let z=0;for(let Q=0;Q<O.length;Q++){const me=O[Q];if(me.size>_b){te.error(`File "${me.name}" is too large (max 10MB)`);continue}try{const Se=await new Promise((Pe,ve)=>{const Be=new FileReader;Be.onload=()=>Pe(Be.result),Be.onerror=ve,Be.readAsDataURL(me)}),he={id:oa(),filename:me.name,mimeType:me.type||"application/octet-stream",size:me.size,dataUrl:Se};p(Pe=>[...Pe,he]),z++}catch(Se){console.error("File attach failed",Se),te.error(`Failed to attach "${me.name}"`)}}z>0&&te.success(`Attached ${z} file${z>1?"s":""}`),v.current&&(v.current.value="")},ae=F=>{p(O=>O.filter(z=>z.id!==F))},E=async F=>{if(F.preventDefault(),!!a.trim()&&!(l.length<2)){w(!0),K();try{const O=l.map(({instanceId:he,...Pe})=>Pe),z=f.map(he=>({mime:he.mimeType,filename:he.filename,url:he.dataUrl})),Q=h.filter(he=>he.trim().length>0),me={name:n.trim(),prompt:a.trim(),models:O,agent:u||void 0,worktreeBaseBranch:L,files:z.length>0?z:void 0,setupCommands:Q.length>0?Q:void 0},Se=await H(me);Se&&(Se.firstSessionId&&ue.getState().setCurrentSession(Se.firstSessionId),r?.())}finally{w(!1)}}},B=!!(n.trim()&&a.trim()&&l.length>=2&&$&&!q);return e.jsxs("div",{className:"flex flex-col h-full bg-background",children:[e.jsxs("header",{className:R("flex h-12 items-center justify-between border-b app-region-drag",P),style:{borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("flex items-center gap-3",I&&T&&A&&"pl-4"),children:e.jsx("h1",{className:"typography-ui-label font-medium",children:"New Multi-Run"})}),t&&e.jsx("div",{className:"flex items-center pr-3",children:e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{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(nt,{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:E,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(ht,{id:"group-name",value:n,onChange:F=>o(F.target.value),placeholder:"e.g. feature-auth, bugfix-login",className:"typography-body max-w-full sm:max-w-xs",required:!0}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Used for worktree directory and branch names"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Worktrees"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Create one worktree per model by creating a new branch from a base branch."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-meta font-medium text-foreground",htmlFor:"multirun-worktree-base-branch",children:"Base branch"}),e.jsx(Am,{directory:k,value:L,onChange:Z,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:L||"HEAD"}),"."]})]}),e.jsxs(va,{open:x,onOpenChange:y,children:[e.jsxs(Sl,{className:"w-full flex items-center justify-between py-1 hover:opacity-80 transition-opacity",children:[e.jsxs("p",{className:"typography-ui-label font-medium text-foreground",children:["Setup commands",h.filter(F=>F.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",h.filter(F=>F.trim()).length," configured)"]})]}),e.jsx(It,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",x&&"rotate-180")})]}),e.jsx(ja,{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."]}),b?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[h.map((F,O)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:F,onChange:z=>{const Q=[...h];Q[O]=z.target.value,j(Q)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const z=h.filter((Q,me)=>me!==O);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"})})]},O)),e.jsxs("button",{type:"button",onClick:()=>j([...h,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",htmlFor:"multirun-agent",children:"Agent"}),e.jsx(Em,{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(Ts,{id:"prompt",value:a,onChange:F=>i(F.target.value),placeholder:"Enter the prompt to send to all models...",className:"typography-body min-h-[120px] max-h-[400px] resize-none overflow-y-auto field-sizing-content",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Attachments"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"(optional, same files for all runs)"})]}),e.jsx("input",{ref:v,type:"file",multiple:!0,className:"hidden",onChange:V,accept:"*/*"}),e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs(Ce,{type:"button",variant:"outline",size:"sm",className:"h-7",onClick:()=>v.current?.click(),children:[e.jsx(qo,{className:"h-3.5 w-3.5 mr-1.5"}),"Attach files"]}),f.map(F=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2 py-1 bg-muted/30 border border-border/30 rounded-md typography-meta",children:[F.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:F.filename,children:F.filename}),e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",F.size<1024?`${F.size}B`:F.size<1024*1024?`${(F.size/1024).toFixed(1)}KB`:`${(F.size/(1024*1024)).toFixed(1)}MB`,")"]}),e.jsx("button",{type:"button",onClick:()=>ae(F.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},F.id))]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Models ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Dm,{selectedModels:l,onAdd:se,onRemove:Y,onUpdate:re,minModels:2,maxModels:Gc})]}),U&&e.jsx("div",{className:"px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/30 text-destructive typography-body",children:U}),e.jsxs("div",{className:"flex items-center justify-end gap-3 pt-4",children:[e.jsx(Ce,{type:"button",variant:"outline",onClick:t,children:"Cancel"}),e.jsx(Ce,{type:"submit",disabled:!B||g,children:g?"Creating...":e.jsxs(e.Fragment,{children:[e.jsx(Xp,{className:"h-4 w-4 mr-2"}),"Start (",l.length," models)"]})})]})]})})})]})},Ob=(s={})=>{const{edgeThreshold:r=30,minSwipeDistance:t=50,maxSwipeTime:n=300,enabled:o=!0}=s,{isMobile:a,setSessionSwitcherOpen:i,isSessionSwitcherOpen:l}=_e(),d=De.useRef(null),u=De.useRef(null);return De.useEffect(()=>{if(!o||!a)return;const m=w=>{const h=w.touches[0];if(!h){d.current=null;return}h.clientX<=r?d.current={x:h.clientX,y:h.clientY,time:Date.now()}:d.current=null},f=w=>{if(!d.current)return;const h=w.touches[0];if(!h)return;h.clientX-d.current.x>10&&w.preventDefault()},p=w=>{if(!d.current)return;const h=w.changedTouches[0];if(!h){d.current=null,u.current=null;return}u.current={x:h.clientX,y:h.clientY,time:Date.now()};const{x:j,y:x,time:y}=d.current,{x:b,y:N,time:v}=u.current,k=b-j,D=N-x,C=v-y,M=Math.abs(D)<Math.abs(k),S=C<=n,A=Math.abs(D)<t;k>=t&&M&&S&&A&&!l&&i(!0),d.current=null,u.current=null},g=()=>{d.current=null,u.current=null};return document.addEventListener("touchstart",m,{passive:!0,capture:!0}),document.addEventListener("touchmove",f,{passive:!1,capture:!0}),document.addEventListener("touchend",p,{passive:!0,capture:!0}),document.addEventListener("touchcancel",g,{passive:!0,capture:!0}),()=>{document.removeEventListener("touchstart",m,{capture:!0}),document.removeEventListener("touchmove",f,{capture:!0}),document.removeEventListener("touchend",p,{capture:!0}),document.removeEventListener("touchcancel",g,{capture:!0})}},[o,a,r,t,n,i,l]),null},Wn=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;De.memo(()=>{const s=De.useRef(null),{addAttachedFile:r}=ue(),{isMobile:t}=_e(),n=mm(),o=t?"h-9 w-9":"h-7 w-7",a=t?"h-5 w-5":"h-[18px] w-[18px]",i=async u=>{let m=0;for(let f=0;f<u.length;f++){const p=u[f],g=ue.getState().attachedFiles.length;try{await r(p),ue.getState().attachedFiles.length>g&&m++}catch(w){console.error("File attach failed",w),te.error(w instanceof Error?w.message:"Failed to attach file")}}m>0&&te.success(`Attached ${m} file${m>1?"s":""}`)},l=async u=>{const m=u.target.files;m&&(await i(m),s.current&&(s.current.value=""))},d=async()=>{try{const m=await(await fetch("/api/vscode/pick-files")).json(),f=Array.isArray(m?.files)?m.files:[],p=Array.isArray(m?.skipped)?m.skipped:[];if(p.length>0){const w=p.map(h=>`${h?.name||"file"}: ${h?.reason||"skipped"}`).join(`
66
- `);te.error(`Some files were skipped:
67
- ${w}`)}const g=f.map(w=>{if(!w?.dataUrl)return null;try{const[h,j]=w.dataUrl.split(","),x=w.mimeType||h?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!j)return null;const y=atob(j),b=new Uint8Array(y.length);for(let v=0;v<y.length;v++)b[v]=y.charCodeAt(v);const N=new Blob([b],{type:x});return new File([N],w.name||"file",{type:x})}catch(h){return console.error("Failed to decode VS Code picked file",h),null}}).filter(Boolean);g.length>0&&await i(g)}catch(u){console.error("VS Code file pick failed",u),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:l,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>{n?d():s.current?.click()},className:R(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(qo,{className:R(a,"text-current")})})]})});const $b=De.memo(({file:s,onRemove:r})=>{const t=()=>s.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):s.mimeType.includes("text")||s.mimeType.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):s.mimeType.includes("json")||s.mimeType.includes("xml")?e.jsx(ma,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),n=i=>i<1024?i+" B":i<1048576?(i/1024).toFixed(1)+" KB":(i/1048576).toFixed(1)+" MB",a=(i=>{const d=i.replace(/\\/g,"/").split("/");return d[d.length-1]||i})(s.filename);return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[e.jsx("div",{title:s.source==="server"?"Server file":"Local file",children:s.source==="server"?e.jsx(Jp,{className:"h-3 w-3 text-primary"}):e.jsx(du,{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"})})]})}),Lb=De.memo(()=>{const{attachedFiles:s,removeAttachedFile:r}=ue();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($b,{file:t,onRemove:()=>r(t.id)},t.id))]})})}),Im=De.memo(({files:s,onShowPopup:r})=>{const t=s.filter(d=>d.type==="file"&&(d.mime||d.url)),n=d=>{if(!d)return"Unnamed file";const m=d.replace(/\\/g,"/").split("/");return m[m.length-1]||d},o=d=>d?d.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5"}):d.includes("text")||d.includes("code")?e.jsx(tr,{className:"h-3.5 w-3.5"}):d.includes("json")||d.includes("xml")?e.jsx(ma,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}):e.jsx(tr,{className:"h-3.5 w-3.5"}),a=t.filter(d=>d.mime?.startsWith("image/")&&d.url),i=t.filter(d=>!d.mime?.startsWith("image/")),l=c.useCallback(d=>{if(!r||!d?.url)return;const u=n(d.filename)||"Image",m={open:!0,title:u,content:"",metadata:{tool:"image-preview",filename:u,mime:d.mime,size:d.size},image:{url:d.url,mimeType:d.mime,filename:u}};r(m)},[r]);return t.length===0?null:e.jsxs("div",{className:"space-y-2 mt-2",children:[i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:i.map((d,u)=>e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta",children:[o(d.mime),e.jsx("span",{children:n(d.filename)})]},`file-${u}`))}),a.length>0&&e.jsx("div",{className:"overflow-x-auto -mx-1 px-1 py-1 scrollbar-thin",children:e.jsx("div",{className:"flex gap-3 snap-x snap-mandatory",children:a.map((d,u)=>{const m=n(d.filename)||"Image";return e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsxs("button",{type:"button",onClick:()=>l(d),className:"relative flex-none w-16 sm:w-20 md:w-24 aspect-square rounded-xl border border-border/40 bg-muted/10 overflow-hidden snap-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-1 focus-visible:ring-primary","aria-label":m,children:[d.url?e.jsx("img",{src:d.url,alt:m,className:"h-full w-full object-cover",loading:"lazy",onError:f=>{const p=f.target;p.style.visibility="hidden"}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-muted/30 text-muted-foreground",children:e.jsx(br,{className:"h-6 w-6"})}),e.jsx("span",{className:"sr-only",children:m})]})}),e.jsx(nt,{side:"top",sideOffset:6,className:"typography-meta px-2 py-1",children:m})]},`img-${u}`)})})})]})}),Pm=De.memo(({message:s,sessionId:r,onEdit:t})=>{const n=Zs(i=>i.removeFromQueue),o=c.useMemo(()=>{const i=s.content.split(`
68
- `),l=i[0]||"",d=50;return l.length>d?l.substring(0,d)+"...":l+(i.length>1?"...":"")},[s.content]),a=s.attachments?.length??0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 bg-muted/30 border border-border/30 rounded-xl typography-meta group",children:[e.jsx(Zp,{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"})})]})});Pm.displayName="QueuedMessageChip";const Kc=[],Tm=De.memo(({onEditMessage:s})=>{const r=ue(a=>a.currentSessionId),t=Zs(c.useCallback(a=>r?a.queuedMessages[r]??Kc:Kc,[r])),n=Zs(a=>a.popToInput),o=c.useCallback(a=>{if(!r)return;const i=n(r,a.id);if(i){if(i.attachments&&i.attachments.length>0){const l=er.getState().attachedFiles;er.setState({attachedFiles:[...l,...i.attachments]})}s(i.content,i.attachments)}},[r,n,s]);return t.length===0||!r?null:e.jsx("div",{className:"pb-2",children:e.jsxs("div",{className:"flex items-center flex-wrap gap-2 px-3 py-2 bg-muted/30 rounded-xl border border-border/30",children:[e.jsx("span",{className:"typography-meta text-muted-foreground font-medium",children:"Queued:"}),t.map(a=>e.jsx(Pm,{message:a,sessionId:r,onEdit:o},a.id))]})})});Tm.displayName="QueuedMessageChips";const Bb=c.forwardRef(({searchQuery:s,onFileSelect:r,onClose:t},n)=>{const{currentDirectory:o}=mt(),{addServerFile:a}=ue(),i=nl(A=>A.searchFiles),l=jl(s,180),[d,u]=c.useState([]),[m,f]=c.useState(!1),[p,g]=c.useState(0),[w,h]=c.useState(360),[j,x]=c.useState({}),[y,b]=c.useState({}),N=c.useRef([]),v=c.useRef([]),k=c.useRef([]),D=c.useRef(null),C=c.useCallback((A,I)=>{const _=A.trim().toLowerCase();if(!_)return 0;const T=I.toLowerCase();let P=0,L=-1,Z=0;for(let q=0;q<_.length;q+=1){const $=_[q];if(!$||$===" ")continue;const H=T.indexOf($,L+1);if(H===-1)return null;const U=H-L-1;if(U===0?Z+=1:Z=0,P+=10,P+=Math.max(0,18-H),P-=Math.max(0,U),H===0)P+=12;else{const K=T[H-1];(K==="/"||K==="_"||K==="-"||K==="."||K===" ")&&(P+=10)}P+=Z>0?12:0,L=H}return P+=Math.max(0,24-Math.round(T.length/3)),P},[]);c.useEffect(()=>{const A=I=>{const _=I.target;!_||!D.current||D.current.contains(_)||t()};return document.addEventListener("pointerdown",A,!0),()=>{document.removeEventListener("pointerdown",A,!0)}},[t]),c.useEffect(()=>{if(!o){u([]);return}const I=(l??"").trim().toLowerCase();let _=!1;return f(!0),i(o,I,80).then(T=>{if(_)return;const P=I?T.map(L=>{const Z=L.relativePath||L.name||L.path,q=C(I,Z);return q===null?null:{file:L,score:q,labelLength:Z.length}}).filter(Boolean):T.map(L=>({file:L,score:0,labelLength:(L.relativePath||L.name||L.path).length}));P.sort((L,Z)=>Z.score-L.score||L.labelLength-Z.labelLength||L.file.path.localeCompare(Z.file.path)),u(P.slice(0,15).map(L=>L.file))}).catch(()=>{_||u([])}).finally(()=>{_||f(!1)}),()=>{_=!0}},[o,l,C,i]),c.useEffect(()=>{g(0),x({}),b({})},[d]),c.useEffect(()=>{N.current[p]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[p]),c.useEffect(()=>{let A=null;const I=()=>{A!==null&&cancelAnimationFrame(A),A=requestAnimationFrame(()=>{const _={},T={};v.current.forEach((P,L)=>{if(!P)return;const q=k.current[L]?.offsetWidth??P.scrollWidth,$=Math.max(0,q-P.clientWidth),H=$>8;if(_[L]=H,H){const U=Math.max(.6,$/110);T[L]=U}}),x(_),b(T)})};return I(),window.addEventListener("resize",I),()=>{A!==null&&cancelAnimationFrame(A),window.removeEventListener("resize",I)}},[d]),c.useEffect(()=>{const A=v.current[p];if(!A)return;const I=()=>{const T=A.clientWidth;T>0&&h(T)};if(I(),typeof ResizeObserver>"u")return;const _=new ResizeObserver(I);return _.observe(A),()=>{_.disconnect()}},[p]);const M=c.useCallback(async A=>{await a(A.path,A.name),r(A)},[a,r]);c.useImperativeHandle(n,()=>({handleKeyDown:A=>{if(A==="Escape"){t();return}const I=d.length;if(I!==0){if(A==="ArrowDown"){g(_=>(_+1)%I);return}if(A==="ArrowUp"){g(_=>(_-1+I)%I);return}if(A==="Enter"||A==="Tab"){const _=(p%I+I)%I,T=d[_];T&&M(T)}}}}),[d,p,t,M]);const S=A=>{switch(A.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(tr,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ma,{className:"h-3.5 w-3.5 text-muted-foreground"})}};return e.jsxs("div",{ref:D,className:"absolute z-[100] min-w-0 w-full max-w-[520px] max-h-64 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(ft,{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(Ar,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"pb-2",children:[d.map((A,I)=>{const _=A.relativePath||A.name,T=Du(_,{maxLength:45}),P=p===I,L=j[I]??!1,Z=y[I]??2.6,q=e.jsxs("div",{ref:$=>{N.current[I]=$},className:R("flex items-center gap-2 px-3 py-1.5 cursor-pointer typography-ui-label rounded-lg",P&&"bg-muted"),onClick:()=>M(A),onMouseEnter:()=>g(I),children:[S(A),e.jsxs("span",{ref:$=>{v.current[I]=$},className:"relative flex-1 min-w-0 overflow-hidden file-mention-marquee-container",style:P?{"--file-mention-marquee-width":`${w}px`,"--file-mention-marquee-duration":`${Z}s`}:void 0,"aria-label":_,children:[e.jsx("span",{ref:$=>{k.current[I]=$},className:"absolute invisible whitespace-nowrap pointer-events-none","aria-hidden":!0,children:_}),L&&P?e.jsx("span",{className:"inline-block whitespace-nowrap file-mention-marquee",children:_}):e.jsx("span",{className:"block truncate",children:T})]})]});return e.jsx(c.Fragment,{children:q},A.path)}),d.length>0&&e.jsx("div",{className:"h-2"}),d.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No files found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})}),Fm=c.forwardRef(({searchQuery:s,onCommandSelect:r,onClose:t},n)=>{const{hasMessagesInCurrentSession:o,currentSessionId:a}=ue(Ji(y=>{const b=y.currentSessionId;return{hasMessagesInCurrentSession:(b?y.messages.get(b)?.length??0:0)>0,currentSessionId:b}})),i=!!a,[l,d]=c.useState([]),[u,m]=c.useState(!1),{commands:f,loadCommands:p}=Rr(),[g,w]=c.useState(0),h=c.useRef([]),j=c.useRef(null);c.useEffect(()=>{const y=b=>{const N=b.target;!N||!j.current||j.current.contains(N)||t()};return document.addEventListener("pointerdown",y,!0),()=>{document.removeEventListener("pointerdown",y,!0)}},[t]),c.useEffect(()=>{p()},[p]),c.useEffect(()=>{(async()=>{m(!0);try{const b=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=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],v=new Map;N.forEach(M=>v.set(M.name,M)),b.forEach(M=>v.set(M.name,M));const k=Array.from(v.values()),D=!o,C=(s?k.filter(M=>Is(M.name,s)||M.description&&Is(M.description,s)):k).filter(M=>D||M.name!=="init");C.sort((M,S)=>{const A=M.name.toLowerCase().startsWith(s.toLowerCase()),I=S.name.toLowerCase().startsWith(s.toLowerCase());return A&&!I?-1:!A&&I?1:M.name.localeCompare(S.name)}),d(C)}catch{const b=!o,N=[...i&&!o?[{name:"init",description:"Create/update AGENTS.md file",isBuiltIn:!0}]:[],...i?[{name:"undo",description:"Undo the last message",isBuiltIn:!0},{name:"redo",description:"Redo previously undone messages",isBuiltIn:!0},{name:"timeline",description:"Jump to a specific message",isBuiltIn:!0}]:[],{name:"compact",description:"Compress session history using AI to reduce context size",isBuiltIn:!0}],v=(s?N.filter(k=>Is(k.name,s)||k.description&&Is(k.description,s)):N).filter(k=>b||k.name!=="init");d(v)}finally{m(!1)}})()},[s,o,i,f]),c.useEffect(()=>{w(0)},[l]),c.useEffect(()=>{h.current[g]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[g]),c.useImperativeHandle(n,()=>({handleKeyDown:y=>{const b=l.length;if(y==="Escape"){t();return}if(b!==0){if(y==="ArrowDown"){w(N=>(N+1)%b);return}if(y==="ArrowUp"){w(N=>(N-1+b)%b);return}if(y==="Enter"||y==="Tab"){const N=(g%b+b)%b,v=l[N];v&&r(v)}}}}),[l,g,t,r]);const x=y=>{switch(y.name){case"init":return e.jsx(tr,{className:"h-3.5 w-3.5 text-green-500"});case"undo":return e.jsx(Qn,{className:"h-3.5 w-3.5 text-orange-500"});case"redo":return e.jsx(sh,{className:"h-3.5 w-3.5 text-orange-500"});case"timeline":return e.jsx(or,{className:"h-3.5 w-3.5 text-blue-500"});case"compact":return e.jsx(th,{className:"h-3.5 w-3.5 text-purple-500"});case"test":case"build":case"run":return e.jsx(Pr,{className:"h-3.5 w-3.5 text-cyan-500"});default:return y.isBuiltIn?e.jsx(eh,{className:"h-3.5 w-3.5 text-yellow-500"}):e.jsx(en,{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(ft,{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(Ar,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs("div",{children:[l.map((y,b)=>{const N=y.isBuiltIn,v=y.scope==="project";return e.jsxs("div",{ref:k=>{h.current[b]=k},className:R("flex items-start gap-2 px-3 py-2 cursor-pointer rounded-lg",b===g&&"bg-muted"),onClick:()=>r(y),onMouseEnter:()=>w(b),children:[e.jsx("div",{className:"mt-0.5",children:x(y)}),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:["/",y.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"}):y.scope?e.jsx("span",{className:R("text-[10px] leading-none uppercase font-bold tracking-tight px-1.5 py-1 rounded border flex-shrink-0",v?"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.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:y.agent})]}),y.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:y.description})]})]},y.name)}),l.length===0&&e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No commands found"})]})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Fm.displayName="CommandAutocomplete";const zb=s=>s?s!=="primary":!1,Rm=c.forwardRef(({searchQuery:s,onAgentSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{getVisibleAgents:m}=rt(),{agents:f,loadAgents:p}=_r();c.useEffect(()=>{f.length===0&&p()},[p,f.length]),c.useEffect(()=>{const h=m().filter(y=>zb(y.mode)).map(y=>{const b=f.find(N=>N.name===y.name);return{name:y.name,description:y.description,mode:y.mode??void 0,scope:b?.scope,isBuiltIn:b?Hr(b):!1}}),j=s.trim(),x=j.length?h.filter(y=>Is(y.name,j)):h;x.sort((y,b)=>y.name.localeCompare(b.name)),d(x),i(0)},[m,s,f]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const w=h=>{const j=h.target;!j||!o.current||o.current.contains(j)||t()};return document.addEventListener("pointerdown",w,!0),()=>{document.removeEventListener("pointerdown",w,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:w=>{if(w==="Escape"){t();return}if(l.length){if(w==="ArrowDown"){i(h=>(h+1)%l.length);return}if(w==="ArrowUp"){i(h=>(h-1+l.length)%l.length);return}if(w==="Enter"||w==="Tab"){const h=l[(a+l.length)%l.length];h&&r(h.name)}}}}),[l,r,t,a]);const g=(w,h)=>{const j=w.isBuiltIn,x=w.scope==="project";return e.jsx("div",{ref:y=>{u.current[h]=y},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",h===a&&"bg-muted"),onClick:()=>r(w.name),onMouseEnter:()=>i(h),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-semibold",children:["#",w.name]}),j?e.jsx("span",{className:"text-[10px] leading-none uppercase font-bold tracking-tight bg-[var(--status-warning-background)] text-[var(--status-warning)] border-[var(--status-warning-border)] px-1.5 py-1 rounded border flex-shrink-0",children:"system"}):w.scope?e.jsx("span",{className:R("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:w.scope}):null]}),w.description&&e.jsx("div",{className:"typography-meta text-muted-foreground mt-0.5 truncate",children:w.description})]})},w.name)};return e.jsxs("div",{ref:o,className:"absolute z-[100] min-w-0 w-full max-w-[360px] max-h-60 bg-background border border-border rounded-xl shadow-none bottom-full mb-2 left-0 flex flex-col",children:[e.jsx(ft,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((w,h)=>g(w,h))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No agents found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});Rm.displayName="AgentMentionAutocomplete";const _m=c.forwardRef(({searchQuery:s,onSkillSelect:r,onClose:t},n)=>{const o=c.useRef(null),[a,i]=c.useState(0),[l,d]=c.useState([]),u=c.useRef([]),{skills:m,loadSkills:f}=Hs();c.useEffect(()=>{f()},[f]),c.useEffect(()=>{const g=s.trim(),h=[...g.length?m.filter(j=>Is(j.name,g)):m].sort((j,x)=>j.scope==="project"&&x.scope!=="project"?-1:j.scope!=="project"&&x.scope==="project"?1:j.name.localeCompare(x.name));d(h),i(0)},[m,s]),c.useEffect(()=>{u.current[a]?.scrollIntoView({behavior:"smooth",block:"nearest"})},[a]),c.useEffect(()=>{const g=w=>{const h=w.target;!h||!o.current||o.current.contains(h)||t()};return document.addEventListener("pointerdown",g,!0),()=>{document.removeEventListener("pointerdown",g,!0)}},[t]),c.useImperativeHandle(n,()=>({handleKeyDown:g=>{if(g==="Escape"){t();return}if(l.length){if(g==="ArrowDown"){i(w=>(w+1)%l.length);return}if(g==="ArrowUp"){i(w=>(w-1+l.length)%l.length);return}if(g==="Enter"||g==="Tab"){const w=l[a];w&&r(w.name)}}}}),[l,r,t,a]);const p=(g,w)=>{const h=g.scope==="project";return e.jsx("div",{ref:j=>{u.current[w]=j},className:R("flex items-start gap-2 px-3 py-1.5 cursor-pointer rounded-lg typography-ui-label",w===a&&"bg-muted"),onClick:()=>r(g.name),onMouseEnter:()=>i(w),children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold truncate",children:g.name}),e.jsx("span",{className:R("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(ft,{outerClassName:"flex-1 min-h-0",className:"px-0 pb-2",fillContainer:!1,children:l.length?e.jsx("div",{children:l.map((g,w)=>p(g,w))}):e.jsx("div",{className:"px-3 py-2 typography-ui-label text-muted-foreground",children:"No skills found"})}),e.jsx("div",{className:"px-3 pt-1 pb-1.5 border-t typography-meta text-muted-foreground",children:"↑↓ navigate • Enter select • Esc close"})]})});_m.displayName="SkillAutocomplete";function Wb({className:s,children:r,...t}){return e.jsxs(rh,{"data-slot":"scroll-area",className:R("relative",s),...t,children:[e.jsx(nh,{"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(Hb,{}),e.jsx(oh,{})]})}function Hb({className:s,orientation:r="vertical",...t}){return e.jsx(ah,{"data-slot":"scroll-area-scrollbar",orientation:r,className:R("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(ih,{"data-slot":"scroll-area-thumb",className:"bg-border relative flex-1 rounded-full"})})}const Ub=({onFilesSelected:s,multiSelect:r=!1,children:t,open:n,onOpenChange:o,presentation:a="dropdown"})=>{const{isMobile:i}=_t(),l=i,{currentDirectory:d}=mt(),u=nl(W=>W.searchFiles),[m,f]=c.useState(!1),[p,g]=c.useState(!1),[w,h]=c.useState(""),j=jl(w,200),[x,y]=c.useState(new Set),[b,N]=c.useState(new Set),[v,k]=c.useState({}),D=c.useRef(new Set),C=c.useRef(new Set),[M,S]=c.useState([]),[A,I]=c.useState(!1),[_,T]=c.useState(!1),[P,L]=c.useState(!1),[Z,q]=c.useState(null),$=n??m,H=o??f,U=c.useCallback(W=>W.slice().sort((G,ee)=>G.type!==ee.type?G.type==="directory"?-1:1:G.name.localeCompare(ee.name)),[]),K=c.useCallback((W,G)=>U(G.filter(ee=>!ee.name.startsWith(".")).map(ee=>{const fe=ee.name,de=!ee.isDirectory&&fe.includes(".")?fe.split(".").pop()?.toLowerCase():void 0;return{name:fe,path:ee.path||`${W}/${fe}`,type:ee.isDirectory?"directory":"file",size:0,extension:de}})),[U]),se=c.useCallback(async W=>{T(!0),q(null);try{const G=await je.listLocalDirectory(W),ee=K(W,G.map(fe=>({name:fe.name,path:fe.path,isDirectory:fe.isDirectory})));D.current=new Set([W]),C.current=new Set,k({[W]:ee}),N(new Set)}catch{q("Failed to load directory contents"),D.current=new Set([W]),C.current=new Set,k({[W]:[]}),N(new Set)}finally{T(!1)}},[K]),Y=c.useCallback(async W=>{const G=W.trim();if(G&&!D.current.has(G)&&!C.current.has(G)){C.current=new Set(C.current),C.current.add(G);try{const ee=await je.listLocalDirectory(G),fe=K(G,ee.map(de=>({name:de.name,path:de.path,isDirectory:de.isDirectory})));D.current=new Set(D.current),D.current.add(G),k(de=>({...de,[G]:fe}))}catch{k(ee=>ee[G]?ee:{...ee,[G]:[]})}finally{C.current=new Set(C.current),C.current.delete(G)}}},[K]);c.useEffect(()=>{($||p)&&d&&se(d)},[$,p,d,se]),c.useEffect(()=>{if(!($||p)||!d){S([]),I(!1);return}const W=j.trim();if(!W){S([]),I(!1);return}let G=!1;return I(!0),u(d,W,150).then(ee=>{if(G)return;const fe=ee.map(de=>({name:de.name,path:de.path,type:"file",extension:de.extension,relativePath:de.relativePath,size:0}));S(fe)}).catch(()=>{G||S([])}).finally(()=>{G||I(!1)}),()=>{G=!0}},[$,p,d,j,u]),c.useEffect(()=>{!$&&!p&&(y(new Set),h(""),S([]),I(!1))},[$,p]);const re=W=>{if(W.type==="directory")return b.has(W.path)?e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"}):e.jsx(ur,{className:"h-3.5 w-3.5 text-primary/60"});switch(W.extension?.toLowerCase()){case"ts":case"tsx":case"js":case"jsx":case"html":case"css":case"scss":case"less":return e.jsx(nr,{className:"h-3.5 w-3.5 text-blue-500"});case"json":return e.jsx(nr,{className:"h-3.5 w-3.5 text-yellow-500"});case"md":case"mdx":return e.jsx(ji,{className:"h-3.5 w-3.5 text-gray-500"});case"png":case"jpg":case"jpeg":case"gif":case"svg":return e.jsx(br,{className:"h-3.5 w-3.5 text-green-500"});default:return e.jsx(ji,{className:"h-3.5 w-3.5 text-muted-foreground"})}},V=async W=>{b.has(W)?N(ee=>{const fe=new Set(ee);return fe.delete(W),fe}):(N(ee=>{const fe=new Set(ee);return fe.add(W),fe}),await Y(W))},ae=W=>{y(r?G=>{const ee=new Set(G);return ee.has(W)?ee.delete(W):ee.add(W),ee}:new Set([W]))},E=async()=>{const W=new Map;Object.values(v).forEach(fe=>{fe.forEach(de=>{de.type==="file"&&W.set(de.path,de)})});const G=new Map(M.map(fe=>[fe.path,fe])),ee=Array.from(x).map(fe=>W.get(fe)??G.get(fe)).filter(fe=>!!fe);L(!0);try{await s(ee),y(new Set),H(!1),g(!1)}finally{L(!1)}},B=c.useMemo(()=>d?v[d]??[]:[],[v,d]),F=w.trim().length>0,O=W=>v[W]??[],z=W=>{if(d&&W.startsWith(d)){const G=W.substring(d.length);return G.startsWith("/")?G.substring(1):G}return W.split("/").pop()||W},Q=(W,G)=>{const ee=F?W.relativePath||z(W.path):W.name,fe=F&&ee.includes("/")&&ee.length>45,de=fe?Du(ee,{maxLength:l?42:48}):ee,Ae=e.jsxs("div",{className:R("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",W.type==="file"&&x.has(W.path)&&"bg-primary/10"),style:{paddingLeft:`${G*12}px`},onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),W.type==="file"&&ae(W.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(W)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left max-w-[360px]","aria-label":ee,children:de})]}),W.type==="file"&&x.has(W.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]});return fe?e.jsxs(at,{delayDuration:120,children:[e.jsx(it,{asChild:!0,children:Ae}),e.jsx(nt,{side:"right",className:"max-w-xs",children:e.jsx("span",{className:"typography-meta text-foreground/80 whitespace-pre-wrap break-all",children:ee})})]},W.path):c.cloneElement(Ae,{key:W.path})},me=(W,G)=>{const ee=W.type==="directory",fe=ee?O(W.path):[],de=b.has(W.path),Ae=ee&&de&&C.current.has(W.path)&&fe.length===0;return e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:R("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&&x.has(W.path)&&"bg-primary/10"),style:{paddingLeft:`${G*12}px`},onClick:Ne=>{Ne.preventDefault(),Ne.stopPropagation(),ee?V(W.path):ae(W.path)},children:[e.jsx("span",{className:"text-muted-foreground",children:re(W)}),e.jsx("span",{className:"flex-1 truncate text-foreground text-left",children:W.name}),!ee&&x.has(W.path)&&e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"})]}),ee&&de&&fe.length>0&&e.jsx("div",{children:fe.map(Ne=>me(Ne,G+1))}),ee&&de&&Ae&&e.jsx("div",{className:"px-2 py-1.5 typography-ui-label text-muted-foreground",style:{paddingLeft:`${(G+1)*12}px`},children:"Loading…"})]},W.path)},Se=x.size>0?`${x.size} file${x.size!==1?"s":""} selected`:"No files selected",he=e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 shrink-0",children:[e.jsx("div",{className:"typography-meta text-muted-foreground",children:Se}),e.jsx(Ce,{size:"sm",onClick:E,disabled:x.size===0||P,className:"h-6 typography-meta",children:P?"Attaching...":"Attach Files"})]}),Pe=l?"flex-1 min-h-[240px]":"h-[300px]",ve=e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsx("div",{className:"font-medium typography-ui-label text-foreground",children:"Select Project Files"})}),e.jsx("div",{className:"px-3 py-2 border-b shrink-0",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{value:w,onChange:W=>h(W.target.value),placeholder:"Search files...",className:"pl-7 h-6 typography-ui-label",onClick:W=>W.stopPropagation()}),w&&e.jsx("button",{onClick:W=>{W.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(Wb,{className:Pe,children:[_&&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..."})}),Z&&e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"typography-ui-label text-destructive",children:Z})}),!_&&!Z&&e.jsxs("div",{className:"py-1 px-2",children:[F?A?e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"Searching files…"}):M.map(W=>Q(W,0)):B.map(W=>me(W,0)),!F&&B.length===0&&e.jsx("div",{className:"px-3 py-4 typography-ui-label text-muted-foreground text-center",children:"No files in this directory"}),F&&!A&&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:W=>{W.preventDefault(),W.stopPropagation(),g(!0)},children:t});return a==="modal"?e.jsxs(e.Fragment,{children:[t?e.jsx("span",{className:"inline-flex cursor-pointer",onClick:W=>{W.preventDefault(),W.stopPropagation(),H(!0)},children:t}):null,e.jsx(vs,{open:$,onClose:()=>H(!1),title:"Select Project Files",footer:he,children:e.jsx("div",{className:"flex flex-col gap-0",children:ve})})]}):l?e.jsxs(e.Fragment,{children:[Be,e.jsx(vs,{open:p,onClose:()=>g(!1),title:"Select Project Files",footer:he,children:e.jsx("div",{className:"flex flex-col gap-0",children:ve})})]}):e.jsxs(Vt,{open:$,onOpenChange:H,children:[e.jsx(Gt,{asChild:!0,children:t}),e.jsxs(qt,{className:R("p-0 overflow-hidden flex flex-col","w-[min(520px,calc(100vw-24px))]"),align:"start",sideOffset:5,collisionPadding:12,children:[ve,e.jsx(Ms,{}),he]})]})},jo=[{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 Nr(s){if(!s||s==="build")return jo[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)%(jo.length-1);return jo[t]}const Vb=s=>typeof s=="object"&&s!==null&&!Array.isArray(s),Om=s=>Vb(s),Gb=s=>s?typeof s=="string"?s==="ask":Om(s)?Object.values(s).some(r=>r==="ask"):!1:!1,qb=s=>s?typeof s=="string"?s==="deny":Om(s)?Object.values(s).some(r=>r==="deny"):!1:!1,$m=({agentDefaultEditMode:s,webfetchPermission:r,bashPermission:t})=>{const n=Gb(t),o=qb(t),a=!n&&!o,i=r==="allow",l=r!=="deny",d=s==="allow"||s==="full",u=s==="ask";let m=s;d&&i&&a?m="full":d&&n?m="allow":u&&(m="ask");const f={ask:u,allow:u||d&&n,full:s!=="deny"&&l&&n,deny:!1},p=f.allow||f.full;return{cascadeDefaultMode:m,modeAvailability:f,autoApproveAvailable:p,bashHasAsk:n,bashHasDeny:o,bashAllAllow:a,webfetchIsAllow:i,webfetchNotDeny:l}},So=s=>s==="primary"||s==="all"||s===void 0||s===null,aa=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},ko=(s,r)=>{const t=aa(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}}},Kb=(s,r)=>{const t=aa(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},Yb=[{key:"tool_call",icon:fa,label:"Tool calling",isActive:s=>s?.tool_call===!0},{key:"reasoning",icon:ar,label:"Reasoning",isActive:s=>s?.reasoning===!0}],Qb={text:{icon:mu,label:"Text"},image:{icon:br,label:"Image"},video:{icon:ch,label:"Video"},audio:{icon:lh,label:"Audio"},pdf:{icon:ma,label:"PDF"}},Xb=s=>s.trim().toLowerCase(),Ln=(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=>Xb(o)))).map(o=>{const a=Qb[o];return a?{key:o,icon:a.icon,label:a.label}:null}).filter(o=>!!o)},Jb=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Zb=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:4,minimumFractionDigits:2}),Os=s=>{if(typeof s!="number"||Number.isNaN(s))return"—";if(s===0)return"0";const r=Jb.format(s);return r.endsWith(".0")?r.slice(0,-2):r},No=s=>typeof s!="number"||!Number.isFinite(s)?"—":Zb.format(s),Za=s=>Yb.filter(r=>r.isActive(s)).map(r=>({key:r.key,icon:r.icon,label:r.label})),Yc=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},Qc=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)},Xc=({className:s})=>{const{providers:r,currentProviderId:t,currentModelId:n,currentVariant:o,currentAgentName:a,settingsDefaultVariant:i,setProvider:l,setModel:d,setCurrentVariant:u,getCurrentModelVariants:m,setAgent:f,getCurrentProvider:p,getModelMetadata:g,getCurrentAgent:w,getVisibleAgents:h}=rt(),j=h(),{currentSessionId:x,messages:y,saveSessionAgentSelection:b,getSessionAgentSelection:N,saveAgentModelForSession:v,getAgentModelForSession:k,saveAgentModelVariantForSession:D,getAgentModelVariantForSession:C,analyzeAndSaveExternalSessionChoices:M,getSessionAgentEditMode:S,setSessionAgentEditMode:A}=ue(),I=St(J=>J.hasHydrated),{toggleFavoriteModel:_,isFavoriteModel:T,addRecentModel:P,isModelSelectorOpen:L,setModelSelectorOpen:Z}=_e(),{favoriteModelsList:q,recentModelsList:$}=Nl(),{isMobile:H}=_t(),U=My(),K=mm(),se=H,[Y,re]=c.useState(null),[V,ae]=c.useState(null),[E,B]=c.useState(""),F=c.useCallback(()=>re(null),[]),O=c.useCallback(()=>ae(null),[]),z=c.useRef(void 0),[Q,me]=c.useState(()=>{const J=new Set;return t&&J.add(t),J}),[Se,he]=c.useState(!1),Pe=L,ve=Z,[Be,W]=c.useState(!1),G=c.useId(),[ee,fe]=c.useState(""),[de,Ae]=c.useState(0),Ne=c.useRef([]);c.useEffect(()=>{Y==="model"&&me(()=>{const J=new Set;return t&&J.add(t),J})},[Y,t]),c.useEffect(()=>{Y!=="agent"&&he(!1),Y!=="model"&&B("")},[Y]);const Oe=c.useRef(Pe);c.useEffect(()=>{const J=Oe.current;Oe.current=Pe,Pe||(W(!1),fe(""),Ae(0),J&&!se&&requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()}))},[Pe,se]),c.useEffect(()=>{Ae(0)},[ee]);const ce=w?.(),dt=c.useMemo(()=>ce?ko(ce.permission,"edit")??"ask":"deny",[ce]),kt=c.useMemo(()=>{if(ce)return ko(ce.permission,"webfetch")},[ce]),we=c.useMemo(()=>{if(!ce)return;const J=Kb(ce.permission,"bash");return J||void 0},[ce]),ne=c.useMemo(()=>$m({agentDefaultEditMode:dt,webfetchPermission:kt,bashPermission:we}),[dt,kt,we]),{cascadeDefaultMode:Qe,modeAvailability:ge,autoApproveAvailable:ye}=ne,qe=!!(x&&a),Ze=qe&&x&&a?S(x,a,Qe):Qe,We={ask:"Ask before edits",allow:"Approve edit tools",full:"Approve every tool",deny:"Editing disabled"},Re=c.useCallback(J=>!ge[J],[ge]),Xe=c.useMemo(()=>!qe||Re(Ze)&&Ze!==Qe?Qe:Ze,[Qe,Re,qe,Ze]),Ct=[{mode:"ask",label:We.ask,disabled:Re("ask")},{mode:"allow",label:We.allow,disabled:Re("allow")},{mode:"full",label:We.full,disabled:Re("full")}],ct=c.useMemo(()=>Wn(Xe),[Xe]),At=!qe||!ye;c.useEffect(()=>{At&&(he(!1),W(!1))},[At]);const Mt=H?"mobile":K?"vscode":"default",ke=Mt==="mobile"?"h-9":Mt==="vscode"?"h-6":"h-8",$e=Mt==="mobile"?"h-5 w-5":"h-4 w-4",Fe=Mt==="mobile"?"h-5 w-5":"h-4 w-4",ot=se?"typography-micro":"typography-meta",Lt=Mt==="mobile"?"gap-x-2":Mt==="vscode"?"gap-x-1":"gap-x-3",es=We[Xe],Wt=c.useCallback((J,ie=$e)=>{const le=R(ie,"flex-shrink-0"),be=Wn(J),Ve={color:be?be.text:"var(--foreground)"};return J==="full"?e.jsx(mr,{className:le,style:Ve}):J==="allow"?e.jsx(Po,{className:le,style:Ve}):J==="deny"?e.jsx(Sn,{className:le,style:Ve}):e.jsx(Qr,{className:le,style:Ve})},[$e]),He=c.useCallback(J=>{At||!x||!a||Re(J)||(A(x,a,J,Qe),ve(!1),he(!1),W(!1))},[Qe,At,x,a,A,ve,W,Re]),et=p(),gt=Array.isArray(et?.models)?et.models:[],Je=t&&n?g(t,n):void 0,bt=Za(Je),X=Ln(Je,"input"),xe=Ln(Je,"output"),pe=c.useMemo(()=>`${t}/${n}`?m():[],[m,t,n]),Le=pe.length>0,Ee=[{label:"Input",value:No(Je?.cost?.input)},{label:"Output",value:No(Je?.cost?.output)},{label:"Cache read",value:No(Je?.cost?.cache_read)},{label:"Cache write",value:No(Je?.cost?.cache_write)}],Ke=[{label:"Context",value:Os(Je?.limit?.context)},{label:"Output",value:Os(Je?.limit?.output)}],pt=c.useRef(void 0),ut=x?y.get(x)?.length??-1:-1,Tt=c.useRef(null),xt=c.useCallback((J,ie,le)=>{if(!J||!ie)return"model-missing";const be=r.find(Ie=>Ie.id===J);return be?(Array.isArray(be.models)?be.models:[]).find(Ie=>Ie.id===ie)?(l(J),d(ie),x&&le&&v(x,le,J,ie),"applied"):"model-missing":"provider-missing"},[r,l,d,x,v]);c.useEffect(()=>{if(!x){Tt.current=null;return}if(!I||r.length===0||j.length===0)return;(!Tt.current||Tt.current.sessionId!==x)&&(Tt.current={sessionId:x,resolved:!1,inFlight:!1});const J=Tt.current;if(!J||J.resolved||J.inFlight)return;let ie=!1;const le=()=>{if(ie)return;const Ie=Tt.current;Ie&&Ie.sessionId===x&&(Ie.resolved=!0,Ie.inFlight=!1)},be=()=>{const Ie=N(x);if(Ie){a!==Ie&&f(Ie);const Ge=k(x,Ie);if(Ge){const Te=xt(Ge.providerId,Ge.modelId,Ie);if(Te==="applied")return"resolved";if(Te==="provider-missing")return"waiting"}else return"resolved"}for(const Ge of j){const Te=k(x,Ge.name);if(!Te)continue;a!==Ge.name&&f(Ge.name),b(x,Ge.name);const st=xt(Te.providerId,Te.modelId,Ge.name);if(st==="applied")return"resolved";if(st==="provider-missing")return"waiting"}return"continue"},Ue=()=>{if(j.length===0)return;const Ie=j.filter(Te=>So(Te.mode)),Ge=j.find(Te=>Te.name==="build")||Ie[0]||j[0];Ge&&(b(x,Ge.name),a!==Ge.name&&f(Ge.name),Ge.model?.providerID&&Ge.model?.modelID&&xt(Ge.model.providerID,Ge.model.modelID,Ge.name))};return(async()=>{try{const Ie=be();if(Ie==="resolved"){le();return}if(Ie==="waiting"||ut===-1)return;if(ut>0){J.inFlight=!0;try{const Ge=await M(x,j);if(ie)return;if(Ge.size>0){let Te=null,st=-1/0;for(const[Nt,vt]of Ge)vt.timestamp>st&&(st=vt.timestamp,Te=Nt);if(Te){b(x,Te),a!==Te&&f(Te);const Nt=Ge.get(Te);if(Nt){const vt=xt(Nt.providerId,Nt.modelId,Te);if(vt==="applied"){le();return}if(vt==="provider-missing")return}else{le();return}}}}catch(Ge){ie||console.error("[ModelControls] Error resolving session from messages:",Ge)}finally{const Ge=Tt.current;!ie&&Ge&&Ge.sessionId===x&&(Ge.inFlight=!1)}}Ue(),le()}catch(Ie){ie||console.error("[ModelControls] Error in session switch:",Ie)}})(),()=>{ie=!0}},[x,ut,j,a,N,k,f,xt,M,b,I,r]),c.useEffect(()=>{if(!I||!x||r.length===0||j.length===0)return;const ie=N(x)||a;if(!ie)return;const le=k(x,ie);if(!le)return;const be=r.find(Ge=>Ge.id===le.providerId);if(!be||!(Array.isArray(be.models)?be.models.some(Ge=>Ge.id===le.modelId):!1))return;const Ve=t===le.providerId,Ie=n===le.modelId;Ve&&Ie||(ie!==a&&f(ie),xt(le.providerId,le.modelId,ie))},[I,x,a,t,n,r,j,N,k,xt,f]),c.useEffect(()=>{if(!I)return;(async()=>{try{if(a!==pt.current&&(pt.current=a,a&&x)){await new Promise(be=>setTimeout(be,50));const ie=k(x,a);if(ie){const be=xt(ie.providerId,ie.modelId,a);if(be==="applied"||be==="provider-missing")return}const le=j.find(be=>be.name===a);if(le?.model?.providerID&&le?.model?.modelID&&xt(le.model.providerID,le.model.modelID,a)==="provider-missing")return}}catch(ie){console.error("[ModelControls] Agent change error:",ie)}})()},[a,x,k,xt,j,I]),c.useEffect(()=>{if(!I||!a){u(void 0);return}if(!t||!n){u(void 0);return}if(pe.length===0){u(void 0);return}if(o&&!pe.includes(o)){u(void 0);return}if(!x){if(!o){const le=i&&pe.includes(i)?i:void 0;u(le)}return}const J=C(x,a,t,n),ie=J&&pe.includes(J)?J:void 0;u(ie)},[pe,I,x,a,t,n,o,C,u,i]);const Me=c.useCallback(J=>{u(J),x&&a&&t&&n&&D(x,a,t,n,J)},[a,n,t,x,D,u]),tt=J=>{try{f(J),ve(!1),x&&b(x,J),se&&F()}catch(ie){console.error("[ModelControls] Handle agent change error:",ie)}},ze=(J,ie)=>{try{const le=xt(J,ie,a||void 0);if(le!=="applied"){le==="provider-missing"?console.error("[ModelControls] Provider not available for selection:",J):le==="model-missing"&&console.error("[ModelControls] Model not available for selection:",{providerId:J,modelId:ie});return}P(J,ie),ve(!1),se&&F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})}catch(le){console.error("[ModelControls] Handle model change error:",le)}},Ye=J=>{const ie=typeof J?.name=="string"?J.name:typeof J?.id=="string"?J.id:"";return ie.length>40?ie.substring(0,37)+"...":ie},wt=()=>r.find(ie=>ie.id===t)?.name||t,Rt=()=>{if(!t||!n||gt.length===0)return"Not selected";const J=gt.find(ie=>ie.id===n);return Ye(J)},ns=()=>{if(!a){const ie=j.filter(Ue=>So(Ue.mode)),be=ie.find(Ue=>Ue.name==="build")||ie[0];return be?ts(be.name):"Select Agent"}const J=j.find(ie=>ie.name===a);return ts(J?J.name:a)},ts=J=>J.charAt(0).toUpperCase()+J.slice(1),ps=(J,ie,le)=>e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-xl bg-muted/60 text-muted-foreground",title:ie,"aria-label":ie,role:"img",children:e.jsx(J,{className:"h-3.5 w-3.5"})},le),lr=c.useCallback(J=>{me(ie=>{const le=new Set(ie);return le.has(J)?le.delete(J):le.add(J),le})},[]),Ot=c.useCallback(J=>{z.current&&clearTimeout(z.current),z.current=setTimeout(()=>{ae(J)},500)},[]),jr=c.useCallback(()=>{z.current&&clearTimeout(z.current)},[]);c.useEffect(()=>()=>{z.current&&clearTimeout(z.current)},[]);const Tn=()=>!se||V!=="model"?null:e.jsx(vs,{open:!0,onClose:O,title:Je?.name||Rt(),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:wt()})]}),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:J,icon:ie,label:le})=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[ps(ie,le,`cap-${J}`),e.jsx("span",{className:"typography-meta text-foreground",children:le})]},J))})]}),(X.length>0||xe.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:[X.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:X.map(({key:J,icon:ie,label:le})=>ps(ie,`${le} input`,`input-${J}`))})]}),xe.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:xe.map(({key:J,icon:ie,label:le})=>ps(ie,`${le} output`,`output-${J}`))})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-2 py-1.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-1",children:"Limits"}),e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Context"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(Je?.limit?.context)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"typography-meta text-muted-foreground/80",children:"Output"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Os(Je?.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:Yc(Je?.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:Qc(Je?.release_date)})]})]})]})]})}),Ca=()=>{if(!se||V!=="agent"||!ce)return null;const J=!!(ce.prompt&&ce.prompt.trim().length>0),ie=ce.model?.providerID&&ce.model?.modelID,le=ce.temperature!==void 0||ce.topP!==void 0,be=Ge=>{const Te=aa(ce.permission)??[],st=Te.some(vt=>vt.permission===Ge&&vt.pattern!=="*"),Nt=ko(Te,Ge)??"ask";return st?{mode:"ask",label:"Custom"}:Nt==="allow"?{mode:"allow",label:"Allow"}:Nt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ue=be("edit"),Ve=be("bash"),Ie=be("webfetch");return e.jsx(vs,{open:!0,onClose:O,title:ts(ce.name),children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[ce.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:ce.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:ce.mode==="primary"?"Primary":ce.mode==="subagent"?"Subagent":ce.mode==="all"?"All":"—"})]}),(ie||le)&&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"}),ie&&e.jsxs("div",{className:"typography-meta text-foreground font-medium mb-1",children:[ce.model.providerID," / ",ce.model.modelID]}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5",children:[ce.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:ce.temperature})]}),ce.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:ce.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:[Wt(Ue.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ue.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:[Wt(Ve.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ve.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:[Wt(Ie.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ie.label})]})]})]})]}),J&&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(Po,{className:"h-4 w-4 text-foreground"})]})})]})})},Ma=()=>{if(!se)return null;const J=E.trim(),ie=r.map(le=>{const be=Array.isArray(le.models)?le.models:[],Ue=J.length===0?!0:Is(le.name,J)||Is(le.id,J),Ve=J.length===0?be:be.filter(Ie=>{const Ge=Ye(Ie),Te=typeof Ie.id=="string"?Ie.id:"";return Is(Ge,J)||Is(Te,J)});return{provider:le,providerModels:Ve,matchesProvider:Ue}}).filter(({matchesProvider:le,providerModels:be})=>le||be.length>0);return e.jsx(vs,{open:Y==="model",onClose:F,title:"Select model",children:e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{value:E,onChange:le=>B(le.target.value),placeholder:"Search providers or models",className:"pl-7 h-9 rounded-xl border-border/40 bg-background/95 typography-meta"}),E&&e.jsx("button",{type:"button",onClick:()=>B(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground","aria-label":"Clear search",children:e.jsx(Sn,{className:"h-4 w-4"})})]})}),ie.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."}),!E&&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(fr,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),"Favorites"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:q.map(({model:le,providerID:be,modelID:Ue})=>{const Ve=be===t&&Ue===n,Ie=g(be,Ue);return e.jsxs("button",{type:"button",onClick:()=>ze(be,Ue),className:R("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",Ve?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(is,{providerId:be,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ye(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ie?.limit?.context||Ie?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ie?.limit?.context?`${Os(Ie?.limit?.context)} ctx`:"",Ie?.limit?.context&&Ie?.limit?.output?" • ":"",Ie?.limit?.output?`${Os(Ie?.limit?.output)} out`:""]})})]},`fav-mobile-${be}-${Ue}`)})})]}),!E&&$.length>0&&e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("div",{className:"px-2 py-1.5 text-xs font-semibold text-muted-foreground uppercase tracking-wider",children:[e.jsx(or,{className:"h-3 w-3 inline-block mr-1.5"}),"Recent"]}),e.jsx("div",{className:"flex flex-col border-t border-border/30",children:$.map(({model:le,providerID:be,modelID:Ue})=>{const Ve=be===t&&Ue===n,Ie=g(be,Ue);return e.jsxs("button",{type:"button",onClick:()=>ze(be,Ue),className:R("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",Ve?"bg-primary/15 text-primary":"hover:bg-muted"),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(is,{providerId:be,className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta font-medium text-foreground truncate",children:Ye(le)})]}),e.jsx("div",{className:"ml-auto flex items-center gap-2",children:(Ie?.limit?.context||Ie?.limit?.output)&&e.jsxs("div",{className:"typography-micro text-muted-foreground whitespace-nowrap",children:[Ie?.limit?.context?`${Os(Ie?.limit?.context)} ctx`:"",Ie?.limit?.context&&Ie?.limit?.output?" • ":"",Ie?.limit?.output?`${Os(Ie?.limit?.output)} out`:""]})})]},`recent-mobile-${be}-${Ue}`)})})]}),ie.map(({provider:le,providerModels:be})=>{if(be.length===0&&!J.length)return null;const Ue=le.id===t,Ve=Q.has(le.id)||J.length>0;return e.jsxs("div",{className:"rounded-xl border border-border/40 bg-background/95 overflow-hidden",children:[e.jsxs("button",{type:"button",onClick:()=>lr(le.id),className:"flex w-full items-center justify-between gap-1.5 px-2 py-1.5 text-left","aria-expanded":Ve,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{providerId:le.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:le.name}),Ue&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),Ve?e.jsx(It,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),Ve&&be.length>0&&e.jsx("div",{className:"flex flex-col border-t border-border/30",children:be.map(Ie=>{const Ge=Ue&&Ie.id===n,Te=g(le.id,Ie.id),st=Za(Te).slice(0,3),Nt=Ln(Te,"input");return e.jsxs("div",{className:R("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",!Ge&&"hover:bg-muted",Ge?"bg-primary/15 text-primary":""),children:[e.jsxs("button",{type:"button",onClick:()=>ze(le.id,Ie.id),className:R("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:Ye(Ie)})}),e.jsxs("div",{className:"ml-auto flex flex-col items-end gap-1 text-right",children:[(Te?.limit?.context||Te?.limit?.output)&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground",children:[Te?.limit?.context?e.jsxs("span",{children:[Os(Te?.limit?.context)," ctx"]}):null,Te?.limit?.context&&Te?.limit?.output?e.jsx("span",{children:"•"}):null,Te?.limit?.output?e.jsxs("span",{children:[Os(Te?.limit?.output)," out"]}):null]}),(st.length>0||Nt.length>0)&&e.jsx("div",{className:"flex items-center justify-end gap-1",children:[...st,...Nt].map(({key:vt,icon:ws,label:Rs})=>e.jsx("span",{className:"flex h-4 w-4 items-center justify-center text-muted-foreground",title:Rs,"aria-label":Rs,children:e.jsx(ws,{className:"h-3 w-3"})},`meta-${le.id}-${Ie.id}-${vt}`))})]})]}),e.jsx("button",{type:"button",onClick:vt=>{vt.preventDefault(),vt.stopPropagation(),_(le.id,Ie.id)},className:R("model-favorite-button flex h-5 w-5 items-center justify-center hover:text-yellow-600 flex-shrink-0",T(le.id,Ie.id)?"text-yellow-500":"text-muted-foreground"),"aria-label":T(le.id,Ie.id)?"Unfavorite":"Favorite",title:T(le.id,Ie.id)?"Remove from favorites":"Add to favorites",children:T(le.id,Ie.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(yn,{className:"h-4 w-4"})})]},Ie.id)})})]},le.id)})]})})},Or=()=>{if(!se||!Le)return null;const J=!o,ie=le=>{Me(le),F(),requestAnimationFrame(()=>{document.querySelector('textarea[data-chat-input="true"]')?.focus()})};return e.jsx(vs,{open:Y==="variant",onClose:F,title:"Thinking",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("button",{type:"button",className:R("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",J?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ie(void 0),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:"Default"}),J&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),pe.map(le=>{const be=o===le,Ue=le.charAt(0).toUpperCase()+le.slice(1);return e.jsxs("button",{type:"button",className:R("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",be?"border-primary/30 bg-primary/10":"border-border/40"),onClick:()=>ie(le),children:[e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Ue}),be&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},le)})]})})},$r=()=>{if(!se)return null;const J=j.filter(ie=>So(ie.mode));return e.jsx(vs,{open:Y==="agent",onClose:F,title:"Select agent",children:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[J.map(ie=>{const le=ie.name===a,be=Nr(ie.name);return e.jsxs("button",{type:"button",className:R("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",be.class,le?"active":"border-border/40"),onClick:()=>tt(ie.name),children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:R("h-2 w-2 rounded-full",be.class)}),e.jsx("span",{className:"typography-meta font-medium text-foreground",style:le?{color:`var(${be.var})`}:void 0,children:ts(ie.name)})]}),ie.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:ie.description})]},ie.name)}),e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30",children:[e.jsxs("button",{type:"button",disabled:At,onClick:()=>{At||he(ie=>!ie)},className:R("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",At?"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:ct?ct.text:"var(--foreground)",mixBlendMode:"normal"},children:es})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!ct&&"text-muted-foreground"),style:ct?{color:ct.text}:void 0,children:Wt(Xe,$e)}),e.jsx(It,{className:R("h-4 w-4 text-muted-foreground transition-transform",Se?"rotate-180":"")})]})]}),Se&&!At&&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:Ct.map(ie=>{const le=ie.mode===Xe,be=Wn(ie.mode);return e.jsxs("button",{type:"button",disabled:ie.disabled,onClick:()=>He(ie.mode),className:R("flex w-full items-start gap-2 rounded-lg px-2 py-1.5 text-left",ie.disabled?"cursor-not-allowed opacity-50":"focus:bg-transparent hover:bg-transparent",le?"bg-primary/10":void 0),style:le&&be?{backgroundColor:be.background??void 0}:void 0,children:[Wt(ie.mode,$e),e.jsx("div",{className:"flex flex-col",children:e.jsx("span",{className:"typography-meta font-medium",style:{color:be?be.text:"var(--foreground)"},children:ie.label})})]},ie.mode)})})})]})]})})},_l=()=>e.jsx(nt,{align:"start",sideOffset:8,className:"max-w-[320px]",children:Je?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:Je.name||Rt()}),e.jsx("span",{className:"typography-meta text-muted-foreground",children:wt()})]}),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:J,icon:ie,label:le})=>ps(ie,le,`cap-${J}`)):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:X.length>0?X.map(({key:J,icon:ie,label:le})=>ps(ie,`${le} input`,`input-${J}`)):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:xe.length>0?xe.map(({key:J,icon:ie,label:le})=>ps(ie,`${le} output`,`output-${J}`)):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)"}),Ee.map(J=>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:J.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:J.value})]},J.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"}),Ke.map(J=>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:J.label}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:J.value})]},J.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:Yc(Je.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:Qc(Je.release_date)})]})]})]}):e.jsx("div",{className:"min-w-[200px] typography-meta text-muted-foreground",children:"Model metadata unavailable."})}),an=(J,ie,le,be,Ue,Ve)=>{const Ie=g(ie,le),Ge=Za(Ie).map(hs=>({...hs,id:`cap-${hs.key}`})),Te=[...Ln(Ie,"input"),...Ln(Ie,"output")],st=Array.from(new Map(Te.map(hs=>[hs.key,hs])).values()).map(hs=>({...hs,id:`mod-${hs.key}`})),Nt=[...Ge,...st],vt=Os(Ie?.limit?.context),ws=t===ie&&n===le,Rs=T(ie,le);return e.jsxs("div",{ref:hs=>{Ne.current[Ue]=hs},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",Ve?"bg-accent":"hover:bg-accent/50"),onClick:()=>ze(ie,le),onMouseEnter:()=>Ae(Ue),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:Ye(J)}),Ie?.limit?.context?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:vt}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[Nt.length>0&&e.jsx("div",{className:R("items-center gap-0.5",Ve?"flex":"hidden group-hover:flex"),children:Nt.map(({id:hs,icon:Af,label:Ol})=>e.jsx("span",{className:"flex h-3.5 w-3.5 items-center justify-center text-muted-foreground","aria-label":Ol,role:"img",title:Ol,children:e.jsx(Af,{className:"h-2.5 w-2.5"})},hs))}),ws&&e.jsx(Pt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:hs=>{hs.preventDefault(),hs.stopPropagation(),_(ie,le)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Rs?"text-yellow-500":"text-muted-foreground"),"aria-label":Rs?"Unfavorite":"Favorite",title:Rs?"Remove from favorites":"Add to favorites",children:Rs?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(yn,{className:"h-3.5 w-3.5"})})]})]},`${be}-${ie}-${le}`)},Fn=(J,ie,le)=>le.trim()?Is(J,le)||Is(ie,le):!0,Da=()=>{const J=q.filter(({model:Te,providerID:st})=>{const vt=r.find(Rs=>Rs.id===st)?.name||st,ws=Ye(Te);return Fn(ws,vt,ee)}),ie=$.filter(({model:Te,providerID:st})=>{const vt=r.find(Rs=>Rs.id===st)?.name||st,ws=Ye(Te);return Fn(ws,vt,ee)}),le=r.map(Te=>{const Nt=(Array.isArray(Te.models)?Te.models:[]).filter(vt=>{const ws=Ye(vt);return Fn(ws,Te.name||Te.id||"",ee)});return{...Te,models:Nt}}).filter(Te=>Te.models.length>0),be=J.length>0||ie.length>0||le.length>0,Ue=[];J.forEach(({model:Te,providerID:st,modelID:Nt})=>{Ue.push({model:Te,providerID:st,modelID:Nt,section:"fav"})}),ie.forEach(({model:Te,providerID:st,modelID:Nt})=>{Ue.push({model:Te,providerID:st,modelID:Nt,section:"recent"})}),le.forEach(Te=>{Te.models.forEach(st=>{Ue.push({model:st,providerID:Te.id,modelID:st.id,section:"provider"})})});const Ve=Ue.length,Ie=Te=>{if(Te.key==="ArrowDown")Te.preventDefault(),Te.stopPropagation(),Ae(st=>(st+1)%Math.max(1,Ve)),setTimeout(()=>{const st=(de+1)%Math.max(1,Ve);Ne.current[st]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Te.key==="ArrowUp")Te.preventDefault(),Te.stopPropagation(),Ae(st=>(st-1+Math.max(1,Ve))%Math.max(1,Ve)),setTimeout(()=>{const st=(de-1+Math.max(1,Ve))%Math.max(1,Ve);Ne.current[st]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0);else if(Te.key==="Enter"){Te.preventDefault(),Te.stopPropagation();const st=Ue[de];st&&ze(st.providerID,st.modelID)}else Te.key==="Escape"&&(Te.preventDefault(),Te.stopPropagation(),ve(!1))};let Ge=0;return e.jsxs(at,{delayDuration:1e3,children:[se?e.jsxs("button",{type:"button",onClick:()=>re("model"),onTouchStart:()=>Ot("model"),onTouchEnd:jr,onTouchCancel:jr,className:R("model-controls__model-trigger flex items-center gap-1.5 min-w-0 focus:outline-none","cursor-pointer hover:opacity-70",ke),children:[t?e.jsx(is,{providerId:t,className:R(Fe,"flex-shrink-0")}):e.jsx(mr,{className:R(Fe,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label typography-micro font-medium truncate min-w-0",!H&&"max-w-[220px]"),children:Rt()})]}):e.jsxs(Vt,{open:Pe,onOpenChange:ve,children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__model-trigger flex items-center gap-1.5 cursor-pointer hover:opacity-70 min-w-0",ke),children:[t?e.jsxs(e.Fragment,{children:[e.jsx(is,{providerId:t,className:R(Fe,"flex-shrink-0")}),e.jsx(mr,{className:R(Fe,"text-primary/60 hidden")})]}):e.jsx(mr,{className:R(Fe,"text-muted-foreground")}),e.jsx("span",{className:R("model-controls__model-label",ot,"font-medium whitespace-nowrap text-foreground truncate min-w-0","max-w-[260px]"),children:Rt()},`${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(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{type:"text",placeholder:"Search models",value:ee,onChange:Te=>fe(Te.target.value),onKeyDown:Ie,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ft,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[!be&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),J.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),J.map(({model:Te,providerID:st,modelID:Nt})=>{const vt=Ge++;return an(Te,st,Nt,"fav",vt,de===vt)})]}),ie.length>0&&e.jsxs(e.Fragment,{children:[J.length>0&&e.jsx(Ms,{}),e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),ie.map(({model:Te,providerID:st,modelID:Nt})=>{const vt=Ge++;return an(Te,st,Nt,"recent",vt,de===vt)})]}),(J.length>0||ie.length>0)&&le.length>0&&e.jsx(Ms,{}),le.map((Te,st)=>e.jsxs(c.Fragment,{children:[st>0&&e.jsx(Ms,{}),e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(is,{providerId:Te.id,className:"h-4 w-4 flex-shrink-0"}),Te.name]}),Te.models.map(Nt=>{const vt=Ge++;return an(Nt,Te.id,Nt.id,"provider",vt,de===vt)})]},Te.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()]})},lo=()=>{if(!ce)return e.jsx(nt,{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 J=!!(ce.prompt&&ce.prompt.trim().length>0),ie=ce.model?.providerID&&ce.model?.modelID,le=ce.temperature!==void 0||ce.topP!==void 0,be=Ge=>{const Te=aa(ce.permission)??[],st=Te.some(vt=>vt.permission===Ge&&vt.pattern!=="*"),Nt=ko(Te,Ge)??"ask";return st?{mode:"ask",label:"Custom"}:Nt==="allow"?{mode:"allow",label:"Allow"}:Nt==="deny"?{mode:"deny",label:"Deny"}:{mode:"ask",label:"Ask"}},Ue=be("edit"),Ve=be("bash"),Ie=be("webfetch");return e.jsx(nt,{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:ts(ce.name)}),ce.description&&e.jsx("span",{className:"typography-meta text-muted-foreground",children:ce.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:ce.mode==="primary"?"Primary":ce.mode==="subagent"?"Subagent":ce.mode==="all"?"All":"—"})]}),(ie||le)&&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"}),ie?e.jsxs("span",{className:"typography-meta text-foreground",children:[ce.model.providerID," / ",ce.model.modelID]}):e.jsx("span",{className:"typography-meta text-muted-foreground",children:"—"}),le&&e.jsxs("div",{className:"flex flex-col gap-0.5 mt-0.5",children:[ce.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:ce.temperature})]}),ce.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:ce.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:[Wt(Ue.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ue.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:[Wt(Ve.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ve.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:[Wt(Ie.mode,"h-3.5 w-3.5"),e.jsx("span",{className:"typography-meta font-medium text-foreground w-12",children:Ie.label})]})]})]}),J&&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(Po,{className:"h-4 w-4 text-foreground"})]})]})})},Aa=()=>{if(!Le)return null;const J=o??"Default",ie=!o,le=ie?"text-muted-foreground":"text-[color:var(--status-info)]";return se?e.jsxs("button",{type:"button",onClick:()=>re("variant"),className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",ke,"cursor-pointer hover:opacity-70"),children:[e.jsx(ar,{className:R(Fe,"flex-shrink-0",le)}),e.jsx("span",{className:R("model-controls__variant-label",ot,"font-medium truncate min-w-0",le),children:J})]}):e.jsxs(at,{delayDuration:800,children:[e.jsxs(Vt,{children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:e.jsxs("div",{className:R("model-controls__variant-trigger flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",ke),children:[e.jsx(ar,{className:R(Fe,"flex-shrink-0",le)}),e.jsx("span",{className:R("model-controls__variant-label",ot,"font-medium min-w-0 truncate",U?"max-w-[180px]":void 0,le),children:J})]})})}),e.jsxs(qt,{align:"end",alignOffset:-40,className:"w-[min(180px,calc(100vw-2rem))]",children:[e.jsx(Ur,{className:"typography-ui-header font-semibold text-foreground",children:"Thinking"}),e.jsx(Dt,{className:"typography-meta",onSelect:()=>Me(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"}),ie&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})}),pe.length>0&&e.jsx(Ms,{}),pe.map(be=>{const Ue=o===be,Ve=be.charAt(0).toUpperCase()+be.slice(1);return e.jsx(Dt,{className:"typography-meta",onSelect:()=>Me(be),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:Ve}),Ue&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]})},be)})]})]}),e.jsx(nt,{side:"top",children:e.jsxs("p",{className:"typography-meta",children:["Thinking: ",J]})})]})},Ea=()=>se?e.jsxs("button",{type:"button",onClick:()=>re("agent"),onTouchStart:()=>Ot("agent"),onTouchEnd:jr,onTouchCancel:jr,className:R("model-controls__agent-trigger flex items-center gap-1.5 transition-opacity min-w-0 focus:outline-none",ke,"cursor-pointer hover:opacity-70",se&&"ml-1"),children:[e.jsx(Xr,{className:R(Fe,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Nr(a).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",ot,"font-medium truncate min-w-0"),style:a?{color:`var(${Nr(a).var})`}:void 0,children:ns()})]}):e.jsx("div",{className:"flex items-center gap-2 min-w-0",children:e.jsxs(at,{delayDuration:1e3,children:[e.jsxs(Vt,{children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:e.jsxs("div",{className:R("flex items-center gap-1.5 transition-opacity cursor-pointer hover:opacity-70 min-w-0",ke),children:[e.jsx(Xr,{className:R(Fe,"flex-shrink-0",a?"":"text-muted-foreground"),style:a?{color:`var(${Nr(a).var})`}:void 0}),e.jsx("span",{className:R("model-controls__agent-label",ot,"font-medium min-w-0 truncate",U?"max-w-[220px]":void 0),style:a?{color:`var(${Nr(a).var})`}:void 0,children:ns()})]})})}),e.jsxs(qt,{align:"end",alignOffset:-40,className:"w-[min(280px,calc(100vw-2rem))]",children:[j.filter(J=>So(J.mode)).map(J=>e.jsx(Dt,{className:"typography-meta",onSelect:()=>tt(J.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:R("h-1 w-1 rounded-full agent-dot",Nr(J.name).class)}),e.jsx("span",{className:"font-medium",children:ts(J.name)})]}),J.description&&e.jsx("span",{className:"typography-meta text-muted-foreground max-w-[200px] ml-2.5 break-words",children:J.description})]})},J.name)),e.jsx(Ms,{}),e.jsxs("div",{className:"flex flex-col gap-1 px-1 py-0.5",children:[e.jsxs("button",{type:"button",disabled:At,onClick:()=>{At||W(J=>!J)},className:R("flex w-full items-center justify-between gap-2 rounded-xl px-2 py-2 text-left","focus:outline-none focus-visible:ring-0",At?"cursor-not-allowed opacity-60":void 0),"aria-expanded":Be,"aria-controls":G,children:[e.jsx("div",{className:"flex flex-col text-left",children:e.jsx("span",{className:"typography-meta font-medium text-foreground",style:{color:ct?ct.text:"var(--foreground)"},children:es})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:R("flex items-center justify-center p-1",!ct&&"text-muted-foreground"),style:ct?{color:ct.text}:void 0,children:Wt(Xe)}),e.jsx(It,{className:R("h-3.5 w-3.5 transition-transform text-muted-foreground",Be?"rotate-180":"")})]})]}),Be&&!At&&e.jsx("div",{id:G,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:Ct.map(J=>{const ie=J.mode===Xe,le=Wn(J.mode);return e.jsxs("button",{type:"button",disabled:J.disabled,onClick:()=>He(J.mode),className:R("flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left",J.disabled?"cursor-not-allowed opacity-50":"focus:outline-none focus-visible:ring-0",ie?"bg-primary/10":void 0),style:ie&&le?{backgroundColor:le.background??void 0}:void 0,children:[Wt(J.mode,$e),e.jsx("span",{className:"typography-meta font-medium",style:{color:le?le.text:"var(--foreground)"},children:J.label})]},J.mode)})})]})]})]}),lo()]})}),oe=R("@container/model-controls flex items-center min-w-0",H&&"w-full",s);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:oe,children:e.jsxs("div",{className:R("flex items-center min-w-0 flex-1 justify-end",Lt,H&&"overflow-hidden"),children:[Aa(),Da(),Ea()]})}),Ma(),Or(),$r(),Tn(),Ca()]})},ew=s=>s?/(\s|\(|\)|\[|\]|\{|\}|"|'|`|,|\.|;|:)/.test(s):!0,Jc=(s,r)=>{if(typeof s!="string"||s.length===0)return{sanitizedText:s,mention:null};const t=r.filter(o=>o.mode&&o.mode!=="primary");if(t.length===0||!s.includes("#"))return{sanitizedText:s,mention:null};let n=null;for(const o of t){const a=new RegExp(`#${o.name}\\b`,"gi");let i;for(;(i=a.exec(s))!==null;){const l=i.index,d=l+i[0].length,u=l>0?s[l-1]:null;if(!ew(u))continue;const m={name:o.name,source:{value:i[0],start:l,end:d}};n||(n=m)}}return n?{sanitizedText:s,mention:n}:{sanitizedText:s,mention:null}},Lm=s=>({id:s.id,content:s.content,status:s.status||"pending",priority:s.priority||"medium"}),$i=zt()(Yt((s,r)=>({sessionTodos:new Map,isLoading:!1,loadTodos:async t=>{if(t){s({isLoading:!0});try{const n=ue.getState().getDirectoryForSession(t),a=(n?await je.withDirectory(n,()=>je.getSessionTodos(t)):await je.getSessionTodos(t)).map(Lm);s(i=>{const l=new Map(i.sessionTodos);return l.set(t,a),{sessionTodos:l,isLoading:!1}})}catch(n){console.warn("[TodoStore] Failed to load todos:",n),s({isLoading:!1})}}},updateTodos:(t,n)=>{s(o=>{const a=new Map(o.sessionTodos);return a.set(t,n),{sessionTodos:a}})},getTodosForSession:t=>r().sessionTodos.get(t)||[],clearTodos:t=>{s(n=>{const o=new Map(n.sessionTodos);return o.delete(t),{sessionTodos:o}})}}),{name:"todo-store"})),tw=(s,r)=>{const t=r.map(Lm);$i.getState().updateTodos(s,t)},Zc=[{variant:"shine",component:({children:s,className:r,...t})=>e.jsx(pn.span,{...t,className:R("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)=>De.createElement(pn.span,{...t,key:n+String(o),className:R("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:R("invisible",r),children:s}),e.jsx("span",{...t,className:R("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:R("absolute top-0 left-0 translate-y-full text-primary-muted transition-transform duration-500","ease-in-out hover:duration-300 group-hover:translate-y-0",r),children:s})]})},{variant:"hover-enter",component:({children:s,className:r,...t})=>{if(typeof s!="string")return null;const n=.25,o=.025,a=s.split("").map(i=>i===" "?" ":i);return e.jsxs(pn.span,{...t,className:R("relative block select-none overflow-hidden whitespace-nowrap text-primary-muted",r),initial:"initial",whileHover:"hovered",style:{lineHeight:.9},children:[e.jsx("div",{children:a.map((i,l)=>e.jsx(pn.span,{className:"inline-block",variants:{initial:{y:0},hovered:{y:"-100%"}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))}),e.jsx("div",{className:R("absolute inset-0"),children:a.map((i,l)=>e.jsx(pn.span,{className:"inline-block",variants:{initial:{y:"100%"},hovered:{y:0}},transition:{duration:n,ease:"easeInOut",delay:o*l},children:i},String(l)))})]})}},{variant:"shake",component:({children:s,className:r,...t})=>e.jsx("span",{...t,className:R("text-primary-muted hover:animate-text-shake",r),children:s})},{variant:"hover-decoration",component:({children:s,className:r,...t})=>e.jsx("div",{className:R("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:R("text-primary-muted",r),children:s})})}];function ei({variant:s="shine",className:r,...t}){const a=Zc.find(i=>i.variant===s)?.component||Zc[0].component;return e.jsx(iu,{children:e.jsx(a,{...t,className:r})})}const ed=1500,sw=2e3;function rw({statusText:s,isGenericStatus:r,isWaitingForPermission:t,wasAborted:n,completionId:o,isComplete:a,onResultVisibilityChange:i}){const[l,d]=De.useState("idle"),[u,m]=De.useState(null),[f,p]=De.useState(!1),g=De.useRef(0),w=De.useRef(null),h=De.useRef(null),j=De.useRef(null),x=De.useRef(null),y=De.useRef(!1),b=De.useRef(!1),N=De.useRef(!1),v=De.useCallback(()=>{h.current&&(clearTimeout(h.current),h.current=null),j.current&&(clearTimeout(j.current),j.current=null)},[]),k=De.useCallback((_,T)=>{v(),w.current=null,m(_),p(T),d("showing"),g.current=Date.now(),y.current=!0},[v]),D=De.useCallback(()=>{if(h.current)return;const _=Date.now()-g.current,T=Math.max(0,ed-_);h.current=setTimeout(()=>{h.current=null;const P=w.current;P&&k(P.text,P.permission)},T)},[k]),C=De.useCallback(_=>{if(v(),w.current=null,!y.current){d("idle"),m(null),i?.(!1);return}if(_==="done"&&o&&x.current===o){d("idle"),m(null),y.current=!1,i?.(!1);return}_==="done"&&o&&(x.current=o),d(_),m(null),i?.(!0),j.current=setTimeout(()=>{j.current=null,d("idle"),y.current=!1,i?.(!1)},sw)},[v,o,i]);if(De.useEffect(()=>{if(n&&!N.current){N.current=!0,C("aborted");return}if(N.current=!!n,a&&!b.current){b.current=!0,C("done");return}if(!a&&b.current&&(b.current=!1),!(l==="done"||l==="aborted")&&s){const T=Date.now()-g.current;if(l==="idle"||!u)k(s,!!t);else if(s!==u||!!t!==f){if(r)return;T>=ed?k(s,!!t):(w.current={text:s,permission:!!t},D())}}},[s,t,n,a,l,u,f,k,C,D,r]),De.useEffect(()=>()=>v(),[v]),De.useEffect(()=>{const _=()=>{typeof document>"u"||document.visibilityState==="visible"&&(l==="done"||l==="aborted")&&(v(),d("idle"),m(null),y.current=!1)};return document.addEventListener("visibilitychange",_),()=>document.removeEventListener("visibilitychange",_)},[l,v]),l==="idle"&&!u)return null;let M,S=!0;l==="done"?(M="Done",S=!1):l==="aborted"?(M="Aborted",S=!1):u?M=u.charAt(0).toUpperCase()+u.slice(1):M="Working";const A=S?`${M}...`:M,I=l!=="idle";return e.jsx("div",{className:`flex h-full items-center text-muted-foreground pl-[2ch] transition-opacity duration-200 ${I?"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:l==="done"?e.jsx(ei,{variant:"hover-enter",className:"typography-ui-header",children:"Done"}):l==="aborted"?e.jsx(ei,{variant:"hover-enter",className:"typography-ui-header text-status-error",children:"Aborted"}):e.jsx(ei,{variant:"shine",className:"typography-ui-header",children:A})})})}const td={in_progress:{textClassName:"text-foreground"},pending:{textClassName:"text-foreground"},completed:{textClassName:"text-muted-foreground line-through"},cancelled:{textClassName:"text-muted-foreground line-through"}},nw=({todo:s})=>{const r=td[s.status]||td.pending;return e.jsx("div",{className:"flex items-start min-w-0 py-0.5",children:e.jsx("span",{className:R("flex-1 typography-ui-label",r.textClassName),children:s.content})})},sd=[],ow=({isWorking:s,statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,abortActive:a,completionId:i,isComplete:l,showAbort:d,onAbort:u,showAbortStatus:m})=>{const[f,p]=c.useState(!1),g=ue(T=>T.currentSessionId),w=$i(T=>g?T.sessionTodos.get(g)??sd:sd),h=$i(T=>T.loadTodos),{isMobile:j}=_e(),x=j||Ut();c.useEffect(()=>{g&&h(g)},[g,h]);const y=c.useMemo(()=>{const T={in_progress:0,pending:1,completed:2,cancelled:3};return[...w].filter(P=>P.status!=="cancelled").sort((P,L)=>T[P.status]-T[L.status])},[w]),b=c.useMemo(()=>y.find(T=>T.status==="in_progress")||y.find(T=>T.status==="pending")||null,[y]),N=c.useMemo(()=>{const T=w.filter(L=>L.status!=="cancelled").length;return{completed:w.filter(L=>L.status==="completed").length,total:T}},[w]),v=y.some(T=>T.status==="in_progress"||T.status==="pending"),k=!m&&(o||!a),[D,C]=c.useState(!1),M=s||l||o||D||v||m,S=c.useRef(null);if(c.useEffect(()=>{if(!f)return;const T=P=>{S.current&&!S.current.contains(P.target)&&p(!1)};return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[f]),!M)return null;const A=()=>p(T=>!T),I=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(Sn,{size:18,"aria-hidden":"true"})}):null,_=v?e.jsxs("button",{type:"button",onClick:A,className:"flex items-center gap-1 flex-shrink-0 text-muted-foreground",children:[!x&&b?e.jsx("span",{className:"typography-ui-label text-foreground truncate max-w-[200px]",children:b.content}):e.jsx("span",{className:"typography-ui-label",children:"Tasks"}),e.jsxs("span",{className:"typography-meta",children:[N.completed,"/",N.total]}),f?e.jsx(ua,{className:"h-3.5 w-3.5"}):e.jsx(It,{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(Sn,{size:16,"aria-hidden":"true"}),"Aborted"]})}):k?e.jsx(rw,{statusText:r,isGenericStatus:t,isWaitingForPermission:n,wasAborted:o,completionId:i??null,isComplete:l,onResultVisibilityChange:C},g??"no-session"):null}),e.jsxs("div",{className:"relative flex items-center gap-2 flex-shrink-0",ref:S,children:[I,_,f&&v&&e.jsxs("div",{style:{maxWidth:"calc(100cqw - 4ch)"},className:R("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:y.map(T=>e.jsx(nw,{todo:T},T.id))})]})]})]})})},Li=s=>!s||typeof s!="object"?!1:!!s.synthetic,rd=s=>!Array.isArray(s)||s.length===0?!1:s.every(r=>Li(r)),aw=s=>!Array.isArray(s)||s.length===0?[]:s.some(t=>!Li(t))?s.filter(t=>!Li(t)):s,iw={phase:"idle",isWorking:!1,isBusy:!1,isCooldown:!1};function lw(s){const r=ue(t=>!s||!t.sessionActivityPhase?"idle":t.sessionActivityPhase.get(s)??"idle");return c.useMemo(()=>{if(r==="idle")return iw;const t=r==="busy",n=r==="cooldown";return{phase:r,isWorking:t||n,isBusy:t,isCooldown:n}},[r])}function Ml(){const s=ue(r=>r.currentSessionId);return lw(s)}const cw={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},nd=s=>s.role==="assistant",dw=s=>s.type==="reasoning",Bm=s=>s.type==="text",od=s=>{if(Bm(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},ad=s=>(Bm(s)||dw(s),s.time),uw=s=>{if(s.tool)return s.tool;const r=s;return typeof r.name=="string"?r.name:"tool"};function zm(){const{currentSessionId:s,messages:r,permissions:t,sessionAbortFlags:n}=ue(Ji(g=>({currentSessionId:g.currentSessionId,messages:g.messages,permissions:g.permissions,sessionAbortFlags:g.sessionAbortFlags}))),{phase:o,isWorking:a,isCooldown:i}=Ml(),l=c.useMemo(()=>s?r.get(s)??[]:[],[s,r]),d=c.useMemo(()=>{if(l.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const g=l.filter(M=>nd(M.info)&&!rd(M.parts));if(g.length===0)return{activePartType:void 0,activeToolName:void 0,statusText:"working",isGenericStatus:!0};const w=[...g].sort((M,S)=>{const A=typeof M.info.time?.created=="number"?M.info.time.created:null,I=typeof S.info.time?.created=="number"?S.info.time.created:null;return A!==null&&I!==null&&A!==I?A-I:M.info.id.localeCompare(S.info.id)}),h=w[w.length-1];let j,x;const y=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 A=S.time??ad(S);(!A||typeof A.end>"u")&&!j&&(j="reasoning");break}case"tool":{const A=S.state?.status;if((A==="running"||A==="pending")&&!j){const I=uw(S);y.has(I)?j="editing":(j="tool",x=I)}break}case"text":{const A=od(S)??"";if(typeof A=="string"&&A.trim().length>0){const I=ad(S);(!I||typeof I.end>"u")&&!j&&(j="text")}break}}}const b={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"],v=M=>b[M]??`using ${M}`,k=()=>N[Math.floor(Math.random()*N.length)],D=j===void 0,C=j==="editing"?"editing file":j==="tool"&&x?v(x):j==="reasoning"?"thinking":j==="text"?"composing":k();return{activePartType:j,activeToolName:x,statusText:C,isGenericStatus:D}},[l]),u=c.useMemo(()=>{const g=s,w=g?n?.get(g)??null:null,h=!!(w&&!w.acknowledged);return{wasAborted:h,abortActive:h}},[s,n]),m=c.useMemo(()=>{if(u.wasAborted)return{...cw,wasAborted:!0,abortActive:u.abortActive,activity:"idle",hasWorkingContext:!1,isWorking:!1,isStreaming:!1,isCooldown:!1,statusText:null,canAbort:!1};const g=a,w=o==="busy",h=i;let j="idle";return g&&(d.activePartType==="tool"||d.activePartType==="editing"?j="tooling":j=h?"cooldown":"streaming"),{activity:j,hasWorkingContext:g,hasActiveTools:d.activePartType==="tool"||d.activePartType==="editing",isWorking:g,isStreaming:w,isCooldown:h,lifecyclePhase:w?"streaming":h?"cooldown":null,statusText:g?d.statusText:null,isGenericStatus:g?d.isGenericStatus:!0,isWaitingForPermission:!1,canAbort:g,compactionDeadline:null,activePartType:g?d.activePartType:void 0,activeToolName:g?d.activeToolName:void 0,wasAborted:!1,abortActive:!1,lastCompletionId:null,isComplete:h}},[o,a,i,d,u]),f=c.useMemo(()=>{const g=a&&d.activePartType==="text";if(!g||l.length===0)return{isActive:g,characterCount:0};const w=l.filter(x=>nd(x.info)&&!rd(x.parts));if(w.length===0)return{isActive:g,characterCount:0};const h=w[w.length-1];let j=0;return(h.parts??[]).forEach(x=>{if(x.type!=="text")return;const y=od(x)??"";typeof y=="string"&&y.trim().length>0&&(j+=y.length)}),{isActive:g,characterCount:j}},[l,a,d.activePartType]),p=c.useMemo(()=>{if(m.wasAborted||m.abortActive)return m;const g=s;return(g?t?.get(g)??[]:[]).length>0?{...m,statusText:"waiting for permission",isWaitingForPermission:!0,canAbort:!1}:m},[s,t,m]);return{forming:f,working:p}}const mw=8,id=[],fw=s=>s==="primary"||s==="all"||s===void 0||s===null,Wm=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},ld=(s,r)=>{const t=Wm(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}}},pw=(s,r)=>{const t=Wm(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},Co=({onOpenSettings:s,scrollToBottom:r})=>{const[t,n]=c.useState(""),[o,a]=c.useState(!1),[i,l]=c.useState(!1),[d,u]=c.useState(""),[m,f]=c.useState(!1),[p,g]=c.useState(""),[w,h]=c.useState(!1),[j,x]=c.useState(""),[y,b]=c.useState(!1),[N,v]=c.useState(""),[k,D]=c.useState(null),C=c.useRef(null),M=c.useRef(null),S=c.useRef(null),A=c.useRef(null),I=c.useRef(null),_=c.useRef(null),T=ue(oe=>oe.sendMessage),P=ue(oe=>oe.currentSessionId),L=ue(oe=>oe.newSessionDraft?.open),Z=ue(oe=>oe.abortCurrentOperation),q=ue(oe=>oe.acknowledgeSessionAbort),$=ue(oe=>oe.abortPromptSessionId),H=ue(oe=>oe.abortPromptExpiresAt),U=ue(oe=>oe.clearAbortPrompt),K=ue(oe=>oe.sessionAbortFlags),se=ue(oe=>oe.attachedFiles),Y=ue(oe=>oe.addAttachedFile),re=ue(oe=>oe.addServerFile),V=ue(oe=>oe.clearAttachedFiles),ae=ue(oe=>oe.saveSessionAgentSelection),E=ue(oe=>oe.consumePendingInputText),B=ue(oe=>oe.pendingInputText),{currentProviderId:F,currentModelId:O,currentVariant:z,currentAgentName:Q,setAgent:me,getVisibleAgents:Se}=rt(),he=Se(),{isMobile:Pe,inputBarOffset:ve,isKeyboardOpen:Be,setTimelineDialogOpen:W}=_e(),{working:G}=zm(),[ee,fe]=c.useState(!1),de=c.useRef(null),Ae=c.useRef(!1),Ne=c.useRef(!1),Oe=Zs(oe=>oe.queueModeEnabled),ce=Zs(c.useCallback(oe=>P?oe.queuedMessages[P]??id:id,[P])),dt=Zs(oe=>oe.addToQueue),kt=Zs(oe=>oe.clearQueue),{phase:we}=Ml(),ne=c.useRef(we),Qe=c.useRef(!1),ge=c.useCallback(oe=>{if(!Pe||oe.pointerType!=="touch")return;const J=C.current;if(!J||document.activeElement===J)return;oe.preventDefault(),oe.stopPropagation();const ie=document.scrollingElement;ie&&ie.scrollTop!==0&&(ie.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0);try{J.focus({preventScroll:!0})}catch{J.focus()}const le=J.value.length;try{J.setSelectionRange(le,le)}catch{}},[Pe]);c.useEffect(()=>{if(B!==null){const oe=E();oe&&(n(oe),setTimeout(()=>{C.current?.focus()},0))}},[B,E]);const ye=c.useMemo(()=>{if(Q)return he.find(oe=>oe.name===Q)},[he,Q]),qe=c.useMemo(()=>ye?ld(ye.permission,"edit")??"ask":"deny",[ye]),Ze=ue(c.useCallback(oe=>!P||!Q?void 0:oe.sessionAgentEditModes.get(P)?.get(Q),[P,Q])),We=c.useMemo(()=>{if(ye)return ld(ye.permission,"webfetch")},[ye]),Re=c.useMemo(()=>{if(!ye)return;const oe=pw(ye.permission,"bash");return oe||void 0},[ye]),Xe=c.useMemo(()=>$m({agentDefaultEditMode:qe,webfetchPermission:We,bashPermission:Re}),[qe,We,Re]),Ct=!!(P&&Q),ct=c.useMemo(()=>Ct&&Ze&&Xe.modeAvailability[Ze]?Ze:Xe.cascadeDefaultMode,[Xe,Ct,Ze]),At=c.useMemo(()=>Wn(ct),[ct]),Mt=c.useCallback(oe=>Ut()?`color-mix(in srgb, ${oe} 55%, transparent)`:oe,[]),ke=c.useMemo(()=>{const oe=Ut()?1:2;if(!At)return{borderWidth:oe};const J=At.border??At.text;return{borderColor:Mt(J),borderWidth:oe}},[At,Mt]),$e=t.trim()||se.length>0,Fe=ce.length>0,ot=$e||Fe,Lt=G.isWorking,es=c.useMemo(()=>P?$===P&&!!H:!1,[$,H,P]),Wt=c.useCallback(()=>{if(!$e||!P)return;const oe=t.replace(/^\n+|\n+$/g,""),J=se.map(ie=>({...ie}));dt(P,{content:oe,attachments:J.length>0?J:void 0}),n(""),J.length>0&&V(),Pe||C.current?.focus()},[$e,P,t,se,dt,V,Pe]),He=async oe=>{if(oe?.preventDefault(),!ot||!P&&!L)return;if(r?.({instant:!0,force:!0}),!F||!O){console.warn("Cannot send message: provider or model not selected");return}let J="",ie=[],le;const be=[];for(let Ie=0;Ie<ce.length;Ie++){const Ge=ce[Ie],{sanitizedText:Te,mention:st}=Jc(Ge.content,he);!le&&st?.name&&(le=st.name),Ie===0?(J=Te,ie=Ge.attachments??[]):be.push({text:Te,attachments:Ge.attachments})}if($e){const Ie=t.replace(/^\n+|\n+$/g,""),{sanitizedText:Ge,mention:Te}=Jc(Ie,he),st=se.map(Nt=>({...Nt}));!le&&Te?.name&&(le=Te.name),ce.length===0?(J=Ge,ie=st):be.push({text:Ge,attachments:st.length>0?st:void 0})}if(!J&&be.length===0)return;P&&Fe&&kt(P),n(""),se.length>0&&V(),Pe&&C.current?.blur();const Ue=J.trimStart();if(Ue.startsWith("/")){const Ie=Ue.slice(1).trim().split(/\s+/)[0]?.toLowerCase();if(Ie==="undo"&&P){await ue.getState().handleSlashUndo(P),r?.({instant:!0,force:!0});return}else if(Ie==="redo"&&P){await ue.getState().handleSlashRedo(P),r?.({instant:!0,force:!0});return}else if(Ie==="timeline"&&P){W(!0),n("");return}else if(Ie==="compact"&&P){try{const{opencodeClient:Ge}=await as(async()=>{const{opencodeClient:Nt}=await Promise.resolve().then(()=>hg);return{opencodeClient:Nt}},void 0),Te=Ge.getDirectory();if((await Ge.getApiClient().session.summarize({sessionID:P,directory:Te||void 0,providerID:F,modelID:O})).error)throw new Error("Failed to compact session");r?.({instant:!0,force:!0})}catch(Ge){console.error("Failed to compact session:",Ge),te.error("Failed to compact session")}n("");return}}const Ve=[...ie,...be.flatMap(Ie=>Ie.attachments??[])];await T(J,F,O,Q,ie,le,be.length>0?be:void 0,z).catch(Ie=>{const Ge=Ie instanceof Error?Ie.message:typeof Ie=="string"?Ie:String(Ie??""),Te=Ge.toLowerCase();console.error("Message send failed:",Ge||Ie),!(Te.includes("timeout")||Te.includes("timed out")||Te.includes("may still be processing")||Te.includes("being processed")||Te.includes("failed to fetch")||Te.includes("networkerror")||Te.includes("network error")||Te.includes("gateway timeout")||Te==="failed to send message")&&(Ve.length>0&&er.setState({attachedFiles:Ve}),te.error(Ge||"Message failed to send. Attachments restored."))}),Pe||C.current?.focus()},et=c.useRef(He);et.current=He,c.useEffect(()=>{const oe=ne.current==="busy"||ne.current==="cooldown",J=we==="idle",ie=P&&K.has(P)&&(()=>{const le=K.get(P);return le?Date.now()-le.timestamp<2e3:!1})();oe&&J&&ce.length>0&&!Qe.current&&!ie&&(Qe.current=!0,setTimeout(()=>{P&&F&&O&&et.current(),Qe.current=!1},100)),ne.current=we},[we,ce.length,P,F,O,K]);const gt=oe=>{if(!kl(oe)){if(m&&A.current&&(oe.key==="Enter"||oe.key==="ArrowUp"||oe.key==="ArrowDown"||oe.key==="Escape"||oe.key==="Tab")){oe.preventDefault(),A.current.handleKeyDown(oe.key);return}if(w&&I.current&&(oe.key==="Enter"||oe.key==="ArrowUp"||oe.key==="ArrowDown"||oe.key==="Escape"||oe.key==="Tab")){oe.preventDefault(),I.current.handleKeyDown(oe.key);return}if(y&&_.current&&(oe.key==="Enter"||oe.key==="ArrowUp"||oe.key==="ArrowDown"||oe.key==="Escape"||oe.key==="Tab")){oe.preventDefault(),_.current.handleKeyDown(oe.key);return}if(i&&S.current&&(oe.key==="Enter"||oe.key==="ArrowUp"||oe.key==="ArrowDown"||oe.key==="Escape"||oe.key==="Tab")){oe.preventDefault(),S.current.handleKeyDown(oe.key);return}if(oe.key==="Tab"&&!m&&!w&&!i){oe.preventDefault(),X();return}if(oe.key==="Enter"&&!oe.shiftKey&&!Pe){oe.preventDefault();const J=oe.ctrlKey||oe.metaKey,ie=$e&&P&&we!=="idle";Oe?J||!ie?He():Wt():J&&ie?Wt():He()}}},Je=c.useCallback(()=>{de.current&&(clearTimeout(de.current),de.current=null),fe(!0),de.current=setTimeout(()=>{fe(!1),de.current=null},1800)},[]),bt=c.useCallback(()=>{U(),Je(),Z()},[Z,U,Je]),X=()=>{const oe=he.filter(be=>fw(be.mode));if(oe.length<=1)return;const ie=(oe.findIndex(be=>be.name===Q)+1)%oe.length,le=oe[ie];me(le.name),P&&ae(P,le.name)},xe=c.useCallback(()=>{const oe=C.current;if(!oe)return;oe.style.height="auto";const J=oe.ownerDocument?.defaultView,ie=J?J.getComputedStyle(oe):null,le=ie?parseFloat(ie.lineHeight):NaN,be=ie?parseFloat(ie.paddingTop):NaN,Ue=ie?parseFloat(ie.paddingBottom):NaN,Ve=22,Ge=Number.isNaN(be)||Number.isNaN(Ue)?16:be+Ue,st=(Number.isNaN(le)?Ve:le)*mw+Ge,Nt=oe.scrollHeight||oe.offsetHeight,vt=Math.min(Nt,st);oe.style.height=`${vt}px`,oe.style.maxHeight=`${st}px`,D(ws=>ws&&ws.height===vt&&ws.maxHeight===st?ws:{height:vt,maxHeight:st})},[]);c.useLayoutEffect(()=>{xe()},[xe,t,Pe]);const pe=c.useCallback((oe,J)=>{if(oe.startsWith("/")){const Ve=oe.indexOf(" "),Ie=oe.indexOf(`
69
- `),Ge=Math.min(Ve===-1?oe.length:Ve,Ie===-1?oe.length:Ie);if(J<=Ge&&Ve===-1){const Te=oe.substring(1,Ge);g(Te),f(!0),l(!1),h(!1),b(!1);return}}f(!1);const ie=oe.substring(0,J),le=ie.lastIndexOf("#");if(le!==-1){const Ve=le>0?ie[le-1]:null,Ie=ie.substring(le+1),Ge=Ie.includes(" ")||Ie.includes(`
70
- `);if((!Ve||/\s/.test(Ve))&&!Ge){x(Ie),h(!0),l(!1);return}}h(!1),x("");const be=ie.lastIndexOf("/");if(be!==-1){const Ve=be>0?ie[be-1]:null,Ie=ie.substring(be+1),Ge=Ie.includes(" ")||Ie.includes(`
71
- `);if((!Ve||/\s/.test(Ve))&&!Ge){v(Ie),b(!0),l(!1),h(!1);return}}b(!1),v("");const Ue=ie.lastIndexOf("@");if(Ue!==-1){const Ve=ie.substring(Ue+1);!Ve.includes(" ")&&!Ve.includes(`
72
- `)?(u(Ve),l(!0)):l(!1)}else l(!1)},[x,g,u,h,f,l,b,v]),Le=c.useCallback(oe=>{if(!oe)return;const J=C.current;if(!J){const Ve=t+oe;n(Ve),pe(Ve,Ve.length),requestAnimationFrame(()=>xe());return}const ie=J.selectionStart??t.length,le=J.selectionEnd??t.length,be=`${t.substring(0,ie)}${oe}${t.substring(le)}`;n(be);const Ue=ie+oe.length;requestAnimationFrame(()=>{const Ve=C.current;Ve&&(Ve.selectionStart=Ue,Ve.selectionEnd=Ue),xe()}),pe(be,Ue)},[xe,t,pe]),Ee=oe=>{const J=oe.target.value,ie=oe.target.selectionStart??J.length;n(J),xe(),pe(J,ie)},Ke=c.useCallback(async oe=>{const J=new Map;Array.from(oe.clipboardData.files||[]).forEach(Ue=>{Ue.type.startsWith("image/")&&J.set(`${Ue.name}-${Ue.size}`,Ue)}),Array.from(oe.clipboardData.items||[]).forEach(Ue=>{if(Ue.kind==="file"&&Ue.type.startsWith("image/")){const Ve=Ue.getAsFile();Ve&&J.set(`${Ve.name}-${Ve.size}`,Ve)}});const ie=Array.from(J.values());if(ie.length===0||!P&&!L)return;oe.preventDefault();const le=oe.clipboardData.getData("text");le&&Le(le);let be=0;for(const Ue of ie){const Ve=ue.getState().attachedFiles.length;try{await Y(Ue),ue.getState().attachedFiles.length>Ve&&(be+=1)}catch(Ie){console.error("Clipboard image attach failed",Ie),te.error(Ie instanceof Error?Ie.message:"Failed to attach image from clipboard")}}be>0&&te.success(`Attached ${be} image${be>1?"s":""} from clipboard`)},[Y,P,L,Le]),pt=oe=>{const J=C.current?.selectionStart||0,le=t.substring(0,J).lastIndexOf("@");if(le!==-1){const be=t.substring(0,le)+oe.name+t.substring(J);n(be)}l(!1),u(""),C.current?.focus()},ut=oe=>{const ie=C.current?.selectionStart??t.length,be=t.substring(0,ie).lastIndexOf("#");if(be!==-1){const Ue=t.substring(0,be)+`#${oe} `+t.substring(ie);n(Ue);const Ve=be+oe.length+2;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=Ve,C.current.selectionEnd=Ve),xe(),pe(Ue,Ve)})}h(!1),x(""),C.current?.focus()},Tt=oe=>{const ie=C.current?.selectionStart??t.length,be=t.substring(0,ie).lastIndexOf("/");if(be!==-1){const Ue=t.substring(0,be)+`${oe} `+t.substring(ie);n(Ue);const Ve=be+oe.length+1;requestAnimationFrame(()=>{C.current&&(C.current.selectionStart=Ve,C.current.selectionEnd=Ve),xe(),pe(Ue,Ve)})}b(!1),v(""),C.current?.focus()},xt=oe=>{n(`/${oe.name} `);const J=C.current;J&&(J._commandMetadata=oe),f(!1),g(""),setTimeout(()=>{C.current&&(C.current.focus(),C.current.setSelectionRange(C.current.value.length,C.current.value.length))},0)};c.useEffect(()=>{P&&C.current&&!Pe&&C.current.focus()},[P,Pe]),c.useEffect(()=>{$&&$!==P&&U()},[$,P,U]);const Me=oe=>{oe.preventDefault(),oe.stopPropagation(),(P||L)&&!o&&a(!0)},tt=oe=>{oe.preventDefault(),oe.stopPropagation(),oe.currentTarget===oe.target&&a(!1)},ze=async oe=>{if(oe.preventDefault(),oe.stopPropagation(),a(!1),!P&&!L)return;const J=Array.from(oe.dataTransfer.files);let ie=0;for(const le of J){const be=ue.getState().attachedFiles.length;try{await Y(le),ue.getState().attachedFiles.length>be&&(ie+=1)}catch(Ue){console.error("File attach failed",Ue),te.error(Ue instanceof Error?Ue.message:"Failed to attach file")}}ie>0&&te.success(`Attached ${ie} file${ie>1?"s":""}`)},Ye=c.useCallback(async oe=>{let J=0;for(const ie of oe){const le=ue.getState().attachedFiles.length;try{await re(ie.path,ie.name),ue.getState().attachedFiles.length>le&&(J+=1)}catch(be){console.error("Server file attach failed",be),te.error(be instanceof Error?be.message:"Failed to attach file")}}J>0&&te.success(`Attached ${J} file${J>1?"s":""}`)},[re]),wt=c.useRef(null),[Rt,ns]=c.useState(!1),ts=c.useCallback(async oe=>{let J=0;const ie=Array.isArray(oe)?oe:Array.from(oe);for(const le of ie){const be=ue.getState().attachedFiles.length;try{await Y(le),ue.getState().attachedFiles.length>be&&(J+=1)}catch(Ue){console.error("File attach failed",Ue),te.error(Ue instanceof Error?Ue.message:"Failed to attach file")}}J>0&&te.success(`Attached ${J} file${J>1?"s":""}`)},[Y]),ps=c.useCallback(async()=>{try{const J=await(await fetch("/api/vscode/pick-files")).json(),ie=Array.isArray(J?.files)?J.files:[],le=Array.isArray(J?.skipped)?J.skipped:[];if(le.length>0){const Ue=le.map(Ve=>`${Ve?.name||"file"}: ${Ve?.reason||"skipped"}`).join(`
73
- `);te.error(`Some files were skipped:
74
- ${Ue}`)}const be=ie.map(Ue=>{if(!Ue?.dataUrl)return null;try{const[Ve,Ie]=Ue.dataUrl.split(","),Ge=Ue.mimeType||Ve?.match(/data:(.*);base64/)?.[1]||"application/octet-stream";if(!Ie)return null;const Te=atob(Ie),st=new Uint8Array(Te.length);for(let vt=0;vt<Te.length;vt++)st[vt]=Te.charCodeAt(vt);const Nt=new Blob([st],{type:Ge});return new File([Nt],Ue.name||"file",{type:Ge})}catch(Ve){return console.error("Failed to decode VS Code picked file",Ve),null}}).filter(Boolean);be.length>0&&await ts(be)}catch(oe){console.error("VS Code file pick failed",oe),te.error(oe instanceof Error?oe.message:"Failed to pick files in VS Code")}},[ts]),lr=c.useCallback(()=>{if(Ut()){ps();return}wt.current?.click()},[ps]),Ot=c.useCallback(async oe=>{const J=oe.target.files;J&&(await ts(J),oe.target.value="")},[ts]),jr="gap-x-1.5 gap-y-0",Tn=Ut(),Ca=Pe?"px-1.5 py-1.5":Tn?"px-1.5 py-1":"px-2.5 py-1.5",Ma=Pe?"h-9 w-9":Tn?"h-[22px] w-[22px]":"h-7 w-7",Or=Pe?"h-5 w-5":Tn?"h-4 w-4":"h-[18px] w-[18px]",$r=R(Ma,"flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0"),an=!Pe&&es&&Lt?e.jsx("button",{type:"button",onClick:bt,className:R($r,"text-[var(--status-error)] hover:text-[var(--status-error)]"),"aria-label":"Stop generating",children:e.jsx(Sn,{className:R(Or)})}):e.jsx("button",{type:Pe?"button":"submit",disabled:!ot||!P&&!L,onPointerDownCapture:oe=>{!Pe||oe.pointerType!=="touch"||!ot||!P&&!L||(Ne.current=!0,oe.preventDefault(),oe.stopPropagation(),He())},onClick:oe=>{if(Pe){if(Ne.current){Ne.current=!1;return}oe.preventDefault(),He()}},className:R($r,ot&&(P||L)?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Send message",children:e.jsx(fu,{className:R(Or)})}),Fn=e.jsxs(e.Fragment,{children:[e.jsx("input",{ref:wt,type:"file",multiple:!0,className:"hidden",onChange:Ot,accept:"*/*"}),e.jsxs("div",{className:"relative inline-flex",children:[e.jsx(Ub,{onFilesSelected:Ye,multiSelect:!0,presentation:Pe?"modal":"dropdown",open:Rt,onOpenChange:ns,children:Pe?null:e.jsx("button",{type:"button",tabIndex:-1,"aria-hidden":"true",className:"absolute inset-0 opacity-0 pointer-events-none"})}),e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx("button",{type:"button",className:$r,title:"Add attachment","aria-label":"Add attachment",children:e.jsx(pu,{className:R(Or,"text-current")})})}),e.jsxs(qt,{align:"start",children:[e.jsxs(Dt,{onSelect:()=>{requestAnimationFrame(()=>lr())},children:[e.jsx(qo,{}),"Attach files"]}),e.jsxs(Dt,{onSelect:()=>{requestAnimationFrame(()=>{ns(!0)})},children:[e.jsx(dh,{}),"Attach from project"]})]})]})]})]}),Da=s?e.jsx("button",{type:"button",onClick:s,className:$r,title:"Model and agent settings","aria-label":"Model and agent settings",children:e.jsx(Xr,{className:R(Or,"text-current")})}):null,lo=e.jsxs(e.Fragment,{children:[Fn,Da]}),Aa=G.statusText;c.useEffect(()=>{const oe=!!G.wasAborted;!Ae.current&&oe&&!ee&&(Je(),P&&q(P)),Ae.current=oe},[q,P,ee,Je,G.wasAborted]),c.useEffect(()=>()=>{de.current&&(clearTimeout(de.current),de.current=null)},[]);const Ea=Pe&&Lt;return e.jsxs("form",{onSubmit:He,className:"pt-0 pb-2 md:pb-4 bottom-safe-area","data-keyboard-avoid":"true",style:Pe&&ve>0&&!Be?{marginBottom:`${ve}px`}:void 0,children:[e.jsx(ow,{isWorking:G.isWorking,statusText:Aa,isGenericStatus:G.isGenericStatus,isWaitingForPermission:G.isWaitingForPermission,wasAborted:G.wasAborted,abortActive:G.abortActive,completionId:G.lastCompletionId,isComplete:G.isComplete,showAbort:Ea,onAbort:bt,showAbortStatus:ee}),e.jsxs("div",{ref:M,className:R("chat-column relative overflow-visible",o&&"ring-2 ring-primary ring-offset-2 rounded-xl"),onDragOver:Me,onDragLeave:tt,onDrop:ze,children:[o&&e.jsx("div",{className:"absolute inset-0 z-50 flex items-center justify-center bg-background/80 backdrop-blur-sm rounded-xl",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"inline-flex justify-center",children:e.jsx("button",{type:"button",className:$r,onClick:()=>lr(),title:"Attach files","aria-label":"Attach files",children:e.jsx(qo,{className:R(Or,"text-current")})})}),e.jsx("p",{className:"mt-2 typography-ui-label text-muted-foreground",children:"Drop files here to attach"})]})}),e.jsx(Lb,{}),e.jsx(Tm,{onEditMessage:oe=>{n(oe),setTimeout(()=>{C.current?.focus()},0)}}),e.jsxs("div",{className:R("rounded-xl border border-border/80 bg-input/10 dark:bg-input/30","flex flex-col relative overflow-visible"),style:ke,children:[m&&e.jsx(Fm,{ref:A,searchQuery:p,onCommandSelect:xt,onClose:()=>f(!1)}),w&&e.jsx(Rm,{ref:I,searchQuery:j,onAgentSelect:ut,onClose:()=>h(!1)}),y&&e.jsx(_m,{ref:_,searchQuery:N,onSkillSelect:Tt,onClose:()=>b(!1)}),i&&e.jsx(Bb,{ref:S,searchQuery:d,onFileSelect:pt,onClose:()=>l(!1)}),e.jsx(Ts,{ref:C,"data-chat-input":"true",value:t,onChange:Ee,onKeyDown:gt,onPaste:Ke,onPointerDownCapture:ge,placeholder:P||L?"# for agents; @ for files; / for commands":"Select or create a session to start chatting",disabled:!P&&!L,className:R("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",Pe?"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:R("rounded-b-xl bg-transparent",Ca,Pe?"flex items-center gap-x-1.5":R("flex items-center justify-between",jr)),"data-chat-input-footer":"true",children:Pe?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:lo}),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(Xc,{className:R("w-full flex items-center justify-end min-w-0")})}),an]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("flex items-center flex-shrink-0",jr),children:lo}),e.jsxs("div",{className:R("flex items-center flex-1 justify-end",jr,"md:gap-x-3"),children:[e.jsx(Xc,{className:R("flex-1 min-w-0 justify-end")}),an]})]})})]})]})]})};function ti({className:s,...r}){return e.jsx("div",{"data-slot":"skeleton",className:R("bg-accent animate-pulse rounded-xl",s),...r})}const cd=(s,r,t,n,o=4)=>{const a=[];for(let i=0;i<o;i++)for(let l=0;l<o;l++){const d=l/o,u=(l+1)/o,m=i/o,f=(i+1)/o,p=(y,b,N)=>y+(b-y)*N,g=(y,b,N,v,k,D)=>{const C=p(y,b,k),M=p(v,N,k);return p(C,M,D)},w={x:g(s.x,r.x,t.x,n.x,d,m),y:g(s.y,r.y,t.y,n.y,d,m)},h={x:g(s.x,r.x,t.x,n.x,u,m),y:g(s.y,r.y,t.y,n.y,u,m)},j={x:g(s.x,r.x,t.x,n.x,u,f),y:g(s.y,r.y,t.y,n.y,u,f)},x={x:g(s.x,r.x,t.x,n.x,d,f),y:g(s.y,r.y,t.y,n.y,d,f)};a.push({path:`M${w.x} ${w.y} L${h.x} ${h.y} L${j.x} ${j.y} L${x.x} ${x.y} Z`,row:i,col:l})}return a},Dl=({className:s="",width:r=70,height:t=70,isAnimated:n=!1})=>{const o=ya();let a=!0;o?a=o.currentTheme.metadata.variant!=="light":typeof window<"u"&&(a=window.matchMedia("(prefers-color-scheme: dark)").matches);const i=a?"white":"black",l=a?"rgba(255,255,255,0.15)":"rgba(0,0,0,0.15)",d=a?"white":"black",u=a?"rgba(255,255,255,0.35)":"rgba(0,0,0,0.4)",m=48,f=.866,p=.5,g=50,w={x:50,y:g-m},h={x:50-m*f,y:g-m*p},j={x:50+m*f,y:g-m*p},x={x:50,y:g},y={x:50-m*f,y:g+m*p},b={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, ${(w.y+h.y+x.y+j.y)/4})`,D=cd(h,x,N,y),C=cd(x,j,b,N),M=De.useMemo(()=>{const S=[];for(let A=0;A<32;A++)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${x.x} ${x.y} L${h.x} ${h.y} L${y.x} ${y.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),D.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:M[A]},`left-${A}`)),e.jsx("path",{d:`M${x.x} ${x.y} L${j.x} ${j.y} L${b.x} ${b.y} L${N.x} ${N.y} Z`,fill:l,stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),C.map((S,A)=>e.jsx("path",{d:S.path,fill:u,opacity:M[A+16]},`right-${A}`)),e.jsx("path",{d:`M${w.x} ${w.y} L${h.x} ${h.y} L${x.x} ${x.y} L${j.x} ${j.y} Z`,fill:"none",stroke:i,strokeWidth:"2",strokeLinejoin:"round"}),e.jsxs("g",{opacity:n?void 0:1,children:[n&&e.jsx("animate",{attributeName:"opacity",values:"0.4;1;0.4",dur:"3s",repeatCount:"indefinite",calcMode:"spline",keySplines:"0.4 0 0.6 1; 0.4 0 0.6 1"}),e.jsxs("g",{transform:`${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 hw({children:s,className:r,interval:t=2,transition:n={duration:.3},variants:o,onIndexChange:a,trigger:i=!0,mode:l="popLayout"}){const[d,u]=De.useState(0),m=De.Children.toArray(s);De.useEffect(()=>{if(!i)return;const p=t*1e3,g=setInterval(()=>{u(w=>{const h=(w+1)%m.length;return a?.(h),h})},p);return()=>clearInterval(g)},[m.length,t,a,i]);const f={initial:{y:20,opacity:0},animate:{y:0,opacity:1},exit:{y:-20,opacity:0}};return e.jsxs("div",{className:R("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(uh,{mode:l,initial:!1,children:e.jsx(pn.div,{initial:"initial",animate:"animate",exit:"exit",transition:n,variants:o||f,className:"absolute whitespace-nowrap",children:m[d]},d)})})]})}const gw=["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"],xw=()=>{const s=ya();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(Dl,{width:140,height:140,className:"opacity-20",isAnimated:!0}),e.jsx(hw,{className:"text-body-md",interval:4,transition:{duration:.5},children:gw.map(n=>e.jsxs("span",{style:{color:t},children:['"',n,'…"']},n))})]})},si=c.memo(xw),yw={'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"}},bw={'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 Mr{static instance;sessionStartTimes=new Map;seenMessageIds=new Set;messageCreationTimes=new Map;constructor(){}static getInstance(){return Mr.instance||(Mr.instance=new Mr),Mr.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 Hm(s){const r=s.colors.syntax,t=s.colors.surface;return{'code[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none"},'pre[class*="language-"]':{color:r.base.foreground,background:"transparent",fontFamily:'Consolas, Monaco, "Andale Mono", "Ubuntu Mono", monospace',fontSize:"1em",textAlign:"left",whiteSpace:"pre",wordSpacing:"normal",wordBreak:"normal",wordWrap:"normal",lineHeight:"1.5",MozTabSize:"4",OTabSize:"4",tabSize:"4",WebkitHyphens:"none",MozHyphens:"none",msHyphens:"none",hyphens:"none",padding:"0",margin:"0",overflow:"auto"},comment:{color:r.base.comment,fontStyle:"italic"},prolog:{color:r.base.comment},doctype:{color:r.base.comment},cdata:{color:r.base.comment},punctuation:{color:r.tokens?.punctuation||t.mutedForeground},property:{color:r.tokens?.variableProperty||r.base.variable},tag:{color:r.tokens?.tag||r.base.keyword},"attr-name":{color:r.tokens?.tagAttribute||r.base.variable},"attr-value":{color:r.tokens?.tagAttributeValue||r.base.string},boolean:{color:r.tokens?.boolean||r.base.number},number:{color:r.base.number},constant:{color:r.tokens?.constant||r.base.number},symbol:{color:r.tokens?.constant||r.base.number},string:{color:r.base.string},char:{color:r.base.string},function:{color:r.base.function},builtin:{color:r.tokens?.functionBuiltin||r.base.function},"class-name":{color:r.tokens?.className||r.base.type},namespace:{color:r.tokens?.namespace||r.base.type,opacity:.8},keyword:{color:r.base.keyword},atrule:{color:r.base.keyword},selector:{color:r.base.function},operator:{color:r.base.operator},variable:{color:r.base.variable},regex:{color:r.tokens?.regex||r.base.string},url:{color:r.base.function,textDecoration:"underline"},entity:{color:r.base.function,cursor:"help"},".language-css .token.string":{color:r.base.string},".style .token.string":{color:r.base.string},deleted:{color:s.colors.status.error,backgroundColor:s.colors.status.errorBackground},inserted:{color:s.colors.status.success,backgroundColor:s.colors.status.successBackground},title:{color:s.colors.primary.base,fontWeight:"bold"},"code-block":{color:r.base.string},"code-snippet":{color:r.base.string},list:{color:r.base.variable},hr:{color:t.mutedForeground},table:{color:r.base.function},blockquote:{color:t.mutedForeground,fontStyle:"italic"},important:{color:r.base.keyword,fontWeight:"bold"},bold:{fontWeight:"bold"},italic:{fontStyle:"italic"},strike:{textDecoration:"line-through"},decorator:{color:r.tokens?.decorator||r.base.function},annotation:{color:r.tokens?.decorator||r.base.function}}}const gs=({children:s,className:r})=>{const[t,n]=c.useState(!1);return c.useEffect(()=>{let o=null;const a=()=>n(!0);return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o=window.requestAnimationFrame(a):a(),()=>{o!==null&&typeof window<"u"&&typeof window.cancelAnimationFrame=="function"&&window.cancelAnimationFrame(o)}},[]),e.jsx("div",{className:R("w-full transition-all duration-300 ease-out",t?"opacity-100 translate-y-0":"opacity-0 translate-y-2",r),children:s})},ww=({isUser:s,providerID:r,agentName:t,modelName:n,variant:o,isDarkTheme:a})=>{const{src:i,onError:l,hasLogo:d}=Cm(r);return e.jsx(gs,{children:e.jsx("div",{className:R("pl-3","mb-2"),children:e.jsx("div",{className:R("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(Fs,{className:"h-4 w-4 text-primary"})}):e.jsx("div",{className:"flex items-center justify-center",children:d&&i?e.jsx("img",{src:i,alt:`${r} logo`,className:"h-4 w-4",style:{filter:a?"brightness(0.9) contrast(1.1) invert(1)":"brightness(0.9) contrast(1.1)"},onError:l}):e.jsx(ar,{className:"h-4 w-4",style:{color:`var(${Nr(t).var})`}})})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:R("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:R("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)]",Nr(t).class),children:[e.jsx(Xr,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:t})]}),!s&&o&&e.jsxs("div",{className:R("flex items-center gap-1 px-1.5 py-0 rounded cursor-default","agent-badge typography-meta","hover:bg-[rgb(from_var(--agent-color-bg)_r_g_b_/_0.1)] hover:border-[rgb(from_var(--agent-color)_r_g_b_/_0.2)]",o==="Default"?void 0:"agent-info"),style:o==="Default"?{"--agent-color":"var(--muted-foreground)","--agent-color-bg":"var(--muted-foreground)"}:void 0,children:[e.jsx(ar,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium",children:o.length>0?o[0].toLowerCase()+o.slice(1):o})]})]})]})})})})},vw=c.memo(ww),dd=(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},ud=()=>{if(!Ut()||typeof window>"u")return kc;const s=window.__OPENCHAMBER_VSCODE_SHIKI_THEMES__;if(s?.light&&s?.dark){const r=dd({...s.light},`vscode-shiki-light:${String(s.light?.name??"theme")}`),t=dd({...s.dark},`vscode-shiki-dark:${String(s.dark?.name??"theme")}`);return[r,t]}return kc},Um=()=>{const[s,r]=c.useState(ud);return c.useEffect(()=>{if(!Ut()||typeof window>"u")return;const t=n=>{r(ud())};return window.addEventListener("openchamber:vscode-shiki-themes",t),()=>window.removeEventListener("openchamber:vscode-shiki-themes",t)},[]),s},Vm=s=>{const r=[],t=[],n=s.querySelector("thead");n&&n.querySelectorAll("th").forEach(i=>r.push(i.innerText.trim()));const o=s.querySelector("tbody");return o&&o.querySelectorAll("tr").forEach(i=>{const l=i.querySelectorAll("td"),d=[];l.forEach(u=>d.push(u.innerText.trim())),t.push(d)}),{headers:r,rows:t}},Gm=({headers:s,rows:r})=>{const t=o=>o.includes(",")||o.includes('"')||o.includes(`
75
- `)?`"${o.replace(/"/g,'""')}"`:o,n=[];return s.length>0&&n.push(s.map(t).join(",")),r.forEach(o=>n.push(o.map(t).join(","))),n.join(`
76
- `)},jw=({headers:s,rows:r})=>{const t=o=>o.replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r"),n=[];return s.length>0&&n.push(s.map(t).join(" ")),r.forEach(o=>n.push(o.map(t).join(" "))),n.join(`
77
- `)},Sw=({headers:s,rows:r})=>{if(s.length===0)return"";const t=o=>o.replace(/\\/g,"\\\\").replace(/\|/g,"\\|"),n=[];return n.push(`| ${s.map(t).join(" | ")} |`),n.push(`| ${s.map(()=>"---").join(" | ")} |`),r.forEach(o=>{const a=s.map((i,l)=>t(o[l]||""));n.push(`| ${a.join(" | ")} |`)}),n.join(`
78
- `)},kw=(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)},Nw=({tableRef:s})=>{const[r,t]=c.useState(!1),[n,o]=c.useState(!1),a=c.useRef(null);c.useEffect(()=>{const l=d=>{a.current&&!a.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",l),()=>document.removeEventListener("mousedown",l)},[]);const i=async l=>{const d=s.current?.querySelector("table");if(d)try{const u=Vm(d),m=l==="csv"?Gm(u):jw(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(Pt,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})}),n&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>i("tsv"),children:"TSV"})]})]})},Cw=({tableRef:s})=>{const[r,t]=c.useState(!1),n=c.useRef(null);c.useEffect(()=>{const a=i=>{n.current&&!n.current.contains(i.target)&&t(!1)};return document.addEventListener("mousedown",a),()=>document.removeEventListener("mousedown",a)},[]);const o=a=>{const i=s.current?.querySelector("table");if(i)try{const l=Vm(i),d=a==="csv"?Gm(l):Sw(l);kw(a==="csv"?"table.csv":"table.md",d,a==="csv"?"text/csv":"text/markdown"),t(!1)}catch(l){console.error("Failed to download table:",l)}};return e.jsxs("div",{className:"relative",ref:n,children:[e.jsx("button",{onClick:()=>t(!r),className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Download table",children:e.jsx(Er,{className:"size-3.5"})}),r&&e.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[100px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("csv"),children:"CSV"}),e.jsx("button",{className:"w-full px-3 py-1.5 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>o("markdown"),children:"Markdown"})]})]})},Mw=({children:s,className:r})=>{const t=c.useRef(null);return e.jsxs("div",{className:"group my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",ref:t,children:[e.jsxs("div",{className:"flex items-center justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(Nw,{tableRef:t}),e.jsx(Cw,{tableRef:t})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsx("table",{className:R("w-full border-collapse border border-border",r),"data-streamdown":"table",children:s})})]})},Dw=({children:s,className:r,style:t,...n})=>{const[o,a]=c.useState(!1),i=c.useRef(null),l=c.useMemo(()=>{if(!t)return t;const m={...t},f=w=>{if(typeof w!="string")return{value:void 0,vars:{}};const[h,...j]=w.split(";").map(y=>y.trim()).filter(Boolean),x={};for(const y of j){const b=y.indexOf(":");if(b===-1)continue;const N=y.slice(0,b).trim(),v=y.slice(b+1).trim();!N.startsWith("--")||v.length===0||(x[N]=v)}return{value:h,vars:x}},p=f(t.backgroundColor);p.value&&(m.backgroundColor=p.value,m["--shiki-light-bg"]=p.value);for(const[w,h]of Object.entries(p.vars))m[w]=h;const g=f(t.color);g.value&&(m.color=g.value,m["--shiki-light"]=g.value);for(const[w,h]of Object.entries(g.vars))m[w]=h;return m},[t]),d=()=>i.current&&i.current.querySelector("code")?.innerText||"",u=async()=>{const m=d();if(m)try{await navigator.clipboard.writeText(m),a(!0),setTimeout(()=>a(!1),2e3)}catch(f){console.error("Failed to copy:",f)}};return e.jsxs("div",{className:"group relative",ref:i,children:[e.jsx("pre",{...n,className:R(r),style:l,children:s}),e.jsx("div",{className:"absolute top-1 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("button",{onClick:u,className:"p-1 rounded hover:bg-muted/60 text-muted-foreground hover:text-foreground transition-colors",title:"Copy",children:o?e.jsx(Pt,{className:"size-3.5"}):e.jsx(Gs,{className:"size-3.5"})})})]})},qm={pre:Dw,table:Mw},Aw=({content:s,part:r,messageId:t,isAnimated:n=!0,className:o,isStreaming:a=!1,variant:i="assistant"})=>{const l=Um(),d=c.useMemo(()=>`markdown-${r?.id?`part-${r.id}`:`message-${t}`}`,[t,r?.id]),u=i==="tool"?"streamdown-content streamdown-tool":"streamdown-content",m=e.jsx("div",{className:R("break-words",o),children:e.jsx(hu,{mode:a?"streaming":"static",shikiTheme:l,className:u,controls:{code:!1,table:!1},components:qm,children:s})});return n?e.jsx(gs,{children:m},d):m},Kr=({content:s,className:r,variant:t="assistant"})=>{const n=Um(),o=t==="tool"?"streamdown-content streamdown-tool":"streamdown-content";return e.jsx("div",{className:R("break-words",r),children:e.jsx(hu,{mode:"static",shikiTheme:n,className:o,controls:{code:!1,table:!1},components:qm,children:s})})},Ew={thinking:{label:"Thinking",Icon:ar},justification:{label:"Justification",Icon:Yi}},Km=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
79
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
80
- `).trim(),Iw=s=>{if(!s)return"";const r=s.trim(),t=r.indexOf(`
81
- `),n=r.indexOf("."),o=[t>=0?t:1/0,n>=0?n:1/0],a=Math.min(...o);return Number.isFinite(a)?r.substring(0,a).trim():r},Al=({text:s,variant:r,onContentChange:t,blockId:n})=>{const[o,a]=c.useState(!1),i=c.useMemo(()=>Iw(s),[s]),{label:l,Icon:d}=Ew[r];return c.useEffect(()=>{s.trim().length!==0&&t?.("structural")},[t,o,s]),!s||s.trim().length===0?null:e.jsxs("div",{className:"my-1","data-reasoning-block-id":n,children:[e.jsxs("div",{className:R("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:R("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:R("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(It,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:l})]}),i&&e.jsx("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70",children:e.jsx("span",{className:"truncate block",children:i})})]}),o&&e.jsx("div",{className:R("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(ft,{as:"blockquote",outerClassName:"max-h-80",className:"whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70 p-0",children:s})})]})},Ym=({part:s,onContentChange:r,messageId:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>Km(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Al,{text:a,variant:"thinking",onContentChange:r,blockId:s.id||`${t}-reasoning`}):null},Pw=s=>Km(s),Tw=({part:s,messageId:r,streamPhase:t,allowAnimation:n,onContentChange:o,renderAsReasoning:a=!1})=>{const i=s,l=i.text,d=typeof l=="string"?l:i.content||i.value||"",u=c.useMemo(()=>a?Pw(d):d,[d,a]),m=t==="streaming",f=t==="cooldown",p=c.useRef(m);if(m||f)return p.current=!0,null;const g=i.time;return!(g&&typeof g.end<"u")&&(!u||u.trim().length===0)||!u||u.trim().length===0?null:a?e.jsx(Al,{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(Aw,{content:u,part:s,messageId:r,isAnimated:n,isStreaming:!1})},s.id||`${r}-text`)},Fw=s=>`https://opencode.ai/docs/agents/#${encodeURIComponent(s)}`,Rw=({part:s,messageId:r,agentMention:t})=>{const n=s,o=n.text,a=typeof o=="string"?o:n.content||n.value||"",[i,l]=c.useState(!1),[d,u]=c.useState(!1),m=c.useRef(null);c.useEffect(()=>{const g=m.current;if(!g||i)return;const w=()=>{u(g.scrollHeight>g.clientHeight)};w();const h=new ResizeObserver(w);return h.observe(g),()=>h.disconnect()},[a,i]);const f=c.useCallback(()=>{(d||i)&&l(g=>!g)},[d,i]);if(!a||a.trim().length===0)return null;const p=()=>{if(!t?.token||!a.includes(t.token))return a;const g=a.indexOf(t.token),w=a.slice(0,g),h=a.slice(g+t.token.length);return e.jsxs(e.Fragment,{children:[w,e.jsx("a",{href:Fw(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:R("break-words whitespace-pre-wrap font-sans typography-markdown",!i&&"line-clamp-3",(d||i)&&"cursor-pointer"),ref:m,onClick:f,children:p()},s.id||`${r}-user-text`)},_w=c.memo(Rw),Ow=s=>{let r=s.replace(/^<file>\s*\n?/,"").replace(/\n?<\/file>\s*$/,"");return r=r.replace(/^\s*\d{5}\|\s?/gm,""),r.trim()},$w=s=>s?s.includes("<file_diagnostics>")||s.includes("This file has errors")||s.includes("please fix"):!1,Lw=s=>s?s.replace(/This file has errors.*?<\/file_diagnostics>/s,"").trim():"",md=(s,r)=>!s||typeof s!="object"?String(s):Cy(s,r||""),ri=(s,r,t)=>{let n=Ow(s);if((r==="edit"||r==="multiedit")&&$w(n)&&(n=Lw(n)),(r==="edit"||r==="multiedit")&&n.trim().length===0&&t?.diff){const o=t.diff;return typeof o=="string"?o:String(o)}return n},Bw=(s,r)=>{try{const t=s.trim().split(`
82
- `).filter(Boolean);if(t.length===0)return null;const n=[];return t.forEach(o=>{const a=o.match(/^(\s*)(.+)$/);if(a){const[,i,l]=a,d=Math.floor(i.length/2),u=!l.endsWith("/");n.push({name:l.replace(/\/$/,""),depth:d,isFile:u})}}),e.jsx("div",{className:R("w-full min-w-0 font-mono space-y-0.5",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:n.map((o,a)=>e.jsx("div",{className:"min-w-0",style:{paddingLeft:`${o.depth*20}px`},children:o.isFile?e.jsx("span",{className:"text-foreground/90 block truncate",children:o.name}):e.jsxs("span",{className:"font-semibold text-foreground block truncate",children:[o.name,"/"]})},a))})}catch{return null}},zw=(s,r,t)=>{try{const n=s.trim().split(`
83
- `).filter(Boolean);if(n.length===0)return null;const o={};return n.forEach(a=>{const i=a.match(/^(.+?):(\d+):(.*)$/)||a.match(/^(.+?):(.*)$/);if(i){const[,l,d,u]=i,m=u!==void 0?d:"",f=u!==void 0?u:d;o[l]||(o[l]=[]),o[l].push({lineNum:m,content:f})}}),e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," match",n.length!==1?"es":""]}),Object.entries(o).map(([a,i])=>e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:a}),e.jsx("div",{className:"pl-4 space-y-1",children:i.map((l,d)=>!l.lineNum&&!l.content?null:e.jsxs("div",{className:R("flex items-start gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0 mt-1.5",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsxs("div",{className:"flex gap-2 min-w-0 flex-1",children:[l.lineNum&&e.jsxs("span",{className:"text-muted-foreground font-mono whitespace-nowrap",children:["Line ",l.lineNum,":"]}),e.jsx("span",{className:"text-foreground font-mono break-words flex-1",children:l.content||" "})]})]},d))})]},a))]})}catch{return null}},Ww=(s,r,t)=>{try{const n=s.trim().split(`
84
- `).filter(Boolean);if(n.length===0)return null;const o={};n.forEach(i=>{const l=i.lastIndexOf("/"),d=l>0?i.substring(0,l):"/",u=l>=0?i.substring(l+1):i;o[d]||(o[d]=[]),o[d].push(u)});const a=Object.keys(o).sort();return e.jsxs("div",{className:R("space-y-2 w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:["Found ",n.length," file",n.length!==1?"s":""]}),a.map(i=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:R("font-medium text-muted-foreground",r?"typography-micro":"typography-code"),children:[i,"/"]}),e.jsx("div",{className:R("pl-4 grid gap-1",r?"grid-cols-1":"grid-cols-2"),children:o[i].sort().map(l=>e.jsxs("div",{className:R("flex items-center gap-2 min-w-0",r?"typography-micro":"typography-code"),children:[e.jsx("div",{className:"w-1.5 h-1.5 rounded-full flex-shrink-0",style:{backgroundColor:"var(--status-info)",opacity:.6}}),e.jsx("span",{className:"text-foreground font-mono truncate",children:l})]},l))})]},i))]})}catch{return null}},Hw=(s,r)=>{try{const t=JSON.parse(s);if(!Array.isArray(t))return null;const n={in_progress:t.filter(a=>a.status==="in_progress"),pending:t.filter(a=>a.status==="pending"),completed:t.filter(a=>a.status==="completed"),cancelled:t.filter(a=>a.status==="cancelled")},o=a=>{const i="w-2 h-2 rounded-full flex-shrink-0 mt-1";switch(a){case"high":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-error)"}});case"medium":return e.jsx("div",{className:i,style:{backgroundColor:"var(--primary)"}});case"low":return e.jsx("div",{className:i,style:{backgroundColor:"var(--status-info)"}});default:return e.jsx("div",{className:i,style:{backgroundColor:"var(--muted-foreground)",opacity:.5}})}};return e.jsxs("div",{className:R("space-y-3 w-full min-w-0",r?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/30"),style:pr.tool.popup,children:[e.jsxs("div",{className:"flex gap-4 typography-meta pb-2 border-b border-border/20",children:[e.jsxs("span",{className:"font-medium",style:{color:"var(--muted-foreground)"},children:["Total: ",t.length]}),n.in_progress.length>0&&e.jsxs("span",{className:"font-medium",style:{color:"var(--foreground)"},children:["In Progress: ",n.in_progress.length]}),n.pending.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)"},children:["Pending: ",n.pending.length]}),n.completed.length>0&&e.jsxs("span",{style:{color:"var(--status-success)"},children:["Completed: ",n.completed.length]}),n.cancelled.length>0&&e.jsxs("span",{style:{color:"var(--muted-foreground)",opacity:.5},children:["Cancelled: ",n.cancelled.length]})]}),n.in_progress.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full animate-pulse",style:{backgroundColor:"var(--foreground)"}}),e.jsx("span",{className:"typography-meta font-semibold text-foreground uppercase tracking-wide",children:"In Progress"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.in_progress.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.pending.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full bg-muted-foreground/50"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wide",children:"Pending"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.pending.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[o(a.priority),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.completed.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pt,{className:"w-3 h-3",style:{color:"var(--status-success)"}}),e.jsx("span",{className:"typography-meta font-semibold uppercase tracking-wide",style:{color:"var(--status-success)"},children:"Completed"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.completed.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pt,{className:"w-3 h-3 mt-0.5 flex-shrink-0",style:{color:"var(--status-success)",opacity:.7}}),e.jsx("span",{className:"typography-code text-foreground flex-1 leading-relaxed",children:a.content})]},a.id||i))})]}),n.cancelled.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50",children:"×"}),e.jsx("span",{className:"typography-meta font-semibold text-muted-foreground/50 uppercase tracking-wide",children:"Cancelled"})]}),e.jsx("div",{className:"space-y-1.5 pl-4",children:n.cancelled.map((a,i)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"w-3 h-3 text-muted-foreground/50 mt-0.5 flex-shrink-0",children:"×"}),e.jsx("span",{className:"typography-code text-muted-foreground/50 line-through flex-1 leading-relaxed",children:a.content})]},a.id||i))})]})]})}catch{return null}},Uw=(s,r,t)=>{try{return e.jsx("div",{className:R("typography-code max-w-none w-full min-w-0",t?.unstyled?null:"p-3 bg-muted/20 rounded-xl border border-border/20"),style:pr.tool.popup,children:e.jsx(Kr,{content:s,variant:"tool"})})}catch{return null}},Qm=s=>{const r=s.split(`
85
- `);let t="";const n=[];let o=0;for(;o<r.length;){const a=r[o];if(a.startsWith("Index:")||a.startsWith("===")||a.startsWith("---")||a.startsWith("+++")){a.startsWith("Index:")&&(t=a.split(" ")[1].split("/").pop()||"file"),o++;continue}if(a.startsWith("@@")){const i=a.match(/@@ -(\d+),\d+ \+(\d+),\d+ @@/),l=i?parseInt(i[1]):0,d=i?parseInt(i[2]):0,u=[];let m=d,f=o+1;for(;f<r.length&&!r[f].startsWith("@@")&&!r[f].startsWith("Index:");){const p=r[f];p.startsWith("+")?(u.push({type:"added",lineNumber:m,content:p.substring(1)}),m++):p.startsWith("-")?u.push({type:"removed",lineNumber:null,content:p.substring(1)}):p.startsWith(" ")&&(u.push({type:"context",lineNumber:m,content:p.substring(1)}),m++),f++}n.push({file:t,oldStart:l,newStart:d,lines:u}),o=f;continue}o++}return n},Bi=(s,r,t)=>Sy(r,s,t),Xm=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(mh,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(gu,{className:r}):t==="read"||t==="view"||t==="file_read"||t==="cat"?e.jsx(ji,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"?e.jsx(Pr,{className:r}):t==="list"||t==="ls"||t==="dir"||t==="list_files"?e.jsx(ur,{className:r}):t==="search"||t==="grep"||t==="find"||t==="ripgrep"?e.jsx(fh,{className:r}):t==="glob"?e.jsx(ph,{className:r}):t==="fetch"||t==="curl"||t==="wget"||t==="webfetch"?e.jsx(Si,{className:r}):t==="web-search"||t==="websearch"||t==="search_web"||t==="codesearch"||t==="google"||t==="bing"||t==="duckduckgo"||t==="perplexity"?e.jsx(Si,{className:r}):t==="todowrite"||t==="todoread"?e.jsx(xu,{className:r}):t==="skill"?e.jsx(yu,{className:r}):t==="question"?e.jsx(hh,{className:r}):t.startsWith("git")?e.jsx($t,{className:r}):e.jsx(fa,{className:r})},Vw=(s,r,t=Date.now())=>{const o=(r?r-s:t-s)/1e3;return`${(o<.05&&r!==void 0?.1:o).toFixed(1)}s`},Gw=({start:s,end:r,active:t})=>{const[n,o]=c.useState(()=>Date.now());return c.useEffect(()=>{if(!t)return;const a=window.setInterval(()=>{o(Date.now())},100);return()=>window.clearInterval(a)},[t]),e.jsx(e.Fragment,{children:Vw(s,r,n)})},qw=s=>{if(!s?.diff||typeof s.diff!="string")return null;const r=s.diff.split(`
86
- `);let t=0,n=0;for(const o of r)o.startsWith("+")&&!o.startsWith("+++")&&t++,o.startsWith("-")&&!o.startsWith("---")&&n++;return t===0&&n===0?null:{added:t,removed:n}},zi=(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},Kw=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},Yw=(s,r,t,n)=>{const o=r,a=o.metadata,i=o.input;if(s.tool==="question"&&i?.questions&&Array.isArray(i.questions)){const d=i.questions.length;return`Asked ${d} question${d!==1?"s":""}`}if((s.tool==="edit"||s.tool==="multiedit")&&i){const d=i?.filePath||i?.file_path||i?.path||a?.filePath||a?.file_path||a?.path;if(typeof d=="string")return zi(d,n,t)}if((s.tool==="read"||s.tool==="write")&&i){const d=i?.filePath||i?.file_path||i?.path;if(typeof d=="string")return zi(d,n,t)}if(s.tool==="bash"&&i?.command&&typeof i.command=="string"){const d=i.command.split(`
87
- `)[0];return t?d.substring(0,50):d.substring(0,100)}if(s.tool==="task"&&i?.description&&typeof i.description=="string")return t?i.description.substring(0,40):i.description.substring(0,80);if(s.tool==="skill"&&i?.name&&typeof i.name=="string")return i.name;const l=i?.description||a?.description||"title"in r&&r.title||"";return typeof l=="string"?l:""},Wi=({children:s,maxHeightClass:r="max-h-[60vh]",className:t,outerClassName:n,disableHorizontal:o=!1})=>e.jsx(ft,{outerClassName:R("w-full min-w-0 flex-none overflow-hidden",r,n),className:R("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})}),Qw=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"},Xw=s=>s.replace(/\n*<task_metadata>[\s\S]*?<\/task_metadata>\s*$/i,"").trimEnd(),Jw=({entries:s,isExpanded:r,hasPrevTool:t,hasNextTool:n,output:o,sessionId:a})=>{const i=ue(h=>h.setCurrentSession),l=c.useMemo(()=>s.filter(h=>h.state?.status==="completed"),[s]),d=typeof o=="string"?Xw(o):"",u=d.length>0,[m,f]=c.useState(!1),p=h=>{h.stopPropagation(),a&&i(a)};if(l.length===0&&!u&&!a)return null;const g=r?l:l.slice(-6),w=Math.max(0,l.length-g.length);return e.jsxs("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',t?"before:top-[-0.45rem]":"before:top-[-0.25rem]",n?"before:bottom-[-0.6rem]":"before:bottom-0"),children:[l.length>0?e.jsx(Wi,{maxHeightClass:r?"max-h-[40vh]":"max-h-56",disableHorizontal:!0,children:e.jsxs("div",{className:"w-full min-w-0 space-y-1",children:[w>0?e.jsxs("div",{className:"typography-micro text-muted-foreground/70",children:["+",w," more…"]}):null,g.map((h,j)=>{const x=typeof h.tool=="string"&&h.tool.trim().length>0?h.tool:"tool",y=Qw(h),b=pl(x).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:Xm(x)}),e.jsx("span",{className:"typography-meta text-foreground/80 flex-shrink-0",children:b}),e.jsx("span",{className:"typography-meta text-muted-foreground/70 truncate",children:y})]},h.id??`${x}-${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(Go,{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:R("space-y-1",(l.length>0||a)&&"pt-1"),children:[e.jsxs("button",{type:"button",className:"flex items-center gap-2 typography-meta text-foreground/80 hover:text-foreground w-full",onPointerDown:h=>h.stopPropagation(),onClick:h=>{h.stopPropagation(),f(j=>!j)},children:[m?e.jsx(It,{className:"h-3.5 w-3.5 flex-shrink-0"}):e.jsx(Us,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"typography-meta text-foreground/80 font-medium",children:"Output"})]}),m?e.jsx(Wi,{maxHeightClass:"max-h-[50vh]",children:e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Kr,{content:d,variant:"tool"})})}):null]}):null]})},Zw=({diff:s,syntaxTheme:r,input:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Qm(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:nn(typeof t?.file_path=="string"?t.file_path:typeof t?.filePath=="string"?t.filePath:n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),ev=({content:s,syntaxTheme:r,filePath:t,displayPath:n})=>{const o=s.split(`
88
- `),a=nn(t??"")||Bi(s,"write",t?{filePath:t}:void 0),i=Math.max(o.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${n} (${l})`}),e.jsx("div",{className:"space-y-0",children:o.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:a||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},tv=({content:s,filePath:r,displayPath:t})=>{const n=Ny(r),o=r.toLowerCase().endsWith(".svg"),a=c.useMemo(()=>o&&!s.startsWith("data:")?`data:image/svg+xml;base64,${btoa(s)}`:s.startsWith("data:")?s:`data:${n};base64,${s}`,[s,n,o]);return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-2",children:t}),e.jsx("div",{className:"flex justify-center p-4 bg-muted/10 rounded-lg border border-border/10",children:e.jsx("img",{src:a,alt:t,className:"max-w-full max-h-96 object-contain rounded",style:{imageRendering:"auto"}})})]})},sv=({part:s,state:r,syntaxTheme:t,isMobile:n,currentDirectory:o,hasPrevTool:a,hasNextTool:i})=>{const l=r,d=l.metadata,u=l.input,m=l.output,f=typeof m=="string"&&m.length>0,p=typeof m=="string"?m:"",g=typeof d?.diff=="string"?d.diff:null,w=s.tool==="write"?typeof u?.filePath=="string"?u.filePath:typeof u?.file_path=="string"?u.file_path:typeof u?.path=="string"?u.path:void 0:void 0,h=s.tool==="write"?typeof u?.content=="string"?u.content:typeof u?.text=="string"?u.text:null:null,j=s.tool==="write"&&!!h,x=w?dm(w):!1,y=j?w?zi(w,o,n):"New file":null,b=c.useMemo(()=>!u||typeof u!="object"||Object.keys(u).length===0?"":"command"in u&&typeof u.command=="string"&&s.tool==="bash"?md(u,s.tool):typeof u.content=="string"?u.content??"":md(u,s.tool),[u,s.tool]),N=b.trim().length>0,v=(D,C)=>e.jsx(Wi,{maxHeightClass:C?.maxHeightClass,className:C?.className,disableHorizontal:C?.disableHorizontal,outerClassName:C?.outerClassName,children:D}),k=()=>{if(s.tool==="question"){if(r.status==="completed"&&f){const D=Kw(p);if(D&&D.length>0)return v(e.jsx("div",{className:"space-y-2",children:D.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 D=Hw(p,{unstyled:!0});return v(D??e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Unable to parse todo list"}))}return r.status==="error"&&"error"in r?e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta font-medium text-muted-foreground mb-1",children:"Error:"}),e.jsx("div",{className:"typography-meta p-2 rounded-xl border",style:{backgroundColor:"var(--status-error-background)",color:"var(--status-error)",borderColor:"var(--status-error-border)"},children:r.error})]}):e.jsx("div",{className:"typography-meta text-muted-foreground",children:"Processing todo list..."})}if(s.tool==="list"&&f){const D=Bw(p,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="grep"&&f){const D=zw(p,n,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="glob"&&f){const D=Ww(p,n,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="task"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Kr,{content:p,variant:"tool"})}));if((s.tool==="web-search"||s.tool==="websearch"||s.tool==="search_web")&&f){const D=Uw(p,t,{unstyled:!0});return v(D??e.jsx("pre",{className:"typography-code font-mono whitespace-pre-wrap break-words w-full min-w-0",children:p}))}if(s.tool==="codesearch"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Kr,{content:p,variant:"tool"})}));if(s.tool==="skill"&&f)return v(e.jsx("div",{className:"w-full min-w-0",children:e.jsx(Kr,{content:p,variant:"tool"})}));if((s.tool==="edit"||s.tool==="multiedit")&&g)return v(e.jsx(Zw,{diff:g,syntaxTheme:t,input:u}),{className:"p-1"});if(f&&p.trim()){if(s.tool==="read"){const D=ri(p,s.tool,d),C=D.split(`
89
- `),M=typeof u?.offset=="number"?u.offset:0,S=typeof u?.limit=="number"?u.limit:void 0,A=I=>I.trim().startsWith("(");return v(e.jsx("div",{className:"typography-code w-full min-w-0 space-y-1",children:C.map((I,_)=>{const T=A(I),P=M+_+1,L=!T&&(S===void 0||_<S);return e.jsxs("div",{className:R("typography-code font-mono flex w-full min-w-0",T&&"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:L?P:""}),e.jsx("div",{className:"flex-1 min-w-0",children:T?e.jsx("div",{className:"whitespace-pre-wrap break-words",children:I}):e.jsx(hr,{style:t,language:Bi(D,s.tool,u),PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},children:I})})]},_)})}),{className:"p-1"})}return v(e.jsx(hr,{style:t,language:Bi(ri(p,s.tool,d),s.tool,u),PreTag:"div",customStyle:{...To.getCollapsedStyles(),padding:0,overflow:"visible"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent"}},wrapLongLines:!0,children:ri(p,s.tool,d)}),{className:"p-1"})}return v(e.jsx("div",{className:"typography-meta text-muted-foreground/70",children:"No output produced"}),{maxHeightClass:"max-h-60"})};return e.jsx("div",{className:R("relative pr-2 pb-2 pt-2 space-y-2 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',a?"before:top-[-0.45rem]":"before:top-[-0.25rem]",i?"before:bottom-[-0.6rem]":"before:bottom-0"),children:s.tool==="todowrite"||s.tool==="todoread"||s.tool==="question"?k():e.jsxs(e.Fragment,{children:[j&&x?e.jsx("div",{className:"my-1",children:v(e.jsx(tv,{content:h,filePath:w,displayPath:y??"New file"}))}):j?e.jsx("div",{className:"my-1",children:v(e.jsx(ev,{content:h,syntaxTheme:t,filePath:w,displayPath:y??"New file"}))}):N?e.jsx("div",{className:"my-1",children:v(e.jsx("blockquote",{className:"tool-input-text whitespace-pre-wrap break-words typography-meta italic text-muted-foreground/70",children:b}),{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})]})]})})},Wo=({part:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,onContentChange:a,hasPrevTool:i=!1,hasNextTool:l=!1})=>{const d=s.state,u=mt(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",w=c.useRef(r);c.useEffect(()=>{!f&&!m||w.current!==r&&(w.current=r,typeof r=="boolean"&&a?.("structural"))},[r,f,m,a]);const h=d,j=h.metadata,x=h.input,y=h.time,b=c.useRef({}),N=c.useRef(s.id);if(N.current!==s.id&&(N.current=s.id,b.current={}),m){if(typeof y?.start=="number"){const P=b.current.start;(typeof P!="number"||y.start<P)&&(b.current.start=y.start)}typeof y?.end=="number"&&(b.current.end=y.end)}const v=m?b.current.start??y?.start:y?.start,k=m?b.current.end??y?.end:y?.end,D=c.useMemo(()=>{if(!m)return;const P=j;return typeof P?.sessionId=="string"?P.sessionId:void 0},[m,j]),C=c.useMemo(()=>{if(!m)return[];const P=j?.summary;return Array.isArray(P)?P.filter(L=>typeof L=="object"&&L!==null):[]},[m,j]),M=c.useRef(C.length);c.useEffect(()=>{m&&M.current!==C.length&&(M.current=C.length,a?.("structural"))},[m,a,C.length]);const S=s.tool==="edit"||s.tool==="multiedit"?qw(j):null,A=Yw(s,d,o,u),I=pl(s.tool).displayName,_=c.useContext(hl),T=P=>{if(m||!_?.editor){t(s.id);return}let L;if((s.tool==="edit"||s.tool==="multiedit"||["write","create","file_write","read","view","file_read","cat"].includes(s.tool))&&(L=x?.filePath||x?.file_path||x?.path||j?.filePath||j?.file_path||j?.path),typeof L=="string"){P.stopPropagation();let Z=L;L.startsWith("/")||(Z=u.endsWith("/")?u+L:u+"/"+L),_.editor.openFile(Z)}else t(s.id)};return!f&&!m?null:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("group/tool flex items-center gap-2 pr-2 pl-px py-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",onClick:P=>{P.stopPropagation(),t(s.id)},children:[e.jsx("div",{className:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),style:!m&&g?{color:"var(--status-error)"}:{},children:Xm(s.tool)}),e.jsx("div",{className:R("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(It,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",style:!m&&g?{color:"var(--status-error)"}:{},children:I})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-1 min-w-0 typography-meta text-muted-foreground/70",children:[A&&e.jsx("span",{className:R("truncate",o&&"max-w-[120px]"),children:A}),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 v=="number"&&e.jsx("span",{className:"text-muted-foreground/80 flex-shrink-0",children:e.jsx(Gw,{start:v,end:typeof k=="number"?k:void 0,active:!!(m&&p&&typeof k!="number")})})]})]}),m&&(C.length>0||p||f||D)?e.jsx(Jw,{entries:C,isExpanded:r,hasPrevTool:i,hasNextTool:l,output:typeof h.output=="string"?h.output:void 0,sessionId:D}):null,!m&&r?e.jsx(sv,{part:s,state:d,syntaxTheme:n,isMobile:o,currentDirectory:u,hasPrevTool:i,hasNextTool:l}):null]})},rv=s=>typeof s!="string"||s.trim().length===0?"":s.split(`
90
- `).map(r=>r.replace(/^>\s?/,"").trimEnd()).filter(r=>r.trim().length>0).join(`
91
- `).trim(),nv=({part:s,messageId:r,onContentChange:t})=>{const n=s,o=n.text||n.content||"",a=c.useMemo(()=>rv(o),[o]);return("time"in s?s.time:null)?.end?e.jsx(Al,{text:a,variant:"justification",onContentChange:t,blockId:s.id||`${r}-justification`}):null},ov=c.memo(nv),av=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(", ")},fd=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}),iv=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},lv=({parts:s,isExpanded:r,onToggle:t,syntaxTheme:n,isMobile:o,expandedTools:a,onToggleTool:i,onContentChange:l,isWorking:d,previewedPartIds:u,diffStats:m})=>{const f=c.useRef(r),[p,g]=c.useState(0);c.useEffect(()=>{if(f.current===r)return;const x=f.current===!1;f.current=r,l?.("structural"),r&&x&&g(y=>y+1)},[r,l]);const w=c.useMemo(()=>fd(d?s.filter(x=>x.part.id&&u.has(x.id)):s),[s,d,u]),h=av(w),j=iv(w);return w.length===0?null:e.jsx(gs,{children:e.jsxs("div",{className:"my-1",children:[e.jsxs("div",{className:R("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:R("absolute inset-0 transition-opacity",r&&"opacity-0",!r&&!o&&"group-hover/tool:opacity-0"),children:e.jsx(Xn,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:R("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(It,{className:"h-3.5 w-3.5"}):e.jsx(Us,{className:"h-3.5 w-3.5"})})]}),e.jsx("span",{className:"typography-meta font-medium",children:"Activity"})]}),(h||m)&&e.jsxs("div",{className:"flex-1 min-w-0 typography-meta text-muted-foreground/70 flex items-center gap-2",children:[h&&e.jsx("span",{className:"truncate block",children:h}),m&&(m.additions>0||m.deletions>0)&&e.jsxs("span",{className:"flex-shrink-0 leading-none",children:[e.jsxs("span",{className:"text-[color:var(--status-success)]",children:["+",Math.max(0,m.additions)]}),e.jsx("span",{className:"text-muted-foreground/50",children:"/"}),e.jsxs("span",{className:"text-destructive",children:["-",Math.max(0,m.deletions)]})]})]})]}),r&&e.jsx("div",{className:R("relative pr-2 pb-1 pt-1 pl-[1.4375rem]",'before:absolute before:left-[0.4375rem] before:w-px before:bg-border/80 before:content-[""]',"before:top-[-0.25rem] before:bottom-0"),children:w.map((x,y)=>{const b=x.part.id||`group-part-${y}`,N=j[b],v=`${b}-exp${p}`;switch(x.kind){case"tool":return e.jsx(gs,{children:e.jsx(Wo,{part:x.part,isExpanded:a.has(b),onToggle:i,syntaxTheme:n,isMobile:o,onContentChange:l,hasPrevTool:N?.hasPrev??!1,hasNextTool:N?.hasNext??!1})},v);case"reasoning":return e.jsx(gs,{children:e.jsx(Ym,{part:x.part,messageId:x.messageId,onContentChange:l})},v);case"justification":return e.jsx(gs,{children:e.jsx(ov,{part:x.part,messageId:x.messageId,onContentChange:l})},v);default:return null}})})]})})},cv=c.memo(lv),dv=({isMigrating:s,children:r,className:t})=>e.jsx("div",{className:R("w-full overflow-hidden",s&&"pointer-events-none",t),style:s?{animation:"oc-migrate-up 220ms ease-out forwards"}:void 0,children:r}),ni=c.memo(dv),Jm=s=>{const r=s,t=r.text;return typeof t=="string"?t:r.content||r.value||""},Zm=s=>{if(s.type!=="text")return!1;const r=Jm(s);return!r||r.trim().length===0},uv=(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"))},mv=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`},fv=(s,r)=>{const t=c.useRef(null),n=c.useRef(null),[o,a]=c.useState(!1),i=c.useRef(s);i.current=s;const l=c.useRef(r);l.current=r;const d=c.useRef(!1),u=r.size>0;return c.useEffect(()=>{s&&s.isWorking&&u&&(d.current||(d.current=!0,t.current=window.setTimeout(()=>{t.current=null,a(!0),n.current=window.setTimeout(()=>{n.current=null,a(!1);const m=i.current;if(!m)return;const f=Array.from(l.current);f.length>0&&m.markPartsPreviewed(f)},300)},1e3)))},[u,s]),c.useEffect(()=>{s&&(!s.isWorking||!u)&&(t.current&&(window.clearTimeout(t.current),t.current=null),n.current&&(window.clearTimeout(n.current),n.current=null),a(!1),d.current=!1)},[u,s]),c.useEffect(()=>()=>{t.current&&window.clearTimeout(t.current),n.current&&window.clearTimeout(n.current)},[]),{isAnimating:o}},pv=new Set(["task"]),fn=s=>typeof s=="string"&&pv.has(s.toLowerCase()),hv=({messageId:s,parts:r,isMobile:t,hasTouchInput:n,hasTextContent:o,onCopyMessage:a,copiedMessage:i,onShowPopup:l,agentMention:d,onRevert:u,onFork:m})=>{const[f,p]=c.useState(!1),g=c.useRef(null),w=c.useMemo(()=>r.filter(C=>C.type!=="text"?!1:!Zm(C)),[r]),h=d?.token;let j=!1;const x=!!a,y=!!i,b=!!(n??t),N=!!o,v=c.useCallback(()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null)},[]),k=c.useCallback(()=>{!b||!x||!N||typeof window>"u"||(v(),p(!0),g.current=window.setTimeout(()=>{p(!1),g.current=null},1800))},[x,v,N,b]);c.useEffect(()=>{N||(p(!1),v())},[v,N]);const D=c.useCallback(C=>{!a||!N||(C.stopPropagation(),C.preventDefault(),a(),b&&k())},[N,b,a,k]);return e.jsxs("div",{className:"relative w-full group/message",style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:b&&x&&N?k:void 0,children:[e.jsx("div",{className:"leading-normal overflow-hidden text-foreground/85",children:w.map((C,M)=>{let S;return d&&h&&!j&&Jm(C).includes(h)&&(S=d,j=!0),e.jsx(gs,{children:e.jsx(_w,{part:C,messageId:s,isMobile:t,agentMention:S})},`user-text-${M}`)})}),e.jsx(Im,{files:r,onShowPopup:l}),x&&N||u||m?e.jsxs("div",{className:R("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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{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(Qn,{className:"h-3.5 w-3.5"})})}),e.jsx(nt,{sideOffset:6,children:"Revert from here"})]}),m&&e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{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($t,{className:"h-3.5 w-3.5"})})}),e.jsx(nt,{sideOffset:6,children:"Fork from here"})]}),x&&N&&e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":f||y?"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:D,onFocus:()=>p(!0),onBlur:()=>{y||p(!1)},children:y?e.jsx(Pt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(nt,{sideOffset:6,children:"Copy message"})]})]}):null]})},gv=({messageId:s,parts:r,isMessageCompleted:t,messageFinish:n,messageCompletedAt:o,syntaxTheme:a,isMobile:i,hasTouchInput:l,expandedTools:d,onToggleTool:u,onShowPopup:m,streamPhase:f,allowAnimation:p,onContentChange:g,hasTextContent:w=!1,onCopyMessage:h,copiedMessage:j=!1,onAuxiliaryContentComplete:x,showReasoningTraces:y=!1,turnGroupingContext:b,errorMessage:N})=>{const[v,k]=c.useState(!1),D=c.useRef(null),C=!!h,M=!!j,S=!!(l??i),A=!t,I=c.useMemo(()=>r.filter(He=>!Zm(He)).filter(He=>He.type!=="compaction"),[r]),_=c.useMemo(()=>I.filter(He=>He.type==="tool"),[I]),T=c.useMemo(()=>I.filter(He=>He.type==="text"),[I]),P=ue(He=>He.createSessionFromAssistantMessage),L=_e(He=>He.openMultiRunLauncherWithPrompt),Z=b?.isLastAssistantInTurn??!1,q=n==="stop",$=_.length>0,H=c.useMemo(()=>_.some(He=>{const gt=(He.state??{})?.status;return gt==="pending"||gt==="running"||gt==="started"}),[_]),U=c.useCallback(He=>{const et=He.state??{},gt=et?.status;if(gt==="pending"||gt==="running"||gt==="started")return!1;const Je=et?.time??{},bt=typeof Je?.end=="number"?Je.end:void 0,X=typeof Je?.start=="number"?Je.start:void 0;return!(typeof bt!="number"||typeof X=="number"&&bt<X)},[]),K=c.useMemo(()=>_.length===0?!0:H?!1:_.every(He=>U(He)),[_,H,U]),se=c.useMemo(()=>T.length===0?!0:T.every(He=>typeof He.time?.end=="number"),[T]),Y=c.useMemo(()=>I.filter(He=>He.type==="reasoning"),[I]),re=c.useMemo(()=>Y.length===0?!0:Y.every(He=>typeof He.time?.end=="number"),[Y]),V=typeof n!="string",ae=Y.length>0&&$&&(H||V||!K),E=c.useMemo(()=>$?T.length===0?V||H||!K:!0:T.length>0?ae:!1,[T.length,V,H,$,ae,K]),B=A||E&&(!se||!K||H||V)||ae,F=A||$&&(H||V||!K),O=A||ae,z=$||Y.length>0,Q=T.length===0,me=z&&Q&&!F&&!O&&K&&re,Se=c.useRef(!1),he=c.useRef(!1);c.useEffect(()=>{he.current=!1},[s]),c.useEffect(()=>{if(!me){Se.current=!1;return}Se.current||(Se.current=!0,x?.())},[me,x]),c.useEffect(()=>{if(A){he.current=!1;return}if($){he.current=!1;return}Y.length!==0&&(O||!re||he.current||(he.current=!0,g?.("structural")))},[A,$,g,re,Y.length,O]);const Pe=!!w&&!A,ve=c.useCallback(()=>{D.current!==null&&typeof window<"u"&&(window.clearTimeout(D.current),D.current=null)},[]),Be=c.useCallback(()=>{!S||!C||!Pe||typeof window>"u"||(ve(),k(!0),D.current=window.setTimeout(()=>{k(!1),D.current=null},1800))},[C,ve,Pe,S]);c.useEffect(()=>{Pe||(k(!1),ve())},[ve,Pe]);const W=c.useCallback(He=>{!h||!Pe||(He.stopPropagation(),He.preventDefault(),h(),S&&Be())},[Pe,S,h,Be]),G=c.useCallback(He=>{He.stopPropagation(),He.preventDefault(),P&&P(s)},[P,s]),ee=c.useCallback(He=>{He.stopPropagation(),He.preventDefault();const et=ul(T);if(!et.trim())return;const gt=`${Bx}
92
-
93
- ${et}`;L(gt)},[T,L]);c.useEffect(()=>()=>{ve()},[ve]);const fe=c.useMemo(()=>{const He={},et=_.filter(gt=>fn(gt.tool)||F?!1:U(gt));return et.forEach((gt,Je)=>{He[gt.id]={hasPrev:Je>0,hasNext:Je<et.length-1}}),He},[_,F,U]),de=c.useMemo(()=>b?.activityParts??[],[b]),Ae=c.useMemo(()=>b?de.filter(He=>He.messageId===s):[],[de,s,b]),Ne=c.useMemo(()=>b?b.activityGroupSegments.filter(He=>He.anchorMessageId===s):[],[s,b]),Oe=c.useMemo(()=>{const He=new Map;return Ae.forEach(et=>{He.set(et.part,et)}),He},[Ae]),ce=c.useMemo(()=>b?(y?de:de.filter(et=>et.kind==="tool")).filter(et=>{if(et.kind!=="tool")return!0;const gt=et.part.tool;return!fn(gt)}):[],[de,y,b]),[dt,kt]=c.useState(!1);c.useEffect(()=>{if(!b)return;const He=b.activityGroupSegments.some(et=>et.afterToolPartId!==null);(ce.length>1||He&&ce.length>0)&&kt(!0)},[b,ce.length]);const we=!!(b&&dt),ne=c.useMemo(()=>{if(!b)return[];if(!we)return[];if(!b.isWorking)return[];const He=[];return Ae.forEach(et=>{if(b.previewedPartIds.has(et.id)||!y&&et.kind!=="tool")return;const gt=et.part;if(et.kind==="tool"){const Je=gt;if(fn(Je.tool)||F||!U(Je))return}else if(et.kind==="reasoning"){if(!y||O||typeof gt.time?.end!="number")return}else if(et.kind==="justification"&&(!y||B||typeof gt.time?.end!="number"))return;He.push(et)}),He},[Ae,U,B,O,F,y,we,b]),Qe=c.useMemo(()=>{const He=new Set;return ne.forEach(et=>{He.add(et.id)}),He},[ne]),{isAnimating:ge}=fv(b,Qe),ye=!!(b&&we&&ce.length>0&&Ne.length>0),qe=c.useMemo(()=>_.filter(He=>fn(He.tool)),[_]),Ze=c.useMemo(()=>{const He=[],et=Je=>{!b||!ye||Ne.filter(bt=>(bt.afterToolPartId??null)===Je).forEach(bt=>{const X=y?bt.parts:bt.parts.filter(xe=>xe.kind==="tool");X.length!==0&&He.push(e.jsx(cv,{parts:X,isExpanded:b.isGroupExpanded,onToggle:b.toggleGroup,syntaxTheme:a,isMobile:i,expandedTools:d,onToggleTool:u,onShowPopup:m,onContentChange:g,isWorking:b.isWorking,previewedPartIds:b.previewedPartIds,diffStats:b.diffStats},`progressive-group-${bt.id}`))})};et(null),qe.forEach(Je=>{He.push(e.jsx(gs,{children:e.jsx(Wo,{part:Je,isExpanded:d.has(Je.id),onToggle:u,syntaxTheme:a,isMobile:i,onContentChange:g,hasPrevTool:!1,hasNextTool:!1})},`standalone-tool-${Je.id}`)),et(Je.id)});const gt=[];return I.forEach((Je,bt)=>{const X=Oe.get(Je);if(!X||!b)return;let xe=null,pe=null;if(!we){if(X.kind==="tool"){const Ee=Je;if(fn(Ee.tool))return;const pt=Ee.state?.time,ut=U(Ee);if(!(!F&&ut))return;const xt=fe[Ee.id];pe=e.jsx(gs,{children:e.jsx(Wo,{part:Ee,isExpanded:d.has(Ee.id),onToggle:u,syntaxTheme:a,isMobile:i,onContentChange:g,hasPrevTool:xt?.hasPrev??!1,hasNextTool:xt?.hasNext??!1})},`tool-${Ee.id}`),xe=ut&&typeof pt?.end=="number"?pt.end:null}pe&&gt.push({part:Je,index:bt,endTime:xe,element:pe});return}if(!b.isWorking||b.isGroupExpanded||b.previewedPartIds.has(X.id)||!y&&X.kind!=="tool")return;const Le=Qe.has(X.id);switch(X.kind){case"tool":{const Ee=Je;if(fn(Ee.tool))break;const pt=Ee.state?.time,ut=U(Ee);if(!(!F&&ut))break;const xt=fe[Ee.id],Me=e.jsx(gs,{children:e.jsx(Wo,{part:Ee,isExpanded:d.has(Ee.id),onToggle:u,syntaxTheme:a,isMobile:i,onContentChange:g,hasPrevTool:xt?.hasPrev??!1,hasNextTool:xt?.hasNext??!1})},`tool-${Ee.id}`);pe=Le?e.jsx(ni,{isMigrating:ge,children:Me},`migrating-tool-${Ee.id}`):Me,xe=ut&&typeof pt?.end=="number"?pt.end:null;break}case"reasoning":{if(!y)break;const Ee=Je.time,Ke=typeof Ee?.end=="number";if(!(Ke&&!O))break;const ut=e.jsx(gs,{children:e.jsx(Ym,{part:Je,messageId:s,onContentChange:g})},`reasoning-${bt}`);pe=Le?e.jsx(ni,{isMigrating:ge,children:ut},`migrating-reasoning-${bt}`):ut,xe=Ke?Ee?.end??null:null;break}case"justification":{if(!y)break;const Ee=Je.time,Ke=typeof Ee?.end=="number";if(!(Ke&&!B))break;const ut=e.jsx(gs,{children:e.jsx(Tw,{part:Je,messageId:s,streamPhase:"completed",allowAnimation:!1,onContentChange:g,renderAsReasoning:!0})},`assistant-text-${bt}`);pe=Le?e.jsx(ni,{isMigrating:ge,children:ut},`migrating-text-${bt}`):ut,xe=Ke?Ee?.end??null:null;break}}pe&&gt.push({part:Je,index:bt,endTime:xe,element:pe})}),gt.sort((Je,bt)=>Je.endTime===null&&bt.endTime===null?Je.index-bt.index:Je.endTime===null?1:bt.endTime===null?-1:Je.endTime-bt.endTime),gt.forEach(({element:Je})=>{He.push(Je)}),He},[Oe,Ne,d,ge,i,U,s,g,m,u,Qe,B,O,F,we,y,a,fe,b,I,qe,ye]),We=b?.turnId,Re=ue(He=>He.currentSessionId),Xe=yt(He=>{if(!We||!Re)return;const et=He.messages.get(Re);if(!et)return;const gt=et.find(X=>X.info?.id===We);if(!gt)return;const bt=gt.info.summary?.body;return typeof bt=="string"&&bt.trim().length>0?bt:void 0}),Ct=typeof b?.summaryBody=="string"&&b.summaryBody.trim().length>0?b.summaryBody:Xe,ct=c.useRef(void 0);Ct&&Ct.trim().length>0&&(ct.current=Ct);const At=c.useRef(We);At.current!==We&&(At.current=We,ct.current=void 0);const Mt=ct.current,ke=b?.isLastAssistantInTurn&&Mt&&Mt.trim().length>0,$e=!!N,Fe=Z&&w&&(q||!!N),[ot,Lt]=c.useState(!1),es=c.useMemo(()=>{if(!Z||!q)return;const He=b?.userMessageCreatedAt;if(!(typeof He!="number"||typeof o!="number")&&!(o<=He))return mv(o-He)},[Z,q,b?.userMessageCreatedAt,o]),Wt=e.jsxs(e.Fragment,{children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:He=>He.stopPropagation(),onClick:G,children:e.jsx(gh,{className:"h-4 w-4"})})}),e.jsx(nt,{sideOffset:6,children:"Start new session from this answer"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{type:"button",size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground bg-transparent hover:text-foreground hover:!bg-transparent active:!bg-transparent focus-visible:!bg-transparent focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:He=>He.stopPropagation(),onClick:ee,children:e.jsx(km,{className:"h-4 w-4"})})}),e.jsx(nt,{sideOffset:6,children:"Start new multi-run from this answer"})]}),h&&e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{type:"button",variant:"ghost",size:"icon","data-visible":v||M?"true":void 0,className:R("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",!Pe&&"opacity-50"),disabled:!Pe,"aria-label":"Copy message text","aria-hidden":!Pe,onPointerDown:He=>He.stopPropagation(),onClick:W,onFocus:()=>{Pe&&k(!0)},onBlur:()=>{M||k(!1)},children:M?e.jsx(Pt,{className:"h-3.5 w-3.5 text-[color:var(--status-success)]"}):e.jsx(Gs,{className:"h-3.5 w-3.5"})})}),e.jsx(nt,{sideOffset:6,children:"Copy answer"})]})]});return e.jsx("div",{className:R("relative w-full group/message"),style:{contain:"layout",transform:"translateZ(0)"},onTouchStart:S&&C&&Pe?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:[Ze,$e&&e.jsx(gs,{children:e.jsx("div",{className:"group/assistant-text relative break-words",children:e.jsx(Kr,{content:N??""})})},"assistant-error"),ke&&e.jsx(gs,{children:e.jsxs("div",{className:"group/assistant-text relative break-words",onMouseEnter:()=>Lt(!0),onMouseLeave:()=>Lt(!1),children:[e.jsx(Kr,{content:Mt}),Fe&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[es?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Bl,{className:"h-3.5 w-3.5"}),es]}):e.jsx("span",{}),e.jsx("div",{className:R("flex items-center gap-2 opacity-0 pointer-events-none transition-opacity duration-150 focus-within:opacity-100 focus-within:pointer-events-auto",ot&&"opacity-100 pointer-events-auto"),children:Wt})]})]})},"summary-body")]}),e.jsx(Im,{files:r,onShowPopup:m}),!ke&&Fe&&e.jsxs("div",{className:"mt-2 mb-1 flex items-center justify-between gap-2",children:[es?e.jsxs("span",{className:"text-sm text-muted-foreground/60 tabular-nums flex items-center gap-1",children:[e.jsx(Bl,{className:"h-3.5 w-3.5"}),es]}):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:Wt})]})]})})},xv=({isUser:s,...r})=>s?e.jsx(hv,{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(gv,{...r}),pd=c.memo(xv),oi=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}},yv=c.lazy(()=>as(()=>import("./ToolOutputDialog-Dn1Yyik_.js"),__vite__mapDeps([2,0,1,3,4]))),bv=new Set(["task","edit","multiedit","write","bash"]),hd=s=>typeof s=="string"&&bv.has(s.toLowerCase());function ai(s){const r=c.useRef({hasValue:!1,value:void 0});return!r.current.hasValue&&s!==void 0&&s!==null&&(r.current={hasValue:!0,value:s}),r.current.hasValue?r.current.value:s}const Js=(s,r)=>{if(typeof s=="object"&&s!==null)return s[r]},wv=({message:s,previousMessage:r,nextMessage:t,onContentChange:n,animationHandlers:o,isPendingAnchor:a=!1,turnGroupingContext:i})=>{const{isMobile:l,hasTouchInput:d}=_t(),{currentTheme:u}=on(),m=c.useRef(null),f=ue(Ji(Me=>({lifecyclePhase:Me.messageStreamStates.get(s.info.id)?.phase??null,isStreamingMessage:(()=>{const tt=s.info.sessionID??Me.currentSessionId??null;return tt?(Me.streamingMessageIds.get(tt)??null)===s.info.id:!1})(),currentSessionId:Me.currentSessionId,getCurrentAgent:Me.getCurrentAgent,getSessionAgentSelection:Me.getSessionAgentSelection,getAgentModelForSession:Me.getAgentModelForSession,getSessionModelSelection:Me.getSessionModelSelection}))),{lifecyclePhase:p,isStreamingMessage:g,currentSessionId:w,getCurrentAgent:h,getSessionAgentSelection:j,getAgentModelForSession:x,getSessionModelSelection:y}=f,b=rt(Me=>Me.providers),N=_e(Me=>Me.showReasoningTraces),v=_e(Me=>Me.toolCallExpansion);c.useEffect(()=>{w&&Mr.getInstance().recordSessionStart(w)},[w]);const[k,D]=c.useState(null),[C,M]=c.useState(!1),[S,A]=c.useState(new Set),[I,_]=c.useState({open:!1,title:"",content:""});c.useEffect(()=>{A(new Set)},[s.info.id,v]);const P=c.useMemo(()=>oi(s.info),[s.info]).isUser,L=c.useMemo(()=>P?s.parts.map(Me=>Me.type==="compaction"?{type:"text",text:"/compact"}:Me):s.parts,[P,s.parts]),Z=c.useMemo(()=>{if(P||!r)return null;const Me=Js(r.info,"clientRole"),tt=Js(r.info,"role");if((typeof Me=="string"?Me:typeof tt=="string"?tt:void 0)!=="user")return null;const Ye=Js(r.info,"mode"),wt=Js(r.info,"providerID"),Rt=Js(r.info,"modelID"),ns=Js(r.info,"variant"),ts=typeof Ye=="string"&&Ye.trim().length>0?Ye:void 0,ps=typeof wt=="string"&&wt.trim().length>0?wt:void 0,lr=typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0,Ot=typeof ns=="string"&&ns.trim().length>0?ns:void 0;return!ts&&!ps&&!lr&&!Ot?null:{agentName:ts,providerId:ps,modelId:lr,variant:Ot}},[P,r]),q=c.useMemo(()=>{if(P)return;const Me=Js(s.info,"mode");if(typeof Me=="string"&&Me.trim().length>0)return Me;if(Z?.agentName)return Z.agentName;const tt=s.info.sessionID;if(!tt)return;const ze=h(tt);return ze||(j(tt)??void 0)},[P,s.info,Z,h,j]),$=s.info.sessionID,H=P?null:Js(s.info,"providerID"),U=P?null:Js(s.info,"modelID"),K=c.useMemo(()=>{if(P||!$)return null;if(Z?.providerId&&Z?.modelId)return{providerId:Z.providerId,modelId:Z.modelId};if(q){const tt=x($,q);if(tt?.providerId&&tt?.modelId)return tt}const Me=y($);return Me?.providerId&&Me?.modelId?Me:null},[P,$,q,Z,x,y]),se=c.useMemo(()=>P?null:typeof H=="string"&&H.trim().length>0?H:K?.providerId??null,[P,H,K]),Y=c.useMemo(()=>P?null:typeof U=="string"&&U.trim().length>0?U:K?.modelId??null,[P,U,K]),re=c.useMemo(()=>{if(!P&&se&&Y&&b.length>0){const Me=b.find(tt=>tt.id===se);if(Me?.models&&Array.isArray(Me.models)){const Ye=Me.models.find(wt=>wt.id===Y)?.name;return typeof Ye=="string"?Ye:void 0}}},[P,se,Y,b]),V=c.useMemo(()=>{if(P||!se||!Y)return!1;const Me=b.find(Ye=>Ye.id===se);if(!Me?.models||!Array.isArray(Me.models))return!1;const ze=Me.models.find(Ye=>Ye.id===Y)?.variants;return!!(ze&&Object.keys(ze).length>0)},[P,Y,se,b]),ae=ai(q),E=ai(se??void 0),B=ai(re),F=ae??void 0,O=E??null,z=B??void 0,Q=c.useMemo(()=>{const Me=s.info.time;return typeof Me?.completed=="number"?Me.completed:null},[s.info.time]),me=c.useMemo(()=>P?!0:!!(Q&&Q>0),[P,Q]),Se=c.useMemo(()=>{const Me=s.info.finish;return typeof Me=="string"?Me:void 0},[s.info]),he=c.useMemo(()=>uv(L,{includeReasoning:N}),[L,N]),Pe=c.useMemo(()=>P||me?he:[],[P,me,he]),ve=c.useMemo(()=>P?[]:he.filter(Me=>Me.type==="text"),[P,he]),Be=c.useMemo(()=>P?[]:he.filter(tt=>tt.type==="tool"),[P,he]),W=c.useMemo(()=>{if(v==="collapsed"||v==="activity")return S;const Me=new Set;for(const ze of Be){const Ye=ze.tool;ze.id&&hd(Ye)&&Me.add(ze.id)}if(i?.isFirstAssistantInTurn)for(const ze of i.activityParts){if(ze.kind!=="tool")continue;const Ye=ze.part;Ye.id&&hd(Ye.tool)&&Me.add(Ye.id)}const tt=new Set(Me);for(const ze of S)tt.has(ze)?tt.delete(ze):tt.add(ze);return tt},[S,v,Be,i]),G=c.useMemo(()=>{if(!P)return;const Me=s.parts.find(wt=>wt.type==="agent");if(!Me)return;const tt=Me,ze=typeof tt.name=="string"?tt.name:void 0;if(!ze)return;const Ye=tt.source&&typeof tt.source.value=="string"&&tt.source.value.trim().length>0?tt.source.value:`#${ze}`;return{name:ze,token:Ye}},[P,s.parts]),ee=typeof Se!="string",fe=c.useMemo(()=>P?!1:ve.length===0||Be.length===0?ee:!0,[ve.length,Be.length,ee,P]),de=u?.metadata.variant,Ae=c.useMemo(()=>de?de==="dark":typeof document<"u"?document.documentElement.classList.contains("dark"):!1,[de]),Ne=c.useMemo(()=>u?Hm(u):Ae?yw:bw,[u,Ae]),Oe=c.useMemo(()=>P?!1:Mr.getInstance().shouldAnimateMessage(s.info,w||s.info.sessionID),[s.info,w,P]),ce=c.useRef(!1),dt=c.useMemo(()=>r?oi(r.info):null,[r]),kt=c.useMemo(()=>t?oi(t.info):null,[t]),we=c.useMemo(()=>P||!kt?!1:!kt.isUser&&kt.role==="assistant",[P,kt]),ne=c.useMemo(()=>me?"completed":p||(g?"streaming":"completed"),[me,p,g]),Qe=c.useMemo(()=>{if(P)return!0;const Me=i?.headerMessageId;if(Me){if(s.info.id===Me){if(ne==="completed")return!0;const ze=ne==="streaming"||ne==="cooldown",Ye=ce.current;return ze&&!Ye&&(ce.current=!0),Ye||ze}return!1}return dt?dt.isUser:!0},[P,dt,i,ne,s.info]),ge=c.useCallback(Me=>{navigator.clipboard.writeText(Me),D(Me),setTimeout(()=>D(null),2e3)},[]),ye=i?.turnId,qe=yt(Me=>{if(!ye)return;const tt=s.info.sessionID;if(!tt)return;const ze=Me.messages.get(tt);if(!ze)return;const Ye=ze.find(ns=>ns.info?.id===ye);if(!Ye)return;const Rt=Ye.info.summary?.body;return typeof Rt=="string"&&Rt.trim().length>0?Rt:void 0}),Ze=yt(Me=>{if(!ye)return;const tt=s.info.sessionID;if(!tt)return;const ze=Me.messages.get(tt);if(!ze)return;const Ye=ze.find(Rt=>Rt.info?.id===ye);if(!Ye)return;const wt=Ye.info.variant;return typeof wt=="string"&&wt.trim().length>0?wt:void 0}),We=P?void 0:Ze??Z?.variant,Re=!P&&V?We??"Default":void 0,Xe=typeof i?.summaryBody=="string"&&i.summaryBody.trim().length>0?i.summaryBody:qe,Ct=c.useRef(void 0);Xe&&Xe.trim().length>0&&(Ct.current=Xe);const ct=c.useRef(ye);ct.current!==ye&&(ct.current=ye,Ct.current=void 0);const At=Ct.current,Mt=c.useMemo(()=>{if(P)return;const Me=s.info?.error;if(!Me)return;const tt=typeof Me.data?.message=="string"?Me.data.message:void 0,ze=typeof Me.message=="string"?Me.message:void 0,Ye=typeof Me.name=="string"?Me.name:void 0,wt=tt||ze||Ye;if(wt)return`Opencode failed to send message with error:
94
- \`${wt}\``},[P,s.info]),ke=c.useMemo(()=>P?Pe.filter(ze=>ze.type==="text").map(ze=>(ze.text||ze.content||"").trim()).filter(ze=>ze.length>0).join(`
95
- `).replace(/\n\s*\n+/g,`
96
- `):Mt&&Mt.trim().length>0?Mt:At&&At.trim().length>0?At:ul(Pe),[Mt,At,Pe,P]),$e=ke.length>0,Fe=c.useCallback(()=>{navigator.clipboard.writeText(ke),M(!0),setTimeout(()=>M(!1),2e3)},[ke]),ot=ue(Me=>Me.revertToMessage),Lt=ue(Me=>Me.forkFromMessage),es=c.useCallback(()=>{!$||!s.info.id||ot($,s.info.id)},[$,s.info.id,ot]),Wt=c.useCallback(()=>{!$||!s.info.id||Lt($,s.info.id)},[$,s.info.id,Lt]),He=c.useCallback(Me=>{A(tt=>{const ze=new Set(tt);return ze.has(Me)?ze.delete(Me):ze.add(Me),ze})},[]),et=o??null,gt=c.useRef(!1),Je=c.useRef(!1),bt=c.useRef(!1),X=c.useRef(!1),xe=c.useRef(!1);c.useEffect(()=>{Je.current=!1,bt.current=!1,X.current=!1,xe.current=!1,gt.current=!1},[s.info.id]);const pe=c.useCallback(()=>{P||gt.current||(gt.current=!0,n?.("structural"))},[P,n]),Le=c.useCallback(Me=>{Me.image&&_(Me)},[]),Ee=c.useCallback(Me=>{_(tt=>({...tt,open:Me}))},[]),Ke=!!Js(s.info,"animationSettled"),pt=ne==="streaming",ut=c.useMemo(()=>P?!1:he.some(Me=>Me.type==="reasoning"),[P,he]),Tt=Oe&&!Ke&&!pt,xt=!P&&Oe&&ve.length>0&&!fe;return c.useEffect(()=>{if(et?.onStreamingCandidate){if(!xt){bt.current&&(ut&&et?.onReasoningBlock?et.onReasoningBlock():et?.onReservationCancelled&&et.onReservationCancelled(),bt.current=!1);return}xe.current||(xe.current=!0,et.onStreamingCandidate(),bt.current=!0)}},[et,xt,ut]),c.useEffect(()=>{et?.onAnimationStart&&Tt&&(X.current||(et.onAnimationStart(),X.current=!0))},[et,Tt]),c.useEffect(()=>{if(P)return;const Me=et?.onAnimatedHeightChange;if(!Me||!(Tt||xt))return;const ze=m.current;if(!ze)return;if(typeof window>"u"||typeof ResizeObserver>"u"){Me(ze.getBoundingClientRect().height);return}let Ye=null;const wt=ns=>{if(typeof window>"u"){Me(ns);return}Ye!==null&&window.cancelAnimationFrame(Ye),Ye=window.requestAnimationFrame(()=>{Me(ns)})},Rt=new ResizeObserver(ns=>{const ts=ns[0];ts&&wt(ts.contentRect.height)});return Rt.observe(ze),wt(ze.getBoundingClientRect().height),()=>{Ye!==null&&(window.cancelAnimationFrame(Ye),Ye=null),Rt.disconnect()}},[Tt,P,et,xt]),e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("group w-full",Qe?"pt-2":"pt-0",P?"pb-2":we?"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(pd,{messageId:s.info.id,parts:he,isUser:P,isMessageCompleted:me,messageFinish:Se,syntaxTheme:Ne,isMobile:l,hasTouchInput:d,copiedCode:k,onCopyCode:ge,expandedTools:S,onToggleTool:He,onShowPopup:Le,streamPhase:ne,allowAnimation:Tt,onContentChange:n,shouldShowHeader:!1,hasTextContent:$e,onCopyMessage:Fe,copiedMessage:C,showReasoningTraces:N,onAuxiliaryContentComplete:pe,agentMention:G,onRevert:es,onFork:P?Wt:void 0,errorMessage:Mt})})})}):e.jsxs("div",{children:[Qe&&e.jsx(vw,{isUser:P,providerID:O,agentName:F,modelName:z,variant:Re,isDarkTheme:Ae}),e.jsx(pd,{messageId:s.info.id,parts:he,isUser:P,isMessageCompleted:me,messageFinish:Se,messageCompletedAt:Q??void 0,syntaxTheme:Ne,isMobile:l,hasTouchInput:d,copiedCode:k,onCopyCode:ge,expandedTools:W,onToggleTool:He,onShowPopup:Le,streamPhase:ne,allowAnimation:Tt,onContentChange:n,shouldShowHeader:Qe,hasTextContent:$e,onCopyMessage:Fe,copiedMessage:C,onAuxiliaryContentComplete:pe,showReasoningTraces:N,agentMention:G,turnGroupingContext:i,errorMessage:Mt})]})})}),e.jsx(c.Suspense,{fallback:null,children:e.jsx(yv,{popup:I,onOpenChange:Ee,syntaxTheme:Ne,isMobile:l})})]})},vv=c.memo(wv),jv=({diff:s,syntaxTheme:r,filePath:t})=>e.jsx("div",{className:"typography-code px-1 pb-1 pt-0 space-y-0",children:Qm(s).map((n,o)=>e.jsxs("div",{className:"-mx-1 px-1 border-b border-border/20 last:border-b-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border-b border-border/10 break-words -mx-1",children:`${n.file||t?.split("/").pop()||"file"} (line ${n.oldStart})`}),e.jsx("div",{children:n.lines.map((a,i)=>e.jsxs("div",{className:R("typography-code font-mono px-2 py-0.5 flex -mx-2",a.type==="context"&&"bg-transparent",a.type==="removed"&&"bg-transparent",a.type==="added"&&"bg-transparent"),style:a.type==="removed"?{backgroundColor:"var(--tools-edit-removed-bg)"}:a.type==="added"?{backgroundColor:"var(--tools-edit-added-bg)"}:{},children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:a.lineNumber||""}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:nn(t||n.file)||"text",PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:a.content})})]},i))})]},o))}),Sv=({content:s,syntaxTheme:r,filePath:t})=>{const n=s.split(`
97
- `),o=nn(t??"")||"text",a=t?.split("/").pop()||"New file",i=Math.max(n.length,1),l=i===1?"line 1":`lines 1-${i}`;return e.jsxs("div",{className:"w-full min-w-0",children:[e.jsx("div",{className:"bg-muted/20 px-2 py-1 typography-meta font-medium text-muted-foreground border border-border/10 rounded-lg mb-1",children:`${a} (${l})`}),e.jsx("div",{className:"space-y-0",children:n.map((d,u)=>e.jsxs("div",{className:"typography-code font-mono px-2 py-0.5 flex -mx-1",children:[e.jsx("span",{className:"text-muted-foreground/60 w-8 flex-shrink-0 text-right pr-2 self-start select-none",children:u+1}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(hr,{style:r,language:o,PreTag:"div",wrapLines:!0,wrapLongLines:!0,customStyle:{margin:0,padding:0,fontSize:"inherit",background:"transparent",backgroundColor:"transparent",borderRadius:0,overflow:"visible",whiteSpace:"pre-wrap",wordBreak:"break-all",overflowWrap:"anywhere"},codeTagProps:{style:{background:"transparent",backgroundColor:"transparent",fontSize:"inherit"}},children:d||" "})})]},u))})]})},kv=s=>{const r="h-3 w-3",t=s.toLowerCase();return t==="edit"||t==="multiedit"||t==="str_replace"||t==="str_replace_based_edit_tool"?e.jsx(mr,{className:r}):t==="write"||t==="create"||t==="file_write"?e.jsx(gu,{className:r}):t==="bash"||t==="shell"||t==="cmd"||t==="terminal"||t==="shell_command"?e.jsx(Pr,{className:r}):t==="webfetch"||t==="fetch"||t==="curl"||t==="wget"?e.jsx(Si,{className:r}):e.jsx(fa,{className:r})},Nv=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},Cv=({permission:s,onResponse:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(!1),{respondToPermission:i}=ue(),{currentTheme:l}=on(),d=c.useMemo(()=>Hm(l),[l]),u=async x=>{n(!0);try{await i(s.sessionID,s.id,x),a(!0),r?.(x)}catch{}finally{n(!1)}};if(o)return null;const m=s.permission||"unknown",f=m.toLowerCase(),p=(x,y="")=>{const b=s.metadata[x];return typeof b=="string"?b:typeof b=="number"?String(b):y},g=x=>{const y=s.metadata[x];return typeof y=="number"?y:void 0},w=x=>!!s.metadata[x],h=Nv(m),j=()=>{if(f==="bash"||f==="shell"||f==="shell_command"){const b=p("command")||p("cmd")||p("script"),N=p("description"),v=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}),v&&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:v})]}),k&&e.jsxs("div",{className:"typography-meta text-muted-foreground mb-2",children:[e.jsx("span",{className:"font-semibold",children:"Timeout:"})," ",k,"ms"]}),b&&e.jsx("div",{children:e.jsx(hr,{language:"bash",style:d,PreTag:"div",customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem",whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word",overflow:"visible"},codeTagProps:{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",overflowWrap:"break-word"}},wrapLongLines:!0,children:b})})]})}if(f==="edit"||f==="multiedit"||f==="str_replace"||f==="str_replace_based_edit_tool"){const b=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("changes")||p("diff"),v=w("replace_all")||w("replaceAll");return e.jsxs(e.Fragment,{children:[v&&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(ft,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(jv,{diff:N,syntaxTheme:d,filePath:b})})]})}if(f==="write"||f==="create"||f==="file_write"){const b=p("path")||p("file_path")||p("filename")||p("filePath"),N=p("content")||p("text")||p("data");return N?e.jsx(ft,{outerClassName:"max-h-[60vh]",className:"tool-output-surface p-1 rounded-xl border border-border/20 bg-transparent",children:e.jsx(Sv,{content:N,syntaxTheme:d,filePath:b})}):null}if(f==="webfetch"||f==="fetch"||f==="curl"||f==="wget"){const b=p("url")||p("uri")||p("endpoint"),N=p("method")||"GET",v=s.metadata.headers&&typeof s.metadata.headers=="object"?s.metadata.headers:void 0,k=p("body")||p("data")||p("payload"),D=g("timeout"),C=p("format")||p("responseType");return e.jsxs(e.Fragment,{children:[b&&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:b})]})]}),v&&Object.keys(v).length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Headers:"}),e.jsx(ft,{outerClassName:"max-h-24",className:"p-0",children:e.jsx(hr,{language:"json",style:d,customStyle:{margin:0,padding:"0.5rem",fontSize:"var(--text-meta)",lineHeight:"1.25rem",background:"rgb(var(--muted) / 0.3)",borderRadius:"0.25rem"},wrapLongLines:!0,children:JSON.stringify(v,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(ft,{outerClassName:"max-h-32",className:"p-0",children:e.jsx(hr,{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)})})]}),(D||C)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:[D&&e.jsxs("span",{children:["Timeout: ",D,"ms"]}),D&&C&&e.jsx("span",{children:" • "}),C&&e.jsxs("span",{children:["Response format: ",C]})]})]})}const x=p("command")||p("content")||p("action")||p("operation"),y=p("description");return e.jsxs(e.Fragment,{children:[y&&e.jsx("div",{className:"typography-meta text-muted-foreground mb-2",children:y}),x&&e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Action:"}),e.jsx(ft,{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(x)})})]}),Object.keys(s.metadata).length>0&&!x&&!y&&e.jsxs("div",{children:[e.jsx("div",{className:"typography-meta text-muted-foreground mb-1",children:"Details:"}),e.jsx(ft,{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(Qr,{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:[kv(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:R("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:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.2)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-success) / 0.1)"},children:[e.jsx(Pt,{className:"h-3 w-3"}),"Allow Once"]}),s.always.length>0?e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("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:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),(()=>{const x=s.always||s.metadata.always||[];if(x.length===0)return"Always Allow";const b=x.slice(0,2).join(", ");return x.length>2?`Always: ${b}...`:`Always: ${b}`})()]}):e.jsxs("button",{onClick:()=>u("always"),disabled:t,className:R("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:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.7)"},onMouseLeave:x=>{x.currentTarget.style.backgroundColor="rgb(var(--muted) / 0.5)"},children:[e.jsx(or,{className:"h-3 w-3"}),"Always Allow"]}),e.jsxs("button",{onClick:()=>u("reject"),disabled:t,className:R("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:x=>{x.currentTarget.style.backgroundColor="rgb(var(--status-error) / 0.2)"},onMouseLeave:x=>{x.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"})})]})]})})})},ii="summary",Mv=({question:s})=>{const{respondToQuestion:r,rejectQuestion:t}=ue(),[n,o]=c.useState("0"),[a,i]=c.useState(!1),[l,d]=c.useState(!1),[u,m]=c.useState({}),[f,p]=c.useState({}),[g,w]=c.useState({}),h=c.useMemo(()=>s.questions??[],[s.questions]),j=n===ii,x=j?-1:Math.max(0,Math.min(h.length-1,Number(n)||0)),y=j?null:h[x];c.useEffect(()=>{o("0"),m({}),p({}),w({}),d(!1)},[s.id]);const b=c.useMemo(()=>{const T=h.map((P,L)=>({value:String(L),label:P.header?.trim()||`Q${L+1}`}));return h.length>1&&T.push({value:ii,label:"Summary"}),T},[h]),N=c.useCallback(T=>{if(!!f[T])return(g[T]??"").trim()||"(no answer)";const L=u[T]??[];return L.length>0?L.join(", "):"(no answer)"},[f,g,u]),v=!!y?.multiple,k=u[x]??[],D=!!f[x],C=c.useMemo(()=>{if(h.length===0)return!1;for(let T=0;T<h.length;T+=1){if(!!f[T]){if(!(g[T]??"").trim())return!1;continue}if((u[T]??[]).length===0)return!1}return!0},[f,g,h.length,u]),M=c.useCallback(()=>{const T=[];for(let P=0;P<h.length;P+=1){if(!!f[P]){const Z=(g[P]??"").trim();T.push(Z?[Z]:[]);continue}T.push(u[P]??[])}return T},[f,g,h.length,u]),S=c.useCallback(T=>{y&&(p(P=>({...P,[x]:!1})),m(P=>{const L=P[x]??[];if(v){const q=L.includes(T)?L.filter($=>$!==T):[...L,T];return{...P,[x]:q}}return{...P,[x]:[T]}}))},[x,y,v]),A=c.useCallback(()=>{p(T=>({...T,[x]:!0})),m(T=>({...T,[x]:[]}))},[x]),I=c.useCallback(async()=>{if(C){i(!0);try{const T=M();await r(s.sessionID,s.id,T),d(!0)}catch{}finally{i(!1)}}},[M,s.id,s.sessionID,C,r]),_=c.useCallback(async()=>{i(!0);try{await t(s.sessionID,s.id),d(!0)}catch{}finally{i(!1)}},[s.id,s.sessionID,t]);return l||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(Qr,{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:[b.length>1?e.jsx("div",{className:"flex items-center gap-1 mb-2 flex-wrap",children:b.map(T=>{const P=n===T.value,L=T.value===ii;return e.jsxs("button",{type:"button",onClick:()=>o(T.value),className:R("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:[L?e.jsx(xu,{className:"h-3 w-3"}):null,T.label]},T.value)})}):null,j?e.jsx("div",{className:"space-y-2",children:h.map((T,P)=>{const L=N(P),Z=L!=="(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:T.header||`Question ${P+1}`}),e.jsx("div",{className:R("typography-meta",Z?"text-foreground":"text-muted-foreground/50 italic"),children:L})]},P)})}):y?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"typography-meta font-medium text-foreground mb-1.5",children:y.question}),v?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:[y.options.map((T,P)=>{const L=k.includes(T.label),Z=/\(recommended\)/i.test(T.label);return e.jsx("button",{type:"button",onClick:()=>S(T.label),disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",L?"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:L?e.jsx(xh,{className:"h-3.5 w-3.5 text-primary"}):e.jsx(ki,{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:R("typography-meta break-all",L?"text-foreground font-medium":"text-foreground/80"),children:T.label}),Z?e.jsx("span",{className:"typography-micro text-primary/80",children:"recommended"}):null]}),T.description?e.jsx("div",{className:"typography-micro text-muted-foreground break-words",children:T.description}):null]})]})},`${P}:${T.label}`)}),e.jsx("button",{type:"button",onClick:A,disabled:a,className:R("w-full px-1.5 py-1 text-left rounded transition-colors","hover:bg-muted/30",D?"bg-muted/20":null,a?"opacity-60 cursor-not-allowed":null),children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oo,{className:R("h-3.5 w-3.5",D?"text-primary":"text-muted-foreground/50")}),e.jsx("span",{className:R("typography-meta",D?"text-foreground font-medium":"text-muted-foreground"),children:"Other…"})]})}),D?e.jsx("div",{className:"pl-6 pr-1 pt-0.5",children:e.jsx("textarea",{ref:T=>{if(T){T.style.height="auto";const P=20,L=P*2,Z=P*4;T.style.height=`${Math.min(Math.max(T.scrollHeight,L),Z)}px`}},value:g[x]??"",onChange:T=>{const P=T.target;P.style.height="auto";const L=20,Z=L*2,q=L*4;P.style.height=`${Math.min(Math.max(P.scrollHeight,Z),q)}px`,w($=>({...$,[x]: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:I,disabled:a||!C,className:R("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(Pt,{className:"h-3 w-3"}),"Confirm"]}),e.jsxs("button",{type:"button",onClick:_,disabled:a,className:R("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]})]})})})},Dv=new Set(["task"]),gd=s=>typeof s=="string"&&Dv.has(s.toLowerCase()),Av=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},Ev=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}}},Iv=s=>{const r=Ev(s);let t;const o=s.userMessage.info.summary?.diffs;if(Array.isArray(o)&&o.length>0){let x=0,y=0,b=0;o.forEach(N=>{if(!N)return;const v=typeof N.additions=="number"?N.additions:0,k=typeof N.deletions=="number"?N.deletions:0;(v!==0||k!==0)&&(b+=1),x+=v,y+=k}),b>0&&(t={additions:x,deletions:y,files:b})}let a=!1,i=!1;s.assistantMessages.forEach(x=>{x.parts.forEach(y=>{y.type==="tool"?a=!0:y.type==="reasoning"&&(i=!0)})});const l=[];let d=0;s.assistantMessages.forEach(x=>{const y=x.info.id;x.info.finish,x.parts.forEach(b=>{const N=typeof b.id=="string"&&b.id.trim().length>0?b.id:`${y}-activity-${d++}`;if(b.type==="tool"){const k=b.state?.time,D=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:s.turnId,messageId:y,kind:"tool",part:b,endedAt:D});return}if(b.type==="reasoning"){const v=b.text??b.content;if(typeof v!="string"||v.trim().length===0)return;const k=b.time,D=typeof k?.end=="number"?k.end:void 0;l.push({id:N,turnId:s.turnId,messageId:y,kind:"reasoning",part:b,endedAt:D});return}})});const u=[],m=new WeakMap;l.forEach(x=>{m.set(x.part,x)});const f=new Map,p=[],g=new Map;let w=null;s.assistantMessages.forEach(x=>{const y=x.info.id;x.parts.forEach(b=>{if(b.type==="tool"){const k=b.tool;if(gd(k)){const D=typeof b.id=="string"&&b.id.trim().length>0?b.id:`${y}-task-${p.length+1}`;f.has(D)||(f.set(D,y),p.push(D)),w=D;return}}const N=m.get(b);if(!N)return;if(N.kind==="tool"){const k=N.part.tool;if(gd(k))return}const v=g.get(w)??[];v.push(N),g.set(w,v)})});const h=x=>{if(x.length===0)return;const y=new Map;x.forEach(v=>{y.set(v.messageId,(y.get(v.messageId)??0)+1)});let b,N=0;for(const v of s.assistantMessages){const k=y.get(v.info.id)??0;if(k>0&&!b&&(b=v.info.id),N+=k,N>=2)return v.info.id}return b};return[null,...p].forEach(x=>{const y=g.get(x)??[];if(y.length===0)return;const b=x===null?h(y):f.get(x);b&&u.push({id:`${s.turnId}:${b}:${x??"start"}`,anchorMessageId:b,afterToolPartId:x,parts:y})}),{activityParts:l,activityGroupSegments:u,hasTools:a,hasReasoning:i,summaryBody:r,diffStats:t}},Pv=s=>{const{isWorking:r}=Ml(),t=c.useMemo(()=>Av(s),[s]),n=c.useMemo(()=>t.length===0?null:t[t.length-1].turnId,[t]),o=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.userMessage.info.id,j),j.assistantMessages.forEach(x=>{h.set(x.info.id,j)})}),h},[t]),a=c.useMemo(()=>{const h=new Map;return t.forEach(j=>{h.set(j.turnId,Iv(j))}),h},[t]),[i,l]=c.useState(()=>new Map),d=_e(h=>h.toolCallExpansion),u=d==="activity"||d==="detailed";c.useEffect(()=>{l(new Map)},[d]);const m=c.useCallback(h=>{const j=i.get(h);return j||{isExpanded:u,previewedPartIds:new Set}},[i,u]),f=c.useCallback(h=>{l(j=>{const x=new Map(j),y=x.get(h)??{isExpanded:u,previewedPartIds:new Set};return x.set(h,{...y,isExpanded:!y.isExpanded}),x})},[u]),p=c.useCallback((h,j)=>{j.length!==0&&l(x=>{const y=new Map(x),b=y.get(h)??{isExpanded:u,previewedPartIds:new Set},N=new Set(b.previewedPartIds);return j.forEach(v=>{v&&v.trim().length>0&&N.add(v)}),y.set(h,{...b,previewedPartIds:N}),y})},[u]),g=c.useCallback(h=>o.get(h),[o]),w=c.useCallback(h=>{const j=o.get(h);if(!j||!j.assistantMessages.some(q=>q.info.id===h))return;const y=a.get(j.turnId),b=y?.activityParts??[],N=y?.activityGroupSegments??[],v=!!y?.hasTools,k=!!y?.hasReasoning,D=y?.summaryBody,C=y?.diffStats,M=j.assistantMessages[0]?.info.id,S=h===M,A=j.assistantMessages[j.assistantMessages.length-1]?.info.id,I=h===A,_=M,T=m(j.turnId),P=r&&n===j.turnId,L=j.userMessage.info.time,Z=typeof L?.created=="number"?L.created:void 0;return{turnId:j.turnId,isFirstAssistantInTurn:S,isLastAssistantInTurn:I,summaryBody:D,activityParts:b,activityGroupSegments:N,headerMessageId:_,hasTools:v,hasReasoning:k,diffStats:C,userMessageCreatedAt:Z,isWorking:P,isGroupExpanded:T.isExpanded,previewedPartIds:T.previewedPartIds,toggleGroup:()=>f(j.turnId),markPartsPreviewed:q=>p(j.turnId,q)}},[m,n,p,o,r,f,a]);return{turns:t,getTurnForMessage:g,getContextForMessage:w}},Tv=({messages:s,permissions:r,questions:t,onMessageContentChange:n,getAnimationHandlers:o,hasMoreAbove:a,isLoadingOlder:i,onLoadOlder:l,scrollToBottom:d,pendingAnchorId:u})=>{c.useEffect(()=>{r.length===0&&t.length===0||n("permission")},[r,t,n]);const m=c.useMemo(()=>{const p=new Set;return s.filter(g=>{const w=g.info?.id;if(typeof w=="string"){if(p.has(w))return!1;p.add(w)}return!0}).map(g=>({...g,parts:aw(g.parts)}))},[s]),{getContextForMessage:f}=Pv(m);return e.jsxs("div",{children:[a&&e.jsx("div",{className:"flex justify-center py-3",children:i?e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground/80",children:"Loading…"}):e.jsx("button",{type:"button",onClick:l,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(vv,{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(Mv,{question:p},p.id)),r.map(p=>e.jsx(Cv,{permission:p},p.id))]})]})},Fv=c.memo(Tv);function Rv(...s){return r=>{s.forEach(t=>{typeof t=="function"?t(r):t&&typeof t=="object"&&(t.current=r)})}}const ef=c.forwardRef(({orientation:s="vertical",offset:r=72,size:t=48,isEnabled:n=!0,hideBottomShadow:o=!1,onVisibilityChange:a,style:i,className:l,children:d,...u},m)=>{const f=c.useRef(null),p=c.useRef("none"),g=u["data-scroll-shadow"];delete u["data-scroll-shadow"];const w=c.useMemo(()=>{const y={...i};return y["--scroll-shadow-size"]=`${t}px`,y},[t,i]),h=c.useCallback((y,b,N,v,k)=>{const D=`${v}${k.charAt(0).toUpperCase()}${k.slice(1)}Scroll`;b&&N?(y.dataset[D]="true",y.removeAttribute(`data-${v}-scroll`),y.removeAttribute(`data-${k}-scroll`)):(y.dataset[`${v}Scroll`]=String(b),y.dataset[`${k}Scroll`]=String(N),y.removeAttribute(`data-${v}-${k}-scroll`))},[]),j=c.useCallback(y=>{["top","bottom","top-bottom","left","right","left-right"].forEach(b=>{y.removeAttribute(`data-${b}-scroll`)})},[]),x=c.useCallback(()=>{const y=f.current;if(!y)return;if(!n){j(y);return}const b=s==="vertical"?y.scrollTop>r:y.scrollLeft>r;let N=s==="vertical"?y.scrollTop+y.clientHeight+r<y.scrollHeight:y.scrollLeft+y.clientWidth+r<y.scrollWidth;o&&s==="vertical"&&(N=!1),h(y,b,N,s==="vertical"?"top":"left",s==="vertical"?"bottom":"right");const v=b&&N?"both":b?s==="vertical"?"top":"left":N?s==="vertical"?"bottom":"right":"none";v!==p.current&&(p.current=v,a?.(v))},[j,o,n,r,a,s,h]);return c.useEffect(()=>{const y=f.current;if(!y)return;const b=()=>x(),N=typeof ResizeObserver<"u"?new ResizeObserver(()=>x()):null,v=typeof MutationObserver<"u"?new MutationObserver(()=>x()):null;return x(),y.addEventListener("scroll",b,{passive:!0}),N?.observe(y),v?.observe(y,{childList:!0,subtree:!0,characterData:!0}),()=>{y.removeEventListener("scroll",b),N?.disconnect(),v?.disconnect()}},[x]),e.jsx("div",{...u,ref:Rv(f,m),className:l,"data-orientation":s,"data-scroll-shadow":g??!0,style:w,children:d})});ef.displayName="ScrollShadow";const _v=160,Ov=({containerRef:s})=>{const[r,t]=c.useState(!0),n=c.useRef(!0),o=c.useRef(!1),a=c.useRef(null),i=c.useRef(null),l=c.useRef(0),d=c.useRef(0),u=c.useCallback(()=>{a.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(a.current),a.current=null,i.current=null},[]),m=c.useCallback(b=>{const N=s.current;if(!N){u();return}i.current===null&&(i.current=b);const v=Math.min(1,(b-i.current)/_v),k=1-Math.pow(1-v,3),D=l.current,C=d.current,M=D+(C-D)*k;if(N.scrollTop=M,v<1){a.current=window.requestAnimationFrame(m);return}N.scrollTop=C,u(),n.current&&(n.current=!1,t(!1))},[u,s,t]),f=c.useCallback((b,N)=>{const v=s.current;if(!v)return;const k=Math.max(0,b),D=N?.instant??!1;if(o.current=!1,typeof window>"u"||D){u(),v.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}if(u(),Math.abs(k-v.scrollTop)<=.5){v.scrollTop=k;const M=k<=1;n.current!==M&&(n.current=M,t(M));return}l.current=v.scrollTop,d.current=k,i.current=null,a.current=window.requestAnimationFrame(m)},[u,s,m,t]),p=c.useCallback(()=>{o.current=!0},[]),g=c.useCallback(()=>{o.current=!0},[]),w=c.useCallback(()=>o.current,[]),h=c.useCallback(()=>s.current?.scrollTop??0,[s]),j=c.useCallback(()=>s.current?.scrollHeight??0,[s]),x=c.useCallback(()=>s.current?.clientHeight??0,[s]),y=c.useCallback(()=>{const b=s.current;if(!b)return;o.current&&a.current!==null&&u();const N=b.scrollTop<=1;n.current!==N&&(n.current=N,t(N))},[u,s]);return c.useEffect(()=>{const b=s.current;if(b)return b.addEventListener("wheel",g,{passive:!0}),b.addEventListener("touchstart",g,{passive:!0}),()=>{b.removeEventListener("wheel",g),b.removeEventListener("touchstart",g)}},[s,g]),c.useEffect(()=>()=>{u()},[u]),c.useMemo(()=>({handleScroll:y,scrollToPosition:f,forceManualMode:p,isAtTop:r,isManualOverrideActive:w,getScrollTop:h,getScrollHeight:j,getClientHeight:x}),[y,f,p,r,w,h,j,x])},xd=typeof window<"u"?c.useLayoutEffect:c.useEffect,yd=50,bd=40,$v=.2,Lv=.1,Bv=150,$s=s=>{const r=s.info;return typeof r?.id=="string"?r.id:null},zv=s=>{const r=s.info;if(r?.userMessageMarker===!0)return!0;const t=r?.clientRole,n=r?.role;return t==="user"||n==="user"},Wv=({currentSessionId:s,sessionMessages:r,updateViewportAnchor:t,updateActiveTurnAnchor:n,getActiveTurnAnchor:o,isSyncing:a,isMobile:i,sessionActivityPhase:l})=>{const d=c.useRef(null),u=Ov({containerRef:d}),[m,f]=c.useState(null),[p,g]=c.useState(0),[w,h]=c.useState(!1),[j,x]=c.useState(null),y=c.useRef(null),b=c.useRef(null),N=c.useRef(r.length),v=c.useRef(r.length>0?$s(r[0]):null),k=c.useRef(r.length>0?$s(r[r.length-1]):null),D=c.useRef(0),C=c.useRef(0),M=c.useRef(void 0),S=c.useRef(null),A=c.useRef(!1),I=c.useRef(!1),_=c.useRef(null),T=s?l?.get(s)??"idle":"idle",P=c.useCallback(E=>{const B=Math.max(0,E);D.current!==B&&(D.current=B,g(B))},[]),L=c.useCallback(()=>{const E=d.current;E&&(C.current=E.clientHeight)},[]),Z=c.useCallback(()=>{if(!m)return null;const E=d.current;return E?E.querySelector(`[data-message-id="${m}"]`):null},[m]),q=c.useCallback(()=>{const E=d.current,B=D.current;if(!E||B<=0)return!0;const F=E.scrollHeight-B;return E.scrollTop+E.clientHeight<F},[]),$=c.useCallback((E,B)=>{const F=E.offsetHeight,O=E.offsetTop;if(F>B*$v){const Q=B*Lv;return O+F-Q}else return O-yd},[]),H=c.useCallback(()=>{const E=d.current;if(!E||!S.current)return;const B=Z();if(!B)return;const F=E.clientHeight,O=E.scrollHeight,Q=$(B,F)+F,me=D.current,Se=O-me;if(!A.current&&Se<Q){const he=Q-Se;he>me&&(P(he),s&&S.current&&n(s,S.current,he))}},[$,s,Z,n,P]),U=c.useCallback(()=>{const E=d.current;if(!E){h(!1);return}if(j){h(!1);return}if(!(E.scrollHeight>E.clientHeight)){h(!1);return}const F=E.scrollHeight-E.scrollTop-E.clientHeight,O=D.current;if(O>0){const z=E.scrollHeight-O,Q=E.scrollTop+E.clientHeight;h(Q<z)}else h(F>bd)},[j]),K=c.useCallback(E=>{const B=d.current;if(!B)return;const F=B.scrollHeight-B.scrollTop-B.clientHeight;if(I.current&&T==="idle"&&!a&&!E?.force&&F>bd)return;E?.force&&(I.current=!1);const z=B.scrollHeight-B.clientHeight;u.scrollToPosition(Math.max(0,z),E)},[T,a,u]),se=c.useCallback(E=>{if(y.current===E)return;y.current=E,x(E);const B=d.current;if(!B){x(null);return}const F=B.scrollHeight,O=D.current,z=F-O,Q=C.current>0?C.current:B.clientHeight,Se=z-yd,he=Se+Q;let Pe=0;z<he&&(Pe=he-z),Pe!==O&&P(Pe),s&&n(s,E,Pe),A.current=!0,window.requestAnimationFrame(()=>{u.scrollToPosition(Se,{instant:!0}),window.requestAnimationFrame(()=>{x(null)})})},[s,u,n,P]),Y=c.useCallback(E=>{const B=d.current;if(!B||!s)return;E?.isTrusted&&(I.current=!0),u.handleScroll(),U(),T==="idle"&&D.current>0&&q()&&(P(0),S.current=null,f(null),n(s,null,0));const{scrollTop:F,scrollHeight:O,clientHeight:z}=B,Q=(F+z/2)/Math.max(O,1),me=Math.floor(Q*r.length);t(s,me)},[s,T,q,u,r.length,n,U,P,t]);c.useEffect(()=>{const E=d.current;if(E)return E.addEventListener("scroll",Y,{passive:!0}),()=>{E.removeEventListener("scroll",Y)}},[Y]),xd(()=>{if(typeof window>"u")return;L();const E=()=>{M.current!==void 0&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{L()},Bv)};return window.addEventListener("resize",E),()=>{window.removeEventListener("resize",E),M.current!==void 0&&window.clearTimeout(M.current)}},[L]),c.useEffect(()=>{if(s&&s!==b.current){b.current=s,Mr.getInstance().recordSessionStart(s),N.current=r.length,v.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null;const E=o(s);T!=="idle"&&E&&E.anchorId?(S.current=E.anchorId,y.current=E.anchorId,A.current=!0,f(E.anchorId),D.current=E.spacerHeight,g(E.spacerHeight),window.requestAnimationFrame(()=>{const F=d.current;if(!F)return;const O=F.querySelector(`[data-message-id="${E.anchorId}"]`);if(O){const z=F.clientHeight,Q=$(O,z);u.scrollToPosition(Q,{instant:!0})}})):(y.current=null,S.current=null,A.current=!1,f(null),D.current=0,g(0),window.requestAnimationFrame(()=>{K({instant:!0,force:!0})})),x(null),h(!1),I.current=!1,_.current=null}},[T,s,K,r.length,o]),xd(()=>{if(a){N.current=r.length,v.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null;return}if(b.current!==s)return;const E=N.current,B=r.length;if(B>E&&E>0){const F=v.current,O=$s(r[0]),z=$s(r[B-1]),Q=k.current,me=F!==null&&O!==F,Se=Q!==null&&z!==Q,he=me&&!Se,Pe=Se&&!me;if(he){S.current=null,A.current=!1,f(null),P(0),N.current=B,v.current=O,k.current=z;return}if(Pe){const Be=r.slice(E,B).find(zv);if(Be){const W=$s(Be);W&&(S.current=W,f(W),se(W))}else H()}}N.current=B,v.current=r.length>0?$s(r[0]):null,k.current=r.length>0?$s(r[r.length-1]):null},[s,a,H,se,r]),c.useEffect(()=>{const E=d.current;if(!E||typeof ResizeObserver>"u")return;const B=new ResizeObserver(()=>{H(),U()});return B.observe(E),()=>{B.disconnect()}},[H,U]),c.useEffect(()=>{if(typeof window>"u"){U();return}const E=window.requestAnimationFrame(()=>{U()});return()=>{window.cancelAnimationFrame(E)}},[s,r.length,U]),c.useEffect(()=>{m&&(H(),U())},[m,H,U]),c.useEffect(()=>{const E=_.current;_.current=T,E!==null&&E!=="idle"&&T==="idle"&&D.current>0&&q()&&S.current!==null&&(P(0),S.current=null,A.current=!1,f(null),s&&n(s,null,0))},[T,s,q,n,P]),c.useEffect(()=>{U()},[p,U]);const re=c.useRef(new Map),V=c.useCallback(()=>{H(),U()},[H,U]),ae=c.useCallback(E=>{const B=re.current.get(E);if(B)return B;const F={onChunk:()=>{H()},onComplete:()=>{H()},onStreamingCandidate:()=>{},onAnimationStart:()=>{},onAnimatedHeightChange:()=>{H()},onReservationCancelled:()=>{},onReasoningBlock:()=>{}};return re.current.set(E,F),F},[H]);return{scrollRef:d,handleMessageContentChange:V,getAnimationHandlers:ae,showScrollButton:w,scrollToBottom:K,spacerHeight:p,pendingAnchorId:j,hasActiveAnchor:m!==null}};function Hv(s){const t=Date.now()-s,n=Math.floor(t/1e3),o=Math.floor(n/60),a=Math.floor(o/60),i=Math.floor(a/24);return n<60?"just now":o<60?`${o}m ago`:a<24?`${a}h ago`:i<7?`${i}d ago`:new Date(s).toLocaleDateString()}const Uv=({open:s,onOpenChange:r,onScrollToMessage:t})=>{const n=ue(h=>h.currentSessionId),o=yt(h=>n?h.messages.get(n)||[]:[]),a=ue(h=>h.revertToMessage),i=ue(h=>h.forkFromMessage),l=ue(h=>h.loadSessions),[d,u]=c.useState(null),[m,f]=c.useState(""),p=c.useMemo(()=>o.filter(j=>j.info.role==="user").reverse(),[o]),g=c.useMemo(()=>{if(!m.trim())return p;const h=m.toLowerCase();return p.filter(j=>wd(j.parts).toLowerCase().includes(h))},[p,m]),w=async h=>{if(n){u(h);try{await i(n,h),await l(),r(!1)}finally{u(null)}}};return n?e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[e.jsxs(ys,{children:[e.jsxs(bs,{className:"flex items-center gap-2",children:[e.jsx(or,{className:"h-5 w-5"}),"Conversation Timeline"]}),e.jsx(Ns,{children:"Navigate to any point in the conversation or fork a new session"})]}),e.jsxs("div",{className:"relative mt-2",children:[e.jsx(yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ht,{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=wd(h.parts),x=h.info.time.created,y=Hv(x),b=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:[b,"."]}),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:y}),e.jsxs("div",{className:"hidden group-hover:flex gap-1",children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{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(Qn,{className:"h-4 w-4"})})}),e.jsx(nt,{sideOffset:6,children:"Revert from here"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",className:"h-5 w-5 flex items-center justify-center text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50",onClick:N=>{N.stopPropagation(),w(h.info.id)},disabled:d===h.info.id,children:d===h.info.id?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx($t,{className:"h-4 w-4"})})}),e.jsx(nt,{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(Qn,{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($t,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:"Create a new session starting from here"})]})]})]})]})}):null};function wd(s){const r=s.find(t=>t.type==="text");return!r||typeof r.text!="string"?"":r.text.replace(/\n/g," ").slice(0,80)}const tf=()=>{const{currentSessionId:s,messages:r,permissions:t,questions:n,streamingMessageIds:o,isLoading:a,loadMessages:i,loadMoreMessages:l,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,sessionMemoryState:f,openNewSessionDraft:p,isSyncing:g,messageStreamStates:w,trimToViewportWindow:h,sessionActivityPhase:j,newSessionDraft:x}=ue(),{isTimelineDialogOpen:y,setTimelineDialogOpen:b}=_e(),N=c.useMemo(()=>s?o.get(s)??null:null,[s,o]),{isMobile:v}=_t(),k=!!x?.open;c.useEffect(()=>{!s&&!k&&p()},[s,k,p]);const D=c.useMemo(()=>s?r.get(s)||[]:[],[s,r]),C=c.useMemo(()=>s?t.get(s)||[]:[],[s,t]),M=c.useMemo(()=>s?n.get(s)||[]:[],[s,n]);c.useMemo(()=>[...C,...M],[C,M]);const{scrollRef:S,handleMessageContentChange:A,getAnimationHandlers:I,showScrollButton:_,scrollToBottom:T,spacerHeight:P,pendingAnchorId:L,hasActiveAnchor:Z}=Wv({currentSessionId:s,sessionMessages:D,updateViewportAnchor:d,updateActiveTurnAnchor:u,getActiveTurnAnchor:m,isSyncing:g,isMobile:v,sessionActivityPhase:j}),$=!!c.useMemo(()=>s?f.get(s)??null:null,[s,f])?.hasMoreAbove,[H,U]=c.useState(!1);c.useEffect(()=>{U(!1)},[s]);const K=c.useRef(null);c.useLayoutEffect(()=>{if(!(!s||s===K.current)&&(K.current=s,!Z)){const re=S.current;re&&(re.scrollTop=re.scrollHeight-re.clientHeight)}},[s,S,Z]);const se=c.useCallback(async()=>{if(!s||H)return;const re=S.current,V=re?.scrollHeight??null,ae=re?.scrollTop??null;U(!0);try{if(await l(s,"up"),re&&V!==null&&ae!==null){const E=re.scrollHeight-V;re.scrollTop=ae+E}}finally{U(!1)}},[s,H,l,S]),Y=c.useCallback(re=>{const V=S.current;if(!V)return;const ae=V.querySelector(`[data-message-id="${re}"]`);if(ae){const E=V.getBoundingClientRect(),O=ae.getBoundingClientRect().top-E.top+V.scrollTop-50;V.scrollTo({top:O,behavior:"smooth"})}},[S]);return c.useEffect(()=>{if(!s||(r.has(s)?r.get(s)??[]:[]).length>0)return;(async()=>{try{await i(s)}finally{typeof window>"u"?T():window.requestAnimationFrame(()=>{T()})}})()},[s,i,r,T]),!s&&!k?e.jsx("div",{className:"flex flex-col h-full bg-background",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:e.jsx(si,{})}):!s&&k?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(si,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Co,{scrollToBottom:T})})]}):s?a&&D.length===0&&!N&&!r.has(s)?e.jsxs("div",{className:"flex flex-col h-full bg-background gap-0",style:v?{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(V=>e.jsxs("div",{className:"flex gap-3 p-4",children:[e.jsx(ti,{className:"h-8 w-8 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ti,{className:"h-4 w-24"}),e.jsx(ti,{className:"h-20 w-full"})]})]},V))})}),e.jsx(Co,{scrollToBottom:T})]}):D.length===0&&!N?e.jsxs("div",{className:"flex flex-col h-full bg-background transform-gpu",style:v?{paddingBottom:"var(--oc-keyboard-inset, 0px)"}:void 0,children:[e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(si,{})}),e.jsx("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:e.jsx(Co,{scrollToBottom:T})})]}):e.jsxs("div",{className:"flex flex-col h-full bg-background",style:v?{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(ef,{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:!!L,children:e.jsxs("div",{className:"relative z-0 min-h-full",children:[e.jsx(Fv,{messages:D,permissions:C,questions:M,onMessageContentChange:A,getAnimationHandlers:I,hasMoreAbove:$,isLoadingOlder:H,onLoadOlder:se,scrollToBottom:T,pendingAnchorId:L}),P>0&&Z&&e.jsx("div",{"data-role":"active-turn-spacer",style:{height:P},"aria-hidden":"true"})]})}),e.jsx(ml,{containerRef:S})]})}),e.jsxs("div",{className:"relative bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 z-10",children:[_&&D.length>0&&e.jsx("div",{className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2",children:e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>T({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(In,{className:"h-4 w-4"})})}),e.jsx(Co,{scrollToBottom:T})]}),e.jsx(Uv,{open:y,onOpenChange:b,onScrollToMessage:Y})]}):null};class sf extends c.Component{constructor(r){super(r),this.state={hasError:!1}}static getDerivedStateFromError(r){return{hasError:!0,error:r}}componentDidCatch(r,t){this.setState({error:r,errorInfo:t})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?e.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:e.jsxs(vl,{className:"w-full max-w-md",children:[e.jsx(gm,{className:"text-center",children:e.jsxs(xm,{className:"flex items-center justify-center gap-2 text-destructive",children:[e.jsx(yh,{className:"h-5 w-5"}),"Chat Error"]})}),e.jsxs(ym,{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(Ce,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[e.jsx(Ps,{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 Hi=()=>{const s=ue(r=>r.currentSessionId);return e.jsx(sf,{sessionId:s||void 0,children:e.jsx(tf,{})})},vd=12,Vv=[{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"}],Gv=({isActive:s,burstKey:r=0,className:t,durationMs:n=900,bursts:o=Vv,onComplete:a})=>{const i=De.useRef(!1);De.useEffect(()=>{!s&&i.current&&a?.(),s&&(i.current=!0)},[s,a]);const l=De.useMemo(()=>Array.from({length:vd},(d,u)=>{const m=Math.PI*2*u/vd;return{x:Math.cos(m),y:Math.sin(m),delay:u*18}}),[]);return s?e.jsx("div",{className:R("fireworks-overlay pointer-events-none",t),"aria-hidden":"true","data-burst-key":r,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${n}ms`};return e.jsx("div",{className:"firework-burst",style:u,children:l.map((m,f)=>{const p=m.x*d.radius,g=m.y*d.radius,w={"--translate-x":`${p}px`,"--translate-y":`${g}px`,"--particle-delay":`${m.delay}ms`,color:`var(${d.colorVar})`};return e.jsx("span",{className:"firework-particle",style:w},`${d.id}-${f}-${r}`)})},`${d.id}-${r}`)})}):null},qv=({durationMs:s=3400}={})=>{const[r,t]=De.useState({isActive:!1,cycle:0}),n=De.useRef(null),o=De.useCallback(()=>{n.current&&(window.clearTimeout(n.current),n.current=null)},[]),a=De.useCallback(()=>{o(),t(l=>l.isActive?{...l,isActive:!1}:l)},[o]),i=De.useCallback(()=>{o(),t(l=>({isActive:!0,cycle:l.cycle+1})),n.current=window.setTimeout(()=>{t(l=>l.isActive?{...l,isActive:!1}:l),n.current=null},s)},[o,s]);return De.useEffect(()=>()=>o(),[o]),{isActive:r.isActive,burstKey:r.cycle,triggerFireworks:i,dismissFireworks:a}},rf=c.createContext(void 0),jd=({children:s})=>{const{isActive:r,burstKey:t,triggerFireworks:n,dismissFireworks:o}=qv(),a=c.useMemo(()=>({triggerFireworks:n,dismissFireworks:o}),[n,o]);return e.jsxs(rf.Provider,{value:a,children:[s,e.jsx(Gv,{isActive:r,burstKey:t})]})},Kv=()=>{const s=c.useContext(rf);if(!s)throw new Error("useFireworksCelebration must be used within FireworksProvider");return s},Sa=zt()(Yt(As((s,r)=>({selectedProfileId: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 wx();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 Nx();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 kx();return s({discoveredCredentials:t}),!0}catch(t){return console.error("Failed to discover git credentials:",t),s({discoveredCredentials:[]}),!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 vx(n),await r().loadProfiles(),!0}catch(n){return console.error("Failed to create git identity profile:",n),!1}},updateProfile:async(t,n)=>{try{const o=r().profiles.find(i=>i.id===t);if(!o)throw new Error("Profile not found");const a={...o,...n};return await jx(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 Sx(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:Es(()=>ds()),partialize:s=>({selectedProfileId:s.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=Sa);const Yv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Qv=({currentBranch:s,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:o,onCreate:a,disabled:i=!1})=>{const[l,d]=c.useState(!1),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(""),[h,j]=c.useState(!1),x=c.useRef(null),y=c.useMemo(()=>Yv(g),[g]),b=c.useMemo(()=>{const M=u.toLowerCase();return M?r.filter(S=>S.toLowerCase().includes(M)):r},[u,r]),N=c.useMemo(()=>{const M=u.toLowerCase();return M?t.filter(S=>S.toLowerCase().includes(M)):t},[u,t]),v=M=>{if(M===s){d(!1);return}o(M),d(!1),m("")},k=()=>{p(!0),setTimeout(()=>x.current?.focus(),50)},D=async()=>{if(!(!y||h)){j(!0);try{await a(y),w(""),p(!1),d(!1)}finally{j(!1)}}},C=()=>{w(""),p(!1)};return c.useEffect(()=>{l||(m(""),p(!1),w(""))},[l]),e.jsxs(Vt,{open:l,onOpenChange:d,children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8",disabled:i,children:[e.jsx($t,{className:"size-4 text-primary"}),e.jsx("span",{className:"max-w-[140px] truncate font-medium",children:s||"Detached HEAD"}),e.jsx(It,{className:"size-4 opacity-60"})]})})}),e.jsxs(nt,{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(wm,{className:"h-full min-h-0",children:[e.jsx(vm,{placeholder:"Search branches...",value:u,onValueChange:m}),e.jsxs(jm,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[e.jsx(Sm,{children:"No branches found."}),e.jsx(vn,{children:f?e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[e.jsx("input",{ref:x,placeholder:"New branch name",value:g,onChange:M=>w(M.target.value),onKeyDown:M=>{M.key==="Enter"?(M.preventDefault(),D()):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:D,disabled:!y||h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:h?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Kt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:C,disabled:h,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Ht,{className:"size-4"})})]}):e.jsxs(os,{onSelect:k,children:[e.jsx(Kt,{className:"size-4"}),e.jsx("span",{children:"Create new branch..."})]})}),e.jsx(ra,{}),e.jsxs(vn,{heading:"Local branches",children:[b.map(M=>e.jsxs(os,{onSelect:()=>v(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}`)),b.length===0&&e.jsx(os,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),e.jsx(ra,{}),e.jsxs(vn,{heading:"Remote branches",children:[N.map(M=>e.jsx(os,{onSelect:()=>v(M),children:e.jsx("span",{className:"typography-ui-label text-foreground",children:M})},`remote-${M}`)),N.length===0&&e.jsx(os,{disabled:!0,className:"justify-center",children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},Xv=s=>s.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),Jv=({currentBranch:s,onRename:r})=>{const[t,n]=c.useState(!1),[o,a]=c.useState(s||""),[i,l]=c.useState(!1),d=c.useRef(null),u=()=>{!s||!r||(a(s),n(!0),setTimeout(()=>d.current?.focus(),0))},m=async()=>{if(!s||!r||!o.trim())return;const g=Xv(o);if(g===s){n(!1);return}l(!0);try{await r(s,g),n(!1),a("")}finally{l(!1)}},f=()=>{n(!1),a("")},p=g=>{g.key==="Enter"?(g.preventDefault(),m()):g.key==="Escape"&&(g.preventDefault(),f())};return t?e.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:e.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:g=>{g.preventDefault(),m()},children:[e.jsx($t,{className:"size-4 text-primary"}),e.jsx("input",{ref:d,value:o,onChange:g=>a(g.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:p,autoFocus:!0}),e.jsx("button",{type:"submit",disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:i?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Pt,{className:"size-4"})}),e.jsx("button",{type:"button",onClick:f,disabled:i,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:e.jsx(Ht,{className:"size-4"})})]})}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 px-2 py-1 h-8",children:[e.jsx($t,{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(Ce,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:u,title:"Rename branch",children:e.jsx(oo,{className:"size-4"})})]})},Zv=({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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:r,disabled:a,children:[s==="fetch"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Ar,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Fetch"})]})}),e.jsx(nt,{sideOffset:8,children:"Fetch from remote"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:t,disabled:a,children:[s==="pull"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(In,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Pull"})]})}),e.jsx(nt,{sideOffset:8,children:"Pull changes"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:n,disabled:a,children:[s==="push"?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(no,{className:"size-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Push"})]})}),e.jsx(nt,{sideOffset:8,children:"Push changes"})]})]})},e0={branch:$t,briefcase:tl,house:el,graduation:Zi,code:nr,heart:bu,user:Fs},t0={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 nf(s){return s&&t0[s]||"var(--primary)"}const Sd=({icon:s,className:r,colorToken:t})=>{const n=e0[s??"branch"]??Fs;return e.jsx(n,{className:r,style:{color:nf(t)}})},s0=({activeProfile:s,identities:r,onSelect:t,isApplying:n})=>{const o=n||r.length===0;return e.jsxs(Vt,{children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Gt,{asChild:!0,children:e.jsxs(Ce,{variant:"ghost",size:"sm",className:"gap-1.5 px-2 py-1 h-8 typography-ui-label",style:{color:nf(s?.color)},disabled:o,children:[n?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(Sd,{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(It,{className:"size-4 opacity-60"})]})})}),e.jsxs(nt,{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(Dt,{onSelect:()=>t(a),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Sd,{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))})]})},r0=({status:s,localBranches:r,remoteBranches:t,branchInfo:n,syncAction:o,onFetch:a,onPull:i,onPush:l,onCheckoutBranch:d,onCreateBranch:u,onRenameBranch:m,activeIdentityProfile:f,availableIdentities:p,onSelectIdentity:g,isApplyingIdentity:w,isWorktreeMode:h})=>s?e.jsxs("header",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 px-3 py-2 bg-background",children:[h?e.jsx(Jv,{currentBranch:s.current,onRename:m}):e.jsx(Qv,{currentBranch:s.current,localBranches:r,remoteBranches:t,branchInfo:n,onCheckout:d,onCreate:u}),(!!s.tracking||s.ahead>0||s.behind>0)&&e.jsxs(at,{delayDuration:800,children:[e.jsx(it,{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(no,{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(In,{className:"size-3.5 text-primary/70"}),e.jsx("span",{className:"font-semibold text-foreground",children:s.behind})]})]})}),e.jsx(nt,{sideOffset:8,children:s.tracking?`Upstream: ${s.tracking}`:"Unpublished commits (no upstream set yet)"})]}),e.jsx(Zv,{syncAction:o,onFetch:a,onPull:i,onPush:l,disabled:!s}),e.jsx("div",{className:"flex-1"}),e.jsx(s0,{activeProfile:f,identities:p,onSelect:g,isApplying:w})]}):null,n0=({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(Ki,{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(Ce,{variant:"outline",onClick:r,disabled:t,children:[t?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(In,{className:"size-4"}),"Pull ",s," commit",s===1?"":"s"]})]}),of={"?":{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"}},o0=of.M;function a0(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 i0(s){const r=a0(s);return of[r]??o0}const l0=c.memo(function({file:r,checked:t,onToggle:n,onViewDiff:o,onRevert:a,isReverting:i,stats:l}){const d=De.useMemo(()=>i0(r),[r]),u=d.description,m=l?.insertions??0,f=l?.deletions??0,p=De.useCallback(h=>{h.key===" "?(h.preventDefault(),n()):h.key==="Enter"&&(h.preventDefault(),o())},[n,o]),g=De.useCallback(h=>{h.preventDefault(),h.stopPropagation(),n()},[n]),w=De.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(Qi,{className:"size-4 text-primary"}):e.jsx(Xi,{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(at,{delayDuration:200,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:w,disabled:i,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes for ${r.path}`,children:i?e.jsx(cs,{className:"size-3.5 animate-spin"}):e.jsx(Ar,{className:"size-3.5"})})}),e.jsx(nt,{sideOffset:8,children:"Revert changes"})]})]})})}),c0=({changeEntries:s,selectedPaths:r,diffStats:t,revertingPaths:n,onToggleFile:o,onSelectAll:a,onClearSelection:i,onViewDiff:l,onRevertFile:d})=>{const u=r.size,m=s.length;return e.jsxs("section",{className:"flex flex-col rounded-xl border border-border/60 bg-background/70",children:[e.jsxs("header",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border/40",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Changes"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[u,"/",m]}),m>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:a,children:"All"}),e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:i,disabled:u===0,children:"None"})]})]})]}),e.jsx(ft,{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(l0,{file:f,checked:r.has(f.path),stats:t?.[f.path],onToggle:()=>o(f.path),onViewDiff:()=>l(f.path),onRevert:()=>d(f.path),isReverting:n.has(f.path)},f.path))})})]})};function Zr({className:s,variant:r,...t}){return e.jsx(Ce,{variant:r,size:"sm",className:R("h-7 px-2 py-0",s),...t})}const li=38,kd=200,d0=({value:s,onChange:r,placeholder:t="Commit message",disabled:n=!1})=>{const o=c.useRef(null);return c.useEffect(()=>{const a=o.current;if(!a)return;a.style.height=`${li}px`;const i=Math.min(Math.max(a.scrollHeight,li),kd);a.style.height=`${i}px`},[s]),e.jsx(Ts,{ref:o,value:s,onChange:a=>r(a.target.value),placeholder:t,rows:1,disabled:n,className:R("rounded-lg bg-background/80 resize-none overflow-y-auto",n&&"opacity-50"),style:{minHeight:li,maxHeight:kd}})},u0=({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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Insert highlights into commit message",children:e.jsx(In,{className:"size-4"})})}),e.jsx(nt,{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))})]})},m0=({selectedCount:s,commitMessage:r,onCommitMessageChange:t,generatedHighlights:n,onInsertHighlights:o,onClearHighlights:a,onGenerateMessage:i,isGeneratingMessage:l,onCommit:d,onCommitAndPush:u,commitAction:m,isBusy:f})=>{const p=s>0,g=r.trim()&&p&&m===null;return e.jsxs(va,{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(ja,{children:e.jsxs("div",{className:"flex flex-col gap-3 p-3 pt-0",children:[e.jsx(u0,{highlights:n,onInsert:o,onClear:a}),e.jsx(d0,{value:r,onChange:t,placeholder:"Commit message",disabled:m!==null}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:i,disabled:l||m!==null||s===0||f,"aria-label":"Generate commit message",children:l?e.jsx(cs,{className:"size-4 animate-spin"}):e.jsx(uu,{className:"size-4 text-primary"})})}),e.jsx(nt,{sideOffset:8,children:"Generate commit message with AI"})]}),e.jsx("div",{className:"flex-1"}),e.jsx(Zr,{variant:"outline",onClick:d,disabled:!g||l,children:m==="commit"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Committing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Ki,{className:"size-4"}),"Commit"]})}),e.jsx(Zr,{variant:"default",onClick:u,disabled:!g||l,children:m==="commitAndPush"?e.jsxs(e.Fragment,{children:[e.jsx(cs,{className:"size-4 animate-spin"}),"Pushing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(no,{className:"size-4"}),"Commit & Push"]})})]})]})})]})};function Nd(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 f0(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 p0=({entry:s,isExpanded:r,onToggle:t,files:n,isLoadingFiles:o,onCopyHash:a})=>e.jsxs("li",{children:[e.jsxs("button",{type:"button",onClick:t,className:R("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:Nd(s.date),children:Nd(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(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:i=>{i.stopPropagation(),a(s.hash)},children:e.jsx(Gs,{className:"size-3"})})}),e.jsx(nt,{sideOffset:8,children:"Copy SHA"})]})]})]})]}),r&&e.jsx("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:o?e.jsxs("div",{className:"flex items-center gap-2 py-2",children:[e.jsx(cs,{className:"size-4 animate-spin text-muted-foreground"}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Loading files..."})]}):n.length===0?e.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:"No files"}):e.jsx("ul",{className:"space-y-0.5 py-2",children:n.map(i=>e.jsxs("li",{className:"flex items-center gap-2 typography-micro",children:[e.jsx("span",{className:R("font-semibold w-3 text-center",f0(i.changeType)),children:i.changeType}),e.jsx("span",{className:"truncate text-foreground min-w-0",title:i.path,children:i.path}),!i.isBinary&&e.jsxs("span",{className:"shrink-0",children:[e.jsxs("span",{style:{color:"var(--status-success)"},children:["+",i.insertions]}),e.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),e.jsxs("span",{style:{color:"var(--status-error)"},children:["-",i.deletions]})]}),i.isBinary&&e.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:"binary"})]},i.path))})})]}),h0=[{label:"25 commits",value:25},{label:"50 commits",value:50},{label:"100 commits",value:100}],g0=({log:s,isLogLoading:r,logMaxCount:t,onLogMaxCountChange:n,expandedCommitHashes:o,onToggleCommit:a,commitFilesMap:i,loadingCommitHashes:l,onCopyHash:d})=>{const[u,m]=c.useState(!0);return s?e.jsxs(va,{open:u,onOpenChange:m,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[e.jsxs(Sl,{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(js,{value:String(t),onValueChange:f=>n(Number(f)),disabled:r,children:[e.jsx(Ss,{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(Jr,{placeholder:"Commits"})}),e.jsx(ks,{children:h0.map(f=>e.jsx(Bt,{value:String(f.value),children:f.label},f.value))})]})}),u?e.jsx(ua,{className:"size-4 text-muted-foreground"}):e.jsx(It,{className:"size-4 text-muted-foreground"})]})]}),e.jsx(ja,{children:e.jsx(ft,{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(p0,{entry:f,isExpanded:o.has(f.hash),onToggle:()=>a(f.hash),files:i.get(f.hash)??[],isLoadingFiles:l.has(f.hash),onCopyHash:d},f.hash))})})})]}):null};let Bn=null;const x0=()=>{const{currentSessionId:s,sessions:r,worktreeMetadata:t}=ue(),{currentDirectory:n}=mt(),o=s?t.get(s)??void 0:void 0,i=r.find(l=>l.id===s)?.directory;return o?.path??i??n??void 0},y0=()=>{const{git:s}=Pn(),r=x0(),{currentSessionId:t,worktreeMetadata:n}=ue(),o=t?n.get(t)??void 0:void 0,{profiles:a,globalIdentity:i,loadProfiles:l,loadGlobalIdentity:d}=Sa(),u=fl(r??null),m=am(r??null),f=im(r??null),p=by(r??null),g=wy(r??null),w=Xt(ke=>ke.isLoadingStatus),h=Xt(ke=>ke.isLoadingLog),{setActiveDirectory:j,fetchAll:x,fetchStatus:y,fetchBranches:b,fetchLog:N,fetchIdentity:v,setLogMaxCount:k}=Xt(),D=c.useMemo(()=>!Bn||Bn.directory!==r?null:Bn,[r]),[C,M]=c.useState(D?.commitMessage??""),[S,A]=c.useState(null),[I,_]=c.useState(null),[T,P]=c.useState(25),[L,Z]=c.useState(!1),{triggerFireworks:q}=Kv(),[$,H]=c.useState(()=>new Set(D?.selectedPaths??[])),[U,K]=c.useState(!1),[se,Y]=c.useState(new Set),[re,V]=c.useState(!1),[ae,E]=c.useState([]),B=c.useCallback(()=>{E([])},[]),[F,O]=c.useState(new Set),[z,Q]=c.useState(new Map),[me,Se]=c.useState(new Set),[he,Pe]=c.useState(null),ve=c.useCallback(ke=>{navigator.clipboard.writeText(ke).then(()=>{te.success("Commit hash copied")}).catch(()=>{te.error("Failed to copy")})},[]),Be=c.useCallback(ke=>{O($e=>{const Fe=new Set($e);return Fe.has(ke)?Fe.delete(ke):Fe.add(ke),Fe})},[]);c.useEffect(()=>{if(!r||!s)return;const ke=Array.from(F).filter($e=>!z.has($e)&&!me.has($e));ke.length!==0&&(Se($e=>{const Fe=new Set($e);return ke.forEach(ot=>Fe.add(ot)),Fe}),ke.forEach($e=>{s.getCommitFiles(r,$e).then(Fe=>{Q(ot=>new Map(ot).set($e,Fe.files))}).catch(Fe=>{console.error("Failed to fetch commit files:",Fe),Q(ot=>new Map(ot).set($e,[]))}).finally(()=>{Se(Fe=>{const ot=new Set(Fe);return ot.delete($e),ot})})}))},[F,r,s,z,me]),c.useEffect(()=>()=>{if(!r){Bn=null;return}Bn={directory:r,selectedPaths:Array.from($),commitMessage:C}},[C,r,$]),c.useEffect(()=>{l(),d()},[l,d]),c.useEffect(()=>{if(!r||!s?.getRemoteUrl){Pe(null);return}s.getRemoteUrl(r).then(Pe).catch(()=>Pe(null))},[r,s]),c.useEffect(()=>{r&&(j(r),Xt.getState().directories.get(r)?.status||x(r,s,{force:!0}))},[r,j,x,s]);const W=c.useCallback(async(ke=!0)=>{if(r)try{await Promise.all([y(r,s),b(r,s)])}catch($e){if(ke){const Fe=$e instanceof Error?$e.message:"Failed to refresh repository state";te.error(Fe)}}},[r,s,y,b]),G=c.useCallback(async()=>{r&&await N(r,s,T)},[r,s,N,T]),ee=c.useCallback(async()=>{r&&await v(r,s)},[r,s,v]),fe=c.useMemo(()=>{if(!m)return[];const ke=m.files??[],$e=new Map;return ke.forEach(Fe=>{$e.set(Fe.path,Fe)}),Array.from($e.values()).sort((Fe,ot)=>Fe.path.localeCompare(ot.path))},[m]);c.useEffect(()=>{if(!m||fe.length===0){H(new Set),K(!1);return}H(ke=>{const $e=new Set,Fe=ke??new Set;return fe.forEach(ot=>{Fe.has(ot.path)?$e.add(ot.path):U||$e.add(ot.path)}),$e})},[m,fe,U]);const de=async ke=>{if(r){A(ke);try{if(ke==="fetch")await s.gitFetch(r),te.success("Fetched latest updates");else if(ke==="pull"){const $e=await s.gitPull(r);te.success(`Pulled ${$e.files.length} file${$e.files.length===1?"":"s"}`)}else ke==="push"&&(await s.gitPush(r),te.success("Pushed to remote"));await W(!1),await G()}catch($e){const Fe=$e instanceof Error?$e.message:`Failed to ${ke==="pull"?"pull":ke}`;te.error(Fe)}finally{A(null)}}},Ae=async(ke={})=>{if(!r)return;if(!C.trim()){te.error("Please enter a commit message");return}const $e=Array.from($).sort();if($e.length===0){te.error("Select at least one file to commit");return}const Fe=ke.pushAfter?"commitAndPush":"commit";_(Fe);try{await s.createGitCommit(r,C.trim(),{files:$e}),te.success("Commit created successfully"),M(""),H(new Set),K(!1),B(),await W(),ke.pushAfter?(await s.gitPush(r),te.success("Pushed to remote"),q(),await W(!1)):await W(!1),await G()}catch(ot){const Lt=ot instanceof Error?ot.message:"Failed to create commit";te.error(Lt)}finally{_(null)}},Ne=c.useCallback(async()=>{if(r){if($.size===0){te.error("Select at least one file to describe");return}V(!0);try{const{message:ke}=await s.generateCommitMessage(r,Array.from($)),$e=ke.subject?.trim()??"",Fe=Array.isArray(ke.highlights)?ke.highlights:[];$e&&M($e),E(Fe),te.success("Commit message generated")}catch(ke){const $e=ke instanceof Error?ke.message:"Failed to generate commit message";te.error($e)}finally{V(!1)}}},[r,$,s]),Oe=async ke=>{if(!r||!m)return;const $e=m.current??null;try{await s.createBranch(r,ke,$e??"HEAD"),te.success(`Created branch ${ke}`);let Fe=!1;try{await s.checkoutBranch(r,ke),await s.gitPush(r,{remote:"origin",branch:ke,options:["--set-upstream"]}),Fe=!0}catch(ot){const Lt=ot instanceof Error?ot.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: ",Lt]})})}finally{if($e)try{await s.checkoutBranch(r,$e)}catch(ot){console.warn("Failed to restore original branch after creation:",ot)}}await W(),await G(),Fe&&te.success(`Upstream set for ${ke}`)}catch(Fe){const ot=Fe instanceof Error?Fe.message:"Failed to create branch";throw te.error(ot),Fe}},ce=async(ke,$e)=>{if(r)try{await s.renameBranch(r,ke,$e),te.success(`Renamed branch ${ke} to ${$e}`),await W(),await G()}catch(Fe){const ot=Fe instanceof Error?Fe.message:`Failed to rename branch ${ke} to ${$e}`;te.error(ot)}},dt=async ke=>{if(!r)return;const $e=ke.replace(/^remotes\//,"");if(m?.current!==$e)try{await s.checkoutBranch(r,$e),te.success(`Checked out ${$e}`),await W(),await G()}catch(Fe){const ot=Fe instanceof Error?Fe.message:`Failed to checkout ${$e}`;te.error(ot)}},kt=async ke=>{if(r){Z(!0);try{await s.setGitIdentity(r,ke.id),te.success(`Applied "${ke.name}" to repository`),await ee()}catch($e){const Fe=$e instanceof Error?$e.message:"Failed to apply git identity";te.error(Fe)}finally{Z(!1)}}},we=c.useMemo(()=>f?.all?f.all.filter(ke=>!ke.startsWith("remotes/")).sort():[],[f]),ne=c.useMemo(()=>f?.all?f.all.filter(ke=>ke.startsWith("remotes/")).map(ke=>ke.replace(/^remotes\//,"")).sort():[],[f]),Qe=c.useMemo(()=>{const ke=new Map;i&&ke.set(i.id,i);let $e=null;if(he)try{let Fe=he.trim();Fe.startsWith("git@")&&(Fe="https://"+Fe.slice(4).replace(":","/")),Fe.endsWith(".git")&&(Fe=Fe.slice(0,-4));const ot=new URL(Fe);$e=ot.hostname+ot.pathname}catch{}for(const Fe of a){if(Fe.authType!=="token"){ke.set(Fe.id,Fe);continue}const ot=Fe.host;if(!ot){ke.set(Fe.id,Fe);continue}if(!ot.includes("/")){ke.set(Fe.id,Fe);continue}$e&&$e===ot&&ke.set(Fe.id,Fe)}return Array.from(ke.values())},[a,i,he]),ge=c.useMemo(()=>{if(g?.userName&&g?.userEmail){const ke=a.find($e=>$e.userName===g.userName&&$e.userEmail===g.userEmail);return ke||(i&&i.userName===g.userName&&i.userEmail===g.userEmail?i:{id:"local-config",name:g.userName,userName:g.userName,userEmail:g.userEmail,sshKey:g.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return i??null},[g,a,i]),ye=fe.length,qe=$.size,Ze=w||S!==null||I!==null,We=ye>0,Re=ke=>{H($e=>{const Fe=new Set($e);return Fe.has(ke)?Fe.delete(ke):Fe.add(ke),Fe}),K(!0)},Xe=()=>{const ke=new Set(fe.map($e=>$e.path));H(ke),K(!0)},Ct=()=>{H(new Set),K(!0)},ct=c.useCallback(async ke=>{if(r){Y($e=>{const Fe=new Set($e);return Fe.add(ke),Fe});try{await s.revertGitFile(r,ke),te.success(`Reverted ${ke}`),await W(!1)}catch($e){const Fe=$e instanceof Error?$e.message:"Failed to revert changes";te.error(Fe)}finally{Y($e=>{const Fe=new Set($e);return Fe.delete(ke),Fe})}}},[r,W,s]),At=c.useCallback(()=>{if(ae.length===0)return;const ke=ae.map($e=>$e.trim()).filter(Boolean);if(ke.length===0){B();return}M($e=>{const Fe=$e.trim(),ot=Fe.length>0?`
98
-
99
- `:"";return`${Fe}${ot}${ke.join(`
100
- `)}`.trim()})},[ae,B]),Mt=c.useCallback(ke=>{P(ke),r&&(k(r,ke),N(r,s,ke))},[r,k,N,s]);return r?w&&u===null?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(cs,{className:"size-4 animate-spin"}),e.jsx("span",{className:"typography-ui-label",children:"Checking repository..."})]})}):u===!1?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[e.jsx($t,{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(r0,{status:m,localBranches:we,remoteBranches:ne,branchInfo:f?.branches,syncAction:S,onFetch:()=>de("fetch"),onPull:()=>de("pull"),onPush:()=>de("push"),onCheckoutBranch:dt,onCreateBranch:Oe,onRenameBranch:ce,activeIdentityProfile:ge,availableIdentities:Qe,onSelectIdentity:kt,isApplyingIdentity:L,isWorktreeMode:!!o}),e.jsx(ft,{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:[We?e.jsx(c0,{changeEntries:fe,selectedPaths:$,diffStats:m?.diffStats,revertingPaths:se,onToggleFile:Re,onSelectAll:Xe,onClearSelection:Ct,onViewDiff:ke=>_e.getState().navigateToDiff(ke),onRevertFile:ct}):e.jsx("div",{className:"lg:col-span-2 flex justify-center",children:e.jsx(n0,{behind:m?.behind??0,onPull:()=>de("pull"),isPulling:S==="pull"})}),fe.length>0&&e.jsx(m0,{selectedCount:qe,commitMessage:C,onCommitMessageChange:M,generatedHighlights:ae,onInsertHighlights:At,onClearHighlights:B,onGenerateMessage:Ne,isGeneratingMessage:re,onCommit:()=>Ae({pushAfter:!1}),onCommitAndPush:()=>Ae({pushAfter:!0}),commitAction:I,isBusy:Ze})]}),e.jsx(g0,{log:p,isLogLoading:h,logMaxCount:T,onLogMaxCountChange:Mt,expandedCommitHashes:F,onToggleCommit:Be,commitFilesMap:z,loadingCommitHashes:me,onCopyHash:ve})]})})]}):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."})})},b0=1e6;function zr(s){let r=s.trim();for(;r.length>1&&r.endsWith("/");)r=r.slice(0,-1);return r}const Mo=s=>({directory:s,terminalSessionId:null,isConnecting:!1,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),Cd=zt((s,r)=>({sessions:new Map,nextChunkId:1,getTerminalSession:t=>{const n=zr(t);return r().sessions.get(n)},setTerminalSession:(t,n)=>{const o=zr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o),u=!l||l.terminalSessionId!==n.sessionId?Mo(o):l??Mo(o);return i.set(o,{...u,terminalSessionId:n.sessionId,directory:o,isConnecting:!1,updatedAt:Date.now()}),{sessions:i}})},setConnecting:(t,n)=>{const o=zr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??Mo(o);return i.set(o,{...l,isConnecting:n,updatedAt:Date.now()}),{sessions:i}})},appendToBuffer:(t,n)=>{if(!n)return;const o=zr(t);s(a=>{const i=new Map(a.sessions),l=i.get(o)??Mo(o),d=a.nextChunkId,u={id:d,data:n},m=[...l.bufferChunks,u];let f=l.bufferLength+n.length;for(;f>b0&&m.length>1;){const g=m.shift();if(!g)break;f-=g.data.length}const p=m.map(g=>g.data).join("");return i.set(o,{...l,buffer:p,bufferChunks:m,bufferLength:f,updatedAt:Date.now()}),{sessions:i,nextChunkId:d+1}})},clearTerminalSession:t=>{const n=zr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i&&a.set(n,{...i,terminalSessionId:null,isConnecting:!1,updatedAt:Date.now()}),{sessions:a}})},clearBuffer:t=>{const n=zr(t);s(o=>{const a=new Map(o.sessions),i=a.get(n);return i?(a.set(n,{...i,buffer:"",bufferChunks:[],bufferLength:0,updatedAt:Date.now()}),{sessions:a}):o})},removeTerminalSession:t=>{const n=zr(t);s(o=>{const a=new Map(o.sessions);return a.delete(n),{sessions:a}})},clearAllTerminalSessions:()=>{s({sessions:new Map,nextChunkId:1})}})),af=()=>({uiFont:"ibm-plex-sans",monoFont:"ibm-plex-mono"}),w0=[{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'}],v0=[{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'}],lf=s=>Object.fromEntries(s.map(r=>[r.id,r])),Md=lf(w0),Wr=lf(v0),j0="ibm-plex-sans",Ho="ibm-plex-mono";function S0(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 k0(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 ci=null;function N0(){return ci||(ci=vh.load()),ci}function C0(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 Ui=c.forwardRef(({sessionKey:s,chunks:r,onInput:t,onResize:n,theme:o,fontFamily:a,fontSize:i,className:l,enableTouchScroll:d},u)=>{const m=c.useRef(null),f=c.useRef(null),p=c.useRef(null),g=c.useRef(null),w=c.useRef(t),h=c.useRef(n),j=c.useRef(null),x=c.useRef(""),y=c.useRef(null),b=c.useRef(!1),N=c.useRef(null),v=c.useRef(null),k=c.useRef(null),D=c.useRef(0),C=c.useRef(null),[,M]=c.useReducer($=>$+1,0),[S,A]=c.useReducer($=>$+1,0);w.current=t,h.current=n;const I=c.useCallback(($,H)=>{const U=C.current,K=m.current;if(!U||!K)return;const se=K.getBoundingClientRect(),Y=se.left+se.width/2,re=se.top+se.height-12,V=typeof $=="number"?$:Y,ae=typeof H=="number"?H:re,E=8,B=Math.max(E,Math.min(se.width-E,V-se.left)),F=Math.max(E,Math.min(se.height-E,ae-se.top));U.style.left=`${B}px`,U.style.top=`${F}px`,U.style.bottom="";try{U.focus({preventScroll:!0})}catch{try{U.focus()}catch{}}},[]),_=c.useCallback(()=>{x.current="",y.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(y.current),y.current=null,b.current=!1,N.current=null},[]),T=c.useCallback(()=>{const $=g.current,H=p.current,U=m.current;if(!$||!H||!U)return;const K=U.getBoundingClientRect();if(!(K.width<24||K.height<24))try{$.fit();const se={cols:H.cols,rows:H.rows},Y=j.current;(!Y||Y.cols!==se.cols||Y.rows!==se.rows)&&(j.current=se,h.current(se.cols,se.rows))}catch{}},[]),P=c.useCallback(()=>{if(b.current)return;const $=p.current;if(!$){_();return}if(!x.current)return;const H=x.current;x.current="",b.current=!0,$.write(H,()=>{b.current=!1,x.current&&(typeof window<"u"?y.current=window.requestAnimationFrame(()=>{y.current=null,P()}):P())})},[_]),L=c.useCallback(()=>{y.current===null&&(typeof window<"u"?y.current=window.requestAnimationFrame(()=>{y.current=null,P()}):P())},[P]),Z=c.useCallback($=>{$&&(x.current+=$,L())},[L]),q=c.useCallback(()=>{if(v.current?.(),v.current=null,k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),!d){D.current=0;return}const $=m.current;if(!$)return;const H=p.current;if(!H)return;D.current=0;const U=2.2,K=2.8,se=25,Y=.25,re=8,V=.05,ae=.015,E={lastY:null,lastTime:null,velocity:0,rafId:null,startX:null,startY:null,didMove:!1},B=()=>typeof performance<"u"?performance.now():Date.now(),F=Math.max(12,Math.round(i*1.35));let O=0;const z=G=>{if(!G)return!1;const ee=H.getViewportY(),fe=O+G,de=Math.trunc(fe/F);return O=fe-de*F,de!==0&&H.scrollLines(de),H.getViewportY()!==ee},Q=()=>{E.rafId!==null&&typeof window<"u"&&window.cancelAnimationFrame(E.rafId),E.rafId=null},me={passive:!1,capture:!1};if(typeof window<"u"&&"PointerEvent"in window){const G=Object.assign(E,{pointerId:null,startX:null,startY:null,moved:!1}),ee=6,fe=Oe=>{if(Oe.pointerType==="touch"){Q(),G.pointerId=Oe.pointerId,G.startX=Oe.clientX,G.startY=Oe.clientY,G.moved=!1,G.lastY=Oe.clientY,G.lastTime=B(),G.velocity=0;try{$.setPointerCapture(Oe.pointerId)}catch{}}},de=Oe=>{if(Oe.pointerType!=="touch"||G.pointerId!==Oe.pointerId)return;if(G.startX!==null&&G.startY!==null&&!G.moved){const qe=Oe.clientX-G.startX,Ze=Oe.clientY-G.startY;Math.hypot(qe,Ze)>=ee&&(G.moved=!0)}if(G.lastY===null){G.lastY=Oe.clientY,G.lastTime=B();return}const ce=G.lastY,dt=G.lastTime??B(),kt=B();G.lastY=Oe.clientY,G.lastTime=kt;const we=ce-Oe.clientY;if(Math.abs(we)<1)return;const ne=Math.max(kt-dt,8),Qe=U+Math.min(K,Math.abs(we)/se),ge=we*Qe,ye=ge/ne;G.velocity=G.velocity*(1-Y)+ye*Y,G.velocity>re?G.velocity=re:G.velocity<-re&&(G.velocity=-re),G.moved&&(Oe.cancelable&&Oe.preventDefault(),Oe.stopPropagation()),z(ge)},Ae=Oe=>{if(Oe.pointerType!=="touch"||G.pointerId!==Oe.pointerId)return;const ce=!G.moved;G.pointerId=null,G.startX=null,G.startY=null,G.moved=!1,G.lastY=null,G.lastTime=null;try{$.releasePointerCapture(Oe.pointerId)}catch{}if(ce){I(Oe.clientX,Oe.clientY);return}if(typeof window>"u")return;if(Math.abs(G.velocity)<V){G.velocity=0;return}let dt=B();const kt=()=>{const we=B(),ne=Math.max(we-dt,8);dt=we;const Qe=z(G.velocity*ne)??!1,ge=Math.sign(G.velocity),ye=Math.max(0,Math.abs(G.velocity)-ae*ne);if(G.velocity=ye*ge,!Qe||ye<=V){Q(),G.velocity=0;return}G.rafId=window.requestAnimationFrame(kt)};G.rafId=window.requestAnimationFrame(kt)};$.addEventListener("pointerdown",fe,me),$.addEventListener("pointermove",de,me),$.addEventListener("pointerup",Ae,me),$.addEventListener("pointercancel",Ae,me);const Ne=$.style.touchAction;$.style.touchAction="manipulation",v.current=()=>{Q(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),D.current=0,$.removeEventListener("pointerdown",fe,me),$.removeEventListener("pointermove",de,me),$.removeEventListener("pointerup",Ae,me),$.removeEventListener("pointercancel",Ae,me),$.style.touchAction=Ne};return}const he=6,Pe=G=>{G.touches.length===1&&(Q(),E.lastY=G.touches[0].clientY,E.lastTime=B(),E.velocity=0,E.startX=G.touches[0].clientX,E.startY=G.touches[0].clientY,E.didMove=!1)},ve=G=>{if(G.touches.length!==1){E.lastY=null,E.lastTime=null,E.velocity=0,E.startX=null,E.startY=null,E.didMove=!1,Q();return}const ee=G.touches[0].clientX,fe=G.touches[0].clientY;if(E.startX!==null&&E.startY!==null&&!E.didMove){const ne=ee-E.startX,Qe=fe-E.startY;Math.hypot(ne,Qe)>=he&&(E.didMove=!0)}if(E.lastY===null){E.lastY=fe,E.lastTime=B();return}const de=E.lastY,Ae=E.lastTime??B(),Ne=B();E.lastY=fe,E.lastTime=Ne;const Oe=de-fe;if(Math.abs(Oe)<1)return;const ce=Math.max(Ne-Ae,8),dt=U+Math.min(K,Math.abs(Oe)/se),kt=Oe*dt,we=kt/ce;E.velocity=E.velocity*(1-Y)+we*Y,E.velocity>re?E.velocity=re:E.velocity<-re&&(E.velocity=-re),E.didMove&&(G.preventDefault(),G.stopPropagation()),z(kt)},Be=G=>{const ee=!E.didMove;E.lastY=null,E.lastTime=null;const fe=E.velocity;if(E.startX=null,E.startY=null,E.didMove=!1,ee){const Ne=G.changedTouches?.[0];I(Ne?.clientX,Ne?.clientY);return}if(typeof window>"u")return;if(Math.abs(fe)<V){E.velocity=0;return}let de=B();const Ae=()=>{const Ne=B(),Oe=Math.max(Ne-de,8);de=Ne;const ce=z(E.velocity*Oe)??!1,dt=Math.sign(E.velocity),kt=Math.max(0,Math.abs(E.velocity)-ae*Oe);if(E.velocity=kt*dt,!ce||kt<=V){Q(),E.velocity=0;return}E.rafId=window.requestAnimationFrame(Ae)};E.rafId=window.requestAnimationFrame(Ae)};$.addEventListener("touchstart",Pe,me),$.addEventListener("touchmove",ve,me),$.addEventListener("touchend",Be,me),$.addEventListener("touchcancel",Be,me);const W=$.style.touchAction;$.style.touchAction="manipulation",v.current=()=>{Q(),k.current!==null&&typeof window<"u"&&(window.clearTimeout(k.current),k.current=null),D.current=0,$.removeEventListener("touchstart",Pe,me),$.removeEventListener("touchmove",ve,me),$.removeEventListener("touchend",Be,me),$.removeEventListener("touchcancel",Be,me),$.style.touchAction=W}},[d,I,i]);return c.useEffect(()=>{let $=!1,H=null,U=null,K=[];const se=m.current;return se?(se.tabIndex=0,(async()=>{try{const re=await N0();if($)return;const V=k0(a,i,o,re),ae=new bh(V),E=new wh;H=ae,p.current=ae,g.current=E,ae.loadAddon(E),ae.open(se),A();const B=C0(se);B?(B.classList.add("overlay-scrollbar-target","overlay-scrollbar-container"),f.current=B,M()):f.current=null,T(),q(),ae.focus(),K=[ae.onData(F=>{w.current(F)})],U=new ResizeObserver(()=>{T()}),U.observe(se),typeof window<"u"&&window.setTimeout(()=>{T()},0)}catch{}})(),()=>{$=!0,v.current?.(),v.current=null,K.forEach(re=>re.dispose()),U?.disconnect(),H?.dispose(),p.current=null,g.current=null,f.current=null,j.current=null,_()}):void 0},[T,a,i,q,o,_]),c.useEffect(()=>{const $=p.current;$&&($.reset(),_(),j.current=null,T(),$.focus())},[s,S,T,_]),c.useEffect(()=>(q(),()=>{v.current?.(),v.current=null}),[q,s]),c.useEffect(()=>{const $=p.current;if(!$)return;if(r.length===0){N.current!==null&&($.reset(),_(),T());return}const H=N.current;let U;if(H===null)U=r;else{const K=r.findIndex(se=>se.id===H);U=K>=0?r.slice(K+1):r}U.length>0&&Z(U.map(K=>K.data).join("")),N.current=r[r.length-1].id},[r,S,Z,T,_]),c.useImperativeHandle(u,()=>({focus:()=>{if(d){I();return}p.current?.focus()},clear:()=>{const $=p.current;$&&($.reset(),_(),T())},fit:()=>{T()}}),[d,I,T,_]),e.jsxs("div",{ref:m,className:R("relative h-full w-full terminal-viewport-container",l),style:{backgroundColor:o.background},onClick:$=>{d?I($.clientX,$.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:$=>{const H=String($.currentTarget.value||"");if(!H)return;const U=H.replace(/\r\n|\r|\n/g,"\r");w.current(U),$.currentTarget.value=""},onKeyDown:$=>{$.key==="Backspace"&&($.currentTarget.value||w.current(""))}}):null,f.current&&!d?e.jsx(ml,{containerRef:f,disableHorizontal:!0,className:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero"}):null]})});Ui.displayName="TerminalViewport";const Dd=13,M0={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},Do={ctrl:"5",cmd:"3"},D0={retry:{maxRetries:3,initialDelayMs:500,maxDelayMs:8e3},connectionTimeoutMs:1e4},A0=(s,r)=>{if(r)switch(s){case"arrow-up":return`\x1B[1;${Do[r]}A`;case"arrow-down":return`\x1B[1;${Do[r]}B`;case"arrow-right":return`\x1B[1;${Do[r]}C`;case"arrow-left":return`\x1B[1;${Do[r]}D`}return M0[s]??null},E0=()=>{const{terminal:s}=Pn(),{currentTheme:r}=on(),{monoFont:t}=af(),{isMobile:n,hasTouchInput:o}=_t(),{currentSessionId:a,sessions:i,worktreeMetadata:l}=ue(),d=a?l.get(a)??void 0:void 0,u=c.useMemo(()=>{if(d?.path)return d.path;if(!a)return null;const ee=i.find(de=>de.id===a),fe=typeof ee?.directory=="string"?ee.directory:null;return fe&&fe.length>0?fe:null},[a,i,d]),{currentDirectory:m,homeDirectory:f}=mt(),p=u||m||null,g=c.useMemo(()=>p?f?p===f?"~":p.startsWith(f+"/")?"~"+p.slice(f.length):p:p:"",[p,f]),w=Cd(),h=w.sessions,j=w.setTerminalSession,x=w.setConnecting,y=w.appendToBuffer,b=w.clearTerminalSession,N=w.removeTerminalSession,v=w.clearBuffer,k=c.useMemo(()=>{if(p)return h.get(p)},[h,p]),D=k?.terminalSessionId??null,C=k?.bufferChunks??[],M=k?.bufferLength??0,S=k?.isConnecting??!1,A=D,[I,_]=c.useState(null),[T,P]=c.useState(!1),[L,Z]=c.useState(null),[q,$]=c.useState(!1),H=c.useRef(null),U=c.useRef(null),K=c.useRef(A),se=c.useRef(p),Y=c.useRef(null),V=_e(ee=>ee.activeMainTab)==="terminal";c.useEffect(()=>{K.current=A},[A]),c.useEffect(()=>{se.current=p},[p]),c.useEffect(()=>{!n&&L!==null&&Z(null)},[n,L,Z]),c.useEffect(()=>{!A&&L!==null&&Z(null)},[A,L,Z]);const ae=c.useCallback(()=>{H.current?.(),H.current=null,U.current=null},[]);c.useEffect(()=>()=>{ae(),K.current=null},[ae]);const E=c.useCallback(ee=>{if(U.current===ee)return;ae();const fe=s.connect(ee,{onEvent:de=>{const Ae=se.current;if(Ae)switch(de.type){case"connected":{(de.runtime||de.ptyBackend)&&console.log(`[Terminal] connected runtime=${de.runtime??"unknown"} pty=${de.ptyBackend??"unknown"}`),x(Ae,!1),_(null),P(!1),Y.current?.focus();break}case"reconnecting":{const Ne=de.attempt??0,Oe=de.maxAttempts??3;_(`Reconnecting (${Ne}/${Oe})...`),P(!1);break}case"data":{de.data&&y(Ae,de.data);break}case"exit":{const Ne=typeof de.exitCode=="number"?de.exitCode:null,Oe=typeof de.signal=="number"?de.signal:null;y(Ae,`\r
101
- [Process exited${Ne!==null?` with code ${Ne}`:""}${Oe!==null?` (signal ${Oe})`:""}]\r
102
- `),b(Ae),x(Ae,!1),_("Terminal session ended"),P(!1),ae();break}}},onError:(de,Ae)=>{const Ne=se.current;if(!Ne)return;const Oe=Ae?`Connection failed: ${de.message}`:de.message||"Terminal stream connection error";_(Oe),P(!!Ae),Ae&&(x(Ne,!1),ae(),N(Ne))}},D0);H.current=()=>{fe.close(),U.current=null},U.current=ee},[y,b,ae,N,x,s,_]);c.useEffect(()=>{let ee=!1;if(!p){_(a?"No working directory available for terminal.":"Select a session to open the terminal."),ae();return}return(async()=>{const de=p;if(!se.current||se.current!==de)return;let Ne=Cd.getState().getTerminalSession(de)?.terminalSessionId??null;if(!Ne){_(null),P(!1),x(de,!0);try{const Oe=await s.createSession({cwd:de});if(ee){try{await s.close(Oe.sessionId)}catch{}return}j(de,Oe),Ne=Oe.sessionId}catch(Oe){ee||(_(Oe instanceof Error?Oe.message:"Failed to start terminal session"),P(!0),x(de,!1));return}}!Ne||ee||(K.current=Ne,E(Ne))})(),()=>{ee=!0,K.current=null,ae()}},[a,p,A,N,x,j,E,ae,s]);const B=c.useCallback(async()=>{if(!p||q)return;$(!0),_(null),P(!1),ae();const ee=K.current;try{if(s.restartSession&&ee){const fe=await s.restartSession(ee,{cwd:p});j(p,fe),K.current=fe.sessionId,E(fe.sessionId)}else{if(ee)try{await s.close(ee)}catch{}N(p)}}catch(fe){_(fe instanceof Error?fe.message:"Failed to restart terminal"),P(!0)}finally{$(!1)}},[p,q,ae,s,j,E,N]),F=c.useCallback(async()=>{if(p&&!q){$(!0),_(null),P(!1),ae();try{s.forceKill&&await s.forceKill({cwd:p})}catch{}N(p),v(p),Y.current?.clear(),await new Promise(ee=>setTimeout(ee,100));try{x(p,!0);const ee=await s.createSession({cwd:p});j(p,ee),K.current=ee.sessionId,E(ee.sessionId)}catch(ee){_(ee instanceof Error?ee.message:"Failed to create terminal"),P(!0),x(p,!1)}finally{$(!1)}}},[p,q,ae,s,N,v,x,j,E]),O=c.useCallback(()=>{if(!p)return;v(p),Y.current?.clear(),Y.current?.focus();const ee=K.current;ee&&s.sendInput(ee,"\f").catch(fe=>{_(fe instanceof Error?fe.message:"Failed to refresh prompt")})},[v,p,_,s]),z=c.useCallback(ee=>{if(!ee)return;let fe=ee,de=!1;if(L&&ee.length>0){const Ne=ee[0];if(Ne.length===1&&/[a-zA-Z]/.test(Ne)){const Oe=Ne.toUpperCase();(L==="ctrl"||L==="cmd")&&(fe=String.fromCharCode(Oe.charCodeAt(0)&31),de=!0)}de||(de=!0)}const Ae=K.current;Ae&&(s.sendInput(Ae,fe).catch(Ne=>{_(Ne instanceof Error?Ne.message:"Failed to send input")}),de&&(Z(null),Y.current?.focus()))},[L,Z,s]),Q=c.useCallback((ee,fe)=>{const de=K.current;de&&s.resize({sessionId:de,cols:ee,rows:fe}).catch(()=>{})},[s]),me=c.useCallback(ee=>{Z(fe=>fe===ee?null:ee),Y.current?.focus()},[Z]),Se=c.useCallback(ee=>{const fe=A0(ee,L);fe&&(z(fe),Z(null),Y.current?.focus())},[L,z,Z]);c.useEffect(()=>{if(!n||!L||!A)return;const ee=fe=>{if(fe.repeat)return;const de=fe.key;if(!de||de==="Control"||de==="Meta"||de==="Alt"||de==="Shift")return;const Ae=de.length===1?de.toLowerCase():de,Ne=fe.code??"",Oe=Ne.startsWith("Key")&&Ne.length===4?Ne.slice(3).toUpperCase():null,ce=de.length===1&&/[a-zA-Z]/.test(de)?de.toUpperCase():Oe,dt={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc",tab:"tab",enter:"enter",arrowup:"arrow-up",arrowdown:"arrow-down",arrowleft:"arrow-left",arrowright:"arrow-right",escape:"esc"};if(Ae in dt){fe.preventDefault(),fe.stopPropagation(),Se(dt[Ae]);return}if(L==="ctrl"&&ce&&ce.length===1&&ce>="A"&&ce<="Z"){const kt=String.fromCharCode(ce.charCodeAt(0)&31);fe.preventDefault(),fe.stopPropagation(),z(kt),Z(null),Y.current?.focus()}};return window.addEventListener("keydown",ee),()=>{window.removeEventListener("keydown",ee)}},[L,Se,z,n,Z,A]);const he=c.useMemo(()=>{const ee=Wr[Ho].stack;if(typeof window>"u")return(Wr[t]??Wr[Ho]).stack;const de=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return de&&de.trim().length>0?de.trim():(Wr[t]??Wr[Ho]).stack??ee},[t]),Pe=c.useMemo(()=>S0(r),[r]),ve=c.useMemo(()=>`${p??"no-dir"}::${A??"pending"}`,[p,A]);c.useEffect(()=>{if(!V)return;const ee=Y.current;if(!ee)return;const fe=()=>{ee.fit()};if(typeof window<"u"){const de=window.requestAnimationFrame(()=>{fe(),ee.focus()}),Ae=[220,400].map(Ne=>window.setTimeout(fe,Ne));return()=>{window.cancelAnimationFrame(de),Ae.forEach(Ne=>window.clearTimeout(Ne))}}fe()},[V,ve,A]);const Be=I?.includes("Reconnecting"),W=I?Be?e.jsx(jh,{size:20,className:"text-amber-400"}):e.jsx(Ht,{size:20,className:"text-destructive"}):A&&!S&&!q?e.jsx(Po,{size:20,className:"text-emerald-400"}):S||q?e.jsx(ki,{size:20,className:"text-amber-400 animate-pulse"}):e.jsx(ki,{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:B,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const G=!A||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:[W,e.jsxs(Ce,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:O,disabled:!M,title:"Clear output",type:"button",children:[e.jsx(qs,{size:16}),"Clear"]}),e.jsxs(Ce,{size:"sm",variant:"default",className:"h-7 px-2 py-0",onClick:B,disabled:q,title:"Restart terminal session",type:"button",children:[e.jsx(Ps,{size:16,className:R((S||q)&&"animate-spin")}),"Restart"]})]})]}),n?e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:[e.jsx(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 px-2 text-xs",onClick:()=>Se("esc"),disabled:G,children:"Esc"}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("tab"),disabled:G,children:[e.jsx(zl,{size:16}),e.jsx("span",{className:"sr-only",children:"Tab"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:L==="ctrl"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>me("ctrl"),disabled:G,children:[e.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),e.jsx("span",{className:"sr-only",children:"Control modifier"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:L==="cmd"?"default":"outline",className:"h-6 w-9 p-0",onClick:()=>me("cmd"),disabled:G,children:[e.jsx(en,{size:16}),e.jsx("span",{className:"sr-only",children:"Command modifier"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("arrow-up"),disabled:G,children:[e.jsx(no,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow up"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("arrow-left"),disabled:G,children:[e.jsx(wu,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow left"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("arrow-down"),disabled:G,children:[e.jsx(In,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow down"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("arrow-right"),disabled:G,children:[e.jsx(zl,{size:16}),e.jsx("span",{className:"sr-only",children:"Arrow right"})]}),e.jsxs(Ce,{type:"button",size:"sm",variant:"outline",className:"h-6 w-9 p-0",onClick:()=>Se("enter"),disabled:G,children:[e.jsx(Qn,{size:16}),e.jsx("span",{className:"sr-only",children:"Enter"})]})]}):null]}),e.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Pe.background},"data-keyboard-avoid":"true",children:[e.jsx("div",{className:"h-full w-full box-border px-3 pt-3 pb-4",children:V?n?e.jsx(Ui,{ref:ee=>{Y.current=ee},sessionKey:ve,chunks:C,onInput:z,onResize:Q,theme:Pe,fontFamily:he,fontSize:Dd,enableTouchScroll:o},ve):e.jsx(ft,{outerClassName:"h-full",className:"h-full w-full",disableHorizontal:!0,children:e.jsx(Ui,{ref:ee=>{Y.current=ee},sessionKey:ve,chunks:C,onInput:z,onResize:Q,theme:Pe,fontFamily:he,fontSize:Dd,enableTouchScroll:o},ve)}):null}),I&&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:I}),T&&e.jsx(Ce,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:F,disabled:q,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]})]})},cf=[{id:"sessions",label:"Sessions",description:"Browse and manage chat sessions scoped to the current directory.",icon:Yi},{id:"agents",label:"Agents",description:"Configure OpenCode agents, prompts, and permissions.",icon:ar},{id:"commands",label:"Commands",description:"Create and maintain custom slash commands for OpenCode.",icon:en},{id:"skills",label:"Skills",description:"Create reusable instruction files for agents to load on-demand.",icon:yu},{id:"providers",label:"Providers",description:"Configure AI model providers and API credentials.",icon:Xn},{id:"git-identities",label:"Git Identities",description:"Manage Git profiles with different credentials and SSH keys.",icon:$t},{id:"settings",label:"OpenChamber",description:"OpenChamber app settings: themes, fonts, and preferences.",icon:Yr}],I0={},P0={},T0={};cf.forEach(s=>{I0[s.id]=s.label,P0[s.id]=s.description,T0[s.id]=s});const F0=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",R0=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},Ad=s=>{const r=R0(s);if(r.length===0)return;const t={};for(const i of r)i.permission&&((t[i.permission]||={})[i.pattern]=i.action);const n=t["*"]?.["*"],o=Object.keys(t);if(o.length===1&&o[0]==="*"&&Object.keys(t["*"]||{}).length===1&&t["*"]?.["*"])return t["*"]["*"];const a={};for(const i of o){const l=t[i],d=Object.keys(l);if(d.length===1&&d[0]==="*"&&i!=="*"){const u=l["*"],m=F0(i);if(n){if(u===n)continue}else if(u===m)continue;a[i]=u}else i==="*"&&d.length===1&&d[0]==="*"?a[i]=l["*"]:a[i]=l}return Object.keys(a).length>0?a:void 0},_0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedAgentName:a,agents:i,setSelectedAgent:l,setAgentDraft:d,createAgent:u,deleteAgent:m,loadAgents:f}=_r(),{setSidebarOpen:p}=_e(),{isMobile:g}=_t(),[w,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=w?"bg-transparent":j?"bg-background":"bg-sidebar",y=()=>{const I="new-agent";let _=I,T=1;for(;i.some(P=>P.name===_);)_=`${I}-${T}`,T++;d({name:_,scope:"user"}),l(_),s?.(),g&&p(!1)},b=async I=>{if(Hr(I)){te.error("Built-in agents cannot be deleted");return}window.confirm(`Are you sure you want to delete agent "${I.name}"?`)&&(await m(I.name)?te.success(`Agent "${I.name}" deleted successfully`):te.error("Failed to delete agent"))},N=async I=>{Hr(I)&&window.confirm(`Are you sure you want to reset agent "${I.name}" to its default configuration?`)&&(await m(I.name)?te.success(`Agent "${I.name}" reset to default`):te.error("Failed to reset agent"))},v=I=>{const _=I.name;let T=1,P=`${_}-copy`;for(;i.some($=>$.name===P);)T++,P=`${_}-copy-${T}`;const L=I,Z=I.model?.providerID&&I.model?.modelID?`${I.model.providerID}/${I.model.modelID}`:null,q=I;d({name:P,scope:L.scope||"user",description:I.description,model:Z,temperature:I.temperature,top_p:I.topP,prompt:I.prompt,mode:I.mode,permission:Ad(I.permission),disable:q.disable}),l(P),g&&p(!1)},k=I=>{o(I.name),t(I)},D=async()=>{if(!r)return;const I=n.trim().replace(/\s+/g,"-");if(!I){te.error("Agent name is required");return}if(I===r.name){t(null);return}if(i.some(L=>L.name===I)){te.error("An agent with this name already exists");return}const _=r.model?.providerID&&r.model?.modelID?`${r.model.providerID}/${r.model.modelID}`:null,T=r;await u({name:I,description:r.description,model:_,temperature:r.temperature,top_p:r.topP,prompt:r.prompt,mode:r.mode,permission:Ad(r.permission),disable:T.disable,scope:T.scope})?await m(r.name)?(te.success(`Agent renamed to "${I}"`),l(I)):te.error("Failed to remove old agent after rename"):te.error("Failed to rename agent"),t(null)},C=I=>{switch(I){case"primary":return e.jsx(Xr,{className:"h-3 w-3 text-primary"});case"all":return e.jsx(ju,{className:"h-3 w-3 text-primary"});case"subagent":return e.jsx(vu,{className:"h-3 w-3 text-primary"});default:return null}},M=i.filter(I=>!Lu(I)),S=M.filter(Hr),A=M.filter(I=>!Hr(I));return e.jsxs("div",{className:R("flex h-full flex-col",x),children:[e.jsx("div",{className:R("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(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(ft,{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(Jn,{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(I=>e.jsx(Ed,{agent:I,isSelected:a===I.name,onSelect:()=>{l(I.name),s?.(),g&&p(!1)},onReset:()=>N(I),onDuplicate:()=>v(I),getAgentModeIcon:C},I.name))]}),A.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Agents"}),A.map(I=>e.jsx(Ed,{agent:I,isSelected:a===I.name,onSelect:()=>{l(I.name),s?.(),g&&p(!1)},onRename:()=>k(I),onDelete:()=>b(I),onDuplicate:()=>v(I),getAgentModeIcon:C},I.name))]})]})}),e.jsx(ms,{open:r!==null,onOpenChange:I=>!I&&t(null),children:e.jsxs(fs,{children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Rename Agent"}),e.jsxs(Ns,{children:['Enter a new name for the agent "@',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:I=>o(I.target.value),placeholder:"New agent name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:I=>{I.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Zr,{onClick:D,children:"Rename"})]})]})})]})},Ed=({agent:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i,getAgentModeIcon:l})=>{const d=s;return e.jsx("div",{className:R("group relative flex items-center rounded-md px-1.5 py-1 transition-all duration-200",r?"dark:bg-accent/80 bg-primary/12":"hover:dark:bg-accent/40 hover:bg-primary/6"),children:e.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[e.jsxs("button",{onClick:t,className:"flex min-w-0 flex-1 flex-col gap-0 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",tabIndex:0,children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"typography-ui-label font-normal truncate text-foreground",children:s.name}),l(s.mode),(d.scope||Hr(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:Hr(s)?"system":d.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(qt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Dt,{onClick:u=>{u.stopPropagation(),a()},children:[e.jsx(oo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Dt,{onClick:u=>{u.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Dt,{onClick:u=>{u.stopPropagation(),o()},children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Dt,{onClick:u=>{u.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})})};function Bs({className:s,variant:r,...t}){return e.jsx(Ce,{variant:r,size:"sm",className:R("h-6 px-2 text-xs",s),...t})}const O0=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),$0=s=>{if(typeof s!="number"||Number.isNaN(s))return"";if(s===0)return"0";const r=O0.format(s);return r.endsWith(".0")?r.slice(0,-2):r},ka=({providerId:s,modelId:r,onChange:t,className:n,allowedProviderIds:o})=>{const{providers:a,modelsMetadata:i}=rt(),l=_e(Y=>Y.isMobile),{toggleFavoriteModel:d,isFavoriteModel:u,addRecentModel:m}=_e(),{favoriteModelsList:f,recentModelsList:p}=Nl(),{isMobile:g}=_t(),w=l||g,[h,j]=c.useState(!1),[x,y]=c.useState(new Set),[b,N]=c.useState(!1),[v,k]=c.useState(""),[D,C]=c.useState(0),M=c.useRef([]),S=c.useMemo(()=>!Array.isArray(o)||o.length===0?null:new Set(o),[o]),A=c.useMemo(()=>S?a.filter(Y=>S.has(String(Y.id))):a,[a,S]),I=()=>j(!1),_=Y=>{y(re=>{const V=new Set(re);return V.has(Y)?V.delete(Y):V.add(Y),V})};c.useEffect(()=>{b||(k(""),C(0))},[b]),c.useEffect(()=>{C(0)},[v]);const T=Y=>{const re=Y?.name||Y?.id||"",V=String(re);return V.length>40?V.substring(0,37)+"...":V},P=(Y,re)=>{const V=`${Y}/${re}`;return i.get(V)},L=(Y,re)=>{t(Y,re),Y&&re&&m(Y,re),N(!1)},Z=(Y,re)=>{if(!v.trim())return!0;const V=v.toLowerCase();return Y.toLowerCase().includes(V)||re.toLowerCase().includes(V)},q=(Y,re,V,ae,E,B)=>{const F=P(re,V),O=$0(F?.limit?.context),z=s===re&&r===V,Q=u(re,V);return e.jsxs("div",{ref:me=>{M.current[E]=me},className:R("typography-meta group flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer",B?"bg-accent":"hover:bg-accent/50"),onClick:()=>L(re,V),onMouseEnter:()=>C(E),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:T(Y)}),O?e.jsx("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:O}):null]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[z&&e.jsx(Pt,{className:"h-4 w-4 text-primary"}),e.jsx("button",{onClick:me=>{me.preventDefault(),me.stopPropagation(),d(re,V)},className:R("model-favorite-button flex h-4 w-4 items-center justify-center hover:text-yellow-600",Q?"text-yellow-500":"text-muted-foreground"),"aria-label":Q?"Unfavorite":"Favorite",title:Q?"Remove from favorites":"Add to favorites",children:Q?e.jsx(fr,{className:"h-3.5 w-3.5"}):e.jsx(yn,{className:"h-3.5 w-3.5"})})]})]},`${ae}-${re}-${V}`)},$=f.filter(({model:Y,providerID:re})=>{if(S&&!S.has(re))return!1;const ae=a.find(B=>B.id===re)?.name||re,E=T(Y);return Z(E,ae)}),H=p.filter(({model:Y,providerID:re})=>{if(S&&!S.has(re))return!1;const ae=a.find(B=>B.id===re)?.name||re,E=T(Y);return Z(E,ae)}),U=A.map(Y=>{const V=(Array.isArray(Y.models)?Y.models:[]).filter(ae=>{const E=T(ae);return Z(E,Y.name||Y.id||"")});return{...Y,models:V}}).filter(Y=>Y.models.length>0),K=$.length>0||H.length>0||U.length>0,se=()=>w?e.jsx(vs,{open:h,onClose:I,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:V})=>{const ae=re===s&&V===r;return e.jsxs("div",{className:R("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:()=>{L(re,V),I()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:T(Y)})]})}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),d(re,V)},className:"model-favorite-button flex h-8 w-8 items-center justify-center text-yellow-500 hover:text-yellow-600 active:scale-95 touch-manipulation","aria-label":"Unfavorite",children:e.jsx(fr,{className:"h-4 w-4"})})]},`fav-mobile-${re}-${V}`)})})]}),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:V})=>{const ae=re===s&&V===r;return e.jsxs("div",{className:R("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:()=>{L(re,V),I()},children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{providerId:re,className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{className:"font-medium truncate",children:T(Y)})]})}),e.jsx("button",{onClick:E=>{E.preventDefault(),E.stopPropagation(),d(re,V)},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(yn,{className:"h-4 w-4"})})]},`recent-mobile-${re}-${V}`)})})]}),A.map(Y=>{const re=Array.isArray(Y.models)?Y.models:[];if(re.length===0)return null;const V=Y.id===s,ae=x.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:()=>_(Y.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(is,{providerId:Y.id,className:"h-3.5 w-3.5"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:Y.name}),V&&e.jsx("span",{className:"typography-micro text-primary/80",children:"Current"})]}),ae?e.jsx(It,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Us,{className:"h-3 w-3 text-muted-foreground"})]}),ae&&e.jsx("div",{className:"border-t border-border/20",children:re.map(E=>{const B=Y.id===s&&E.id===r;return e.jsxs("div",{className:R("flex w-full items-center justify-between px-2 py-1.5 text-left","typography-meta",B?"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:()=>{L(Y.id,E.id),I()},children:e.jsx("span",{className:"font-medium truncate",children:T(E)})}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsx("button",{onClick:F=>{F.preventDefault(),F.stopPropagation(),d(Y.id,E.id)},className:R("flex h-8 w-8 items-center justify-center active:scale-95 touch-manipulation",u(Y.id,E.id)?"text-yellow-500":"text-muted-foreground/50"),"aria-label":u(Y.id,E.id)?"Unfavorite":"Favorite",children:u(Y.id,E.id)?e.jsx(fr,{className:"h-4 w-4"}):e.jsx(yn,{className:"h-4 w-4"})}),B&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]})]},E.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:()=>{L("",""),I()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No model (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[w?e.jsxs("button",{type:"button",onClick:()=>j(!0),className:R("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(is,{providerId:s,className:"h-3.5 w-3.5"}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-meta font-medium text-foreground",children:s&&r?`${s}/${r}`:"Select model..."})]}),e.jsx(It,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Vt,{open:b,onOpenChange:N,children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("div",{className:R("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(is,{providerId:s,className:"h-3 w-3 flex-shrink-0"}),e.jsx(mr,{className:"h-3 w-3 text-primary/60 hidden"})]}):e.jsx(mr,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"typography-micro font-medium whitespace-nowrap",children:s&&r?`${s}/${r}`:"Not selected"}),e.jsx(It,{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=[];$.forEach(({model:E,providerID:B,modelID:F})=>{Y.push({model:E,providerID:B,modelID:F,section:"fav"})}),H.forEach(({model:E,providerID:B,modelID:F})=>{Y.push({model:E,providerID:B,modelID:F,section:"recent"})}),U.forEach(E=>{E.models.forEach(B=>{Y.push({model:B,providerID:E.id,modelID:B.id,section:"provider"})})});const re=Y.length,V=E=>{if(E.key==="ArrowDown"){E.preventDefault(),E.stopPropagation();const B=(D+1)%Math.max(1,re);C(B),setTimeout(()=>{M.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(E.key==="ArrowUp"){E.preventDefault(),E.stopPropagation();const B=(D-1+Math.max(1,re))%Math.max(1,re);C(B),setTimeout(()=>{M.current[B]?.scrollIntoView({behavior:"smooth",block:"nearest"})},0)}else if(E.key==="Enter"){E.preventDefault(),E.stopPropagation();const B=Y[D];B&&L(B.providerID,B.modelID)}else E.key==="Escape"&&(E.preventDefault(),E.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(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ht,{type:"text",placeholder:"Search models",value:v,onChange:E=>k(E.target.value),onKeyDown:V,className:"pl-8 h-8 typography-meta",autoFocus:!0})]})}),e.jsx(ft,{outerClassName:"max-h-[min(400px,calc(100dvh-12rem))] flex-1",children:e.jsxs("div",{className:"p-1",children:[e.jsxs("div",{className:R("typography-meta flex items-center gap-2 px-2 py-1.5 rounded-md cursor-pointer","hover:bg-accent/50"),onClick:()=>L("",""),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(Pt,{className:"h-4 w-4 text-primary ml-auto"})]}),e.jsx(Ms,{}),!K&&v&&e.jsx("div",{className:"px-2 py-4 text-center typography-meta text-muted-foreground",children:"No models found"}),$.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),"Favorites"]}),$.map(({model:E,providerID:B,modelID:F})=>{const O=ae++;return q(E,B,F,"fav",O,D===O)})]}),H.length>0&&e.jsxs(e.Fragment,{children:[$.length>0&&e.jsx(Ms,{}),e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(or,{className:"h-4 w-4"}),"Recent"]}),H.map(({model:E,providerID:B,modelID:F})=>{const O=ae++;return q(E,B,F,"recent",O,D===O)})]}),($.length>0||H.length>0)&&U.length>0&&e.jsx(Ms,{}),U.map((E,B)=>e.jsxs(c.Fragment,{children:[B>0&&e.jsx(Ms,{}),e.jsxs(Ur,{className:"typography-ui-header font-semibold text-foreground flex items-center gap-2 px-2 py-1.5",children:[e.jsx(is,{providerId:E.id,className:"h-4 w-4 flex-shrink-0"}),E.name]}),E.models.map(F=>{const O=ae++;return q(F,E.id,F.id,"provider",O,D===O)})]},E.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"})]})})()})]}),se()]})},L0=["read","edit","glob","grep","list","bash","task","skill","lsp","todoread","todowrite","webfetch","websearch","codesearch","external_directory","doom_loop"],xr=s=>s==="allow"||s==="ask"||s==="deny",B0=s=>{if(xr(s))return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const r=s["*"];if(xr(r))return r}},z0=s=>{if(xr(s))return{entries:{"*":s}};if(!s||typeof s!="object"||Array.isArray(s))return{entries:{}};const r={};for(const[t,n]of Object.entries(s)){const o=B0(n);o!==void 0&&(r[t]=o)}return{entries:r}},W0=s=>{const r={...s},t=r["*"];return xr(t)?(delete r["*"],{defaultOverride:t,overrides:r}):{defaultOverride:"default",overrides:r}},Na=s=>s==="doom_loop"||s==="external_directory"?"ask":"allow",Uo=(s,r)=>r==="default"?Na(s):r,Id=(s,r)=>{const t={...s};for(const[n,o]of Object.entries(s)){if(n==="*")continue;const a=Uo(n,r),i=Na(n);if(!(xr(o)&&o!==i)){if(xr(o)&&o===a){delete t[n];continue}if(o&&typeof o=="object"&&!Array.isArray(o)){const l=o,d=Object.keys(l),u=l["*"];if(u!==void 0&&u!==i)continue;d.length===1&&d[0]==="*"&&u===a&&delete t[n]}}}return t},df=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},H0=s=>{const r=df(s);if(!r||r.length===0)return{entries:{}};const t={};for(const a of r)!a.permission||a.permission==="invalid"||a.pattern==="*"&&(t[a.permission]=a.action);const n=t["*"],o={};for(const[a,i]of Object.entries(t)){if(a==="*"){o[a]=i;continue}const l=Na(a);if(n){if(i===n)continue}else if(i===l)continue;o[a]=i}return{entries:o}},U0=()=>{const{selectedAgentName:s,getAgentByName:r,createAgent:t,updateAgent:n,agents:o,agentDraft:a,setAgentDraft:i}=_r();rt();const l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,w]=c.useState(""),[h,j]=c.useState("subagent"),[x,y]=c.useState(""),[b,N]=c.useState(void 0),[v,k]=c.useState(void 0),[D,C]=c.useState(""),[M,S]=c.useState("default"),[A,I]=c.useState({}),[_,T]=c.useState(""),[P,L]=c.useState(!1),Z=mt(O=>O.currentDirectory??null),[q,$]=c.useState([]),H=so(O=>O.permissions);c.useEffect(()=>{let O=!1;return(async()=>{const Q=await je.listToolIds({directory:Z});if(O)return;const me=new Set(["write","patch","multiedit"]),Se=Q.map(he=>typeof he=="string"?he.trim():"").filter(Boolean).filter(he=>he!=="*").filter(he=>he!=="invalid").filter(he=>!me.has(he));$(Array.from(new Set(Se)).sort((he,Pe)=>he.localeCompare(Pe)))})(),()=>{O=!0}},[Z]);const U=c.useMemo(()=>{const O=new Set;for(const z of o){const Q=df(z.permission);if(Q)for(const me of Q)me.permission&&me.permission!=="*"&&me.permission!=="invalid"&&O.add(me.permission)}for(const z of H.values())for(const Q of z){const me=Q.permission?.trim();me&&me!=="invalid"&&O.add(me)}for(const z of q)O.add(z);return Array.from(O).sort((z,Q)=>z.localeCompare(Q))},[o,H,q]),K=c.useCallback(O=>{const z=A[O];if(xr(z))return z;if(z&&typeof z=="object"&&!Array.isArray(z)){const Q=z["*"];if(xr(Q))return Q}},[A]),se=c.useCallback(O=>{const z=A[O];return!z||typeof z!="object"||Array.isArray(z)?0:Object.keys(z).filter(me=>me!=="*").length},[A]),Y=c.useCallback((O,z)=>{O!=="*"&&I(Q=>{const me={...Q},Se=me[O],he=Uo(O,M),Pe=Na(O),ve=z===he&&z===Pe;if(Se&&typeof Se=="object"&&!Array.isArray(Se)){const Be={...Se};Be["*"]=z;const W=Object.keys(Be).filter(G=>G!=="*");return ve&&W.length===0?(delete me[O],me):(me[O]=Be,me)}return ve?(delete me[O],me):(me[O]=z,me)})},[M]),re=c.useCallback(O=>{I(z=>{if(!(O in z))return z;const Q={...z};return delete Q[O],Q})},[]),V=c.useMemo(()=>{const O=Object.entries(A).filter(([z])=>z!=="*");return O.sort(([z],[Q])=>z.localeCompare(Q)),O},[A]),ae=c.useMemo(()=>{const O=new Set;for(const z of L0)O.add(z);for(const z of U)O.add(z);for(const z of Object.keys(A))O.delete(z);return Array.from(O).sort((z,Q)=>z.localeCompare(Q))},[U,A]),E=c.useCallback(O=>{const z=_.trim();if(!z)return;const Q=Uo(z,M);if(O===Q){const me=M==="default"?"OpenCode defaults":`Default Permissions ("${M}")`;te.message(`"${z}" already matches ${me} (${Q}).`),T("");return}Y(z,O),T("")},[_,Y,M]),B=c.useCallback(O=>O==="webfetch"?"WebFetch":O==="websearch"?"WebSearch":O==="codesearch"?"CodeSearch":O==="doom_loop"?"Doom Loop":O==="external_directory"?"External Directory":O==="todowrite"?"TodoWrite":O==="todoread"?"TodoRead":O.split(/[_-]+/g).filter(Boolean).map(z=>z.charAt(0).toUpperCase()+z.slice(1)).join(" "),[]);c.useEffect(()=>{T("");const O=z=>{const Q=W0(z);S(Q.defaultOverride),I(Id(Q.overrides,Q.defaultOverride))};if(d&&a){m(a.name||""),p(a.scope||"user"),w(a.description||""),j(a.mode||"subagent"),y(a.model||""),N(a.temperature),k(a.top_p),C(a.prompt||"");const z=z0(a.permission);O(z.entries);return}if(l&&s===l.name){w(l.description||""),j(l.mode||"subagent"),l.model?.providerID&&l.model?.modelID?y(`${l.model.providerID}/${l.model.modelID}`):y(""),N(l.temperature),k(l.topP),C(l.prompt||"");const z=H0(l.permission);O(z.entries)}},[a,d,l,s]);const F=async()=>{const O=d?u.trim().replace(/\s+/g,"-"):s?.trim();if(!O){te.error("Agent name is required");return}if(d&&o.some(z=>z.name===O)){te.error("An agent with this name already exists");return}L(!0);try{const z=x.trim(),Q={name:O,description:g.trim()||void 0,mode:h,model:z===""?null:z,temperature:b,top_p:v,prompt:D.trim()||void 0,permission:(()=>{const Se=Id(A,M),he=M==="default"?Se:{"*":M,...Se},Pe=["doom_loop","external_directory"];for(const Be of Pe)if(!(Be in he)){const W=A[Be];xr(W)?he[Be]=W:he[Be]=Uo(Be,M)}return Object.keys(he).length===0?d?void 0:null:he})(),scope:d?f:void 0};let me;d?(me=await t(Q),me&&i(null)):me=await n(O,Q),me?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 Q=z instanceof Error&&z.message?z.message:"An error occurred while saving";te.error(Q)}finally{L(!1)}};return s?e.jsx(ft,{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(ht,{value:u,onChange:O=>m(O.target.value),placeholder:"agent-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(js,{value:f,onValueChange:O=>p(O),children:[e.jsxs(Ss,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(ks,{align:"end",children:[e.jsx(Bt,{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(Fs,{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(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:g,onChange:O=>w(O.target.value),placeholder:"What does this agent do?",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Mode"}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsxs(Bs,{variant:h==="primary"?"default":"outline",onClick:()=>j("primary"),className:R("gap-2",h==="primary"?void 0:"text-foreground"),children:[e.jsx(Xr,{className:"h-3 w-3"}),"Primary"]}),e.jsxs(Bs,{variant:h==="subagent"?"default":"outline",onClick:()=>j("subagent"),className:R("gap-2",h==="subagent"?void 0:"text-foreground"),children:[e.jsx(vu,{className:"h-3 w-3"}),"Subagent"]}),e.jsxs(Bs,{variant:h==="all"?"default":"outline",onClick:()=>j("all"),className:R("gap-2",h==="all"?void 0:"text-foreground"),children:[e.jsx(ju,{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(ka,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(O,z)=>{y(O&&z?`${O}/${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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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,(b!==void 0?b:.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(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(ht,{type:"text",inputMode:"decimal",value:b!==void 0?b:"",onChange:O=>{const z=O.target.value;if(z===""){N(void 0);return}const Q=parseFloat(z);!isNaN(Q)&&Q>=0&&Q<=2&&N(Q)},onBlur:O=>{const z=O.target.value;if(z!==""){const Q=parseFloat(z);if(!isNaN(Q)){const me=Math.max(0,Math.min(2,Q));N(parseFloat(me.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,(b!==void 0?b:.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(Kt,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2",children:["Top P",e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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,(v!==void 0?v:.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(Ta,{className:"h-3.5 w-3.5"})}),e.jsx(ht,{type:"text",inputMode:"decimal",value:v!==void 0?v:"",onChange:O=>{const z=O.target.value;if(z===""){k(void 0);return}const Q=parseFloat(z);!isNaN(Q)&&Q>=0&&Q<=1&&k(Q)},onBlur:O=>{const z=O.target.value;if(z!==""){const Q=parseFloat(z);if(!isNaN(Q)){const me=Math.max(0,Math.min(1,Q));k(parseFloat(me.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,(v!==void 0?v:.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(Kt,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-h2 font-semibold text-foreground",children:"System Prompt"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Override the default system prompt for this agent"})]}),e.jsx(Ts,{value:D,onChange:O=>C(O.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(Ce,{size:"sm",variant:M==="default"?"default":"outline",onClick:()=>S("default"),className:"h-6 px-2 text-xs",children:"Default"}),e.jsx(Ce,{size:"sm",variant:M==="allow"?"default":"outline",onClick:()=>S("allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:M==="ask"?"default":"outline",onClick:()=>S("ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ce,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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(js,{value:_,onValueChange:T,children:[e.jsx(Ss,{className:"h-8 w-full sm:w-72",children:_?e.jsx("span",{className:"truncate",children:B(_)}):e.jsx("span",{className:"text-muted-foreground",children:"Add override…"})}),e.jsx(ks,{children:ae.map(O=>e.jsx(Bt,{value:O,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(O)}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:O})]})},O))})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{size:"sm",variant:"outline",disabled:!_,onClick:()=>E("allow"),className:"h-8 px-3 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:"outline",disabled:!_,onClick:()=>E("ask"),className:"h-8 px-3 text-xs",children:"Ask"}),e.jsx(Ce,{size:"sm",variant:"outline",disabled:!_,onClick:()=>E("deny"),className:"h-8 px-3 text-xs",children:"Deny"})]})]})}),V.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:V.map(([O])=>{const z=K(O),Q=se(O),me=B(O);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:me}),e.jsx("span",{className:"typography-micro text-muted-foreground font-mono",children:O}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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']}),Q>0?e.jsxs("p",{children:[e.jsx("strong",{children:"Patterns:"})," ",Q," pattern rules preserved"]}):null]})})]})]}),e.jsxs(Ce,{size:"sm",variant:"outline",onClick:()=>re(O),className:"h-6 px-2 text-xs gap-1",children:[e.jsx(Ta,{className:"h-3 w-3"}),"Remove"]})]}),e.jsxs("div",{className:"flex gap-1 w-fit",children:[e.jsx(Ce,{size:"sm",variant:z==="allow"?"default":"outline",onClick:()=>Y(O,"allow"),className:"h-6 px-2 text-xs",children:"Allow"}),e.jsx(Ce,{size:"sm",variant:z==="ask"?"default":"outline",onClick:()=>Y(O,"ask"),className:"h-6 px-2 text-xs",children:"Ask"}),e.jsx(Ce,{size:"sm",variant:z==="deny"?"default":"outline",onClick:()=>Y(O,"deny"),className:"h-6 px-2 text-xs",children:"Deny"})]})]},O)})})]})]}),e.jsx("div",{className:"flex justify-end border-t border-border/40 pt-4",children:e.jsxs(Ce,{size:"sm",variant:"default",onClick:F,disabled:P,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pa,{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(Jn,{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"})]})})},V0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedCommandName:a,commands:i,setSelectedCommand:l,setCommandDraft:d,createCommand:u,deleteCommand:m,loadCommands:f}=Rr(),{setSidebarOpen:p}=_e(),{isMobile:g}=_t(),[w,h]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),j=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||h(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const x=w?"bg-transparent":j?"bg-background":"bg-sidebar",y=()=>{const S="new-command";let A=S,I=1;for(;i.some(_=>_.name===A);)A=`${S}-${I}`,I++;d({name:A,scope:"user"}),l(A),s?.(),g&&p(!1)},b=async S=>{if(hn(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=>{hn(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"))},v=S=>{const A=S.name;let I=1,_=`${A}-copy`;for(;i.some(T=>T.name===_);)I++,_=`${A}-copy-${I}`;d({name:_,scope:S.scope||"user",description:S.description,template:S.template,agent:S.agent,model:S.model,subtask:S.subtask}),l(_),g&&p(!1)},k=S=>{o(S.name),t(S)},D=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(i.some(I=>I.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}"`),l(S)):te.error("Failed to remove old command after rename"):te.error("Failed to rename command"),t(null)},C=i.filter(hn),M=i.filter(S=>!hn(S));return e.jsxs("div",{className:R("flex h-full flex-col",x),children:[e.jsx("div",{className:R("border-b px-3",g?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(ft,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Pr,{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,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Pd,{command:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),g&&p(!1)},onReset:()=>N(S),onDuplicate:()=>v(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,A)=>S.name.localeCompare(A.name)).map(S=>e.jsx(Pd,{command:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),g&&p(!1)},onRename:()=>k(S),onDelete:()=>b(S),onDuplicate:()=>v(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(Ns,{children:['Enter a new name for the command "/',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:S=>o(S.target.value),placeholder:"New command name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Zr,{onClick:D,children:"Rename"})]})]})})]})},Pd=({command:s,isSelected:r,onSelect:t,onDelete:n,onReset:o,onRename:a,onDuplicate:i})=>e.jsx("div",{className:R("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||hn(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:hn(s)?"system":s.scope})]}),s.description&&e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:s.description})]}),e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(qt,{align:"end",className:"w-fit min-w-20",children:[a&&e.jsxs(Dt,{onClick:l=>{l.stopPropagation(),a()},children:[e.jsx(oo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Dt,{onClick:l=>{l.stopPropagation(),i()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),o&&e.jsxs(Dt,{onClick:l=>{l.stopPropagation(),o()},children:[e.jsx(Ps,{className:"h-4 w-4 mr-px"}),"Reset"]}),n&&e.jsxs(Dt,{onClick:l=>{l.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})]})]})]})}),uf=({agentName:s,onChange:r,className:t})=>{const{loadAgents:n,getVisibleAgents:o}=_r(),a=o(),i=_e(w=>w.isMobile),{isMobile:l}=_t(),d=i||l,[u,m]=c.useState(!1);c.useEffect(()=>{n()},[n]);const f=()=>m(!1),p=w=>{r(w)},g=()=>d?e.jsx(vs,{open:u,onClose:f,title:"Select Agent",children:e.jsxs("div",{className:"space-y-1",children:[a.map(w=>{const h=w.name===s;return e.jsxs("button",{type:"button",className:R("flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",h?"bg-primary/10 text-primary":"text-foreground"),onClick:()=>{p(w.name),f()},children:[e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{className:"typography-meta font-medium",children:w.name}),w.description&&e.jsx("span",{className:"typography-micro text-muted-foreground",children:w.description})]}),h&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"})]},w.name)}),e.jsx("button",{type:"button",className:"flex w-full items-center justify-between rounded-lg border border-border/40 bg-background/95 px-2 py-1.5 text-left",onClick:()=>{p(""),f()},children:e.jsx("span",{className:"typography-meta text-muted-foreground",children:"No agent (optional)"})})]})}):null;return e.jsxs(e.Fragment,{children:[d?e.jsxs("button",{type:"button",onClick:()=>m(!0),className:R("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(Jn,{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(It,{className:"h-3 w-3 text-muted-foreground"})]}):e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("div",{className:R("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(Jn,{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(It,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(qt,{className:"max-w-[300px]",children:[a.map(w=>e.jsx(Dt,{className:"typography-meta",onSelect:()=>p(w.name),children:e.jsx("span",{className:"font-medium",children:w.name})},w.name)),e.jsx(Dt,{className:"typography-meta",onSelect:()=>p(""),children:e.jsx("span",{className:"text-muted-foreground",children:"No agent (optional)"})})]})]}),g()]})},G0=()=>{const{selectedCommandName:s,getCommandByName:r,createCommand:t,updateCommand:n,commands:o,commandDraft:a,setCommandDraft:i}=Rr(),l=s?r(s):null,d=!!(a&&a.name===s&&!l),[u,m]=c.useState(""),[f,p]=c.useState("user"),[g,w]=c.useState(""),[h,j]=c.useState(""),[x,y]=c.useState(""),[b,N]=c.useState(""),[v,k]=c.useState(!1),[D,C]=c.useState(!1);c.useEffect(()=>{d&&a?(m(a.name||""),p(a.scope||"user"),w(a.description||""),j(a.agent||""),y(a.model||""),N(a.template||""),k(a.subtask||!1)):l&&(w(l.description||""),j(l.agent||""),y(l.model||""),N(l.template||""),k(l.subtask||!1))},[l,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(!b.trim()){te.error("Command template is required");return}if(d&&o.some(A=>A.name===S)){te.error("A command with this name already exists");return}C(!0);try{const A=h.trim(),I=x.trim(),_=b.trim(),T={name:S,description:g.trim()||void 0,agent:A===""?null:A,model:I===""?null:I,template:_,subtask:v,scope:d?f:void 0};let P;d?(P=await t(T),P&&i(null)):P=await n(S,T),P?te.success(d?"Command created successfully":"Command updated successfully"):te.error(d?"Failed to create command":"Failed to update command")}catch(A){console.error("Error saving command:",A),te.error("An error occurred while saving")}finally{C(!1)}};return s?e.jsx(ft,{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(ht,{value:u,onChange:S=>m(S.target.value),placeholder:"command-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"})]}),e.jsxs(js,{value:f,onValueChange:S=>p(S),children:[e.jsxs(Ss,{className:"!h-9 w-auto gap-1.5",children:[f==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:f})]}),e.jsxs(ks,{align:"end",children:[e.jsx(Bt,{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(Fs,{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(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Description"}),e.jsx(Ts,{value:g,onChange:S=>w(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(uf,{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(ka,{providerId:x?x.split("/")[0]:"",modelId:x?x.split("/")[1]:"",onChange:(S,A)=>{y(S&&A?`${S}/${A}`:"")}}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Default model for this command (optional)"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground flex items-center gap-2 cursor-pointer",children:[e.jsxs("div",{className:"relative",children:[e.jsx("input",{type:"checkbox",checked:v,onChange:S=>k(S.target.checked),className:"sr-only"}),e.jsx("div",{className:R("w-5 h-5 rounded border-2 flex items-center justify-center",v?"bg-primary border-primary":"bg-background border-border hover:border-primary/50"),children:v&&e.jsx(Pt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(Ts,{value:b,onChange:S=>N(S.target.value),placeholder:`Your command template here...
103
-
104
- Use $ARGUMENTS to reference user input.
105
- Use !\`shell command\` to inject shell output.
106
- Use @filename to include file contents.`,rows:12,className:"font-mono typography-meta"}),e.jsxs("div",{className:"typography-meta text-muted-foreground/80 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Template Features:"}),e.jsxs("ul",{className:"list-disc list-inside space-y-0.5 ml-2",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"bg-muted px-1 rounded",children:"$ARGUMENTS"}),e.jsx("span",{children:"- User input after command"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3 w-3 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(Ce,{size:"sm",variant:"default",onClick:M,disabled:D,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pa,{className:"h-3 w-3"}),D?"Saving...":"Save Changes"]})})]})]})}):e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Pr,{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"})]})})},q0=({onItemSelect:s})=>{const[r,t]=c.useState(null),[n,o]=c.useState(""),{selectedSkillName:a,skills:i,setSelectedSkill:l,setSkillDraft:d,createSkill:u,deleteSkill:m,loadSkills:f,getSkillDetail:p}=Hs(),{setSidebarOpen:g}=_e(),{isMobile:w}=_t(),[h,j]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),x=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||j(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{f()},[f]);const y=h?"bg-transparent":x?"bg-background":"bg-sidebar",b=()=>{const S="new-skill";let A=S,I=1;for(;i.some(_=>_.name===A);)A=`${S}-${I}`,I++;d({name:A,scope:"user",description:""}),l(A),s?.(),w&&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"))},v=async S=>{const A=S.name;let I=1,_=`${A}-copy`;for(;i.some(P=>P.name===_);)I++,_=`${A}-copy-${I}`;const T=await p(S.name);if(!T){te.error("Failed to load skill details for duplication");return}d({name:_,scope:S.scope||"user",description:(T.sources.md.fields.includes("description"),""),instructions:""}),l(_),w&&g(!1)},k=S=>{o(S.name),t(S)},D=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(i.some(_=>_.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}"`),l(S)):te.error("Failed to remove old skill after rename"):te.error("Failed to rename skill"),t(null)},C=i.filter(S=>S.scope==="project"),M=i.filter(S=>S.scope==="user");return e.jsxs("div",{className:R("flex h-full flex-col",y),children:[e.jsx("div",{className:R("border-b px-3",w?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",i.length]}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:b,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(ft,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2 overflow-x-hidden",children:i.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx(Su,{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(Td,{skill:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),w&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>v(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(Td,{skill:S,isSelected:a===S.name,onSelect:()=>{l(S.name),s?.(),w&&g(!1)},onRename:()=>k(S),onDelete:()=>N(S),onDuplicate:()=>v(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(Ns,{children:['Enter a new name for the skill "',r?.name,'"']})]}),e.jsx(ht,{value:n,onChange:S=>o(S.target.value),placeholder:"New skill name...",className:"text-foreground placeholder:text-muted-foreground",onKeyDown:S=>{S.key==="Enter"&&D()}}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>t(null),className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Zr,{onClick:D,children:"Rename"})]})]})})]})},Td=({skill:s,isSelected:r,onSelect:t,onDelete:n,onRename:o,onDuplicate:a})=>e.jsx("div",{className:R("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(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsxs(qt,{align:"end",className:"w-fit min-w-20",children:[e.jsxs(Dt,{onClick:i=>{i.stopPropagation(),o()},children:[e.jsx(oo,{className:"h-4 w-4 mr-px"}),"Rename"]}),e.jsxs(Dt,{onClick:i=>{i.stopPropagation(),a()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Duplicate"]}),e.jsxs(Dt,{onClick:i=>{i.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{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 i=c.useRef(null),l=c.useRef(null),d=c.useCallback(()=>{const u=i.current,m=l.current;if(!u||!m)return;const f=u.offsetWidth;if(!f)return;const{offsetLeft:p,offsetWidth:g}=m,w=Math.max(0,Math.min(100,p/f*100)),h=Math.max(0,Math.min(100,(p+g)/f*100));u.style.clipPath=`inset(0 ${Number(100-h).toFixed(2)}% 0 ${Number(w).toFixed(2)}% round 8px)`},[]);return c.useLayoutEffect(()=>{d()},[d,r,s.length]),c.useEffect(()=>{const u=i.current;if(!u)return;const m=new ResizeObserver(()=>d());return m.observe(u),()=>m.disconnect()},[d]),e.jsxs("div",{className:R("relative isolate w-full",n),children:[e.jsx("div",{ref:i,"aria-hidden":!0,className:R("pointer-events-none absolute inset-0 z-10 overflow-hidden rounded-lg [clip-path:inset(0_75%_0_0_round_8px)]",a?"[transition:clip-path_200ms_ease]":null),children:e.jsx("div",{className:"flex h-9 items-center gap-1 rounded-lg bg-accent px-1.5 text-accent-foreground",children:s.map(u=>{const m=u.icon;return e.jsxs("div",{className:"flex h-7 flex-1 items-center justify-center gap-1.25 rounded-lg px-2.5 text-sm font-semibold",children:[m?e.jsx(m,{className:"h-4 w-4"}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})}),e.jsx("div",{className:"relative z-20 flex h-9 items-center gap-1 rounded-lg bg-muted/20 px-1.5",children:s.map(u=>{const m=r===u.value,f=u.icon;return e.jsxs("button",{ref:m?l:null,type:"button",onClick:()=>{o&&t(u.value)},className:R("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:R("h-4 w-4",m?"text-accent-foreground":"text-muted-foreground")}):null,e.jsx("span",{className:"truncate",children:u.label})]},u.value)})})]})}const K0=()=>`custom:${Date.now()}-${Math.random().toString(16).slice(2)}`,Y0=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},Q0=async()=>{try{if(Zt())return await sn();const s=vr()?.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}},X0=({open:s,onOpenChange:r})=>{const{scanRepo:t,loadCatalog:n,isScanning:o}=ao(),[a,i]=c.useState(""),[l,d]=c.useState(""),[u,m]=c.useState(""),[f,p]=c.useState([]),[g,w]=c.useState(null),[h,j]=c.useState(!1),[x,y]=c.useState([]),[b,N]=c.useState(null);c.useEffect(()=>{s&&(i(""),d(""),m(""),w(null),j(!1),y([]),N(null),(async()=>{const C=await Q0(),M=Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[];p(M||[])})())},[s]);const v=c.useMemo(()=>{const C=l.trim(),M=u.trim();return f.some(S=>{const A=(S.source||"").trim(),I=(S.subpath||"").trim();return A===C&&I===M})},[f,l,u]),k=async()=>{const C=l.trim();if(!C){te.error("Repository source is required");return}a.trim()||i(Y0(C)),j(!1),w(null);const M=await t({source:C,subpath:u.trim()||void 0,gitIdentityId:b||void 0});if(!M.ok){if(M.error?.kind==="authRequired"){if(Ut()){te.error("Private repositories are not supported in VS Code yet");return}const A=M.error.identities||[];y(A),!b&&A.length>0&&N(A[0].id),te.error("Authentication required. Select a Git identity and scan again.");return}te.error(M.error?.message||"Failed to scan repository");return}const S=M.items?.length||0;if(w(S),S===0){te.error("No skills found in this repository"),j(!1);return}y([]),j(!0),te.success(`Found ${S} skill(s)`)},D=async()=>{const C=a.trim(),M=l.trim(),S=u.trim();if(!C){te.error("Catalog name is required");return}if(!M){te.error("Repository source is required");return}if(!h){te.error("Scan the repository before adding this catalog");return}if(v){te.error("This catalog already exists");return}const A={id:K0(),label:C,source:M,...S?{subpath:S}:{},...b?{gitIdentityId:b}:{}},I=[...f,A];try{await rs({skillCatalogs:I}),p(I),te.success("Catalog added"),await n({refresh:!0}),r(!1)}catch(_){te.error(_ instanceof Error?_.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(Ns,{children:["Add a Git repository as a new catalog source. OpenChamber will scan it for folders containing ",e.jsx("code",{className:"font-mono",children:"SKILL.md"}),"."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Catalog name"}),e.jsx(ht,{value:a,onChange:C=>i(C.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(ht,{value:l,onChange:C=>{d(C.target.value),j(!1),w(null)},placeholder:"owner/repo or git@github.com:owner/repo.git"}),e.jsx("p",{className:"typography-micro text-muted-foreground",children:"Public repos work everywhere. Private repos require SSH identity (Desktop/Web only)."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Optional subpath"}),e.jsx(ht,{value:u,onChange:C=>{m(C.target.value),j(!1),w(null)},placeholder:"e.g. skills"})]}),x.length>0&&!Ut()?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(js,{value:b||"",onValueChange:C=>N(C),children:[e.jsx(Ss,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:x.find(C=>C.id===b)?.name||"Choose identity"})}),e.jsx(ks,{align:"start",children:x.map(C=>e.jsx(Bt,{value:C.id,className:"pr-2 [&>span:first-child]:hidden",children:C.name},C.id))})]})}),e.jsx("div",{className:"typography-micro text-muted-foreground mt-2",children:"Configure identities in Settings → Git Identities."})]}):null,g!==null?e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Scan result: ",g," skill(s) found"]}):null,v?e.jsx("div",{className:"typography-meta text-muted-foreground",children:"This catalog is already added."}):null]}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsxs(Ce,{variant:"outline",onClick:()=>{k()},disabled:o||!l.trim(),className:"gap-2",children:[e.jsx(Sh,{className:"h-4 w-4"}),o?"Scanning…":"Scan"]}),e.jsx(Ce,{variant:"default",onClick:()=>{D()},disabled:!h||v||!a.trim()||!l.trim(),children:"Add catalog"})]})]})})},J0=({open:s,onOpenChange:r,conflicts:t,onConfirm:n})=>{const[o,a]=c.useState({});c.useEffect(()=>{if(!s)return;const d={};for(const u of t)d[u.skillName]="skip";a(d)},[s,t]);const i=d=>{const u={};for(const m of t)u[m.skillName]=d;a(u)},l=t.length>0&&t.every(d=>o[d.skillName]);return e.jsx(ms,{open:s,onOpenChange:r,children:e.jsxs(fs,{className:"max-w-2xl",children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Skills already exist"}),e.jsx(Ns,{children:"Some selected skills are already installed in this scope. Choose whether to skip or overwrite them."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[t.length," conflict(s)"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>i("skip"),children:"Skip all"}),e.jsx(Ce,{variant:"outline",size:"sm",onClick:()=>i("overwrite"),children:"Overwrite all"})]})]}),e.jsx("div",{className:"space-y-2",children:t.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"typography-ui-label truncate",children:d.skillName}),e.jsxs("div",{className:"typography-micro text-muted-foreground",children:["Installed in ",d.scope," scope"]})]}),e.jsxs(js,{value:o[d.skillName]||"skip",onValueChange:u=>a(m=>({...m,[d.skillName]:u})),children:[e.jsx(Ss,{className:"!h-9 w-36 justify-between",children:e.jsx("span",{className:"capitalize",children:o[d.skillName]||"skip"})}),e.jsxs(ks,{align:"end",children:[e.jsx(Bt,{value:"skip",className:"pr-2 [&>span:first-child]:hidden",children:"Skip"}),e.jsx(Bt,{value:"overwrite",className:"pr-2 [&>span:first-child]:hidden",children:"Overwrite"})]})]})]},d.skillName))})]}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Zr,{onClick:()=>n(o),disabled:!l,children:"Continue"})]})]})})},Z0=({open:s,onOpenChange:r,item:t})=>{const{installSkills:n,isInstalling:o}=ao(),[a,i]=c.useState("user"),[l,d]=c.useState(!1),[u,m]=c.useState([]),[f,p]=c.useState(null);c.useEffect(()=>{s&&(i("user"),d(!1),m([]),p(null))},[s]);const g=async w=>{const h={skillDir:w.skillDir};t?.clawdhub&&(h.clawdhub={slug:t.clawdhub.slug,version:t.clawdhub.version});const j=await n({source:w.source,subpath:w.subpath,gitIdentityId:t?.gitIdentityId,scope:w.scope,selections:[h],conflictPolicy:"prompt",conflictDecisions:w.conflictDecisions});if(j.ok){te.success("Skill installed successfully"),r(!1);return}if(j.error?.kind==="conflicts"){p({source:w.source,subpath:w.subpath,scope:w.scope,skillDir:w.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(Ns,{children:["Install ",e.jsx("span",{className:"font-semibold text-foreground",children:t.skillName})," into user or project scope."]})]}),e.jsx("div",{className:"space-y-3",children:t.warnings?.length?e.jsxs("div",{className:"rounded-lg border bg-muted/30 px-3 py-2",children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Warnings"}),e.jsx("ul",{className:"mt-1 space-y-1",children:t.warnings.map(w=>e.jsx("li",{className:"typography-meta text-muted-foreground",children:w},w))})]}):null}),e.jsxs(Ks,{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(js,{value:a,onValueChange:w=>i(w),children:[e.jsx(Ss,{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(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:a})]})}),e.jsxs(ks,{align:"start",children:[e.jsx(Bt,{value:"user",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fs,{className:"h-4 w-4"}),e.jsx("span",{children:"User"})]})}),e.jsx(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]})})]})]})}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:justify-end",children:[e.jsx(Ce,{className:"w-full sm:w-auto",variant:"ghost",onClick:()=>r(!1),children:"Cancel"}),e.jsx(Ce,{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(J0,{open:l,onOpenChange:d,conflicts:u,onConfirm:w=>{f&&(g({source:f.source,subpath:f.subpath,scope:f.scope,skillDir:f.skillDir,conflictDecisions:w}),d(!1))}})]}):null},ej=async()=>{try{if(Zt())return await sn();const s=vr()?.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}},tj=({mode:s,onModeChange:r})=>{const{sources:t,itemsBySource:n,selectedSourceId:o,setSelectedSource:a,loadCatalog:i,isLoadingCatalog:l,lastCatalogError:d}=ao(),[u,m]=c.useState(""),[f,p]=c.useState(!1),[g,w]=c.useState(!1),[h,j]=c.useState(null),[x,y]=c.useState(!1);c.useEffect(()=>{i()},[i]);const b=c.useMemo(()=>o?n[o]||[]:[],[n,o]),N=c.useMemo(()=>{const C=u.trim().toLowerCase();return C?b.filter(M=>{const S=M.skillName.toLowerCase(),A=(M.description||"").toLowerCase(),I=(M.frontmatterName||"").toLowerCase();return S.includes(C)||A.includes(C)||I.includes(C)}):b},[b,u]),v=c.useMemo(()=>t.find(C=>C.id===o)||null,[t,o]),k=!!(o&&o.startsWith("custom:")),D=async()=>{if(!(!o||!k)&&window.confirm("Remove this catalog?")){y(!0);try{const C=await ej(),S=(Array.isArray(C?.skillCatalogs)?C?.skillCatalogs:[]).filter(A=>A.id!==o);await rs({skillCatalogs:S}),await i({refresh:!0})}finally{y(!1)}}};return e.jsx(ft,{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(js,{value:o||"",onValueChange:C=>a(C),children:[e.jsx(Ss,{className:"!h-9 w-full justify-between",children:e.jsx("span",{children:v?.label||"Select source"})}),e.jsx(ks,{align:"start",children:t.map(C=>e.jsx(Bt,{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(Ce,{type:"button",variant:"outline",onClick:()=>{i({refresh:!0})},disabled:l,className:"gap-2",children:[e.jsx(Ar,{className:"h-4 w-4"}),"Refresh"]}),k?e.jsxs(Ce,{type:"button",variant:"outline",onClick:()=>{D()},disabled:x,className:"gap-2",children:[e.jsx(qs,{className:"h-4 w-4"}),"Remove"]}):null,e.jsxs(Ce,{type:"button",variant:"default",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(Kt,{className:"h-4 w-4"}),"Add catalog"]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx(ht,{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:l?"Loading…":`${N.length} skill(s)`})]}),d?e.jsxs("div",{className:"rounded-lg border bg-muted/20 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Catalog error"}),e.jsx("div",{className:"typography-meta text-muted-foreground mt-1",children:d.message})]}):null]}),e.jsx("div",{className:"space-y-2",children:N.length===0?e.jsxs("div",{className:"py-10 text-center text-muted-foreground",children:[e.jsx("p",{className:"typography-body",children:"No skills found"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Try a different search or refresh the catalog"})]}):N.map(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(Er,{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(yn,{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(Ce,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:!C.installable,onClick:()=>{j(C),w(!0)},children:"Install"})]})},`${C.sourceId}:${C.skillDir}`)})}),e.jsx(X0,{open:f,onOpenChange:p}),e.jsx(Z0,{open:g,onOpenChange:w,item:h})]})})},sj=()=>{const{selectedSkillName:s,getSkillByName:r,getSkillDetail:t,createSkill:n,updateSkill:o,skills:a,skillDraft:i,setSkillDraft:l,setSelectedSkill:d}=Hs(),u=s?r(s):null,m=!!(i&&i.name===s&&!u),f=!!(s&&!u&&!i),[p,g]=c.useState("manual");c.useEffect(()=>{!m&&p!=="manual"&&g("manual")},[m,p]),c.useEffect(()=>{f&&d(null)},[f,d]);const w=m?e.jsx(mf,{tabs:[{value:"manual",label:"Manual"},{value:"external",label:"External"}],value:p,onValueChange:g,animate:!1}):null,[h,j]=c.useState(""),[x,y]=c.useState("user"),[b,N]=c.useState(""),[v,k]=c.useState(""),[D,C]=c.useState([]),[M,S]=c.useState([]),[A,I]=c.useState(!1),[_,T]=c.useState(!1),[P,L]=c.useState(""),[Z,q]=c.useState(""),[$,H]=c.useState(!1),[U,K]=c.useState(""),[se,Y]=c.useState(""),[re,V]=c.useState(null),[ae,E]=c.useState(!1),[B,F]=c.useState(""),O=m?h.trim()!==""||b.trim()!==""||v.trim()!==""||M.length>0:b!==P||v!==Z,z=re?se!==B:U.trim()!=="";c.useEffect(()=>{if(p==="external")return;(async()=>{if(m&&i)j(i.name||""),y(i.scope||"user"),N(i.description||""),k(i.instructions||""),L(""),q(""),C([]),S(i.pendingFiles||[]);else if(s&&u){T(!0);try{const Be=await t(s);if(Be){const W=Be.sources.md;N(W.description||""),k(W.instructions||""),L(W.description||""),q(W.instructions||""),C(W.supportingFiles||[])}}catch(Be){console.error("Failed to load skill details:",Be)}finally{T(!1)}}})()},[u,m,s,a,i,t,p]);const Q=async()=>{const ve=m?h.trim().replace(/\s+/g,"-").toLowerCase():s?.trim();if(!ve){te.error("Skill name is required");return}if(!/^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$/.test(ve)||ve.length>64){te.error("Skill name must be 1-64 lowercase alphanumeric characters with hyphens, cannot start or end with hyphen");return}if(!b.trim()){te.error("Description is required");return}if(m&&a.some(Be=>Be.name===ve)){te.error("A skill with this name already exists");return}I(!0);try{const Be={name:ve,description:b.trim(),instructions:v.trim()||void 0,scope:m?x:void 0,supportingFiles:m&&M.length>0?M:void 0};let W;m?(W=await n(Be),W&&(l(null),S([]),d(ve))):(W=await o(ve,Be),W&&(L(b.trim()),q(v.trim()))),W?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{I(!1)}},me=()=>{V(null),K(""),Y(""),F(""),H(!0)},Se=async ve=>{if(V(ve),K(ve),m){const W=M.find(G=>G.path===ve)?.content||"";Y(W),F(W),H(!0);return}if(s){E(!0),H(!0);try{const{readSupportingFile:Be}=Hs.getState(),W=await Be(s,ve);Y(W||""),F(W||"")}catch{te.error("Failed to load file content"),Y(""),F("")}finally{E(!1)}}},he=async()=>{if(!U.trim()){te.error("File name is required");return}const ve=U.trim(),Be=re!==null;if(m){if(Be)S(ee=>ee.map(fe=>fe.path===re?{path:ve,content:se}:fe)),te.success(`File "${ve}" updated`);else{if(M.some(ee=>ee.path===ve)){te.error("A file with this name already exists");return}S(ee=>[...ee,{path:ve,content:se}]),te.success(`File "${ve}" added`)}H(!1),V(null);return}if(!s){te.error("No skill selected");return}const{writeSupportingFile:W}=Hs.getState();if(await W(s,ve,se)){te.success(Be?`File "${ve}" updated`:`File "${ve}" created`),H(!1),V(null);const ee=await t(s);ee&&C(ee.sources.md.supportingFiles||[])}else te.error(Be?"Failed to update file":"Failed to create file")},Pe=async ve=>{if(m){S(Be=>Be.filter(W=>W.path!==ve)),te.success(`File "${ve}" removed`);return}if(s&&window.confirm(`Are you sure you want to delete "${ve}"?`)){const{deleteSupportingFile:Be}=Hs.getState();if(await Be(s,ve)){te.success(`File "${ve}" deleted`);const G=await t(s);G&&C(G.sources.md.supportingFiles||[])}else te.error("Failed to delete file")}};return m&&p==="external"?e.jsx(tj,{mode:p,onModeChange:g}):!s&&!i||f?e.jsx("div",{className:"flex h-full items-center justify-center",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Su,{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"})]})}):_?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(ft,{keyboardAvoid:!0,outerClassName:"h-full",className:"w-full",children:e.jsxs("div",{className:"mx-auto max-w-3xl space-y-6 p-6",children:[m?w:null,e.jsxs("div",{className:"space-y-1",children:[e.jsx("h1",{className:"typography-ui-header font-semibold text-lg",children:m?"New Skill":s}),u&&e.jsxs("p",{className:"typography-meta text-muted-foreground",children:[u.scope==="project"?"Project":"User"," skill",u.source==="claude"&&" (Claude-compatible)"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Basic Information"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Configure skill identity and description"})]}),m&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Skill Name & Scope"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ht,{value:h,onChange:ve=>j(ve.target.value.toLowerCase().replace(/\s+/g,"-")),placeholder:"skill-name",className:"flex-1 text-foreground placeholder:text-muted-foreground"}),e.jsxs(js,{value:x,onValueChange:ve=>y(ve),children:[e.jsxs(Ss,{className:"!h-9 w-auto gap-1.5",children:[x==="user"?e.jsx(Fs,{className:"h-4 w-4"}):e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{className:"capitalize",children:x})]}),e.jsxs(ks,{align:"end",children:[e.jsx(Bt,{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(Fs,{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(Bt,{value:"project",className:"pr-2 [&>span:first-child]:hidden",children:e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Project"})]}),e.jsx("span",{className:"typography-micro text-muted-foreground ml-6",children:"Only in current project"})]})})]})]})]}),e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Lowercase letters, numbers, and hyphens only. Cannot start or end with hyphen."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"typography-ui-label font-medium text-foreground",children:["Description ",e.jsx("span",{className:"text-destructive",children:"*"})]}),e.jsx(Ts,{value:b,onChange:ve=>N(ve.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(Ts,{value:v,onChange:ve=>k(ve.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(Ce,{variant:"outline",size:"sm",onClick:me,className:"gap-1.5",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add File"]})]}),(()=>{const ve=m?M:D;return ve.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:ve.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:()=>Se(Be.path),children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(tr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("span",{className:"typography-ui-label truncate",children: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(Ce,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:W=>{W.stopPropagation(),Pe(Be.path)},children:e.jsx(qs,{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(Ce,{size:"sm",variant:"default",onClick:Q,disabled:A||!O,className:"gap-2 h-6 px-2 text-xs w-fit",children:[e.jsx(pa,{className:"h-3 w-3"}),A?"Saving...":m?"Create Skill":"Save Changes"]})}),e.jsx(ms,{open:$,onOpenChange:ve=>{H(ve),ve||V(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(Ns,{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(ht,{value:U,onChange:ve=>K(ve.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(Ts,{value:se,onChange:ve=>Y(ve.target.value),placeholder:"File content...",className:"font-mono typography-meta flex-1 min-h-[200px] max-h-full resize-none"})]})]}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"ghost",onClick:()=>{H(!1),V(null)},className:"text-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),e.jsx(Zr,{onClick:he,disabled:ae||!z,children:re?"Save Changes":"Create File"})]})]})})]})})},rj="__add_provider__",nj=({onItemSelect:s})=>{const r=rt(u=>u.providers),t=rt(u=>u.selectedProviderId),n=rt(u=>u.setSelectedProvider),{isMobile:o}=_t(),[a,i]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),l=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||i(typeof window.opencodeDesktop<"u")},[]);const d=a?"bg-transparent":l?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",d),children:[e.jsx("div",{className:R("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(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:()=>{n(rj),s?.()},"aria-label":"Connect provider",title:"Connect provider",children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsx(ft,{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(Xn,{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:R("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(is,{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)})})]})},oj=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short",maximumFractionDigits:1,minimumFractionDigits:0}),Fd=s=>{if(typeof s!="number"||Number.isNaN(s))return null;if(s===0)return"0";const r=oj.format(s);return r.endsWith(".0")?r.slice(0,-2):r},Rd="__add_provider__",An=s=>typeof s=="object"&&s!==null,_d=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()},aj=s=>{if(!An(s))return{};const r={};for(const[t,n]of Object.entries(s))Array.isArray(n)&&(r[t]=n.filter(o=>An(o)));return r},ij=s=>{if(typeof s=="string")return{id:s};if(!An(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}},lj=s=>{let r=[];Array.isArray(s)?r=s:An(s)&&(Array.isArray(s.all)?r=s.all:Array.isArray(s.providers)&&(r=s.providers));const t=r.map(o=>ij(o)).filter(o=>!!o),n=new Set;return t.filter(o=>n.has(o.id)?!1:(n.add(o.id),!0))},cj=()=>{const s=rt(F=>F.providers),r=rt(F=>F.selectedProviderId),t=rt(F=>F.setSelectedProvider),n=rt(F=>F.getModelMetadata),[o,a]=c.useState({}),[i,l]=c.useState(!1),[d,u]=c.useState({}),[m,f]=c.useState(null),[p,g]=c.useState(""),[w,h]=c.useState(null),[j,x]=c.useState({}),[y,b]=c.useState({}),[N,v]=c.useState([]),[k,D]=c.useState(!1),[C,M]=c.useState(null),[S,A]=c.useState(""),[I,_]=c.useState(""),[T,P]=c.useState(!1);c.useEffect(()=>{!r&&s.length>0&&t(s[0].id)},[s,r,t]),c.useEffect(()=>{let F=!0;return(async()=>{l(!0);try{const 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 Q=await z.json().catch(()=>({}));if(!F)return;a(aj(Q))}catch(z){if(!F)return;console.error("Failed to load provider auth methods:",z),te.error("Failed to load provider authentication methods")}finally{F&&l(!1)}})(),()=>{F=!1}},[]),c.useEffect(()=>{let F=!0;return(async()=>{D(!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 Q=await z.json().catch(()=>({}));if(!F)return;v(lj(Q))}catch(z){if(!F)return;console.error("Failed to load available providers:",z),M("Unable to load provider list")}finally{F&&D(!1)}})(),()=>{F=!1}},[]);const L=c.useMemo(()=>new Set(s.map(F=>F.id)),[s]),Z=c.useMemo(()=>N.filter(F=>!L.has(F.id)),[N,L]);c.useEffect(()=>{if(r===Rd){if(!S&&Z.length>0){A(Z[0].id);return}S&&!Z.some(F=>F.id===S)&&A(Z[0]?.id??"")}},[r,S,Z]);const q=s.find(F=>F.id===r),$=async F=>{const O=d[F]?.trim()??"";if(!O){te.error("API key is required");return}const z=`api:${F}`;f(z);try{const Q=await fetch(`/api/auth/${encodeURIComponent(F)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"api",key:O})}),me=await Q.json().catch(()=>null);if(!Q.ok){const Se=me?.error||"Failed to save API key";throw new Error(Se)}te.success("API key saved"),u(Se=>({...Se,[F]:""})),await Vn({scopes:["providers"],mode:"active"}),t(F)}catch(Q){console.error("Failed to save API key:",Q),te.error("Failed to save API key")}finally{f(null)}},H=async(F,O)=>{const z=`oauth:${F}:${O}`;f(z);try{const Q=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/authorize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({method:O})}),me=await Q.json().catch(()=>null);if(!Q.ok){const G=me?.error||"Failed to start OAuth flow";throw new Error(G)}const Se=An(me)?me:{},he=An(Se.data)?Se.data:Se,Pe=typeof he.url=="string"&&he.url||typeof he.verification_uri_complete=="string"&&he.verification_uri_complete||typeof he.verification_uri=="string"&&he.verification_uri||void 0,ve=typeof he.instructions=="string"&&he.instructions||typeof he.message=="string"&&he.message||void 0,Be=typeof he.user_code=="string"&&he.user_code||typeof he.code=="string"&&he.code||typeof he.userCode=="string"&&he.userCode||void 0;if(!Pe&&!ve&&!Be)throw new Error("No OAuth details returned");const W=`${F}:${O}`;b(G=>({...G,[W]:{url:Pe,instructions:ve,userCode:Be}})),Pe&&window.open(Pe,"_blank","noopener,noreferrer"),h({providerId:F,methodIndex:O}),te.message("Complete the OAuth flow in your browser")}catch(Q){console.error("Failed to start OAuth flow:",Q),te.error("Failed to start OAuth flow")}finally{f(null)}},U=async(F,O)=>{const z=`${F}:${O}`,Q=j[z]?.trim(),me=`oauth-complete:${F}:${O}`;f(me);try{const Se={method:O};Q&&(Se.code=Q);const he=await fetch(`/api/provider/${encodeURIComponent(F)}/oauth/callback`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Se)}),Pe=await he.json().catch(()=>null);if(!he.ok){const ve=Pe?.error||"Failed to complete OAuth flow";throw new Error(ve)}te.success("OAuth connection completed"),x(ve=>({...ve,[z]:""})),h(null),await Vn({scopes:["providers"],mode:"active"}),t(F)}catch(Se){console.error("Failed to complete OAuth flow:",Se),te.error("Failed to complete OAuth flow")}finally{f(null)}},K=async F=>{try{await navigator.clipboard.writeText(F),te.success("OAuth link copied")}catch(O){console.error("Failed to copy OAuth link:",O),te.error("Failed to copy OAuth link")}},se=async F=>{try{await navigator.clipboard.writeText(F),te.success("Device code copied")}catch(O){console.error("Failed to copy device code:",O),te.error("Failed to copy device code")}},Y=async F=>{const O=`disconnect:${F}`;f(O);try{const z=await fetch(`/api/provider/${encodeURIComponent(F)}/auth`,{method:"DELETE",headers:{"Content-Type":"application/json"}}),Q=await z.json().catch(()=>null);if(!z.ok){const me=Q?.error||"Failed to disconnect provider";throw new Error(me)}te.success("Provider disconnected"),await Vn({scopes:["providers"],mode:"active"})}catch(z){console.error("Failed to disconnect provider:",z),te.error("Failed to disconnect provider")}finally{f(null)}},re=r===Rd;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(Xn,{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(ft,{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}):Z.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"All available providers are already connected."}):e.jsxs(Vt,{open:T,onOpenChange:F=>{P(F),F||_("")},children:[e.jsx(Gt,{asChild:!0,children:e.jsxs("button",{type:"button",className:R("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?Z.find(F=>F.id===S)?.name||S:"Select provider"}),e.jsx(It,{className:"h-4 w-4 text-muted-foreground"})]})}),e.jsxs(qt,{align:"start",className:"min-w-[200px] p-0",onCloseAutoFocus:F=>F.preventDefault(),children:[e.jsxs("div",{className:"flex items-center gap-2 border-b px-3 py-2",onKeyDown:F=>F.stopPropagation(),children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("input",{type:"text",value:I,onChange:F=>_(F.target.value),onKeyDown:F=>F.stopPropagation(),placeholder:"Search providers...",className:"flex-1 bg-transparent typography-meta outline-none placeholder:text-muted-foreground",autoFocus:!0})]}),e.jsx(ft,{outerClassName:"max-h-[240px]",className:"p-1",children:(()=>{const F=Z.filter(O=>{const z=I.toLowerCase();return(O.name||O.id).toLowerCase().includes(z)||O.id.toLowerCase().includes(z)});return F.length===0?e.jsx("p",{className:"py-4 text-center typography-meta text-muted-foreground",children:"No providers found"}):F.map(O=>e.jsxs(Dt,{onSelect:()=>{A(O.id),P(!1),_("")},className:"flex items-center justify-between",children:[e.jsx("span",{children:O.name||O.id}),S===O.id&&e.jsx(Pt,{className:"h-4 w-4 text-primary"})]},O.id))})()})]})]})]}),S&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground",children:"Authentication"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{type:"password",value:d[S]??"",onChange:F=>u(O=>({...O,[S]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ce,{size:"sm",onClick:()=>$(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 O=(o[S]??[]).filter(z=>_d(z)==="oauth");return O.length===0?null:e.jsx("div",{className:"space-y-3",children:O.map((z,Q)=>{const me=z.label||z.name||`OAuth method ${Q+1}`,Se=`${S}:${Q}`,he=w?.providerId===S&&w?.methodIndex===Q;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:me}),(z.description||z.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(z.description||z.help)})]}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>H(S,Q),disabled:m===`oauth:${S}:${Q}`,className:"h-8",children:"Connect"})]}),y[Se]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:y[Se]?.instructions}),y[Se]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:y[Se]?.userCode,readOnly:!0}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>se(y[Se]?.userCode??""),className:"h-8",children:"Copy code"})]}),y[Se]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:y[Se]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:y[Se]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>K(y[Se]?.url??""),className:"h-8",children:"Copy link"})]})]}),he&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:j[Se]??"",onChange:Pe=>x(ve=>({...ve,[Se]:Pe.target.value})),placeholder:"Authorization code (if required)"}),e.jsx(Ce,{size:"sm",onClick:()=>U(S,Q),disabled:m===`oauth-complete:${S}:${Q}`,className:"h-8",children:m===`oauth-complete:${S}:${Q}`?"Saving…":"Complete"})]})]},`${S}-${me}`)})})})()]})]})]})});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(Xn,{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 V=Array.isArray(q.models)?q.models:[],E=(o[q.id]??[]).filter(F=>_d(F)==="oauth"),B=V.filter(F=>{const O=typeof F?.name=="string"?F.name:"",z=typeof F?.id=="string"?F.id:"",Q=p.trim().toLowerCase();return Q?O.toLowerCase().includes(Q)||z.toLowerCase().includes(Q):!0});return e.jsx(ft,{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(is,{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"}),i?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading authentication methods…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"API key"}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{type:"password",value:d[q.id]??"",onChange:F=>u(O=>({...O,[q.id]:F.target.value})),placeholder:"sk-..."}),e.jsx(Ce,{size:"sm",onClick:()=>$(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(Ce,{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"})}),E.length>0&&e.jsx("div",{className:"space-y-3",children:E.map((F,O)=>{const z=F.label||F.name||`OAuth method ${O+1}`,Q=`${q.id}:${O}`,me=w?.providerId===q.id&&w?.methodIndex===O;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}),(F.description||F.help)&&e.jsx("div",{className:"typography-meta text-muted-foreground",children:String(F.description||F.help)})]}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>H(q.id,O),disabled:m===`oauth:${q.id}:${O}`,className:"h-8",children:"Connect"})]}),y[Q]?.instructions&&e.jsx("p",{className:"typography-meta text-muted-foreground",children:y[Q]?.instructions}),y[Q]?.userCode&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:y[Q]?.userCode,readOnly:!0}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>se(y[Q]?.userCode??""),className:"h-8",children:"Copy code"})]}),y[Q]?.url&&e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center",children:[e.jsx(ht,{value:y[Q]?.url,readOnly:!0}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ce,{size:"sm",variant:"outline",className:"h-8",asChild:!0,children:e.jsx("a",{href:y[Q]?.url,target:"_blank",rel:"noopener noreferrer",children:"Open link"})}),e.jsx(Ce,{size:"sm",variant:"outline",onClick:()=>K(y[Q]?.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(ht,{value:j[Q]??"",onChange:Se=>x(he=>({...he,[Q]:Se.target.value})),placeholder:"Paste authorization code"}),e.jsx(Ce,{size:"sm",onClick:()=>U(q.id,O),disabled:m===`oauth-complete:${q.id}:${O}`,className:"h-8",children:m===`oauth-complete:${q.id}:${O}`?"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(ht,{value:p,onChange:F=>g(F.target.value),placeholder:"Filter models..."}),e.jsx("div",{className:"border-t border-border/40",children:B.length===0?e.jsx("p",{className:"typography-meta text-muted-foreground py-3 px-2",children:"No models match this filter."}):B.map(F=>{const O=typeof F?.id=="string"?F.id:"",z=typeof F?.name=="string"?F.name:O,Q=O?n(q.id,O):void 0,me=Fd(Q?.limit?.context),Se=Fd(Q?.limit?.output),he=[];return Q?.tool_call&&he.push({key:"tools",icon:fa,label:"Tool calling"}),Q?.reasoning&&he.push({key:"reasoning",icon:ar,label:"Reasoning"}),Q?.attachment&&he.push({key:"image",icon:br,label:"Image input"}),e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 border-b border-border/40",children:[e.jsx("span",{className:"typography-meta font-medium text-foreground truncate flex-1 min-w-0",children:z}),(me||Se)&&e.jsxs("span",{className:"typography-micro text-muted-foreground flex-shrink-0",children:[me?`${me} ctx`:"",me&&Se?" · ":"",Se?`${Se} out`:""]}),he.length>0&&e.jsx("div",{className:"flex items-center gap-1 flex-shrink-0",children:he.map(({key:Pe,icon:ve,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(ve,{className:"h-3 w-3"})},Pe))})]},O)})})]})]})})},dj={branch:$t,briefcase:tl,house:el,graduation:Zi,code:nr,heart:bu},uj={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)"},mj=({onItemSelect:s})=>{const{selectedProfileId:r,profiles:t,globalIdentity:n,setSelectedProfile:o,deleteProfile:a,loadProfiles:i,loadGlobalIdentity:l,loadDiscoveredCredentials:d,getUnimportedCredentials:u}=Sa(),{setSidebarOpen:m}=_e(),{isMobile:f}=_t(),[p,g]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),w=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||g(typeof window.opencodeDesktop<"u")},[]);const h=u();c.useEffect(()=>{i(),l(),d()},[i,l,d]);const j=N=>{o(`import:${N.host}:${N.username}`),s?.(),f&&m(!1)},x=p?"bg-transparent":w?"bg-background":"bg-sidebar",y=()=>{o("new"),s?.(),f&&m(!1)},b=async N=>{window.confirm(`Are you sure you want to delete profile "${N.name}"?`)&&(await a(N.id)?te.success(`Profile "${N.name}" deleted successfully`):te.error("Failed to delete profile"))};return e.jsxs("div",{className:R("flex h-full flex-col",x),children:[e.jsx("div",{className:R("border-b px-3",f?"mt-2 py-3":"py-3"),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Total ",t.length]}),e.jsx(Ce,{type:"button",variant:"ghost",size:"icon",className:"h-7 w-7 -my-1 text-muted-foreground",onClick:y,children:e.jsx(Kt,{className:"size-4"})})]})}),e.jsxs(ft,{outerClassName:"flex-1 min-h-0",className:"space-y-1 px-3 py-2",children:[n&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 pb-1.5 pt-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"System Default"}),e.jsx(Od,{profile:n,isSelected:r==="global",onSelect:()=>{o("global"),s?.(),f&&m(!1)},onDelete:void 0,isReadOnly:!0})]}),t.length>0&&e.jsx("div",{className:"px-2 pb-1.5 pt-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom Profiles"}),t.length===0&&!n&&h.length===0?e.jsxs("div",{className:"py-12 px-4 text-center text-muted-foreground",children:[e.jsx($t,{className:"mx-auto mb-3 h-10 w-10 opacity-50"}),e.jsx("p",{className:"typography-ui-label font-medium",children:"No profiles configured"}),e.jsx("p",{className:"typography-meta mt-1 opacity-75",children:"Use the + button above to create one"})]}):e.jsx(e.Fragment,{children:t.map(N=>e.jsx(Od,{profile:N,isSelected:r===N.id,onSelect:()=>{o(N.id),s?.(),f&&m(!1)},onDelete:()=>b(N)},N.id))}),h.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"}),h.map(N=>e.jsx(pj,{credential:N,onImport:()=>j(N)},`${N.host}-${N.username}`))]})]})]})},Od=({profile:s,isSelected:r,onSelect:t,onDelete:n,isReadOnly:o=!1})=>{const a=dj[s.icon||"branch"]||$t,i=uj[s.color||""],l=s.authType||"ssh";return e.jsx("div",{className:R("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(a,{className:"w-4 h-4 flex-shrink-0",style:{color:i}}),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:l})]}),e.jsx("div",{className:"typography-micro text-muted-foreground/60 truncate leading-tight",children:l==="token"&&s.host?s.host:s.userEmail})]}),!o&&n&&e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsx(qt,{align:"end",className:"w-fit min-w-20",children:e.jsxs(Dt,{onClick:d=>{d.stopPropagation(),n()},className:"text-destructive focus:text-destructive",children:[e.jsx(qs,{className:"h-4 w-4 mr-px"}),"Delete"]})})]})]})})},fj=s=>{const r=s.split("/");return r.length>=3?r[r.length-1]:s},pj=({credential:s,onImport:r})=>{const t=fj(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(Ce,{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(Er,{className:"h-3 w-3"}),"Import"]})]})})},$d=[{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)"}],hj=[{key:"branch",Icon:$t,label:"Branch"},{key:"briefcase",Icon:tl,label:"Work"},{key:"house",Icon:el,label:"Personal"},{key:"graduation",Icon:Zi,label:"School"},{key:"code",Icon:nr,label:"Code"}],gj=()=>{const{selectedProfileId:s,getProfileById:r,createProfile:t,updateProfile:n,deleteProfile:o}=Sa(),a=c.useMemo(()=>{if(s?.startsWith("import:")){const[,T,P]=s.split(":");return{host:T,username:P}}return null},[s]),i=c.useMemo(()=>s&&s!=="new"&&!a?r(s):null,[s,r,a]),l=s==="new"||a!==null,d=s==="global",[u,m]=c.useState(""),[f,p]=c.useState(""),[g,w]=c.useState(""),[h,j]=c.useState("ssh"),[x,y]=c.useState(""),[b,N]=c.useState(""),[v,k]=c.useState("keyword"),[D,C]=c.useState("branch"),[M,S]=c.useState(!1);c.useEffect(()=>{if(a){const T=a.host.split("/"),P=T.length>=3?T[T.length-1]:a.host;m(P),p(a.username),w(""),j("token"),y(""),N(a.host),k("string"),C("code")}else l?(m(""),p(""),w(""),j("ssh"),y(""),N(""),k("keyword"),C("branch")):i&&(m(i.name),p(i.userName),w(i.userEmail),j(i.authType||"ssh"),y(i.sshKey||""),N(i.host||""),k(i.color||"keyword"),C(i.icon||"branch"))},[i,l,s,a]);const A=async()=>{if(!f.trim()||!g.trim()){te.error("User name and email are required");return}if(h==="token"&&!b.trim()){te.error("Host is required for token-based authentication");return}S(!0);try{const T={name:u.trim()||f.trim(),userName:f.trim(),userEmail:g.trim(),authType:h,sshKey:h==="ssh"&&x.trim()||null,host:h==="token"&&b.trim()||null,color:v,icon:D};let P;if(l)P=await t(T);else if(s)P=await n(s,T);else return;P?te.success(l?"Profile created successfully":"Profile updated successfully"):te.error(l?"Failed to create profile":"Failed to update profile")}catch(T){console.error("Error saving profile:",T),te.error("An error occurred while saving")}finally{S(!1)}},I=async()=>{if(!(!s||l)&&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(T){console.error("Error deleting profile:",T),te.error("An error occurred while deleting")}},_=c.useMemo(()=>$d.find(P=>P.key===v)?.cssVar||"var(--syntax-keyword)",[v]);return s?e.jsx(ft,{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":l?"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`:l?"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(ht,{value:u,onChange:T=>m(T.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:$d.map(T=>e.jsx("button",{onClick:()=>k(T.key),className:R("w-8 h-8 rounded-lg border-2 transition-all",v===T.key?"border-foreground scale-110":"border-transparent hover:border-border"),style:{backgroundColor:T.cssVar},title:T.label},T.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:hj.map(T=>{const P=T.Icon;return e.jsx("button",{onClick:()=>C(T.key),className:R("w-8 h-8 rounded-lg border-2 transition-all flex items-center justify-center",D===T.key?"border-primary bg-accent scale-110":"border-border hover:border-primary/50"),title:T.label,children:e.jsx(P,{className:"w-4 h-4",style:{color:_}})},T.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(ht,{value:f,onChange:T=>p(T.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(ht,{type:"email",value:g,onChange:T=>w(T.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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:R("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(kh,{className:"w-4 h-4"}),e.jsx("span",{className:"typography-ui-label",children:"SSH Key"})]}),e.jsxs("button",{type:"button",onClick:()=>j("token"),className:R("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(Nh,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(ht,{value:x,onChange:T=>y(T.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(ht,{value:b,onChange:T=>N(T.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:[!l&&e.jsxs(Ce,{size:"sm",variant:"destructive",onClick:I,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(qs,{className:"h-3 w-3"}),"Delete Profile"]}),e.jsx("div",{className:R("flex gap-2",l&&"ml-auto"),children:e.jsxs(Ce,{size:"sm",variant:"default",onClick:A,disabled:M,className:"gap-2 h-6 px-2 text-xs",children:[e.jsx(pa,{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(Fs,{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 di(s,r,t){return Math.min(t,Math.max(r,s))}const ia=De.forwardRef(({value:s,onValueChange:r,min:t=-1/0,max:n=1/0,step:o=1,className:a,containerClassName:i,onBlur:l,onKeyDown:d,disabled:u,...m},f)=>{const p=De.useRef(null);De.useImperativeHandle(f,()=>p.current);const[g,w]=De.useState(()=>String(s));De.useEffect(()=>{document.activeElement!==p.current&&w(String(s))},[s]);const h=De.useCallback(()=>{p.current?.focus()},[]),j=De.useCallback(S=>{const A=di(S,t,n);r(A),w(String(A))},[n,t,r]),x=De.useCallback(()=>{const S=Number(g);return Number.isFinite(S)?S:s},[g,s]),y=De.useCallback(()=>{j(x()+o),h()},[j,x,h,o]),b=De.useCallback(()=>{j(x()-o),h()},[j,x,h,o]),N=S=>{const A=S.target.value;w(A);const I=Number(A);Number.isFinite(I)&&r(di(I,t,n))},v=S=>{const A=Number(g);if(!Number.isFinite(A))w(String(s));else{const I=di(A,t,n);I!==A&&r(I),w(String(I))}l?.(S)},k=S=>{if(S.key==="ArrowUp"){S.preventDefault(),y();return}if(S.key==="ArrowDown"){S.preventDefault(),b();return}d?.(S)},D=x(),C=u||D<=t,M=u||D>=n;return e.jsxs("div",{className:R("flex h-8 items-stretch overflow-hidden rounded-lg border border-border bg-background","focus-within:border-ring focus-within:ring-ring/50 focus-within:ring-[3px]",u&&"opacity-50",i),children:[e.jsx("input",{...m,ref:p,type:"number",inputMode:"numeric",min:Number.isFinite(t)?t:void 0,max:Number.isFinite(n)?n:void 0,step:o,value:g,onChange:N,onBlur:v,onKeyDown:k,disabled:u,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:R("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:y,className:R("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(ua,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button","aria-label":"Decrease value",disabled:C,onClick:b,className:R("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(It,{className:"h-3.5 w-3.5"})})]})]})});ia.displayName="NumberInput";const xj=[{value:"system",label:"System"},{value:"light",label:"Light"},{value:"dark",label:"Dark"}],Ld=[{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"}],Bd=[{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."}],El=({visibleSettings:s})=>{const{isMobile:r}=_t(),t=_e(b=>b.showReasoningTraces),n=_e(b=>b.setShowReasoningTraces),o=_e(b=>b.toolCallExpansion),a=_e(b=>b.setToolCallExpansion),i=_e(b=>b.fontSize),l=_e(b=>b.setFontSize),d=_e(b=>b.padding),u=_e(b=>b.setPadding),m=_e(b=>b.inputBarOffset),f=_e(b=>b.setInputBarOffset),p=_e(b=>b.diffLayoutPreference),g=_e(b=>b.setDiffLayoutPreference),w=Zs(b=>b.queueModeEnabled),h=Zs(b=>b.setQueueMode),{themeMode:j,setThemeMode:x}=on(),y=b=>s?s.includes(b):!0;return e.jsxs("div",{className:"w-full space-y-8",children:[y("theme")&&!Ut()&&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:xj.map(b=>e.jsx(Bs,{variant:j===b.value?"default":"outline",className:R(j===b.value?void 0:"text-foreground"),onClick:()=>x(b.value),children:b.label},b.value))})]}),y("fontSize")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Font Size"})}),e.jsxs("div",{className:"flex items-center gap-3 w-full max-w-md",children:[e.jsx("input",{type:"range",min:"50",max:"200",step:"5",value:i,onChange:b=>l(Number(b.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(ia,{value:i,onValueChange:l,min:50,max:200,step:5,"aria-label":"Font size percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>l(100),disabled:i===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset font size",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),y("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:b=>u(Number(b.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Spacing percentage"}),e.jsx("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:d}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ps,{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:b=>u(Number(b.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(ia,{value:d,onValueChange:u,min:50,max:200,step:5,"aria-label":"Spacing percentage"}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>u(100),disabled:d===100,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset spacing",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),y("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:b=>f(Number(b.target.value)),className:"flex-1 min-w-0 h-3 bg-muted rounded-full appearance-none cursor-pointer [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:w-5 [&::-webkit-slider-thumb]:h-5 [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-primary [&::-moz-range-thumb]:w-5 [&::-moz-range-thumb]:h-5 [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:bg-primary [&::-moz-range-thumb]:border-0","aria-label":"Input bar offset in pixels"}),e.jsxs("span",{className:"typography-ui-label font-medium text-foreground tabular-nums rounded-md border border-border bg-background px-2 py-1.5 min-w-[3.75rem] text-center",children:[m,"px"]}),e.jsx(Bs,{type:"button",variant:"ghost",onClick:()=>f(0),disabled:m===0,className:"h-8 w-8 px-0 border border-border bg-background hover:bg-accent disabled:opacity-100 disabled:bg-background","aria-label":"Reset input bar offset",title:"Reset",children:e.jsx(Ps,{className:"h-3.5 w-3.5"})})]})]}),y("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:Ld.find(b=>b.value===o)?.description})]}),e.jsx("div",{className:"flex gap-1 w-fit",children:Ld.map(b=>e.jsx(Bs,{variant:o===b.value?"default":"outline",className:R(o===b.value?void 0:"text-foreground"),onClick:()=>a(b.value),children:b.label},b.value))})]}),y("diffLayout")&&!r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Diff layout (Diff tab)"}),e.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Choose the default layout for file diffs. You can still override layout per file from the Diff tab."})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"flex gap-1 w-fit",children:Bd.map(b=>e.jsx(Bs,{variant:p===b.id?"default":"outline",className:R(p===b.id?void 0:"text-foreground"),onClick:()=>g(b.id),children:b.label},b.id))}),e.jsx("p",{className:"typography-meta text-muted-foreground/80 max-w-xl",children:Bd.find(b=>b.id===p)?.description})]})]}),y("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:b=>n(b.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Show thinking / reasoning traces"})]}),y("queueMode")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:w,onChange:b=>h(b.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Queue messages by default"})]}),e.jsx("p",{className:"typography-meta text-muted-foreground pl-5",children:w?`Enter queues messages, ${Jt()}+Enter sends immediately.`:`Enter sends immediately, ${Jt()}+Enter queues messages.`})]})]})},zd="https://github.com/btriapitsyn/openchamber",yj=800,ff=()=>{const[s,r]=c.useState(!1),[t,n]=c.useState(!1),o=ha(),{isMobile:a}=_t(),i=o.info?.currentVersion||"unknown",l=c.useRef(!1);c.useEffect(()=>{if(o.checking)n(!0),l.current=!0;else if(t){const u=setTimeout(()=>{n(!1),l.current&&!o.available&&!o.error&&(te.success("You are on the latest version"),l.current=!1)},yj);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:()=>Vn(),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ps,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Reload OpenCode Configuration"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["v",i]}),!o.available&&!o.error&&e.jsx("button",{onClick:()=>o.checkForUpdates(),disabled:d,className:R("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(Er,{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:zd,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ni,{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(ku,{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(Ci,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Fi,{open:s,onOpenChange:r,info:o.info,downloading:o.downloading,downloaded:o.downloaded,progress:o.progress,error:o.error,onDownload:o.downloadUpdate,onRestart:o.restartToUpdate,runtimeType:o.runtimeType})]}):e.jsxs("div",{className:"w-full space-y-6",children:[e.jsx("div",{className:"space-y-1",children:e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"About OpenChamber"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx("div",{className:"typography-ui-label text-muted-foreground",children:"Version"}),e.jsx("div",{className:"typography-ui-header font-mono",children:i})]}),o.checking&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Io,{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:R("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(Er,{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:R("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:zd,target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ni,{className:"h-4 w-4"}),e.jsx("span",{children:"GitHub"})]}),e.jsxs("a",{href:"https://x.com/btriapitsyn",target:"_blank",rel:"noopener noreferrer",className:R("flex items-center gap-1.5 text-muted-foreground hover:text-foreground","typography-meta transition-colors"),children:[e.jsx(Ci,{className:"h-4 w-4"}),e.jsx("span",{children:"@btriapitsyn"})]})]}),e.jsx(Fi,{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})]})},bj=1440*60*1e3,pf=5,Wd=1440*60*1e3,ui=s=>s.time?.updated??s.time?.created??0,Hd=({sessions:s,currentSessionId:r,cutoffDays:t,keepRecent:n=pf,now:o=Date.now()})=>{if(!Array.isArray(s)||t<=0)return[];const a=o-t*bj,i=[...s].sort((d,u)=>ui(u)-ui(d)),l=new Set(i.slice(0,n).map(d=>d.id));return i.filter(d=>{if(!d?.id||l.has(d.id)||d.id===r||d.share)return!1;const u=ui(d);return u?u<a:!1}).map(d=>d.id)},hf=s=>{const r=s?.autoRun!==!1,t=ue(h=>h.sessions),n=ue(h=>h.currentSessionId),o=ue(h=>h.isLoading),a=ue(h=>h.deleteSessions),i=_e(h=>h.autoDeleteEnabled),l=_e(h=>h.autoDeleteAfterDays),d=_e(h=>h.autoDeleteLastRunAt),u=_e(h=>h.setAutoDeleteLastRunAt),[m,f]=c.useState(!1),p=c.useRef(!1),g=c.useMemo(()=>l<=0?[]:Hd({sessions:t,currentSessionId:n,cutoffDays:l}),[l,n,t]),w=c.useCallback(async({force:h=!1}={})=>{if(p.current)return{deletedIds:[],failedIds:[],skippedReason:"running"};if((!i||l<=0)&&!h)return{deletedIds:[],failedIds:[],skippedReason:"disabled"};if(o)return{deletedIds:[],failedIds:[],skippedReason:"loading"};const j=Date.now();if(!h&&d&&j-d<Wd)return{deletedIds:[],failedIds:[],skippedReason:"cooldown"};if(t.length===0)return{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};const x=Hd({sessions:t,currentSessionId:n,cutoffDays:l,now:j});if(x.length===0)return u(j),{deletedIds:[],failedIds:[],skippedReason:"no-candidates"};p.current=!0,f(!0);try{return await a(x,{silent:!0})}finally{p.current=!1,f(!1),u(Date.now())}},[l,i,d,n,a,o,t,u]);return c.useEffect(()=>{if(!r||!i||l<=0||o||t.length===0)return;const h=Date.now();d&&h-d<Wd||w()},[l,i,d,r,o,t.length,w]),{candidates:g,isRunning:m,runCleanup:w,keepRecentCount:pf}},mi=1,fi=365,gf=()=>{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,i]=c.useState(String(t));c.useEffect(()=>{i(String(t))},[t]);const{candidates:l,isRunning:d,runCleanup:u}=hf({autoRun:!1}),m=l.length,f=c.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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{sideOffset:8,className:"max-w-xs",children:["Automatically delete inactive sessions based on their last activity.",e.jsx("br",{}),"You can also run a one-time cleanup without enabling auto-cleanup.",e.jsx("br",{}),"Keeps the most recent 5 sessions, and never deletes shared sessions."]})]})]})}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:r,onChange:p=>n(p.target.checked)}),e.jsx("span",{className:"typography-ui-header font-semibold text-foreground",children:"Enable auto-cleanup"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[s?e.jsx("input",{type:"number",inputMode:"numeric",value:a,onChange:p=>{const g=p.target.value;if(i(g),g.trim()==="")return;const w=Number(g);if(!Number.isFinite(w))return;const h=Math.min(fi,Math.max(mi,Math.round(w)));o(h)},onBlur:()=>{if(a.trim()===""){i(String(t));return}const p=Number(a);if(!Number.isFinite(p)){i(String(t));return}const g=Math.min(fi,Math.max(mi,Math.round(p)));o(g),i(String(g))},"aria-label":"Retention period in days",className:"h-8 w-16 rounded-lg border border-border bg-background px-2 text-center typography-ui-label text-foreground focus:border-ring focus:outline-none focus:ring-2 focus:ring-ring/50"}):e.jsx(ia,{value:t,onValueChange:o,min:mi,max:fi,step:1,"aria-label":"Retention period in days"}),e.jsx("span",{className:"typography-ui-label text-muted-foreground",children:"days since last activity"})]}),e.jsx(Bs,{type:"button",variant:"outline",onClick:f,disabled:d,children:d?"Cleaning up...":"Run cleanup now"})]}),e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["Eligible for deletion right now: ",m]})]})},Ud="opencode",Vd="big-pickle",wj=(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===Ud)?.models.some(o=>o.id===Vd))return{providerId:Ud,modelId:Vd};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},xf=()=>{const s=rt(S=>S.setProvider),r=rt(S=>S.setModel),t=rt(S=>S.setAgent),n=rt(S=>S.setCurrentVariant),o=rt(S=>S.setSettingsDefaultModel),a=rt(S=>S.setSettingsDefaultVariant),i=rt(S=>S.setSettingsDefaultAgent),l=rt(S=>S.settingsAutoCreateWorktree),d=rt(S=>S.setSettingsAutoCreateWorktree),u=rt(S=>S.providers),[m,f]=c.useState(),[p,g]=c.useState(),[w,h]=c.useState(),[j,x]=c.useState(!0),y=c.useMemo(()=>wj(m,u),[m,u]);c.useEffect(()=>{(async()=>{try{let A=null;if(Zt())A=await sn();else{const I=vr()?.settings;if(I)try{const T=(await I.load())?.settings;T&&(A={defaultModel:typeof T.defaultModel=="string"?T.defaultModel:void 0,defaultVariant:typeof T.defaultVariant=="string"?T.defaultVariant:void 0,defaultAgent:typeof T.defaultAgent=="string"?T.defaultAgent:void 0})}catch{}if(!A){const _=await fetch("/api/config/settings",{method:"GET",headers:{Accept:"application/json"}});_.ok&&(A=await _.json())}}if(A){const I=typeof A.defaultModel=="string"&&A.defaultModel.trim().length>0?A.defaultModel.trim():void 0,_=typeof A.defaultVariant=="string"&&A.defaultVariant.trim().length>0?A.defaultVariant.trim():void 0,T=typeof A.defaultAgent=="string"&&A.defaultAgent.trim().length>0?A.defaultAgent.trim():void 0;I!==void 0&&f(I),_!==void 0&&g(_),T!==void 0&&h(T)}}catch(A){console.warn("Failed to load defaults settings:",A)}finally{x(!1)}})()},[]);const b=c.useCallback(async(S,A)=>{const I=S&&A?`${S}/${A}`:void 0;f(I),g(void 0),a(void 0),n(void 0),o(I),S&&A&&u.find(T=>T.id===S)&&(s(S),r(A));try{if(await rs({defaultModel:I??"",defaultVariant:""}),!Zt()){const _=await fetch("/api/config/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({defaultModel:I})});_.ok||console.warn("Failed to save default model to server:",_.status,_.statusText)}}catch(_){console.warn("Failed to save default model:",_)}},[u,n,s,r,o,a]),N="__default__",v=c.useCallback(async S=>{const A=S===N?void 0:S||void 0;g(A),a(A),n(A);try{await rs({defaultVariant:A??""})}catch(I){console.warn("Failed to save default variant:",I)}},[n,a]),k=c.useCallback(async S=>{const A=S||void 0;h(A),i(A),S&&t(S);try{await rs({defaultAgent:A??""})}catch(I){console.warn("Failed to save default agent:",I)}},[t,i]),D=c.useMemo(()=>{if(!y.providerId||!y.modelId)return[];const I=u.find(_=>_.id===y.providerId)?.models.find(_=>_.id===y.modelId)?.variants;return I?Object.keys(I):[]},[y.modelId,y.providerId,u]),C=D.length>0;c.useEffect(()=>{!C&&p&&(g(void 0),a(void 0),n(void 0),rs({defaultVariant:""}).catch(()=>{}))},[p,n,a,C]);const M=c.useCallback(async S=>{const A=S.target.checked;d(A);try{await rs({autoCreateWorktree:A})}catch(I){console.warn("Failed to save auto create worktree setting:",I)}},[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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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(ka,{providerId:y.providerId,modelId:y.modelId,onChange:b})]}),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(js,{value:p??N,onValueChange:v,children:[e.jsx(Ss,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Jr,{placeholder:"Thinking"})}),e.jsxs(ks,{children:[e.jsx(Bt,{value:N,className:"pr-2 [&>span:first-child]:hidden",children:"Default"}),D.map(S=>e.jsx(Bt,{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(uf,{agentName:w||"",onChange:k})]})]}),(y.providerId||w)&&e.jsxs("div",{className:"typography-meta text-muted-foreground",children:["New sessions will start with:"," ",y.providerId&&e.jsxs("span",{className:"text-foreground",children:[y.providerId,"/",y.modelId,C?` (${p??"default"})`:""]}),y.providerId&&w&&" / ",w&&e.jsx("span",{className:"text-foreground",children:w})]}),e.jsxs("div",{className:"pt-2",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"h-3.5 w-3.5 accent-primary",checked:l,onChange: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:l?`New session (Worktree): ${Jt()} + N • New session (Standard): Shift + ${Jt()} + N`:`New session (Standard): ${Jt()} + N • New session (Worktree): Shift + ${Jt()} + N`})]})]})},Yn="opencode",Gd="big-pickle",vj=(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===Yn)?.models.some(o=>o.id===Gd))return{providerId:Yn,modelId:Gd};const n=r[0];return n?.models[0]?{providerId:n.id,modelId:n.models[0].id}:{providerId:"",modelId:""}},jj=()=>{const s=rt(d=>d.settingsCommitMessageModel),r=rt(d=>d.setSettingsCommitMessageModel),t=rt(d=>d.providers),[n,o]=c.useState(!0),a=c.useMemo(()=>t.filter(d=>d.id===Yn),[t]),i=c.useMemo(()=>{const d=s?.startsWith(`${Yn}/`)?s:void 0;return vj(d,a)},[s,a]);c.useEffect(()=>{(async()=>{try{let u=null;if(Zt())u=await sn();else{const m=vr()?.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 l=c.useCallback(async(d,u)=>{const m=d&&u?`${d}/${u}`:void 0;r(m);try{await rs({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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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(ka,{providerId:i.providerId,modelId:i.modelId,onChange:l,allowedProviderIds:[Yn]}),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"})]})]})]})})]})},Sj=()=>{const s=Ft(E=>E.getActiveProject()),r=Ft(E=>E.updateWorktreeDefaults),t=s?.path??null,n=s?.worktreeDefaults,o=fl(t),a=im(t),{sessions:i,getWorktreeMetadata:l}=ue(),[d,u]=c.useState(n?.branchPrefix??""),[m,f]=c.useState(n?.baseBranch??"HEAD"),[p,g]=c.useState([]),[w,h]=c.useState(!1),[j,x]=c.useState(!1),[y,b]=c.useState(null),[N,v]=c.useState(null),[k,D]=c.useState([]),[C,M]=c.useState(!1),S=".openchamber",A=c.useCallback((E,B)=>{const F=E.replace(/\\/g,"/").replace(/\/+$/,""),O=!F||F==="/"?`/${S}`:`${F}/${S}`;return B?`${O}/${B}`:O},[]),I=c.useCallback(async()=>{if(!(!t||y===!1))try{const B=(await Nn(t)).map(Q=>Cn(t,Q)),O=`${A(t,"")}/`,z=B.filter(Q=>Q.path.startsWith(O));D(z)}catch{}},[t,y,A]);c.useEffect(()=>{if(!t)return;let E=!1;return x(!0),M(!0),b(null),v(null),D([]),(async()=>{try{const B=await rn(t);if(E)return;if(b(B),B){const[F,O]=await Promise.all([ll(t),Nn(t).catch(()=>[])]);if(!E){F&&v({all:F.all,current:F.current});const z=O.map(he=>Cn(t,he)),me=`${`${t.replace(/\\/g,"/").replace(/\/+$/,"")}/${S}`}/`,Se=z.filter(he=>he.path.startsWith(me));D(Se)}}}catch{}finally{E||(x(!1),M(!1))}})(),()=>{E=!0}},[t]),c.useEffect(()=>{if(!t)return;let E=!1;return h(!0),(async()=>{try{const B=await io(t);E||g(B.length>0?B:[""])}catch{E||g([""])}finally{E||h(!1)}})(),()=>{E=!0}},[t]),c.useEffect(()=>{u(n?.branchPrefix??""),f(n?.baseBranch??"HEAD")},[n]);const _=N??a,T=y??o,P=c.useMemo(()=>{const E=[],B=_?.current?`Current (HEAD: ${_.current})`:"Current (HEAD)";return E.push({value:"HEAD",label:B,group:"special"}),_&&(_.all.filter(z=>!z.startsWith("remotes/")).sort((z,Q)=>z.localeCompare(Q)).forEach(z=>{E.push({value:z,label:z,group:"local"})}),_.all.filter(z=>z.startsWith("remotes/")).map(z=>z.replace(/^remotes\//,"")).sort((z,Q)=>z.localeCompare(Q)).forEach(z=>{E.push({value:z,label:z,group:"remote"})})),E},[_]),L=c.useRef(null),Z=c.useCallback(E=>{u(E),L.current=E},[]),q=c.useCallback(E=>{s?.id&&(r(s.id,{branchPrefix:E}),L.current=null)},[s?.id,r]),$=c.useCallback(()=>{q(d)},[d,q]);c.useEffect(()=>()=>{L.current!==null&&s?.id&&r(s.id,{branchPrefix:L.current})},[s?.id,r]);const H=c.useCallback(E=>{f(E),s?.id&&r(s.id,{baseBranch:E})},[s?.id,r]),U=c.useCallback((E,B)=>{g(F=>{const O=[...F];return O[E]=B,O})},[]),K=c.useCallback(()=>{g(E=>[...E,""])},[]),se=c.useCallback(E=>{g(B=>B.filter((F,O)=>O!==E))},[]),Y=c.useCallback(async()=>{if(!t)return;const E=p.filter(B=>B.trim().length>0);await qu(t,E)},[t,p]),re=c.useCallback(()=>{Y()},[Y]),V=c.useCallback(E=>{const B=E.path.replace(/\\/g,"/").replace(/\/+$/,""),F=i.filter(he=>{if(l(he.id)?.path===E.path)return!0;const ve=he.directory;return!!(ve&&ve.replace(/\\/g,"/").replace(/\/+$/,"")===B)}),O=new Set(F.map(he=>he.id)),z=he=>{const Pe=i.filter(Be=>{const W=Be.parentID;return W&&he.has(W)});if(Pe.length===0)return[];const ve=new Set(Pe.map(Be=>Be.id));return[...Pe,...z(ve)]},Q=z(O),me=new Set,Se=[...F,...Q].filter(he=>me.has(he.id)?!1:(me.add(he.id),!0));Dn.requestDelete({sessions:Se,mode:"worktree",worktree:E})},[i,l]),ae=c.useMemo(()=>i.map(E=>E.id).join(","),[i]);return c.useEffect(()=>{y&&t&&I()},[ae,y,t,I]),t?j?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):T===!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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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(ht,{value:d,onChange:E=>Z(E.target.value),onBlur:$,placeholder:"feature",className:"max-w-xs"})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Base branch"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(nt,{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(js,{value:m,onValueChange:H,children:[e.jsx(Ss,{className:"w-auto max-w-xs typography-meta text-foreground",children:e.jsx(Jr,{placeholder:"Select a branch"})}),e.jsxs(ks,{children:[e.jsxs(qr,{children:[e.jsx(jn,{children:"Default"}),P.filter(E=>E.group==="special").map(E=>e.jsx(Bt,{value:E.value,children:E.label},E.value))]}),P.some(E=>E.group==="local")&&e.jsxs(e.Fragment,{children:[e.jsx(na,{}),e.jsxs(qr,{children:[e.jsx(jn,{children:"Local branches"}),P.filter(E=>E.group==="local").map(E=>e.jsx(Bt,{value:E.value,children:E.label},E.value))]})]}),P.some(E=>E.group==="remote")&&e.jsxs(e.Fragment,{children:[e.jsx(na,{}),e.jsxs(qr,{children:[e.jsx(jn,{children:"Remote branches"}),P.filter(E=>E.group==="remote").map(E=>e.jsx(Bt,{value:E.value,children:E.label},E.value))]})]})]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Setup commands"}),e.jsxs("p",{className:"typography-meta text-muted-foreground",children:["Run automatically when a new worktree is created. Use ",e.jsx("code",{className:"font-mono text-xs bg-sidebar-accent/50 px-1 rounded",children:"$ROOT_WORKTREE_PATH"})," for the project root."]})]}),w?e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):e.jsxs("div",{className:"space-y-2",children:[p.map((E,B)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:E,onChange:F=>U(B,F.target.value),onBlur:re,placeholder:"e.g., bun install",className:"flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{se(B),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"})})]},B)),e.jsxs("button",{type:"button",onClick:K,className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]}),e.jsxs("div",{className:"space-y-4 border-t border-border/40 pt-6",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:"Existing worktrees"}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(ss,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsxs(nt,{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(E=>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:E.label||E.branch||"Detached HEAD"}),e.jsx("p",{className:"typography-micro text-muted-foreground/60 truncate",children:E.relativePath||E.path})]}),e.jsx("button",{type:"button",onClick:()=>V(E),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 ${E.branch||E.label}`,children:e.jsx(qs,{className:"h-4 w-4"})})]},E.path))})]})]}):e.jsx("p",{className:"typography-meta text-muted-foreground",children:"Select a project to configure worktree defaults."})},kj=()=>{const s=_e(d=>d.nativeNotificationsEnabled),r=_e(d=>d.setNativeNotificationsEnabled),t=_e(d=>d.notificationMode),n=_e(d=>d.setNotificationMode),[o,a]=c.useState("default");c.useEffect(()=>{typeof Notification<"u"&&a(Notification.permission)},[]);const i=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"))},l=typeof Notification<"u"&&Notification.permission==="granted";return kn()?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(sa,{checked:s&&l,onCheckedChange:i,className:"data-[state=checked]:bg-status-info"})]}),s&&l&&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(sa,{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},Nj=({section:s})=>{const{isMobile:r}=_t(),t=r&&kn();if(!s)return e.jsxs(ft,{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(El,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(xf,{})}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gf,{})}),t&&e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(ff,{})})]});const n=()=>{switch(s){case"visual":return e.jsx(Cj,{});case"chat":return e.jsx(Mj,{});case"sessions":return e.jsx(Dj,{});case"git":return e.jsx(Aj,{});case"notifications":return e.jsx(Ej,{});default:return null}};return e.jsx(ft,{keyboardAvoid:!0,outerClassName:"h-full",className:"openchamber-page-body mx-auto max-w-3xl space-y-6 p-3 sm:p-6",children:n()})},Cj=()=>e.jsx(El,{visibleSettings:["theme","fontSize","spacing","inputBarOffset"]}),Mj=()=>e.jsx(El,{visibleSettings:["toolOutput","diffLayout","reasoning","queueMode"]}),Dj=()=>e.jsxs("div",{className:"space-y-6",children:[e.jsx(xf,{}),e.jsx("div",{className:"border-t border-border/40 pt-6",children:e.jsx(gf,{})})]}),Aj=()=>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(Sj,{})]})]}),Ej=()=>e.jsx(kj,{}),Ij=[{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"]},{id:"notifications",label:"Notifications",items:["Native"],webOnly:!0}],Pj=({selectedSection:s,onSelectSection:r})=>{const{isMobile:t}=_t(),n=t&&kn(),[o,a]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),i=c.useMemo(()=>Ut(),[]),l=c.useMemo(()=>kn(),[]);c.useEffect(()=>{typeof window>"u"||a(typeof window.opencodeDesktop<"u")},[]);const d=c.useMemo(()=>Ij.filter(m=>!m.webOnly||l),[l]),u=o?"bg-transparent":i?"bg-background":"bg-sidebar";return e.jsxs("div",{className:R("flex h-full flex-col",u),children:[e.jsx(ft,{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:R("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(ff,{})})]})},Tj=(()=>{const s=cf.filter(n=>n.id!=="sessions"),r=s.find(n=>n.id==="settings"),t=s.filter(n=>n.id!=="settings");return r?[r,...t]:s})(),pi=200,hi=500,Fj=264,Rj=700,Vi=({onClose:s,forceMobile:r})=>{const t=_t(),n=r??t.isMobile,[o,a]=c.useState("settings"),[i,l]=c.useState("visual"),[d,u]=c.useState(!1),[m,f]=c.useState(()=>typeof window<"u"?Math.min(hi,Math.max(pi,Math.floor(window.innerWidth*.2))):Fj),[p,g]=c.useState(!1),[w,h]=c.useState(!1),[j,x]=c.useState(0),y=c.useRef(null),b=c.useRef(0),N=c.useRef(m),[v,k]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u"),D=c.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),C=c.useMemo(()=>Ut(),[]);c.useEffect(()=>{typeof window>"u"||k(typeof window.opencodeDesktop<"u")},[]),c.useEffect(()=>{const E=y.current;if(!E)return;const B=new ResizeObserver(F=>{for(const O of F)x(O.contentRect.width)});return B.observe(E),x(E.clientWidth),()=>B.disconnect()},[]);const M=Ft(E=>E.projects),S=Ft(E=>E.activeProjectId),A=Ft(E=>E.setActiveProject),I=c.useMemo(()=>[...M].sort((E,B)=>(E.label||E.path).localeCompare(B.label||B.path)),[M]),_=c.useMemo(()=>I.length===0?null:I.find(E=>E.id===S)??I[0],[S,I]),T=c.useCallback(E=>E.replace(/[-_]/g," ").replace(/\b\w/g,B=>B.toUpperCase()),[]),P=c.useMemo(()=>{if(!_)return"Project";const E=_.label&&_.label.trim().length>0?_.label:_.path.split("/").filter(Boolean).pop()||_.path;return T(E)},[_,T]),L=I.length>0,Z=j===0||j>=Rj;c.useEffect(()=>{if(o==="agents"){setTimeout(()=>{_r.getState().loadAgents()},0);return}if(o==="commands"){setTimeout(()=>{Rr.getState().loadCommands()},0);return}o==="skills"&&(Hs.getState().loadSkills(),ao.getState().loadCatalog())},[S,o]),c.useEffect(()=>{if(typeof window>"u")return;const E=()=>{if(!p){const B=Math.min(hi,Math.max(pi,Math.floor(window.innerWidth*.2)));f(B)}};return window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[p]),c.useEffect(()=>{if(!w)return;const E=F=>{const O=F.clientX-b.current,z=Math.min(hi,Math.max(pi,N.current+O));f(z),g(!0)},B=()=>h(!1);return window.addEventListener("pointermove",E),window.addEventListener("pointerup",B,{once:!0}),()=>{window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",B)}},[w]);const q=E=>{h(!0),b.current=E.clientX,N.current=m,E.preventDefault()},$=c.useCallback(async E=>{if(!E.target.closest("button, a, input, select, textarea")&&E.button===0&&v)try{const{getCurrentWindow:B}=await as(async()=>{const{getCurrentWindow:O}=await import("./vendor-.bun-94fMDU1C.js").then(z=>z.cw);return{getCurrentWindow:O}},__vite__mapDeps([0,1]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[v]),H=c.useCallback(async E=>{if(E.button===0&&v)try{const{getCurrentWindow:B}=await as(async()=>{const{getCurrentWindow:O}=await import("./vendor-.bun-94fMDU1C.js").then(z=>z.cw);return{getCurrentWindow:O}},__vite__mapDeps([0,1]));await B().startDragging()}catch(B){console.error("Failed to start window dragging:",B)}},[v]),U=c.useCallback(E=>{a(E),u(!1)},[]),K=c.useCallback(()=>{n&&u(!0)},[n]),se=()=>{switch(o){case"settings":return e.jsx(Pj,{selectedSection:i,onSelectSection:E=>{l(E),K()}});case"agents":return e.jsx(_0,{onItemSelect:K});case"commands":return e.jsx(V0,{onItemSelect:K});case"skills":return e.jsx(q0,{onItemSelect:K});case"providers":return e.jsx(nj,{onItemSelect:K});case"git-identities":return e.jsx(mj,{onItemSelect:K});default:return null}},Y=()=>{switch(o){case"agents":return e.jsx(U0,{});case"commands":return e.jsx(G0,{});case"skills":return e.jsx(sj,{});case"providers":return e.jsx(cj,{});case"git-identities":return e.jsx(gj,{});case"settings":return e.jsx(Nj,{section:i});default:return null}},re=Jt(),V=c.useMemo(()=>v&&D?"pl-[5.75rem]":"",[v,D]),ae=v&&D;return e.jsxs("div",{ref:y,className:R("flex h-full flex-col overflow-hidden",v?"bg-transparent":"bg-background"),children:[e.jsxs("div",{onMouseDown:n?void 0:$,className:R("flex select-none items-center justify-between border-b",n?"h-auto px-3 py-2":"app-region-drag h-12",!n&&V,v?"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(Ch,{className:"h-5 w-5"})}),n&&e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:R("flex items-center",n?"gap-1":"h-full"),children:[!n&&ae&&e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"}),Tj.map(({id:E,label:B,icon:F})=>{const O=o===E,z=F;return n?e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{onClick:()=>U(E),className:R("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",O?"text-foreground":"text-muted-foreground"),"aria-pressed":O,"aria-label":B,children:e.jsx(z,{className:"h-5 w-5",weight:"regular"})})}),e.jsx(nt,{children:e.jsx("p",{children:B})})]},E):e.jsxs(c.Fragment,{children:[e.jsxs("button",{onClick:()=>U(E),onMouseDown:O?H:void 0,className:R("relative flex h-full items-center gap-2 px-4 typography-ui-label font-medium transition-colors",O?"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",O?"text-foreground":"text-muted-foreground"),"aria-pressed":O,"aria-label":B,children:[e.jsx(z,{className:"h-4 w-4",weight:"regular"}),Z&&e.jsx("span",{children:B})]}),e.jsx("div",{className:"h-full w-px bg-border","aria-hidden":"true"})]},E)})]}),(s||L)&&e.jsxs("div",{className:R("flex items-center gap-2",n?"":"pr-3"),children:[L&&e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:n?e.jsx("button",{type:"button","aria-label":"Switch project",title:P,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:e.jsx(ir,{className:"h-5 w-5"})}):e.jsxs("button",{type:"button","aria-label":"Switch project",title:P,className:R("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:P}),e.jsx(It,{className:"size-4 opacity-50"})]})}),e.jsx(qt,{align:"end",className:"w-auto",children:e.jsx(lm,{value:_?.id??"",onValueChange:E=>{E&&A(E)},children:I.map(E=>{const B=E.label?.trim()?E.label.trim():E.path.split("/").filter(Boolean).pop()||E.path,F=T(B);return e.jsx(cm,{value:E.id,children:e.jsx("span",{className:"min-w-0 truncate typography-ui",children:F})},E.id)})})})]}),s&&e.jsxs(at,{delayDuration:500,children:[e.jsx(it,{asChild:!0,children:e.jsx("button",{type:"button",onClick:s,"aria-label":"Close settings",className:R("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(nt,{children:e.jsxs("p",{children:["Close Settings (",re,"+,)"]})})]})]})]}),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(ls,{children:Y()})}):e.jsx("div",{className:R("flex-1 overflow-hidden",C?"bg-background":"bg-sidebar"),children:e.jsx(ls,{children:se()})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:R("relative overflow-hidden border-r",v?"bg-[color:var(--sidebar-overlay-strong)] backdrop-blur supports-[backdrop-filter]:bg-[color:var(--sidebar-overlay-soft)]":C?"bg-background":"bg-sidebar",w?"transition-none":""),style:{width:`${m}px`,minWidth:`${m}px`,borderColor:"var(--interactive-border)"},children:[e.jsx("div",{className:R("absolute right-0 top-0 z-20 h-full w-[6px] -mr-[3px] cursor-col-resize",w?"bg-primary/30":"bg-transparent hover:bg-primary/20"),onPointerDown:q,role:"separator","aria-orientation":"vertical","aria-label":"Resize settings sidebar"}),e.jsx(ls,{children:se()})]}),e.jsx("div",{className:"flex-1 overflow-hidden bg-background",children:e.jsx(ls,{children:Y()})})]})})]})},_j=()=>{const{isSidebarOpen:s,activeMainTab:r,setIsMobile:t,isSessionSwitcherOpen:n,setSessionSwitcherOpen:o,isSettingsDialogOpen:a,setSettingsDialogOpen:i,isMultiRunLauncherOpen:l,setMultiRunLauncherOpen:d,multiRunLauncherPrefillPrompt:u}=_e(),{isMobile:m}=_t(),[f,p]=c.useState(()=>typeof window>"u"?!1:typeof window.opencodeDesktop<"u");c.useEffect(()=>{typeof window>"u"||p(typeof window.opencodeDesktop<"u")},[]),Ob({enabled:!0});const g=ha(x=>x.checkForUpdates);c.useEffect(()=>{const x=setTimeout(()=>{g()},3e3);return()=>clearTimeout(x)},[g]),c.useEffect(()=>{_e.getState().isMobile!==m&&t(m)},[m,t]),c.useEffect(()=>{if(typeof window>"u")return;let x;const y=()=>{x!==void 0&&window.clearTimeout(x),x=window.setTimeout(()=>{_e.getState().updateProportionalSidebarWidths()},150)};return window.addEventListener("resize",y),()=>{window.removeEventListener("resize",y),x!==void 0&&window.clearTimeout(x)}},[]),c.useEffect(()=>{if(typeof window>"u"||typeof document>"u")return;const x=document.documentElement;let y=0,b=!1,N=0,v=null;const k=_e.getState().setKeyboardOpen,D=()=>{v&&(v.style.setProperty("--oc-keyboard-avoid-offset","0px"),v.removeAttribute("data-keyboard-avoid-active"),v=null)},C=T=>{if(!T)return null;const P=T.closest("[data-keyboard-avoid]");if(P)return P;if(T.classList.contains("overlay-scrollbar-container")){const L=T.parentElement;if(L instanceof HTMLElement)return L}return T},M=()=>{y=0,b=!0,x.style.setProperty("--oc-keyboard-inset","0px"),k(!1)},S=()=>{const T=window.visualViewport,P=T?Math.round(T.height):window.innerHeight,L=T?Math.max(0,Math.round(T.offsetTop)):0;x.style.setProperty("--oc-visual-viewport-offset-top",`${L}px`);const Z=document.activeElement,q=Z?.tagName,H=q==="INPUT"||q==="TEXTAREA"||q==="SELECT"||!!Z?.isContentEditable,U=Math.round(x.clientHeight||window.innerHeight),K=P+L,se=Math.max(0,U-K),re=se>=(H?120:180)?se:0;if(b)re===0&&(b=!1),y=0;else if(y===0)re>0&&H&&(y=re);else{const ae=!H&&P>N+6;re===0?(y=0,k(!1)):ae?M():(re>0&&H||re>y)&&(y=re,k(!0))}x.style.setProperty("--oc-keyboard-inset",`${y}px`),N=P;const V=H?C(Z):null;if(!m||!V||!Z)D();else{V!==v&&(D(),v=V);const ae=L+P,B=Z.getBoundingClientRect().bottom-ae,F=8,O=Math.max(y,re),z=B>F&&O>0?Math.min(B,O):0,Q=v;Q&&(Q.style.setProperty("--oc-keyboard-avoid-offset",`${z}px`),Q.setAttribute("data-keyboard-avoid-active","true"))}if(m&&H){const ae=document.scrollingElement;ae&&ae.scrollTop!==0&&(ae.scrollTop=0),window.scrollY!==0&&window.scrollTo(0,0)}};S();const A=window.visualViewport;A?.addEventListener("resize",S),A?.addEventListener("scroll",S),window.addEventListener("resize",S),window.addEventListener("orientationchange",S);const I=T=>{const P=T.target;if(!P)return;const L=P.tagName;(L==="INPUT"||L==="TEXTAREA"||L==="SELECT"||P.isContentEditable)&&(b=!1),S()};document.addEventListener("focusin",I,!0);const _=T=>{const P=T.target;if(!P)return;const L=P.tagName;if(L==="INPUT"||L==="TEXTAREA"||L==="SELECT"||P.isContentEditable){const q=T.relatedTarget,$=q?.tagName;if($==="INPUT"||$==="TEXTAREA"||$==="SELECT"||q?.isContentEditable)return;M()}};return document.addEventListener("focusout",_,!0),()=>{A?.removeEventListener("resize",S),A?.removeEventListener("scroll",S),window.removeEventListener("resize",S),window.removeEventListener("orientationchange",S),document.removeEventListener("focusin",I,!0),document.removeEventListener("focusout",_,!0),D()}},[m]);const w=c.useMemo(()=>{switch(r){case"git":return e.jsx(y0,{});case"diff":return e.jsx(Xy,{});case"terminal":return e.jsx(E0,{});default:return null}},[r]),h=r==="chat",j=a&&!m;return e.jsx(Mb,{children:e.jsxs("div",{className:R("main-content-safe-area h-[100dvh]",m?"flex flex-col":"flex",f?"bg-transparent":"bg-background"),children:[e.jsx(pb,{}),e.jsx(xb,{}),e.jsx(jb,{}),m?e.jsxs(e.Fragment,{children:[!(a||l)&&e.jsx(Ac,{}),e.jsx("div",{className:R("flex flex-1 overflow-hidden bg-background",(a||l)&&"hidden"),style:{paddingTop:"var(--oc-header-height, 56px)"},children:e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative",children:[e.jsx("div",{className:R("absolute inset-0",!h&&"invisible"),children:e.jsx(ls,{children:e.jsx(Hi,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:w})})]})}),e.jsx(vs,{open:n,onClose:()=>o(!1),title:"Sessions",children:e.jsx(Ri,{mobileVariant:!0})}),l&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background header-safe-area",children:e.jsx(ls,{children:e.jsx(qc,{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(ls,{children:e.jsx(Vi,{onClose:()=>i(!1)})})})]}):e.jsxs(e.Fragment,{children:[!j&&e.jsx(cb,{isOpen:s,isMobile:m,children:e.jsx(Ri,{})}),e.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden relative",children:[e.jsxs("div",{className:R("absolute inset-0 flex flex-col",(j||l)&&"invisible"),children:[e.jsx(Ac,{}),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:R("absolute inset-0",!h&&"invisible"),children:e.jsx(ls,{children:e.jsx(Hi,{})})}),w&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(ls,{children:w})})]})})]}),l&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(ls,{children:e.jsx(qc,{initialPrompt:u,onCreated:()=>d(!1),onCancel:()=>d(!1)})})})]}),j&&e.jsx("div",{className:R("absolute inset-0 z-10",f?"bg-transparent":"bg-background"),children:e.jsx(ls,{children:e.jsx(Vi,{onClose:()=>i(!1)})})})]}),!j&&e.jsx(nb,{})]})})},Oj=550,$j=()=>{const[s,r]=c.useState("chat"),[t,n]=c.useState(0),o=c.useRef(null),a=ue(D=>D.currentSessionId),i=ue(D=>D.sessions),l=ue(D=>!!D.newSessionDraft?.open),d=ue(D=>D.openNewSessionDraft),[u,m]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),f=rt(D=>D.isInitialized),p=rt(D=>D.initializeApp),g=ue(D=>D.loadSessions),w=ue(D=>D.loadMessages),h=ue(D=>D.messages),[j,x]=c.useState(()=>f),[y,b]=c.useState(!1),N=c.useRef(0);c.useEffect(()=>{a&&r("chat")},[a]),c.useEffect(()=>{!a&&!l&&d()},[a,l,d]);const v=c.useCallback(()=>{r("sessions")},[]);c.useEffect(()=>{const D=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&m(D);const C=M=>{const A=M.detail?.status;(A==="connected"||A==="connecting"||A==="error"||A==="disconnected")&&m(A)};return window.addEventListener("openchamber:connection-status",C),()=>window.removeEventListener("openchamber:connection-status",C)},[]),c.useEffect(()=>{const D=C=>{const S=C.detail?.view;S==="settings"?r("settings"):S==="chat"?r("chat"):S==="sessions"&&r("sessions")};return window.addEventListener("openchamber:navigate",D),()=>window.removeEventListener("openchamber:navigate",D)},[]),c.useEffect(()=>{(async()=>{if(y||j||u!=="connected")return;const C=Date.now();if(!(C-N.current<750)){N.current=C,b(!0);try{const M=(()=>{if(typeof window>"u")return!1;try{return window.localStorage.getItem("openchamber_stream_debug")==="1"}catch{return!1}})();M&&console.log("[OpenChamber][VSCode][bootstrap] attempt",{configInitialized:f}),f||await p();const S=rt.getState();if(!S.isInitialized||!S.isConnected||S.providers.length===0||S.agents.length===0)return;await g();const A=ue.getState().error;if(M&&console.log("[OpenChamber][VSCode][bootstrap] post-load",{providers:S.providers.length,agents:S.agents.length,sessions:ue.getState().sessions.length,sessionsError:A}),typeof A=="string"&&A.length>0)return;x(!0)}catch{}finally{b(!1)}}})()},[u,f,j,p,y,g]),c.useEffect(()=>{(async()=>{if(!j||u!=="connected"||s!=="chat"||l||!a)return;if(!(h.has(a)&&(h.get(a)?.length||0)>0))try{await w(a)}catch{}})()},[u,a,s,j,w,h,l]),c.useEffect(()=>{const D=o.current;if(!D)return;const C=new ResizeObserver(M=>{for(const S of M)n(S.contentRect.width)});return C.observe(D),n(D.clientWidth),()=>C.disconnect()},[]);const k=t>0&&t<Oj;return e.jsx("div",{ref:o,className:"h-full w-full bg-background text-foreground flex flex-col",children:s==="sessions"?e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(qd,{title:"Sessions"}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(Ri,{mobileVariant:!0,allowReselect:!0,onSessionSelected:()=>r("chat"),hideDirectoryControls:!0,showOnlyMainWorkspace:!0})})]}):s==="settings"?e.jsx(Vi,{onClose:()=>r("sessions"),forceMobile:k}):e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsx(qd,{title:l&&!a?"New session":i.find(D=>D.id===a)?.title||"Chat",showBack:!0,onBack:v,showMcp:!0,showContextUsage:!0}),e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ls,{children:e.jsx(Hi,{})})})]})})},qd=({title:s,showBack:r,onBack:t,onNewSession:n,onSettings:o,onAgentManager:a,showMcp:i,showContextUsage:l})=>{const{getCurrentModel:d}=rt(),u=ue(h=>h.getContextUsage),m=d(),f=m?.limit&&typeof m.limit=="object"?m.limit:null,p=typeof f?.context=="number"?f.context:0,g=typeof f?.output=="number"?f.output:0,w=u(p,g);return e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border bg-background shrink-0",children:[r&&t&&e.jsx("button",{onClick:t,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back to sessions",children:e.jsx(wu,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-sm font-medium truncate flex-1 h-9 w-9 items-center justify-center p-2",title:s,children:s}),n&&e.jsx("button",{onClick:n,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"New session",children:e.jsx(Kt,{className:"h-5 w-5"})}),a&&e.jsx("button",{onClick:a,className:"inline-flex h-9 w-9 items-center justify-center p-2 text-muted-foreground hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Agent Manager",children:e.jsx(Jn,{className:"h-5 w-5"})}),i&&e.jsx(Ti,{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(Yr,{className:"h-5 w-5"})}),l&&w&&w.totalTokens>0&&e.jsx(Pi,{totalTokens:w.totalTokens,percentage:w.percentage,contextLimit:w.contextLimit,outputLimit:w.outputLimit??0,size:"compact"})]})},Gi=".openchamber",Ao=s=>{const r=Ft.getState(),t=r.activeProjectId,n=t?r.projects.find(l=>l.id===t)?.path:void 0;if(typeof n=="string"&&n.trim().length>0)return n;const o=typeof s=="string"?Et(s):"",a=`/${Gi}/`,i=o.indexOf(a);return i>0?o.slice(0,i):s?Et(s):null},Et=s=>{if(!s)return"";const r=s.replace(/\\/g,"/");return r==="/"?"/":r.replace(/\/+$/,"")},Kd=s=>{const r=Et(s);return!r||r==="/"?`/${Gi}`:`${r}/${Gi}`},Lj=(s,r)=>{const t=Et(s);return r.map(n=>{const o=typeof n.path=="string"&&n.path.trim().length>0?n.path:null;if(o){const i=Et(o);if(i)return i}const a=typeof n.name=="string"?n.name.trim():"";return!a||!t?null:`${t}/${a}`}).filter(n=>!!n)},Bj=async s=>{const r=Et(s);if(!r)return[];try{const n=(await je.listLocalDirectory(r)).filter(o=>o.isDirectory);return Lj(r,n)}catch{return[]}},Cr=(s,r)=>{const t=Et(s),n=Et(r);if(!t||!n)return!1;if(t===n)return!0;const o=n==="/"?"/":`${n}/`;return t.startsWith(o)},yf=async(s,r)=>{const t=Et(r);if(!t)return t;try{const n=await s.path.get({directory:t});return Et(n.data?.directory??"")||t}catch{return t}},bf=async(s,r)=>{const t=Et(r);if(!t)return[];const n=await yf(s,t),o=i=>i.filter(l=>{const d=Et(l.directory??"");return d?Cr(d,t)||n!==t&&Cr(d,n):!1}),a=async i=>{const l=await s.session.list({directory:i});return Array.isArray(l.data)?l.data:[]};try{const i=o(await a(t));if(i.length>0)return i}catch{}if(n&&n!==t)try{const i=o(await a(n));if(i.length>0)return i}catch{}try{const i=await s.session.list(void 0),l=Array.isArray(i.data)?i.data:[];return o(l)}catch{return[]}},zj=async(s,r)=>{const t=new Map;s.sessions.forEach(o=>{o.worktreeMetadata&&t.set(Et(o.path),o.worktreeMetadata)});const n=Array.from(new Set(s.sessions.map(o=>Et(o.path)))).filter(Boolean).filter(o=>!t.has(o));if(n.length===0)return t;try{const o=await Nn(r),a=new Map(o.map(i=>[Et(i.worktree),i]));n.forEach(i=>{const l=a.get(i);l&&t.set(i,Cn(r,l))})}catch{}return t},gi=async s=>{const{apiClient:r,group:t,projectDirectory:n,worktreePaths:o}=s,a=await zj(t,n),i=ue.getState(),l=Array.from(new Set(o.map(p=>Et(p)).filter(Boolean))),d=5;let u=0;const m=[],f=async()=>{for(;u<l.length;){const p=l[u];u+=1;const g=t.sessions.filter(y=>Et(y.path)===p).map(y=>y.id),w=i.getSessionsByDirectory(p),h=Array.isArray(w)?w.map(y=>y.id):[];let j=[];if(h.length===0)try{j=(await bf(r,p)).map(b=>b.id)}catch{j=[]}const x=Array.from(new Set([...h,...j,...g].filter(Boolean)));m.push({worktreePath:p,sessionIds:x,metadata:a.get(p)})}};return await Promise.all(Array.from({length:Math.min(d,l.length)},f)),m};function Wj(s){if(!s)return null;const r=s.split("/");if(r.length<3)return null;const t=r[0];if(!t||t.includes(" "))return null;const n=r[1];if(!n)return null;const o=r[r.length-1],a=parseInt(o,10),i=r.length>=4&&!isNaN(a)&&String(a)===o,l=i?r.slice(2,-1):r.slice(2);if(l.length===0)return null;const d=l.join("/");return{groupSlug:t,provider:n,model:d,index:i?a:1}}const Dr=zt()(Yt((s,r)=>({groups:[],selectedGroupName:null,selectedSessionId:null,isLoading:!1,error:null,loadGroups:async()=>{const t=mt.getState().currentDirectory,n=Ao(t);if(!n){s({groups:[],isLoading:!1,error:"No project directory selected"});return}const o=Et(n),a=Kd(o),i=r().groups;s({isLoading:!0,error:null});try{const l=je.getApiClient(),d=await yf(l,o),u=Kd(d);let m=new Map,f=[];try{f=await Nn(o),m=new Map(f.map(b=>[Et(b.worktree),b]))}catch{console.debug("Failed to list git worktrees")}const p=async()=>{try{const N=await l.session.list({directory:o}),v=Array.isArray(N.data)?N.data:[];if(v.some(k=>{const D=Et(k.directory??"");return Cr(D,a)||Cr(D,u)}))return v}catch{}const b=await l.session.list(void 0);return Array.isArray(b.data)?b.data:[]},g=async b=>{const N=new Map,v=5;let k=0;const D=async()=>{for(;k<b.length;){const C=b[k];k+=1;const M=Et(C);if(M)try{(await bf(l,M)).forEach(A=>N.set(A.id,A))}catch(S){console.debug("Failed to fetch sessions from worktree:",M,S)}}};return await Promise.all(Array.from({length:Math.min(v,b.length)},D)),Array.from(N.values())};let h=(await p()).filter(b=>{const N=Et(b.directory??"");return N?Cr(N,a)||Cr(N,u):!1});if(h.length===0){const b=new Set;f.map(v=>Et(v.worktree)).filter(v=>Cr(v,a)||Cr(v,u)).forEach(v=>b.add(v));const N=Array.from(new Set([a,u].map(v=>Et(v)).filter(Boolean)));await Promise.all(N.map(async v=>{(await Bj(v)).forEach(D=>b.add(D))})),b.size>0&&(h=await g(Array.from(b)))}const j=new Map;for(const b of h){const N=b.time?.updated??0;j.set(b.id,typeof N=="number"?N:0)}const x=new Map;for(const b of h){const N=Wj(b.title);if(!N)continue;const v=Et(b.directory),k=m.get(v),D={id:b.id,path:v,providerId:N.provider,modelId:N.model,instanceNumber:N.index,branch:k?.branch??"",displayLabel:`${N.provider}/${N.model}`,worktreeMetadata:k?Cn(o,k):void 0},C=x.get(N.groupSlug);C?C.push(D):x.set(N.groupSlug,[D])}const y=Array.from(x.entries()).map(([b,N])=>{const v=N.reduce((k,D)=>{const C=j.get(D.id)??0;return Math.max(k,C)},0);return{name:b,sessions:N.sort((k,D)=>{const C=k.providerId.localeCompare(D.providerId);if(C!==0)return C;const M=k.modelId.localeCompare(D.modelId);return M!==0?M:k.instanceNumber-D.instanceNumber}),lastActive:v||Date.now(),sessionCount:N.length}});y.sort((b,N)=>b.name.localeCompare(N.name)),s({groups:y,isLoading:!1,error:null})}catch(l){console.error("Failed to load agent groups:",l),s({groups:i.length>0?i:[],isLoading:!1,error:l instanceof Error?l.message:"Failed to load agent groups"})}},selectGroup:t=>{const{groups:n}=r(),o=n.find(a=>a.name===t);s({selectedGroupName:t,selectedSessionId:o?.sessions[0]?.id??null})},selectSession:t=>{s({selectedSessionId:t})},deleteGroup:async t=>{const n=r().groups.find(i=>i.name===t);if(!n)return!1;const o=mt.getState().currentDirectory,a=Ao(o);if(!a)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const i=je.getApiClient(),l=await gi({apiClient:i,group:n,projectDirectory:Et(a),worktreePaths:n.sessions.map(f=>f.path)}),d=ue.getState(),u=new Set;l.forEach(({worktreePath:f,sessionIds:p,metadata:g})=>{p.forEach(w=>{u.add(w),g&&(d.setWorktreeMetadata(w,g),d.setSessionDirectory(w,f))})});const{failedIds:m}=await d.deleteSessions(Array.from(u),{archiveWorktree:!0,silent:!0});return m.length>0&&s({error:"Failed to delete some sessions"}),r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),await r().loadGroups(),m.length===0}catch(i){return s({error:i instanceof Error?i.message:"Failed to delete group"}),!1}finally{s({isLoading:!1})}},deleteGroupWorktree:async(t,n)=>{const o=r().groups.find(d=>d.name===t);if(!o)return!1;const a=Et(n);if(!a)return!1;const i=mt.getState().currentDirectory,l=Ao(i);if(!l)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const d=je.getApiClient(),u=await gi({apiClient:d,group:o,projectDirectory:Et(l),worktreePaths:[a]}),m=ue.getState(),f=new Set;u.forEach(({worktreePath:w,sessionIds:h,metadata:j})=>{h.forEach(x=>{f.add(x),j&&(m.setWorktreeMetadata(x,j),m.setSessionDirectory(x,w))})});const{failedIds:p}=await m.deleteSessions(Array.from(f),{archiveWorktree:!0,silent:!0});p.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups();const g=r().groups.find(w=>w.name===t);if(!g)return r().selectedGroupName===t&&s({selectedGroupName:null,selectedSessionId:null}),p.length===0;if(r().selectedGroupName===t){const w=r().selectedSessionId,h=new Set(g.sessions.map(j=>j.id));(!w||!h.has(w))&&s({selectedSessionId:g.sessions[0]?.id??null})}return p.length===0}catch(d){return s({error:d instanceof Error?d.message:"Failed to delete worktree"}),!1}finally{s({isLoading:!1})}},keepOnlyGroupWorktree:async(t,n)=>{const o=r().groups.find(m=>m.name===t);if(!o)return!1;const a=Et(n);if(!a)return!1;const l=Array.from(new Set(o.sessions.map(m=>Et(m.path)).filter(Boolean))).filter(m=>m!==a);if(l.length===0)return!0;const d=mt.getState().currentDirectory,u=Ao(d);if(!u)return s({error:"No project directory selected"}),!1;s({isLoading:!0,error:null});try{const m=je.getApiClient(),f=await gi({apiClient:m,group:o,projectDirectory:Et(u),worktreePaths:l}),p=ue.getState(),g=new Set;f.forEach(({worktreePath:h,sessionIds:j,metadata:x})=>{j.forEach(y=>{g.add(y),x&&(p.setWorktreeMetadata(y,x),p.setSessionDirectory(y,h))})});const{failedIds:w}=await p.deleteSessions(Array.from(g),{archiveWorktree:!0,silent:!0});if(w.length>0&&s({error:"Failed to delete some sessions"}),await r().loadGroups(),r().selectedGroupName===t){const h=r().groups.find(x=>x.name===t),j=h?.sessions.find(x=>Et(x.path)===a)??h?.sessions[0]??null;s({selectedSessionId:j?.id??null})}return w.length===0}catch(m){return s({error:m instanceof Error?m.message:"Failed to remove other worktrees"}),!1}finally{s({isLoading:!1})}},getSelectedGroup:()=>{const{groups:t,selectedGroupName:n}=r();return n?t.find(o=>o.name===n)??null:null},getSelectedSession:()=>{const{selectedSessionId:t}=r(),n=r().getSelectedGroup();return!n||!t?null:n.sessions.find(o=>o.id===t)??null},clearError:()=>{s({error:null})}}),{name:"agent-groups-store"})),Hj=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`},Uj=({group:s,isSelected:r,onSelect:t})=>{const[n,o]=c.useState(!1),[a,i]=c.useState(!1),[l,d]=c.useState(!1),u=Dr(f=>f.deleteGroup),m=c.useCallback(async()=>{if(l)return;if(d(!0),te.info(`Deleting "${s.name}"...`),await u(s.name))te.success(`Deleted "${s.name}"`);else{const p=Dr.getState().error;te.error(p||`Failed to delete "${s.name}"`)}d(!1),i(!1)},[u,s.name,l]);return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:R("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($t,{className:"h-3 w-3"}),s.sessionCount," model",s.sessionCount!==1?"s":""]}),e.jsx("span",{className:"typography-micro text-muted-foreground/60",children:Hj(s.lastActive)})]})]}),e.jsx("div",{className:"flex items-center gap-1.5 self-stretch",children:e.jsxs(Vt,{open:n,onOpenChange:o,children:[e.jsx(Gt,{asChild:!0,children:e.jsx("button",{type:"button",className:R("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(Tr,{className:"h-3.5 w-3.5"})})}),e.jsx(qt,{align:"end",className:"min-w-[140px]",children:e.jsx(Dt,{variant:"destructive",onSelect:f=>{f.stopPropagation(),o(!1),i(!0)},children:"Delete"})})]})})]})}),e.jsx(ms,{open:a,onOpenChange:i,children:e.jsxs(fs,{className:"max-w-md",keyboardAvoid:!0,children:[e.jsxs(ys,{children:[e.jsx(bs,{children:"Delete agent group"}),e.jsxs(Ns,{children:["Delete ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"? This removes all worktrees and sessions in this group."]})]}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"outline",onClick:()=>i(!1),disabled:l,children:"Cancel"}),e.jsx(Ce,{variant:"destructive",onClick:()=>{m()},disabled:l,children:l?"Deleting…":"Delete"})]})]})})]})},Vj=({className:s,selectedGroupName:r,onGroupSelect:t,onNewAgent:n})=>{const[o,a]=c.useState(""),[i,l]=c.useState(!1),{groups:d,isLoading:u,loadGroups:m}=Dr(),f=mt(j=>j.currentDirectory);c.useEffect(()=>{f&&m()},[f,m]);const p=5,g=c.useMemo(()=>{if(!o.trim())return d;const j=o.toLowerCase();return d.filter(x=>x.name.toLowerCase().includes(j))},[o,d]),w=i?g:g.slice(0,p),h=g.length-p;return e.jsxs("div",{className:R("flex h-full flex-col bg-background/50 dark:bg-neutral-900/80 text-foreground border-r border-border/30",s),children:[e.jsx("div",{className:"px-2.5 pt-3 pb-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ht,{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(Ce,{variant:"outline",className:"w-full justify-start gap-2 h-8",onClick:n,children:[e.jsx(Kt,{className:"h-4 w-4"}),e.jsx("span",{className:"typography-ui-label",children:"New Agent Group"})]})}),e.jsxs("div",{className:"px-2.5 py-1.5 flex items-center gap-1",children:[e.jsx(It,{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(ft,{outerClassName:"flex-1 min-h-0",className:"space-y-0.5 px-2.5 pb-2",children:[w.map(j=>e.jsx(Uj,{group:j,isSelected:r===j.name,onSelect:()=>t?.(j.name)},j.name)),!i&&h>0&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:["... More (",h,")"]}),i&&g.length>p&&e.jsx("button",{type:"button",onClick:()=>l(!1),className:"mt-1 flex items-center justify-start rounded-md px-1.5 py-0.5 text-left typography-micro text-muted-foreground/70 hover:text-foreground hover:underline",children:"Show less"}),!u&&g.length===0&&e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("p",{className:"typography-meta text-muted-foreground",children:o.trim()?"No groups found":"No agent groups yet"}),!o.trim()&&e.jsx("p",{className:"typography-micro text-muted-foreground/60 mt-1",children:"Create a new agent group to get started"})]})]})]})},Gj=10*1024*1024,qj=5,Kj=({className:s,onCreateGroup:r,isCreating:t=!1})=>{const[n,o]=c.useState(""),[a,i]=c.useState(""),[l,d]=c.useState([]),[u,m]=c.useState(""),[f,p]=c.useState("HEAD"),[g,w]=c.useState([]),[h,j]=c.useState(!1),[x,y]=c.useState([]),[b,N]=c.useState(!1),[v,k]=c.useState(!1),D=c.useRef(null),C=c.useRef(null),M=mt(V=>V.currentDirectory??null),{isGitRepository:S,isLoading:A}=Cl(M),I=c.useMemo(()=>{if(typeof window>"u")return null;const V=window.__VSCODE_CONFIG__?.workspaceFolder;return typeof V=="string"&&V.trim().length>0?V.trim():null},[]),_=c.useMemo(()=>typeof window>"u"?!1:!!window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode,[]),T=Ft(V=>V.activeProjectId),P=Ft(V=>V.projects),L=c.useMemo(()=>{if(_&&I)return I;if(T){const F=P.find(O=>O.id===T);if(F?.path)return F.path}const V=M??I;if(!V)return null;const ae=V.replace(/\\/g,"/").replace(/\/+$/,"")||V,B=ae.indexOf("/.openchamber/");return B>0?ae.slice(0,B):ae.endsWith("/.openchamber")?ae.slice(0,ae.length-13):ae},[T,P,M,I,_]);c.useEffect(()=>{if(!L)return;let V=!1;return k(!0),(async()=>{try{const ae=await io(L);V||y(ae)}catch{}finally{V||k(!1)}})(),()=>{V=!0}},[L]);const Z=c.useCallback(V=>{l.length>=qj||d(ae=>[...ae,V])},[l.length]),q=c.useCallback(V=>{d(ae=>ae.filter((E,B)=>B!==V))},[]),$=c.useCallback((V,ae)=>{d(E=>E.map((B,F)=>F===V?ae:B))},[]),H=async V=>{const ae=V.target.files;if(!ae)return;let E=0;for(let B=0;B<ae.length;B++){const F=ae[B];if(F.size>Gj){te.error(`File "${F.name}" is too large (max 10MB)`);continue}try{const O=await new Promise((Q,me)=>{const Se=new FileReader;Se.onload=()=>Q(Se.result),Se.onerror=me,Se.readAsDataURL(F)}),z={id:oa(),filename:F.name,mimeType:F.type||"application/octet-stream",size:F.size,dataUrl:O};w(Q=>[...Q,z]),E++}catch(O){console.error("File attach failed",O),te.error(`Failed to attach "${F.name}"`)}}E>0&&te.success(`Attached ${E} file${E>1?"s":""}`),D.current&&(D.current.value="")},U=V=>{w(ae=>ae.filter(E=>E.id!==V))},K=h||t,se=!!(n.trim()&&a.trim()&&l.length>=1&&S&&!A),Y=async V=>{if(V.preventDefault(),!(!se||K)){j(!0);try{const ae=l.map(({providerID:F,modelID:O,displayName:z,variant:Q})=>({providerID:F,modelID:O,displayName:z,variant:Q})),E=g.length>0?g.map(F=>({mime:F.mimeType,filename:F.filename,url:F.dataUrl})):void 0,B=x.filter(F=>F.trim().length>0);await r?.({name:n.trim(),prompt:a.trim(),models:ae,agent:u||void 0,worktreeBaseBranch:f,files:E,setupCommands:B.length>0?B:void 0}),o(""),i(""),d([]),m(""),w([]),p("HEAD")}catch(ae){console.error("Failed to create agent group:",ae),te.error("Failed to create agent group")}finally{j(!1)}}},re=V=>{kl(V)||V.key==="Enter"&&!V.shiftKey&&(V.preventDefault(),se&&!K&&Y(V))};return e.jsx("div",{className:R("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(ht,{id:"group-name",value:n,onChange:V=>o(V.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($t,{className:"h-4 w-4 text-muted-foreground"}),"Base Branch"]}),e.jsx(Am,{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(va,{open:b,onOpenChange:N,children:[e.jsxs(Sl,{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",x.filter(V=>V.trim()).length>0&&e.jsxs("span",{className:"font-normal text-muted-foreground/70",children:[" ","(",x.filter(V=>V.trim()).length," configured)"]})]}),e.jsx(It,{className:R("h-4 w-4 text-muted-foreground transition-transform duration-200",b&&"rotate-180")})]}),e.jsx(ja,{children:e.jsxs("div",{className:"pt-2 space-y-2",children:[e.jsxs("p",{className:"typography-micro text-muted-foreground/70",children:["Commands run in each new worktree. Use ",e.jsx("code",{className:"font-mono text-xs",children:"$ROOT_WORKTREE_PATH"})," for project root."]}),v?e.jsx("p",{className:"typography-meta text-muted-foreground/70",children:"Loading..."}):e.jsxs("div",{className:"space-y-1.5",children:[x.map((V,ae)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ht,{value:V,onChange:E=>{const B=[...x];B[ae]=E.target.value,y(B)},placeholder:"e.g., bun install",className:"h-8 flex-1 font-mono text-xs"}),e.jsx("button",{type:"button",onClick:()=>{const E=x.filter((B,F)=>F!==ae);y(E)},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:()=>y([...x,""]),className:"flex items-center gap-1.5 typography-meta text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Kt,{className:"h-3.5 w-3.5"}),"Add command"]})]})]})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"typography-ui-label font-medium text-foreground",children:"Agent"}),e.jsx(Em,{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(Dm,{selectedModels:l,onAdd:Z,onRemove:q,onUpdate:$,minModels:1,addButtonLabel:"Add model",maxModels:5})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{htmlFor:"prompt",className:"typography-ui-label font-medium text-foreground",children:"Prompt"}),e.jsxs("div",{className:"rounded-xl border border-border/60 bg-input/10 dark:bg-input/30 overflow-hidden",children:[e.jsx(Ts,{ref:C,id:"prompt",value:a,onChange:V=>i(V.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(V=>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:[V.mimeType.startsWith("image/")?e.jsx(br,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[120px]",title:V.filename,children:V.filename}),e.jsx("button",{type:"button",onClick:()=>U(V.id),className:"text-muted-foreground hover:text-destructive ml-0.5",children:e.jsx(Ht,{className:"h-3.5 w-3.5"})})]},V.id))}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-t border-border/40",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{ref:D,type:"file",multiple:!0,className:"hidden",onChange:H,accept:"*/*"}),e.jsx("button",{type:"button",onClick:()=>D.current?.click(),className:"inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:text-foreground transition-colors","aria-label":"Add attachment",children:e.jsx(pu,{className:"h-[18px] w-[18px]"})})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"typography-meta text-muted-foreground",children:[l.length," model",l.length!==1?"s":""," selected"]})}),e.jsx("button",{type:"submit",disabled:!se||K,className:R("flex items-center justify-center text-muted-foreground transition-none outline-none focus:outline-none flex-shrink-0",se?"text-primary hover:text-primary":"opacity-30"),"aria-label":"Start Agent Group",children:K?e.jsx(Mh,{className:"h-[18px] w-[18px] animate-spin"}):e.jsx(fu,{className:"h-[18px] w-[18px]"})})]})]})]})]})})},Yj=({group:s,className:r})=>{const{selectedSessionId:t,selectSession:n,deleteGroupWorktree:o,keepOnlyGroupWorktree:a}=Dr(),{setCurrentSession:i,currentSessionId:l}=ue(),[d,u]=c.useState(null),[m,f]=c.useState(!1),p=c.useMemo(()=>t?s.sessions.find(b=>b.id===t)??s.sessions[0]??null:s.sessions[0]??null,[s.sessions,t]),g=c.useCallback(b=>{n(b.id),i(b.id)},[n,i]);c.useEffect(()=>{if(s.sessions.length>0){const b=t?s.sessions.find(N=>N.id===t)??s.sessions[0]:s.sessions[0];b&&(b.id!==l&&i(b.id),t||n(b.id))}},[s.name,s.sessions,t,l,n,i]);const w=p?.id===l,h=c.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=c.useCallback(async()=>{p&&u({kind:"remove",path:p.path,label:p.displayLabel})},[p]),x=c.useCallback(async()=>{p&&u({kind:"keepOnly",path:p.path,label:p.displayLabel})},[p]),y=c.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=Dr.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=Dr.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:R("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($t,{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(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsxs(Ce,{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(is,{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(It,{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(b=>e.jsxs(Dt,{onClick:()=>g(b),className:"flex items-center gap-2 py-2",children:[e.jsx(is,{providerId:b.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:b.modelId}),b.instanceNumber>1&&e.jsxs("span",{className:"typography-meta text-muted-foreground",children:["#",b.instanceNumber]})]}),b.branch&&e.jsxs("div",{className:"flex items-center gap-1 typography-micro text-muted-foreground/60",children:[e.jsx($t,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:b.worktreeMetadata?.label||b.branch})]})]}),p?.id===b.id&&e.jsx(Pt,{className:"h-4 w-4 text-primary flex-shrink-0"})]},b.id))})]})}),e.jsxs(Vt,{children:[e.jsx(Gt,{asChild:!0,children:e.jsx(Ce,{variant:"outline",size:"icon",className:"h-10 w-10 flex-shrink-0","aria-label":"Worktree actions",children:e.jsx(Tr,{className:"h-4 w-4"})})}),e.jsxs(qt,{align:"end",className:"min-w-[220px]",children:[e.jsx(Dt,{onSelect:b=>{b.preventDefault(),j()},variant:"destructive",children:"Remove this worktree"}),e.jsx(Dt,{onSelect:b=>{b.preventDefault(),x()},children:"Leave this one, remove others"}),e.jsxs(Dt,{onClick:b=>{b.stopPropagation(),h()},disabled:!p?.path,children:[e.jsx(Gs,{className:"h-4 w-4 mr-px"}),"Copy Worktree Path"]})]})]})]})]}),e.jsx(ms,{open:!!d,onOpenChange:b=>{b||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(Ns,{children:d?.kind==="remove"?e.jsxs(e.Fragment,{children:["Remove ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label}),"? This deletes all sessions in that worktree and removes the worktree itself."]}):e.jsxs(e.Fragment,{children:["Keep ",e.jsx("span",{className:"text-foreground font-medium",children:d?.label})," and remove the other worktrees in ",e.jsx("span",{className:"text-foreground font-medium",children:s.name}),"."]})})]}),e.jsxs(Ks,{children:[e.jsx(Ce,{variant:"outline",onClick:()=>u(null),disabled:m,children:"Cancel"}),e.jsx(Ce,{variant:d?.kind==="remove"?"destructive":"default",onClick:()=>{y()},disabled:m,children:m?"Working…":d?.kind==="remove"?"Remove":"Remove others"})]})]})}),e.jsx("div",{className:"flex-1 min-h-0",children:p?w?e.jsx(sf,{sessionId:p.id,children:e.jsx(tf,{})}):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(is,{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"})})})]})},Qj=({className:s})=>{const r=!!(typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isVSCode),[t,n]=c.useState(()=>(typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:"connecting")||"connecting"),o=rt(b=>b.isInitialized),a=rt(b=>b.initializeApp),i=ue(b=>b.loadSessions),l=mt(b=>b.setDirectory),d=c.useRef(0),{selectedGroupName:u,selectGroup:m,getSelectedGroup:f,loadGroups:p}=Dr(),{createMultiRun:g,isLoading:w}=Kn();c.useEffect(()=>{if(!r)return;const b=typeof window<"u"?window.__OPENCHAMBER_CONNECTION__?.status:void 0;(b==="connected"||b==="connecting"||b==="error"||b==="disconnected")&&n(b);const N=v=>{const D=v.detail?.status;(D==="connected"||D==="connecting"||D==="error"||D==="disconnected")&&n(D)};return window.addEventListener("openchamber:connection-status",N),()=>window.removeEventListener("openchamber:connection-status",N)},[r]),c.useEffect(()=>{if(!r||t!=="connected")return;const b=Date.now();if(b-d.current<750)return;d.current=b;const N=typeof window<"u"?window.__VSCODE_CONFIG__?.workspaceFolder:null;if(typeof N=="string"&&N.trim().length>0)try{l(N,{showOverlay:!1})}catch{}(async()=>{try{o||await a();const k=rt.getState();if(!k.isInitialized||!k.isConnected||k.providers.length===0||k.agents.length===0)return;await i(),Qt()&&console.log("[OpenChamber][VSCode][agentManager] bootstrap complete",{providers:k.providers.length,agents:k.agents.length,sessions:ue.getState().sessions.length})}catch{}})()},[t,o,a,r,i,l]);const h=c.useCallback(b=>{m(b)},[m]),j=c.useCallback(()=>{m(null)},[m]),x=c.useCallback(async b=>{te.info(`Creating agent group "${b.name}" with ${b.models.length} model(s)...`);const N=await g(b);if(N){te.success(`Agent group "${b.name}" created with ${N.sessionIds.length} session(s)`);const v=N.groupSlug,k=async(D=6)=>{for(let C=0;C<D;C+=1){if(await p(),Dr.getState().groups.some(S=>S.name===v))return!0;await new Promise(S=>setTimeout(S,500))}return!1};try{await ue.getState().loadSessions()}catch{}await k(),m(v)}else{const v=Kn.getState().error;te.error(v||"Failed to create agent group")}},[g,p,m]),y=f();return e.jsxs("div",{className:R("flex h-full w-full bg-background",s),children:[e.jsx("div",{className:"w-64 flex-shrink-0",children:e.jsx(Vj,{selectedGroupName:u,onGroupSelect:h,onNewAgent:j})}),e.jsx("div",{className:"flex-1 min-w-0",children:y?e.jsx(Yj,{group:y}):e.jsx(Kj,{onCreateGroup:x,isCreating:w})})]})},xi=({...s})=>{const{theme:r="system"}=Dh();return e.jsx(Ah,{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})},Xj=(s=5e3)=>{const[r,t]=De.useState(null);return De.useEffect(()=>{if(!Zt())return;let n=!1,o=null;const a=async()=>{const i=await Qh();n||(t(i),o=setTimeout(a,s))};return a(),()=>{n=!0,o&&clearTimeout(o)}},[s]),r},Jj=({onClose:s})=>{const{sessions:r,messages:t,sessionMemoryState:n,currentSessionId:o,trimToViewportWindow:a,evictLeastRecentlyUsed:i}=ue(),l=Xj(4e3),d=c.useMemo(()=>{let f=0;return t.forEach(p=>{f+=p.length}),f},[t]),u=c.useMemo(()=>r.map(f=>{const p=t.get(f.id)?.length||0,g=n.get(f.id);return{id:f.id,title:f.title||"Untitled",messageCount:p,isStreaming:g?.isStreaming||!1,isZombie:g?.isZombie||!1,backgroundCount:g?.backgroundMessageCount||0,lastAccessed:g?.lastAccessedAt||0,isCurrent:f.id===o}}).sort((f,p)=>p.lastAccessed-f.lastAccessed),[r,t,n,o]),m=t.size;return e.jsxs(vl,{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(Eh,{className:"h-4 w-4"}),e.jsx("h3",{className:"font-semibold typography-ui-label",children:"Memory Debug Panel"})]}),s&&e.jsx(Ce,{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]})]})]}),l&&e.jsxs("div",{className:"grid grid-cols-2 gap-2 typography-meta border-t pt-2",children:[e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"Desktop Host"}),e.jsx("div",{className:"typography-markdown font-mono text-xs",children:l.host??"unknown"})]}),e.jsxs("div",{className:"bg-muted/50 rounded p-2",children:[e.jsx("div",{className:"text-muted-foreground",children:"OpenCode Port"}),e.jsxs("div",{className:"typography-markdown font-semibold",children:[l.openCodePort??"n/a",e.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:l.ready?"ready":"starting"})]})]})]}),e.jsxs("div",{className:"typography-meta space-y-1 border-t pt-2",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Viewport Window:"}),e.jsxs("span",{children:[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(ft,{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(Ih,{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(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsxs(Ce,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{o&&a(o,10)},children:[e.jsx(qs,{className:"h-3 w-3 mr-1"}),"Force Trim (10)"]})}),e.jsx(nt,{side:"top",children:"Trim current session to only 10 most recent messages"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{size:"sm",variant:"outline",className:"typography-meta",onClick:()=>{i()},children:"Evict LRU"})}),e.jsx(nt,{side:"top",children:"Remove least recently used sessions from memory cache"})]}),e.jsxs(at,{delayDuration:1e3,children:[e.jsx(it,{asChild:!0,children:e.jsx(Ce,{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(nt,{side:"top",children:"Log current memory state to browser console"})]})]})]})]})},Zj="openchamber-message-cursors",En="cursors",eS=1,wf="openchamber.messageCursors",Il=()=>typeof window<"u",Pl=()=>Il()&&typeof indexedDB<"u",vf=()=>Pl()?new Promise((s,r)=>{const t=indexedDB.open(Zj,eS);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(En)||n.createObjectStore(En)},t.onerror=()=>{r(t.error??new Error("Failed to open IndexedDB"))},t.onsuccess=()=>{s(t.result)}}):Promise.reject(new Error("IndexedDB not supported")),jf=()=>{if(!Il())return{};try{const s=window.localStorage.getItem(wf);if(!s)return{};const r=JSON.parse(s);return r&&typeof r=="object"?r:{}}catch{return{}}},tS=s=>{if(Il())try{window.localStorage.setItem(wf,JSON.stringify(s))}catch{}},sS=async(s,r,t)=>{if(!s||!r)return;if(Pl())try{const o=await vf();await new Promise((a,i)=>{const l=o.transaction(En,"readwrite");l.objectStore(En).put({messageId:r,completedAt:t},s),l.oncomplete=()=>a(),l.onerror=()=>i(l.error??new Error("Cursor write failed")),l.onabort=()=>i(l.error??new Error("Cursor write aborted"))}),o.close();return}catch{}const n=jf();n[s]={messageId:r,completedAt:t},tS(n)},rS=async s=>{if(!s)return null;if(Pl())try{const t=await vf(),n=await new Promise((o,a)=>{const i=t.transaction(En,"readonly"),d=i.objectStore(En).get(s);d.onsuccess=()=>{o(d.result??null)},d.onerror=()=>a(d.error??new Error("Cursor read failed")),i.onerror=()=>a(i.error??new Error("Cursor read failed")),i.onabort=()=>a(i.error??new Error("Cursor read aborted"))});return t.close(),n}catch{}return jf()[s]??null},nS=50,oS=750,Yd=new WeakMap,Qd=s=>{if(!s||!Array.isArray(s))return 0;const r=Yd.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 Yd.set(s,t),t},aS=10,Xd=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<aS?null:n},Jd=(s,r)=>{const t=Xd(s),n=Xd(r);return!t||!n||t.length!==n.length?!0:t>n},qi=new Map,Zd=(s,r)=>{const t=`${s}:${r}`,n=qi.get(t);if(n&&n.sessionId===s)return n.message;const i=(ue.getState().messages.get(s)||[]).find(l=>l.info.id===r)||null;return qi.set(t,{sessionId:s,message:i}),i},iS=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(" ")},lS=()=>{const{addStreamingPart:s,completeStreamingMessage:r,updateMessageInfo:t,updateSessionCompaction:n,addPermission:o,addQuestion:a,dismissQuestion:i,currentSessionId:l,applySessionMetadata:d,sessions:u,getWorktreeMetadata:m,loadMessages:f,loadSessions:p,updateSession:g,removeSessionFromStore:w}=ue(),{checkConnection:h}=rt(),j=_e(we=>we.nativeNotificationsEnabled),x=_e(we=>we.notificationMode),y=mt(we=>we.currentDirectory),b=c.useMemo(()=>{if(!l)return;try{const ne=m?.(l);if(ne?.path)return ne.path}catch(ne){console.warn("Failed to inspect worktree metadata for session directory:",ne)}const we=u.find(ne=>ne.id===l);if(we&&typeof we.directory=="string"&&we.directory.trim().length>0)return we.directory.trim()},[l,m,u]),N=c.useMemo(()=>{if(b&&b.length>0)return b;if(typeof y=="string"&&y.trim().length>0)return y.trim()},[b,y]);c.useEffect(()=>{let we=!1;const ne=async()=>{try{const ge=await je.listPendingPermissions();if(we||ge.length===0)return;ge.forEach(ye=>{o(ye)})}catch{}},Qe=async()=>{try{const ye=Ft.getState().projects.map(Re=>Re.path),qe=u.map(Re=>Re.directory),Ze=[N,...ye,...qe],We=await je.listPendingQuestions({directories:Ze});if(we||We.length===0)return;We.forEach(Re=>{a(Re)})}catch{}};return ne(),Qe(),()=>{we=!0}},[o,a,N,u]);const v=c.useCallback(we=>{if(typeof we!="string")return null;const ne=we.trim();if(!ne)return null;const Qe=ne.replace(/\\/g,"/");return Qe.length>1?Qe.replace(/\/+$/,""):Qe},[]),k=c.useCallback(we=>{if(!we)return null;try{const Qe=m?.(we),ge=v(Qe?.path??null);if(ge)return ge}catch{}const ne=u.find(Qe=>Qe.id===we);return v(ne?.directory??null)},[m,v,u]),D=_e(we=>we.setEventStreamStatus),C=c.useRef(null),M=c.useCallback((we,ne)=>{const Qe=ne??null,ge=C.current;if(!(ge&&ge.status===we&&ge.hint===Qe)){if(C.current={status:we,hint:Qe},Qt()){const qe={idle:"[IDLE]",connecting:"[CONNECT]",connected:"[CONNECTED]",reconnecting:"[RECONNECT]",paused:"[PAUSED]",offline:"[OFFLINE]",error:"[ERROR]"}[we]??"[INFO]",Ze=Qe?`${qe} SSE ${we}: ${Qe}`:`${qe} SSE ${we}`;console.info(Ze)}D(we,Qe)}},[D]),S=c.useCallback((we,ne)=>{if(!we)return Promise.resolve();const Qe=Date.now();if(H.current)return H.current;if(Qe-U.current<oS)return Promise.resolve();const ge=f(we).catch(ye=>{console.warn(`[useEventStream] Failed to resync messages (${ne}):`,ye)}).finally(()=>{H.current=null,U.current=Date.now()});return H.current=ge,ge},[f]),A=c.useCallback(async we=>{Qt()&&console.info("[useEventStream] Bootstrapping state:",we);try{await Promise.all([p(),l?S(l,we):Promise.resolve()])}catch(ne){console.warn("[useEventStream] Bootstrap failed:",we,ne)}},[l,p,S]),I=c.useCallback((we,ne,Qe)=>{Qt()&&console.debug(`[MessageTracker] ${we}: ${ne}`,Qe)},[]),_=c.useCallback(we=>{Qt()&&console.debug(`[MessageTracker] ${we}: reported`)},[]),T=c.useRef(null),P=c.useRef(null),L=c.useRef(0);c.useRef(new Set);const Z=c.useRef(new Map),q=c.useRef(null),$=c.useRef(!1),H=c.useRef(null),U=c.useRef(0),K=c.useRef(new Set),se=c.useRef(new Set),Y=c.useRef(new Set),re=c.useCallback(()=>{if(typeof document>"u")return"visible";const we=document.visibilityState;return we==="hidden"&&document.hasFocus()?"visible":we},[]),V=c.useRef(re()),ae=c.useRef(typeof navigator>"u"?!0:navigator.onLine),E=c.useRef(!1),B=c.useRef(null),F=c.useRef(null),O=c.useRef(Date.now()),z=c.useRef(!1),Q=c.useCallback(we=>{const ne=Date.now();ne-O.current>25e3&&(A(we),O.current=ne)},[A]);c.useEffect(()=>{typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__?.runtime?.isDesktop&&(z.current=!0)},[]);const me=c.useRef(new Map),Se=c.useRef(new Map),he=c.useRef(0),Pe=c.useRef(null),ve=c.useRef(l),Be=c.useRef(null),W=c.useRef(null);c.useEffect(()=>{ve.current=l},[l]);const G=c.useCallback((we,ne)=>{if(!we)return;const Qe=Date.now(),ge=Z.current,ye=ge.get(we);if(ye&&Qe-ye<3e3)return;ge.set(we,Qe);const qe=Ze=>{if(typeof ne=="string"&&ne.trim().length>0)return ne.trim();try{const Re=m?.(Ze);if(Re?.path)return Re.path}catch{}const We=u.find(Re=>Re.id===Ze);return We&&typeof We.directory=="string"&&We.directory.trim().length>0?We.directory.trim():null};setTimeout(async()=>{try{const Ze=qe(we),We=Ze?await je.withDirectory(Ze,()=>je.getSession(we)):await je.getSession(we);if(We){const Re={};typeof We.title=="string"&&We.title.length>0&&(Re.title=We.title),We.summary!==void 0&&(Re.summary=We.summary),Object.keys(Re).length>0&&d(we,Re)}}catch(Ze){console.warn("Failed to refresh session metadata:",Ze)}},100)},[d,m,u]),ee=c.useCallback((we,ne)=>{if(ue.getState().sessionActivityPhase?.get(we)===ne){Se.current=new Map(ue.getState().sessionActivityPhase??new Map);return}const ge=me.current.get(we);ge&&(clearTimeout(ge),me.current.delete(we));const ye=new Map(ue.getState().sessionActivityPhase??new Map);if(ye.set(we,ne),Se.current=ye,ue.setState({sessionActivityPhase:ye}),ne==="cooldown"){const qe=setTimeout(()=>{if(me.current.delete(we),ue.getState().sessionActivityPhase?.get(we)==="cooldown"){const We=new Map(ue.getState().sessionActivityPhase??new Map);We.set(we,"idle"),Se.current=We,ue.setState({sessionActivityPhase:We})}},2e3);me.current.set(we,qe)}},[]),fe=c.useCallback(async()=>{const we=Date.now();if(Pe.current)return Pe.current;if(we-he.current<1500)return;he.current=we;const ne=ge=>{const ye=new Set,qe=new Set(u.map(We=>We.id));Object.entries(ge).forEach(([We,Re])=>{if(!We||!Re)return;ye.add(We);const Xe=Re.type==="busy"||Re.type==="retry"?"busy":"idle";ee(We,Xe)});const Ze=ue.getState().sessionActivityPhase;if(Ze)for(const[We,Re]of Ze.entries())qe.has(We)&&(Re==="busy"||Re==="cooldown")&&!ye.has(We)&&ee(We,"idle")},Qe=(async()=>{try{const ge=await je.getGlobalSessionStatus();if(ge&&Object.keys(ge).length>0){ne(ge);return}const ye=new Set;u.forEach(Xe=>{const Ct=k(Xe.id);Ct&&ye.add(Ct)});const qe=v(N??null);qe&&ye.add(qe);const Ze=Array.from(ye);if(Ze.length===0){const Xe=await je.getSessionStatus();Xe&&ne(Xe);return}const We=await Promise.allSettled(Ze.map(Xe=>je.getSessionStatusForDirectory(Xe))),Re={};if(We.forEach(Xe=>{Xe.status!=="fulfilled"||!Xe.value||Object.assign(Re,Xe.value)}),Object.keys(Re).length===0&&Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(Ct=>Ct==="busy"||Ct==="cooldown")&&!await je.checkHealth().catch(()=>!1))return;ne(Re)}catch{}})().finally(()=>{Pe.current=null});return Pe.current=Qe,Qe},[N,v,k,u,ee]);c.useEffect(()=>{const we=l??null,ne=Be.current,Qe=k(we),ge=W.current;ne&&we&&ne!==we&&ge&&Qe&&ge!==Qe&&fe(),Be.current=we,W.current=Qe},[l,fe,k]);const de=c.useCallback(we=>{if(O.current=Date.now(),Qt()&&console.debug("[useEventStream] Received event:",we.type,we.properties),!we.properties)return;const ne=we.properties;if(!new Set(["session.abort","session.error"]).has(we.type)){const ge=(typeof ne.session=="object"&&ne.session!==null?ne.session:null)||(typeof ne.sessionInfo=="object"&&ne.sessionInfo!==null?ne.sessionInfo:null);if(ge){const ye=ge,qe=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.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 Ze=typeof ye.title=="string"?ye.title:typeof ne.title=="string"?ne.title:void 0,We=typeof ye.summary=="object"&&ye.summary!==null?ye.summary:typeof ne.summary=="object"&&ne.summary!==null?ne.summary:void 0;if(Ze!==void 0||We!==void 0){const Re={};Ze!==void 0&&(Re.title=Ze),We!==void 0&&(Re.summary=We),d(qe,Re)}}}}switch(we.type){case"server.connected":h();break;case"global.disposed":case"server.instance.disposed":{A("server_disposed_event");break}case"openchamber:session-activity":{const ge=typeof ne.sessionId=="string"?ne.sessionId:null,ye=typeof ne.phase=="string"?ne.phase:null;ge&&(ye==="idle"||ye==="busy"||ye==="cooldown")&&(ee(ge,ye),G(ge,typeof ne.directory=="string"?ne.directory:null));break}case"mcp.tools.changed":{const ge=typeof ne.directory=="string"?ne.directory:N;zn.getState().refresh({directory:ge??null,silent:!0});break}case"session.status":if(z.current)break;{const ge=typeof ne.sessionID=="string"?ne.sessionID:null,ye=typeof ne.status=="object"&&ne.status!==null?ne.status:null,qe=typeof ye?.type=="string"?ye.type:null;ge&&qe&&(ee(ge,qe==="busy"||qe==="retry"?"busy":"idle"),G(ge,typeof ne.directory=="string"?ne.directory:null))}break;case"message.part.updated":{const ge=typeof ne.part=="object"&&ne.part!==null?ne.part:null;if(!ge)break;const ye=ge,qe=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,Ze=typeof qe.sessionID=="string"?qe.sessionID:null,We=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof Ze=="string"&&Ze.length>0?Ze:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,Re=typeof qe.id=="string"?qe.id:null,Xe=typeof ye.messageID=="string"&&ye.messageID.length>0?ye.messageID:typeof Re=="string"&&Re.length>0?Re:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!We||!Xe){Qt()&&console.debug("[useEventStream] Skipping message.part.updated without resolvable session/message id",{sessionID:ye.sessionID??Ze??ne.sessionID,messageID:ye.messageID??Re??ne.messageID});break}const Ct=We,ct=Xe,At=ue.getState().sessionMemoryState.get(Ct)?.trimmedHeadMaxId;if(At&&!Jd(ct,At)){Qt()&&console.debug("[useEventStream] Skipping message.part.updated for trimmed message",{sessionId:Ct,messageId:ct,trimmedHeadMaxId:At});break}let Mt="assistant";if(qe&&typeof qe.role=="string")Mt=qe.role;else{const $e=Zd(Ct,ct);if($e){const Fe=$e.info.role;typeof Fe=="string"&&(Mt=Fe)}}if(I(ct,"part_received",{role:Mt}),Mt==="user"&&ye.synthetic===!0){I(ct,"skipped_synthetic_user_part");break}const ke={...ge,type:ge.type||"text"};I(ct,"addStreamingPart_called"),s(Ct,ct,ke,Mt);break}case"message.updated":{const ge=typeof ne.info=="object"&&ne.info!==null?ne.info:ne,ye=ge,qe=typeof ye.sessionID=="string"&&ye.sessionID.length>0?ye.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,Ze=typeof ye.id=="string"&&ye.id.length>0?ye.id:typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;if(!qe||!Ze){Qt()&&console.debug("[useEventStream] Skipping message.updated without resolvable session/message id",{sessionID:ye.sessionID??ne.sessionID,messageID:ye.id??ne.messageID});break}const We=qe,Re=Ze,Xe=ue.getState().sessionMemoryState.get(We)?.trimmedHeadMaxId;if(Xe&&!Jd(Re,Xe)){Qt()&&console.debug("[useEventStream] Skipping message.updated for trimmed message",{sessionId:We,messageId:Re,trimmedHeadMaxId:Xe});break}if(z.current&&Qt())try{const X=ne.parts||ye.parts||[],pe=(Array.isArray(X)?X.filter(Le=>Le?.type==="text"):[]).map(Le=>{const Ee=Le;return typeof Ee?.text=="string"?Ee.text:typeof Ee?.content=="string"?Ee.content:""}).join(`
107
- `);console.info("[STREAM-TRACE] message.updated",{messageId:Re,role:ye.role,status:ye.status,textLen:pe.length,textPreview:pe.slice(0,120),partsCount:Array.isArray(X)?X.length:0})}catch{}if(I(Re,"message_updated",{role:ye.role}),ye.role==="user"){const X=ne.parts||ye.parts,xe=Array.isArray(X)?X:[],pe={...ge,userMessageMarker:!0,clientRole:"user"};if(t(We,Re,pe),xe.length>0)for(let Le=0;Le<xe.length;Le++){const Ee=xe[Le];if(Ee.synthetic===!0)continue;const Ke={...Ee,type:Ee?.type||"text",sessionID:Ee?.sessionID||We,messageID:Ee?.messageID||Re};s(We,Re,Ke,"user")}I(Re,"user_message_created_from_event",{partsCount:xe.length});break}const Ct=Zd(We,Re),ct=Qd(Ct?.parts||[]),At=Ct?.info?.finish==="stop",Mt=ne.parts||ye.parts,ke=Array.isArray(Mt)?Mt:[],$e=ke.length>0,ot=typeof(ye.time||{})?.completed=="number";if(!$e&&!ot)break;const Lt=ge.finish,es=typeof Lt=="string"?Lt:null,Wt=es==="stop";if(ye.role==="assistant"&&$e){const X=Qd(ke);if(ct>0&&X+nS<ct&&!Wt){I(Re,"skipped_shrinking_update",{incomingLen:X,existingLen:ct});break}if(z.current){const pe=ct>0&&X<ct,Le=ke.some(Ke=>{if(!Ke||Ke.type!=="text")return!1;const pt=Ke;return typeof pt.text=="string"&&pt.text.length>0});if(pe&&!(Wt&&Le)){I(Re,"desktop_shrinking_update_suppressed",{incomingLen:X,existingLen:ct});break}}}if(t(We,Re,ge),$e&&ye.role!=="user"){const pe=(ue.getState().messages.get(We)||[]).find(Ke=>Ke.info.id===Re),Le=!pe||pe.parts.length===0;I(Re,Le?"server_parts_injected":"server_parts_refreshed",{count:ke.length});const Ee=z.current&&ye.role==="assistant"?ke.filter(Ke=>Ke?.type!=="text"):ke;for(let Ke=0;Ke<Ee.length;Ke++){const pt=Ee[Ke],ut={...pt,type:pt?.type||"text",sessionID:pt?.sessionID||We,messageID:pt?.messageID||Re};s(We,Re,ut,ye.role),I(Re,`server_part_${Ke}`)}}const He=ge.time,et=He?.completed,gt=typeof et=="number"&&Number.isFinite(et),Je=es==="stop"||At;if(ge.role==="assistant"&&(gt||Je)&&ge.role==="assistant"){const xe=ue.getState().messages.get(We)||[];let pe=null,Le="";for(let xt=0;xt<xe.length;xt++){const Me=xe[xt];Me.info.role==="assistant"&&Me.info.id>Le&&(Le=Me.info.id,pe=Me.info.id)}if(l===We&&Re!==pe)break;if(!Je&&z.current){I(Re,"desktop_completion_without_stop");break}const Ke=gt?et:Date.now();if(gt||t(We,Re,{...ge,time:{...He??{},completed:Ke}}),I(Re,"completed",{timeCompleted:Ke}),_(Re),sS(We,Re,Ke),r(We,Re),es==="stop"&&kn()&&j&&(x==="always"||V.current==="hidden")){const Me=Y.current;if(!Me.has(Re)){Me.add(Re);const tt=vr();if(tt?.notifications){const ze=ye.mode||"agent",Ye=ye.modelID||"assistant",wt=`${ze.charAt(0).toUpperCase()+ze.slice(1)} agent is ready`,Rt=`${iS(Ye)} completed the task`;tt.notifications.notifyAgentCompletion({title:wt,body:Rt,tag:Re})}}}z.current||es==="stop"&&ue.getState().sessionActivityPhase?.get(We)==="busy"&&ee(We,"cooldown");const pt=ge.sessionID,ut=typeof pt=="string"&&pt.length>0?pt:We;G(ut,typeof ne.directory=="string"?ne.directory:null),ge.summary&&typeof ut=="string"&&n(ut,null)}break}case"session.created":case"session.updated":{const ge=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,ye=typeof ge.id=="string"&&ge.id.length>0?ge.id:typeof ge.sessionID=="string"&&ge.sessionID.length>0?ge.sessionID:typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:typeof ne.id=="string"&&ne.id.length>0?ne.id:void 0;if(ye){const qe=typeof ge.time=="object"&&ge.time!==null?ge.time:typeof ne.time=="object"&&ne.time!==null?ne.time:null,Ze=qe&&typeof qe.compacting=="number"?qe.compacting:null;n(ye,Ze);const We=typeof ge.directory=="string"?ge.directory:typeof ne.directory=="string"?ne.directory:null,Re={...ge,id:ye,...We?{directory:We}:{}};g(Re)}break}case"session.deleted":{const ge=typeof ne.sessionID=="string"?ne.sessionID:typeof ne.id=="string"?ne.id:null;ge&&w(ge);break}case"session.abort":{const ge=typeof ne.sessionID=="string"&&ne.sessionID.length>0?ne.sessionID:null,ye=typeof ne.messageID=="string"&&ne.messageID.length>0?ne.messageID:null;ge&&ye&&r(ge,ye);break}case"permission.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const ge=ne;o(ge);const ye=`${ge.sessionID}:${ge.id}`;K.current.has(ye)||setTimeout(()=>{if(ve.current===ge.sessionID||!ue.getState().permissions.get(ge.sessionID)?.some(Re=>Re.id===ge.id))return;K.current.add(ye);const We=ue.getState().sessions.find(Re=>Re.id===ge.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-94fMDU1C.js").then(Xe=>Xe.cv);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.warning("Permission required",{description:We,action:{label:"Open",onClick:()=>{_e.getState().setActiveMainTab("chat"),ue.getState().setCurrentSession(ge.sessionID)}}})})},0);break}case"permission.replied":break;case"question.asked":{if(!("sessionID"in ne)||typeof ne.sessionID!="string")break;const ge=ne;a(ge);const ye=`${ge.sessionID}:${ge.id}`;se.current.has(ye)||setTimeout(()=>{if(ve.current===ge.sessionID||!ue.getState().questions.get(ge.sessionID)?.some(Re=>Re.id===ge.id))return;se.current.add(ye);const We=ue.getState().sessions.find(Re=>Re.id===ge.sessionID)?.title||"Session";as(async()=>{const{toast:Re}=await import("./vendor-.bun-94fMDU1C.js").then(Xe=>Xe.cv);return{toast:Re}},__vite__mapDeps([0,1])).then(({toast:Re})=>{Re.info("Input needed",{description:We,action:{label:"Open",onClick:()=>{_e.getState().setActiveMainTab("chat"),ue.getState().setCurrentSession(ge.sessionID)}}})})},0);break}case"question.replied":{const ge=typeof ne.sessionID=="string"?ne.sessionID:null,ye=typeof ne.requestID=="string"?ne.requestID:null;ge&&ye&&i(ge,ye);break}case"todo.updated":{const ge=typeof ne.sessionID=="string"?ne.sessionID:null,ye=Array.isArray(ne.todos)?ne.todos:null;ge&&ye&&tw(ge,ye);break}}},[l,j,x,s,r,t,o,a,i,h,G,n,d,I,_,ee,g,w,A,N]),Ae=c.useCallback(()=>{const we=re();return V.current=we,we==="visible"&&ae.current},[re]),Ne=c.useCallback(()=>{Qt()&&console.debug("[useEventStream] Connection state:",{isDesktopRuntime:z.current,hasUnsubscribe:!!T.current,currentSessionId:ve.current,effectiveDirectory:N,onlineStatus:ae.current,visibilityState:V.current,lastEventTimestamp:O.current,reconnectAttempts:L.current})},[N]),Oe=c.useCallback(async()=>!0,[]),ce=c.useCallback(()=>{if($.current){Qt()&&console.info("[useEventStream] Already cleaning up, skipping stopStream");return}if($.current=!0,P.current&&(clearTimeout(P.current),P.current=null),T.current){const we=T.current;T.current=null;try{we()}catch(ne){console.warn("[useEventStream] Error during unsubscribe:",ne)}}$.current=!1},[]),dt=c.useCallback(async we=>{if(Ne(),!Ae()){E.current=!0,ae.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}z.current&&(await Oe()||console.warn("[useEventStream] Desktop bridge not ready, falling back to SDK")),we?.resetAttempts&&(L.current=0),ce(),O.current=Date.now(),M("connecting",null),Qt()&&console.info("[useEventStream] Starting event stream...");const ne=ge=>{console.warn("Event stream error:",ge)},Qe=()=>{const ge=E.current;if(L.current=0,E.current=!1,O.current=Date.now(),M("connected",null),h(),Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(qe=>qe==="busy"||qe==="cooldown")&&fe(),ge)A("sse_reconnected");else{const qe=ve.current;qe&&setTimeout(()=>{S(qe,"sse_reconnected").then(()=>G(qe)).catch(Ze=>{console.warn("[useEventStream] Failed to resync messages after reconnect:",Ze)})},0)}};if(Qt()&&console.info("[useEventStream] Connecting to event source (SDK SSE only):",{effectiveDirectory:N,isCleaningUp:$.current}),$.current){Qt()&&console.info("[useEventStream] Skipping subscription due to cleanup in progress");return}try{const ge=je.subscribeToGlobalEvents(qe=>{const Ze=qe.payload,We=qe.payload,Re=typeof We.properties=="object"&&We.properties!==null?We.properties:{},Xe=qe.directory&&qe.directory!=="global"?{...Re,directory:qe.directory}:Re;de({type:typeof Ze.type=="string"?Ze.type:"",properties:Xe})},ne,Qe),ye=()=>{try{ge()}catch(qe){console.warn("[useEventStream] Error during unsubscribe:",qe)}};$.current?ye():T.current=ye}catch(ge){console.error("[useEventStream] Error during subscription:",ge),ne(ge)}},[Ae,ce,M,h,S,G,de,N,fe,Oe,Ne,A]),kt=c.useCallback(we=>{if(!Ae()){E.current=!0,ce(),ae.current?M("paused","Paused while hidden"):M("offline","Waiting for network");return}const ne=L.current+1;L.current=ne;const Qe=we??`Retrying (${ne})`;M("reconnecting",Qe);const ge=ne<=3?Math.min(1e3*Math.pow(2,ne-1),8e3):Math.min(2e3*Math.pow(2,ne-3),32e3),ye=Math.floor(Math.random()*250),qe=ge+ye;P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{dt({resetAttempts:!1})},qe)},[Ae,ce,M,dt]);c.useEffect(()=>{const we=me.current;typeof window<"u"&&(window.__messageTracker=I);let ne=null;z.current&&typeof window<"u"&&(ne=Xe=>{const Ct=typeof Xe.detail?.sessionId=="string"?Xe.detail.sessionId:null,ct=typeof Xe.detail?.phase=="string"?Xe.detail.phase:null;Ct&&(ct==="idle"||ct==="busy"||ct==="cooldown")&&(ee(Ct,ct),G(Ct))},window.addEventListener("openchamber:session-activity",ne));const Qe=()=>{B.current&&(clearTimeout(B.current),B.current=null)},ge=()=>{B.current||(B.current=setTimeout(()=>{const Xe=re();V.current=Xe,Xe!=="visible"?(ce(),E.current=!0,M("paused","Paused while hidden")):Qe()},5e3))},ye=()=>{if(V.current=re(),V.current==="visible"){if(Qe(),Q("visibility_restore"),E.current||!T.current){console.info("[useEventStream] Visibility restored, triggering soft refresh...");const Xe=ve.current;Xe&&(S(Xe,"visibility_restore").catch(()=>{}),G(Xe)),fe(),M("connecting","Resuming stream"),dt({resetAttempts:!0})}}else M("paused","Paused while hidden"),ge()},qe=()=>{if(V.current=re(),V.current==="visible"&&(Qe(),Q("window_focus"),E.current||!T.current)){console.info("[useEventStream] Window focused after pause, triggering soft refresh...");const Xe=ve.current;Xe&&(G(Xe),S(Xe,"window_focus").then(()=>console.info("[useEventStream] Messages refreshed on focus")).catch(Ct=>console.warn("[useEventStream] Failed to refresh messages:",Ct))),fe(),M("connecting","Resuming stream"),dt({resetAttempts:!0})}},Ze=()=>{ae.current=!0,Q("network_restored"),(E.current||!T.current)&&(M("connecting","Network restored"),dt({resetAttempts:!0}))},We=()=>{ae.current=!1,E.current=!0,M("offline","Waiting for network"),ce()};typeof document<"u"&&document.addEventListener("visibilitychange",ye),typeof window<"u"&&(window.addEventListener("online",Ze),window.addEventListener("offline",We),window.addEventListener("focus",qe));const Re=setTimeout(()=>{dt({resetAttempts:!0})},100);return F.current&&clearInterval(F.current),F.current=setInterval(()=>{if(!Ae())return;const Xe=Date.now();Array.from(ue.getState().sessionActivityPhase?.values?.()??[]).some(ct=>ct==="busy"||ct==="cooldown")&&fe(),Xe-O.current>25e3&&Promise.resolve().then(async()=>{try{await je.checkHealth()?O.current=Date.now():kt("Refreshing stalled stream")}catch(ct){console.warn("Health check after stale stream failed:",ct),kt("Refreshing stalled stream")}})},1e4),()=>{clearTimeout(Re),ne&&typeof window<"u"&&window.removeEventListener("openchamber:session-activity",ne),typeof document<"u"&&document.removeEventListener("visibilitychange",ye),typeof window<"u"&&(window.removeEventListener("online",Ze),window.removeEventListener("offline",We),window.removeEventListener("focus",qe)),Qe(),F.current&&(clearInterval(F.current),F.current=null),we.forEach(Xe=>clearTimeout(Xe)),we.clear(),qi.clear(),Y.current.clear(),E.current=!1,V.current=re(),ae.current=typeof navigator>"u"?!0:navigator.onLine,ce(),q.current&&(clearTimeout(q.current),q.current=null),M("idle",null)}},[N,I,re,ce,M,dt,kt,f,G,ee,fe,Ae,p,Q,S])},cS=()=>{const{openNewSessionDraft:s,abortCurrentOperation:r,armAbortPrompt:t,clearAbortPrompt:n,currentSessionId:o}=ue(),{toggleCommandPalette:a,toggleHelpDialog:i,toggleSidebar:l,setSessionSwitcherOpen:d,setActiveMainTab:u,setSettingsDialogOpen:m,setModelSelectorOpen:f}=_e(),{themeMode:p,setThemeMode:g}=on(),{working:w}=zm(),h=c.useRef(null),j=c.useRef(null),x=c.useRef(!1),y=c.useCallback(()=>{j.current&&(clearTimeout(j.current),j.current=null),h.current=null,n()},[n]);c.useEffect(()=>{const b=N=>{if(Cs(N)&&N.key==="k"&&(N.preventDefault(),a()),Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="l"){const k=vr()?.diagnostics;if(!k||(N.preventDefault(),x.current))return;x.current=!0,k.downloadLogs().then(({fileName:D,content:C})=>{const M=D||"openchamber.log",S=new Blob([C],{type:"text/plain;charset=utf-8"}),A=URL.createObjectURL(S),I=document.createElement("a");I.href=A,I.download=M,document.body.appendChild(I),I.click(),document.body.removeChild(I),URL.revokeObjectURL(A)}).finally(()=>{x.current=!1});return}if(Cs(N)&&N.key==="."&&(N.preventDefault(),i()),Cs(N)&&N.key.toLowerCase()==="n"){if(N.preventDefault(),rt.getState().settingsAutoCreateWorktree?!N.shiftKey:N.shiftKey){u("chat"),d(!1),ba();return}u("chat"),d(!1),s()}if(Cs(N)&&N.key==="/"){N.preventDefault();const v=["light","dark","system"],D=(v.indexOf(p)+1)%v.length;g(v[D])}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="t"){N.preventDefault();const{isTimelineDialogOpen:v,setTimelineDialogOpen:k}=_e.getState();k(!v);return}if(Cs(N)&&!N.shiftKey&&N.key===","){N.preventDefault();const{isSettingsDialogOpen:v}=_e.getState();m(!v);return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="l"){N.preventDefault();const{isMobile:v,isSessionSwitcherOpen:k}=_e.getState();v?d(!k):l();return}if(Cs(N)&&!N.shiftKey&&N.key.toLowerCase()==="i"){N.preventDefault(),document.querySelector('textarea[data-chat-input="true"]')?.focus();return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="m"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S,isModelSelectorOpen:A}=_e.getState();if(v||k||D||C||M||!(S==="chat"))return;N.preventDefault(),f(!A);return}if(Cs(N)&&N.shiftKey&&N.key.toLowerCase()==="t"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=_e.getState();if(v||k||D||C||M||!(S==="chat"))return;const _=rt.getState();if(_.getCurrentModelVariants().length===0)return;N.preventDefault(),_.cycleCurrentVariant();const P=rt.getState().currentVariant,L=ue.getState(),Z=L.currentSessionId,q=rt.getState().currentAgentName,$=rt.getState().currentProviderId,H=rt.getState().currentModelId;Z&&q&&$&&H&&L.saveAgentModelVariantForSession(Z,q,$,H,P);return}if(N.key==="Escape"){const{isSettingsDialogOpen:v,isCommandPaletteOpen:k,isHelpDialogOpen:D,isSessionSwitcherOpen:C,isAboutDialogOpen:M,activeMainTab:S}=_e.getState();if(v){N.preventDefault(),m(!1),y();return}if(k||D||C||M||!(S==="chat")){y();return}const _=o;if(!(w.canAbort&&!!_)){y();return}const P=Date.now(),L=h.current;if(L&&P<L){N.preventDefault(),y(),r();return}N.preventDefault();const Z=t(3e3)??P+3e3;h.current=Z,j.current&&clearTimeout(j.current);const q=Math.max(Z-P,0);j.current=setTimeout(()=>{h.current&&Date.now()>=h.current&&y()},q||0);return}};return window.addEventListener("keydown",b),()=>{window.removeEventListener("keydown",b)}},[s,r,a,i,l,d,u,m,f,g,p,w,t,y,o]),c.useEffect(()=>()=>{y()},[y])},eu="openchamber:menu-action",dS=s=>{const{openNewSessionDraft:r}=ue(),{toggleCommandPalette:t,toggleHelpDialog:n,toggleSidebar:o,setSessionSwitcherOpen:a,setActiveMainTab:i,setSettingsDialogOpen:l,setAboutDialogOpen:d}=_e(),{addProject:u}=Ft(),{requestAccess:m,startAccessing:f}=wa(),{setThemeMode:p}=on(),g=c.useRef(!1),w=c.useCallback(()=>{Zt()?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")}):Dn.requestDirectoryDialog()},[u,m,f]);c.useEffect(()=>{const h=j=>{switch(j.detail){case"about":d(!0);break;case"settings":l(!0);break;case"command-palette":t();break;case"new-session":i("chat"),a(!1),r();break;case"new-worktree-session":i("chat"),a(!1),ba();break;case"change-workspace":w();break;case"open-git-tab":{const{activeMainTab:y}=_e.getState();i(y==="git"?"chat":"git");break}case"open-diff-tab":{const{activeMainTab:y}=_e.getState();i(y==="diff"?"chat":"diff");break}case"open-terminal-tab":{const{activeMainTab:y}=_e.getState();i(y==="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 b=vr()?.diagnostics;if(!b||g.current)break;g.current=!0,b.downloadLogs().then(({fileName:N,content:v})=>{const k=N||"openchamber.log",D=new Blob([v],{type:"text/plain;charset=utf-8"}),C=URL.createObjectURL(D),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(eu,h),()=>window.removeEventListener(eu,h)},[r,t,n,o,a,i,l,d,p,s,w])},uS=s=>s.role==="assistant",tu=s=>{const r=s.info;if(!uS(r))return;const t=r.time?.completed;return typeof t=="number"?t:void 0},Vo=s=>{if(!s)return!1;if(s.role==="user")return!0;const r=s;return r.clientRole==="user"?!0:!!r.userMessageMarker},su=s=>(Array.isArray(s?.parts)?s.parts:[]).map(n=>Gn(n)).join(" ").replace(/\s+/g," ").trim(),mS=(s,r)=>{if(!s||!Vo(s.info))return-1;const t=su(s),n=typeof s.info?.time?.created=="number"?s.info.time.created:void 0;let o=-1,a=Number.POSITIVE_INFINITY;return r.forEach((i,l)=>{if(!Vo(i.info))return;const d=su(i),u=!!(t&&d&&d===t),m=typeof i.info?.time?.created=="number"?i.info.time.created:void 0,f=typeof n=="number"&&typeof m=="number"?Math.abs(m-n):null;if(u){const p=typeof f=="number"?f:0;p<a&&(o=l,a=p);return}!t&&!d&&typeof f=="number"&&f<1500&&f<a&&(o=l,a=f)}),o!==-1?o:typeof n=="number"?r.findIndex(i=>{if(!Vo(i.info))return!1;const l=typeof i.info?.time?.created=="number"?i.info.time.created:void 0;return typeof l!="number"?!1:Math.abs(l-n)<1e3}):-1},fS=()=>{const{currentSessionId:s,messages:r,streamingMessageIds:t}=ue(),n=c.useMemo(()=>s?t.get(s)??null:null,[s,t]),o=c.useRef(void 0),a=c.useRef(0),i=c.useCallback(async()=>{if(!s||n)return;const l=Date.now();if(!(l-a.current<2e3)){a.current=l;try{const d=r.get(s)||[],u=await je.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),w=p===-1?mS(f,u):p;if(w!==-1)if(w<u.length-1){const h=u.slice(w+1);console.log(`[SYNC] Found ${h.length} new messages to append`);const j=[...d,...h],{syncMessages:x}=ue.getState();x(s,j)}else{const h=u[w],j=d[d.length-1],x=tu(h),y=tu(j);if(x&&!y){console.log("[SYNC] Last message completed on server");const b=[...d.slice(0,-1),h],{syncMessages:N}=ue.getState();N(s,b)}}else if(Vo(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}=ue.getState();j(s,h)}else console.log("[SYNC] Local messages not found on server - skipping sync")}else if(m){const p=u.findIndex(g=>g.info.id===m.messageId);if(p!==-1){if(p<u.length-1){const w=u.slice(p+1).slice(-us.VIEWPORT_MESSAGES);if(w.length>0){console.log(`[SYNC] Restoring ${w.length} messages after cursor`);const{syncMessages:h}=ue.getState();h(s,w)}}}else if(u.length>0){console.log("[SYNC] Cursor not found on server response, loading recent messages");const g=u.slice(-us.VIEWPORT_MESSAGES),{syncMessages:w}=ue.getState();w(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}=ue.getState();g(s,p)}}catch(d){console.debug("Background sync failed:",d)}}},[s,r,n]);c.useEffect(()=>{const l=()=>{console.log("[FOCUS] Window focused - checking for updates"),i()};return window.addEventListener("focus",l),()=>window.removeEventListener("focus",l)},[i]),c.useEffect(()=>{if(!s||n)return;const l=()=>{document.visibilityState==="visible"&&i(),o.current=setTimeout(l,3e4)};return o.current=setTimeout(l,3e4),()=>{o.current&&clearTimeout(o.current)}},[s,n,i]),c.useEffect(()=>{const l=()=>{document.visibilityState==="visible"&&(console.log("[FOCUS] Tab became visible - checking for updates"),i())};return document.addEventListener("visibilitychange",l),()=>document.removeEventListener("visibilitychange",l)},[i])},pS=()=>{c.useEffect(()=>{let s=!1;return(async()=>{try{const t=await je.getSessionStatus();if(s||!t)return;const n=new Map;Object.entries(t).forEach(([o,a])=>{if(!o||!a)return;const i=a,l=i.type==="busy"||i.type==="retry"?"busy":"idle";n.set(o,l)}),n.size>0&&ue.setState({sessionActivityPhase:n})}catch{}})(),()=>{s=!0}},[])};function hS(){const{git:s}=Pn(),r=mt(m=>m.currentDirectory),{currentSessionId:t,sessions:n,worktreeMetadata:o}=ue(),{setActiveDirectory:a,startPolling:i,stopPolling:l,fetchAll:d}=Xt(),u=c.useMemo(()=>{const m=t?o.get(t)??void 0:void 0,p=n.find(g=>g.id===t)?.directory??null;return m?.path??p??r??null},[t,n,o,r]);c.useEffect(()=>{if(!u||!s){l();return}return a(u),d(u,s),i(s),()=>{l()}},[u,s,a,i,l,d])}function gS({children:s}){return hS(),e.jsx(e.Fragment,{children:s})}const xS=()=>{const[{isUpdating:s,message:r},t]=c.useState(()=>xg());return c.useEffect(()=>gg(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(Dl,{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]=c.useState(null);c.useEffect(()=>{if(!s)return;typeof window<"u"&&!!window.opencodeDesktop?(async()=>{try{const{getVersion:l}=await as(async()=>{const{getVersion:u}=await import("./vendor-.bun-94fMDU1C.js").then(m=>m.cx);return{getVersion:u}},__vite__mapDeps([0,1])),d=await l();n(d)}catch{n("1.4.8")}})():n("1.4.8")},[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(Dl,{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(Ni,{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(ku,{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(Ci,{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 yi({apis:s,children:r}){return e.jsx(hl.Provider,{value:s,children:r})}const bS="curl -fsSL https://opencode.ai/install | bash",wS=3e3;function vS({onCopy:s}){return e.jsxs("div",{className:"flex items-center justify-center gap-3",children:[e.jsxs("code",{children:[e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"curl"}),e.jsx("span",{className:"text-muted-foreground",children:" -fsSL "}),e.jsx("span",{style:{color:"var(--syntax-string)"},children:"https://opencode.ai/install"}),e.jsx("span",{className:"text-muted-foreground",children:" | "}),e.jsx("span",{style:{color:"var(--syntax-keyword)"},children:"bash"})]}),e.jsx("button",{onClick:s,className:"inline-flex items-center text-muted-foreground hover:text-foreground transition-colors",title:"Copy to clipboard",children:e.jsx(Gs,{className:"h-4 w-4"})})]})}const jS=3e4;function SS({onCliAvailable:s}){const[r,t]=c.useState(!1),[n,o]=c.useState(!1),[a,i]=c.useState(!1);c.useEffect(()=>{const m=setTimeout(()=>o(!0),jS);return()=>clearTimeout(m)},[]),c.useEffect(()=>{i(typeof window.opencodeDesktop<"u")},[]);const l=c.useCallback(async m=>{if(!m.target.closest("button, a, input, select, textarea, code")&&m.button===0&&a)try{const{getCurrentWindow:f}=await as(async()=>{const{getCurrentWindow:g}=await import("./vendor-.bun-94fMDU1C.js").then(w=>w.cw);return{getCurrentWindow:g}},__vite__mapDeps([0,1]));await f().startDragging()}catch(f){console.error("Failed to start window dragging:",f)}},[a]),d=c.useCallback(async()=>{try{const m=await fetch("/health");return m.ok?(await m.json()).cliAvailable===!0:!1}catch{return!1}},[]),u=c.useCallback(async()=>{try{await navigator.clipboard.writeText(bS),t(!0),setTimeout(()=>t(!1),2e3)}catch(m){console.error("Failed to copy:",m)}},[]);return c.useEffect(()=>{const m=async()=>{await d()&&s?.()},f=setInterval(m,wS);return m(),()=>clearInterval(f)},[d,s]),e.jsxs("div",{className:"h-full flex items-center justify-center bg-transparent p-8 relative cursor-default select-none",onMouseDown:l,children:[e.jsxs("div",{className:"w-full space-y-4 text-center",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-foreground",children:"Welcome to OpenChamber"}),e.jsxs("p",{className:"text-muted-foreground",children:[e.jsxs("a",{href:"https://opencode.ai",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline inline-flex items-center gap-1",children:["OpenCode CLI",e.jsx(Go,{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(Pt,{className:"h-4 w-4"}),"Copied to clipboard"]}):e.jsx(vS,{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(Go,{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 kS=()=>{const{isAboutDialogOpen:s,setAboutDialogOpen:r}=_e();return e.jsx(yS,{open:s,onOpenChange:r})};function NS({apis:s}){const{initializeApp:r,isInitialized:t,isConnected:n}=rt(),{error:o,clearError:a,loadSessions:i}=ue(),l=mt(v=>v.currentDirectory),d=mt(v=>v.isSwitchingDirectory),[u,m]=c.useState(!1),{uiFont:f,monoFont:p}=af(),[g,w]=c.useState(()=>s.runtime.isDesktop),[h,j]=c.useState(()=>s.runtime.isVSCode),[x,y]=c.useState(()=>s.runtime.isDesktop?Xh():!0);c.useEffect(()=>{w(s.runtime.isDesktop),j(s.runtime.isVSCode)},[s.runtime.isDesktop,s.runtime.isVSCode]),c.useEffect(()=>(ql(s),()=>ql(null)),[s]),c.useEffect(()=>{if(typeof document>"u")return;const v=document.documentElement,k=Md[f]?.stack??Md[j0].stack,D=Wr[p]?.stack??Wr[Ho].stack;v.style.setProperty("--font-sans",k),v.style.setProperty("--font-heading",k),v.style.setProperty("--font-family-sans",k),v.style.setProperty("--font-mono",D),v.style.setProperty("--font-family-mono",D),v.style.setProperty("--ui-regular-font-weight","400"),document.body&&(document.body.style.fontFamily=k)},[f,p]),c.useEffect(()=>{if(t){const k=setTimeout(()=>{const D=document.getElementById("initial-loading");D&&(D.classList.add("fade-out"),setTimeout(()=>{D.remove()},300))},150);return()=>clearTimeout(k)}},[t]),c.useEffect(()=>{const v=setTimeout(()=>{const k=document.getElementById("initial-loading");k&&!t&&(k.classList.add("fade-out"),setTimeout(()=>{k.remove()},300))},5e3);return()=>clearTimeout(v)},[t]),c.useEffect(()=>{(async()=>h||await r())()},[r,h]),c.useEffect(()=>{if(d)return;(async()=>h||n&&(je.setDirectory(l),await i()))()},[l,d,i,n,h]),lS(),cS();const b=c.useCallback(()=>{m(v=>!v)},[]);dS(b),fS(),pS(),hf(),c.useEffect(()=>{const v=k=>{Cs(k)&&k.shiftKey&&k.key==="D"&&(k.preventDefault(),m(D=>!D))};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[]),c.useEffect(()=>{o&&setTimeout(()=>a(),5e3)},[o,a]);const N=c.useCallback(()=>{y(!0),window.location.reload()},[]);return g&&!x?e.jsx(ls,{children:e.jsx("div",{className:"h-full text-foreground bg-transparent",children:e.jsx(SS,{onCliAvailable:N})})}):h?(typeof window<"u"?window.__OPENCHAMBER_PANEL_TYPE__:"chat")==="agentManager"?e.jsx(ls,{children:e.jsx(yi,{apis:s,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(Qj,{}),e.jsx(xi,{})]})})}):e.jsx(ls,{children:e.jsx(yi,{apis:s,children:e.jsx(jd,{children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx($j,{}),e.jsx(xi,{})]})})})}):e.jsx(ls,{children:e.jsx(yi,{apis:s,children:e.jsx(gS,{children:e.jsx(jd,{children:e.jsxs("div",{className:`h-full text-foreground ${g?"bg-transparent":"bg-background"}`,children:[e.jsx(_j,{}),e.jsx(xi,{}),e.jsx(xS,{}),e.jsx(kS,{}),u&&e.jsx(Jj,{onClose:()=>m(!1)})]})})})})})}const Sf=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=mt.getState();s&&t.homeDirectory!==s&&t.synchronizeHomeDirectory(s),r&&t.setDirectory(r,{showOverlay:!1})},kf="/auth/session",CS=async()=>fetch(kf,{method:"GET",credentials:"include",headers:{Accept:"application/json"}}),ru=async s=>fetch(kf,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:s})}),Tl=({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})]}),MS=({message:s="Preparing workspace…"})=>e.jsx(Tl,{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})})}),DS=({onRetry:s})=>e.jsx(Tl,{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(Ce,{type:"button",onClick:s,className:"w-full max-w-xs",children:"Retry"})]})}),AS=()=>{try{return new URLSearchParams(window.location.search).get("token")}catch{return null}},ES=()=>{try{const s=new URL(window.location.href);s.searchParams.delete("token"),window.history.replaceState({},"",s.toString())}catch{}},IS=({children:s})=>{const r=c.useMemo(()=>Zt(),[]),t=c.useMemo(()=>Ut(),[]),n=r||t,[o,a]=c.useState(()=>n?"authenticated":"pending"),[i,l]=c.useState(""),[d,u]=c.useState(!1),[m,f]=c.useState(""),p=c.useRef(null),g=c.useRef(n),w=c.useRef(!1),h=c.useCallback(async()=>{if(n){a("authenticated");return}a(x=>x==="authenticated"?x:"pending");try{const x=await CS();if(x.ok){a("authenticated"),f("");return}if(x.status===401){a("locked");return}a("error")}catch(x){console.warn("Failed to check session status:",x),a("error")}},[n]);c.useEffect(()=>{n||h()},[h,n]),c.useEffect(()=>{!n&&o==="locked"&&(g.current=!1)},[n,o]),c.useEffect(()=>{o==="locked"&&p.current&&(p.current.focus(),p.current.select())},[o]),c.useEffect(()=>{if(n||o!=="locked"||w.current||d)return;const x=AS();x&&(w.current=!0,ES(),u(!0),f(""),ru(x).then(y=>{if(y.ok){l(""),a("authenticated");return}if(y.status===401){f("URL token invalid. Please enter password manually."),a("locked");return}f("Unexpected response from server."),a("error")}).catch(y=>{console.warn("Failed to submit URL token:",y),f("Network error. Check connection and retry."),a("error")}).finally(()=>{u(!1)}))},[n,o,d]),c.useEffect(()=>{n||o==="authenticated"&&!g.current&&(g.current=!0,(async()=>(await Pu(),await Tu(),await Sf()))())},[n,o]);const j=async x=>{if(x.preventDefault(),!(!i||d)){u(!0),f("");try{const y=await ru(i);if(y.ok){l(""),a("authenticated");return}if(y.status===401){f("Incorrect password. Try again."),a("locked");return}f("Unexpected response from server."),a("error")}catch(y){console.warn("Failed to submit UI password:",y),f("Network error. Check connection and retry."),a("error")}finally{u(!1)}}};return o==="pending"?e.jsx(MS,{}):o==="error"?e.jsx(DS,{onRetry:()=>{h()}}):o==="locked"?e.jsx(Tl,{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(Ph,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground/60"}),e.jsx(ht,{id:"openchamber-ui-password",ref:p,type:"password",autoComplete:"current-password",placeholder:"Enter password",value:i,onChange:x=>{l(x.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(Ce,{type:"submit",size:"icon",disabled:!i||d,"aria-label":d?"Unlocking":"Unlock",children:d?e.jsx(cs,{className:"h-4 w-4 animate-spin"}):e.jsx(Th,{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})},bi=s=>{if(!s||typeof s!="string")return null;const r=s.trim();if(!r.startsWith("#"))return null;let t=r.slice(1);if((t.length===3||t.length===4)&&(t=t.split("").map(l=>l+l).join("")),t.length===8&&(t=t.slice(0,6)),t.length!==6)return null;const n=Number.parseInt(t,16);if(Number.isNaN(n))return null;const o=n>>16&255,a=n>>8&255,i=n&255;return`${o} ${a} ${i}`};class PS{inheritanceMap=new Map;constructor(){this.initializeInheritanceMap()}generate(r){const t=[];return t.push(...this.generateTailwindVariables(r)),t.push(...this.generatePrimaryColors(r.colors.primary)),t.push(...this.generateSurfaceColors(r.colors.surface)),t.push(...this.generateInteractiveColors(r.colors.interactive)),t.push(...this.generateStatusColors(r.colors.status)),t.push(...this.generateSyntaxColors(r.colors.syntax)),t.push(...this.generateComponentColors(r.colors,r)),t.push(...this.generateTypographyVariables()),r.config&&t.push(...this.generateConfigVariables(r.config)),t.join(`
108
- `)}generateTailwindVariables(r){const t=[];t.push(` --background: ${r.colors.surface.background} !important;`),t.push(` --foreground: ${r.colors.surface.foreground} !important;`),t.push(` --muted: ${r.colors.surface.muted} !important;`),t.push(` --muted-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --card: ${r.colors.surface.elevated} !important;`),t.push(` --card-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --popover: ${r.colors.surface.elevated} !important;`),t.push(` --popover-foreground: ${r.colors.surface.elevatedForeground} !important;`),t.push(` --border: ${r.colors.interactive.border} !important;`),t.push(` --input: ${r.colors.interactive.border} !important;`),t.push(` --primary: ${r.colors.primary.base} !important;`),t.push(` --primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --secondary: ${r.colors.surface.muted} !important;`),t.push(` --secondary-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --accent: ${r.colors.surface.subtle} !important;`),t.push(` --accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --destructive: ${r.colors.status.error} !important;`),t.push(` --destructive-foreground: ${r.colors.status.errorForeground} !important;`),t.push(` --ring: ${r.colors.interactive.focusRing} !important;`),r.config?.radius?.md&&t.push(` --radius: ${r.config.radius.md} !important;`);const n=bi(r.colors.surface.muted),o=bi(r.colors.surface.subtle),a=bi(r.colors.interactive.border);t.push(` --sidebar-base: ${r.colors.surface.muted} !important;`),n&&t.push(` --sidebar-base-rgb: ${n} !important;`),t.push(" --sidebar: var(--sidebar-base) !important;"),t.push(` --sidebar-foreground: ${r.colors.surface.mutedForeground} !important;`),t.push(` --sidebar-primary: ${r.colors.primary.base} !important;`),t.push(` --sidebar-primary-foreground: ${r.colors.primary.foreground} !important;`),t.push(` --sidebar-accent-base: ${r.colors.surface.subtle} !important;`),o&&t.push(` --sidebar-accent-base-rgb: ${o} !important;`),t.push(" --sidebar-accent: var(--sidebar-accent-base) !important;"),t.push(` --sidebar-accent-foreground: ${r.colors.surface.foreground} !important;`),t.push(` --sidebar-border: ${r.colors.interactive.border} !important;`),a&&t.push(` --sidebar-border-rgb: ${a} !important;`),t.push(` --sidebar-ring: ${r.colors.interactive.focusRing} !important;`);const i=r.metadata.variant==="dark",l=i?.8:.95,d=i?.7:.9;if(n)t.push(` --sidebar-overlay-strong: rgb(${n} / ${l}) !important;`),t.push(` --sidebar-overlay-soft: rgb(${n} / ${d}) !important;`);else{const u=r.colors.surface.muted;t.push(` --sidebar-overlay-strong: ${this.opacity(u,l)} !important;`),t.push(` --sidebar-overlay-soft: ${this.opacity(u,d)} !important;`)}return r.colors.charts?.series&&Array.isArray(r.colors.charts.series)&&r.colors.charts.series.forEach((u,m)=>{t.push(` --chart-${m+1}: ${u};`)}),r.colors.loading?(t.push(` --loading-spinner: ${r.colors.loading.spinner||r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.loading.spinnerTrack||r.colors.surface.muted};`)):(t.push(` --loading-spinner: ${r.colors.primary.base};`),t.push(` --loading-spinner-track: ${r.colors.surface.muted};`)),t}apply(r){const t=this.generate(r),n=document.createElement("style");n.id="opencode-theme-variables";let o="";r.metadata.variant==="dark"?(o=`:root {
109
- ${t}
110
- }
111
-
112
- .dark {
113
- ${t}
114
- }`,document.documentElement.classList.add("dark"),document.documentElement.classList.remove("light")):(o=`:root {
115
- ${t}
116
- }
117
-
118
- :root:not(.dark) {
119
- ${t}
120
- }`,document.documentElement.classList.remove("dark"),document.documentElement.classList.add("light")),n.textContent=o;const a=document.getElementById("opencode-theme-variables");a&&a.remove(),document.head.appendChild(n),document.documentElement.setAttribute("data-theme",r.metadata.variant)}generatePrimaryColors(r){const t=[];return t.push(` --primary-base: ${r.base};`),t.push(` --primary-hover: ${r.hover||this.darken(r.base,10)};`),t.push(` --primary-active: ${r.active||this.darken(r.base,20)};`),t.push(` --primary-foreground: ${r.foreground||"#ffffff"};`),t.push(` --primary-muted: ${r.muted||this.opacity(r.base,.5)};`),t.push(` --primary-emphasis: ${r.emphasis||this.lighten(r.base,10)};`),t}generateSurfaceColors(r){const t=[];return t.push(` --surface-background: ${r.background};`),t.push(` --surface-foreground: ${r.foreground};`),t.push(` --surface-muted: ${r.muted};`),t.push(` --surface-muted-foreground: ${r.mutedForeground};`),t.push(` --surface-elevated: ${r.elevated};`),t.push(` --surface-elevated-foreground: ${r.elevatedForeground};`),t.push(` --surface-overlay: ${r.overlay};`),t.push(` --surface-subtle: ${r.subtle};`),t}generateInteractiveColors(r){const t=[];return t.push(` --interactive-border: ${r.border};`),t.push(` --interactive-border-hover: ${r.borderHover};`),t.push(` --interactive-border-focus: ${r.borderFocus};`),t.push(` --interactive-selection: ${r.selection};`),t.push(` --interactive-selection-foreground: ${r.selectionForeground};`),t.push(` --interactive-focus: ${r.focus};`),t.push(` --interactive-focus-ring: ${r.focusRing};`),t.push(` --interactive-cursor: ${r.cursor};`),t.push(` --interactive-hover: ${r.hover};`),t.push(` --interactive-active: ${r.active};`),t}generateStatusColors(r){const t=[];return t.push(` --status-error: ${r.error};`),t.push(` --status-error-foreground: ${r.errorForeground};`),t.push(` --status-error-background: ${r.errorBackground};`),t.push(` --status-error-border: ${r.errorBorder};`),t.push(` --status-warning: ${r.warning};`),t.push(` --status-warning-foreground: ${r.warningForeground};`),t.push(` --status-warning-background: ${r.warningBackground};`),t.push(` --status-warning-border: ${r.warningBorder};`),t.push(` --status-success: ${r.success};`),t.push(` --status-success-foreground: ${r.successForeground};`),t.push(` --status-success-background: ${r.successBackground};`),t.push(` --status-success-border: ${r.successBorder};`),t.push(` --status-info: ${r.info};`),t.push(` --status-info-foreground: ${r.infoForeground};`),t.push(` --status-info-background: ${r.infoBackground};`),t.push(` --status-info-border: ${r.infoBorder};`),t}generateSyntaxColors(r){const t=[];t.push(` --syntax-background: ${r.base.background};`),t.push(` --syntax-foreground: ${r.base.foreground};`),t.push(` --syntax-comment: ${r.base.comment};`),t.push(` --syntax-keyword: ${r.base.keyword};`),t.push(` --syntax-string: ${r.base.string};`),t.push(` --syntax-number: ${r.base.number};`),t.push(` --syntax-function: ${r.base.function};`),t.push(` --syntax-variable: ${r.base.variable};`),t.push(` --syntax-type: ${r.base.type};`),t.push(` --syntax-operator: ${r.base.operator};`);const n=this.generateSyntaxTokens(r);for(const[o,a]of Object.entries(n))t.push(` --syntax-${this.kebabCase(o)}: ${a};`);return t}generateSyntaxTokens(r){const t=r.base,n=r.tokens||{};return{commentDoc:n.commentDoc||this.lighten(t.comment,10),stringEscape:n.stringEscape||this.darken(t.string,20),stringInterpolation:n.stringInterpolation||t.variable,stringRegex:n.stringRegex||this.adjustHue(t.string,15),keywordControl:n.keywordControl||t.keyword,keywordOperator:n.keywordOperator||t.operator,keywordImport:n.keywordImport||this.lighten(t.keyword,10),keywordReturn:n.keywordReturn||this.emphasize(t.keyword),functionCall:n.functionCall||this.lighten(t.function,5),functionBuiltin:n.functionBuiltin||this.darken(t.function,10),method:n.method||t.function,methodCall:n.methodCall||this.lighten(t.function,5),variableBuiltin:n.variableBuiltin||this.emphasize(t.variable),variableProperty:n.variableProperty||this.lighten(t.variable,10),variableReadonly:n.variableReadonly||t.number,parameter:n.parameter||t.variable,typePrimitive:n.typePrimitive||this.darken(t.type,10),typeInterface:n.typeInterface||t.type,className:n.className||this.emphasize(t.type),enum:n.enum||t.type,boolean:n.boolean||t.number,null:n.null||this.opacity(t.number,.7),constant:n.constant||t.number,punctuation:n.punctuation||this.opacity(t.foreground,.7),delimiter:n.delimiter||this.opacity(t.foreground,.8),bracket:n.bracket||t.foreground,tag:n.tag||t.keyword,tagAttribute:n.tagAttribute||t.variable,tagAttributeValue:n.tagAttributeValue||t.string,tagBracket:n.tagBracket||this.opacity(t.foreground,.8),decorator:n.decorator||t.function,annotation:n.annotation||t.function,namespace:n.namespace||this.opacity(t.type,.8),module:n.module||this.opacity(t.type,.8),...n}}generateComponentColors(r,t){const n=[];return r.markdown?n.push(...this.generateMarkdownColors(r.markdown,t)):n.push(...this.generateDefaultMarkdownColors(t)),r.chat?n.push(...this.generateChatColors(r.chat,t)):n.push(...this.generateDefaultChatColors(t)),r.tools?n.push(...this.generateToolColors(r.tools,t)):n.push(...this.generateDefaultToolColors(t)),n}generateMarkdownColors(r,t){const n=[],o=t.colors.primary.base,a=t.colors.chat?.background||t.colors.surface.background;return n.push(` --markdown-heading1: ${r.heading1||o};`),n.push(` --markdown-heading2: ${r.heading2||this.opacity(o,.9)};`),n.push(` --markdown-heading3: ${r.heading3||this.opacity(o,.8)};`),n.push(` --markdown-heading4: ${r.heading4||t.colors.surface.foreground};`),n.push(` --markdown-link: ${r.link||o};`),n.push(` --markdown-link-hover: ${r.linkHover||t.colors.primary.hover||this.darken(o,10)};`),n.push(` --markdown-inline-code: ${r.inlineCode||t.colors.syntax.base.string};`),n.push(` --markdown-inline-code-bg: ${r.inlineCodeBackground||a};`),n.push(` --markdown-blockquote: ${r.blockquote||t.colors.surface.mutedForeground};`),n.push(` --markdown-blockquote-border: ${r.blockquoteBorder||t.colors.interactive.border};`),n.push(` --markdown-list-marker: ${r.listMarker||this.opacity(o,.6)};`),n.push(` --markdown-bold: ${r.bold||t.colors.surface.foreground};`),n.push(` --markdown-italic: ${r.italic||this.opacity(t.colors.surface.foreground,.9)};`),n.push(` --markdown-strikethrough: ${r.strikethrough||t.colors.surface.mutedForeground};`),n.push(` --markdown-hr: ${r.hr||t.colors.interactive.border};`),n}generateDefaultMarkdownColors(r){const t=[],n=r.colors.primary.base,o=r.colors.chat?.background||r.colors.surface.background;return t.push(` --markdown-heading1: ${n};`),t.push(` --markdown-heading2: ${this.opacity(n,.9)};`),t.push(` --markdown-heading3: ${this.opacity(n,.8)};`),t.push(` --markdown-heading4: ${r.colors.surface.foreground};`),t.push(` --markdown-link: ${n};`),t.push(` --markdown-link-hover: ${r.colors.primary.hover||this.darken(n,10)};`),t.push(` --markdown-inline-code: ${r.colors.syntax.base.string};`),t.push(` --markdown-inline-code-bg: ${o};`),t.push(` --markdown-blockquote: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-blockquote-border: ${r.colors.interactive.border};`),t.push(` --markdown-list-marker: ${this.opacity(n,.6)};`),t.push(` --markdown-bold: ${r.colors.surface.foreground};`),t.push(` --markdown-italic: ${this.opacity(r.colors.surface.foreground,.9)};`),t.push(` --markdown-strikethrough: ${r.colors.surface.mutedForeground};`),t.push(` --markdown-hr: ${r.colors.interactive.border};`),t}generateChatColors(r,t){const n=[],o=r.background||t.colors.surface.background;return n.push(` --chat-background: ${o};`),n.push(` --chat-user-message: ${r.userMessage||t.colors.surface.foreground};`),n.push(` --chat-user-message-bg: ${r.userMessageBackground||t.colors.surface.elevated};`),n.push(` --chat-assistant-message: ${r.assistantMessage||t.colors.surface.foreground};`),n.push(` --chat-assistant-message-bg: ${r.assistantMessageBackground||t.colors.surface.muted};`),n.push(` --chat-timestamp: ${r.timestamp||t.colors.surface.mutedForeground};`),n.push(` --chat-divider: ${r.divider||t.colors.interactive.border};`),n.push(` --chat-typing: ${r.typing||t.colors.surface.mutedForeground};`),n}generateDefaultChatColors(r){const t=[];return t.push(` --chat-background: ${r.colors.surface.background};`),t.push(` --chat-user-message: ${r.colors.surface.foreground};`),t.push(` --chat-user-message-bg: ${r.colors.surface.elevated};`),t.push(` --chat-assistant-message: ${r.colors.surface.foreground};`),t.push(` --chat-assistant-message-bg: ${r.colors.surface.muted};`),t.push(` --chat-timestamp: ${r.colors.surface.mutedForeground};`),t.push(` --chat-divider: ${r.colors.interactive.border};`),t.push(` --chat-typing: ${r.colors.surface.mutedForeground};`),t}generateToolColors(r,t){const n=[];return n.push(` --tools-background: ${r?.background||this.opacity(t.colors.surface.muted,.2)};`),n.push(` --tools-border: ${r?.border||this.opacity(t.colors.interactive.border,.3)};`),n.push(` --tools-header-hover: ${r?.headerHover||this.opacity(t.colors.surface.muted,.3)};`),n.push(` --tools-icon: ${r?.icon||t.colors.surface.mutedForeground};`),n.push(` --tools-title: ${r?.title||t.colors.surface.foreground};`),n.push(` --tools-description: ${r?.description||this.opacity(t.colors.surface.mutedForeground,.6)};`),r?.edit?(n.push(` --tools-edit-added: ${r.edit.added||t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${r.edit.addedBackground||t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${r.edit.removed||t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${r.edit.removedBackground||t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${r.edit.modified||t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${r.edit.modifiedBackground||t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${r.edit.lineNumber||this.opacity(t.colors.surface.mutedForeground,.6)};`)):(n.push(` --tools-edit-added: ${t.colors.status.success};`),n.push(` --tools-edit-added-bg: ${t.colors.status.successBackground};`),n.push(` --tools-edit-removed: ${t.colors.status.error};`),n.push(` --tools-edit-removed-bg: ${t.colors.status.errorBackground};`),n.push(` --tools-edit-modified: ${t.colors.status.info};`),n.push(` --tools-edit-modified-bg: ${t.colors.status.infoBackground};`),n.push(` --tools-edit-line-number: ${this.opacity(t.colors.surface.mutedForeground,.6)};`)),n}generateDefaultToolColors(r){const t=[];return t.push(` --tools-background: ${this.opacity(r.colors.surface.muted,.2)};`),t.push(` --tools-border: ${this.opacity(r.colors.interactive.border,.3)};`),t.push(` --tools-header-hover: ${this.opacity(r.colors.surface.muted,.3)};`),t.push(` --tools-icon: ${r.colors.surface.mutedForeground};`),t.push(` --tools-title: ${r.colors.surface.foreground};`),t.push(` --tools-description: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t.push(` --tools-edit-added: ${r.colors.status.success};`),t.push(` --tools-edit-added-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.successBackground),.15)};`),t.push(` --tools-edit-removed: ${r.colors.status.error};`),t.push(` --tools-edit-removed-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.errorBackground),.15)};`),t.push(` --tools-edit-modified: ${r.colors.status.info};`),t.push(` --tools-edit-modified-bg: ${this.addTransparency(this.removeTransparency(r.colors.status.infoBackground),.15)};`),t.push(` --tools-edit-line-number: ${this.opacity(r.colors.surface.mutedForeground,.6)};`),t}generateConfigVariables(r){const t=[];return r&&(r.fonts&&(r.fonts.sans&&(t.push(` --font-sans: ${r.fonts.sans};`),t.push(` --font-family-sans: ${r.fonts.sans};`)),r.fonts.mono&&(t.push(` --font-mono: ${r.fonts.mono};`),t.push(` --font-family-mono: ${r.fonts.mono};`)),r.fonts.heading&&t.push(` --font-heading: ${r.fonts.heading};`)),r.radius&&(r.radius.none&&t.push(` --radius-none: ${r.radius.none};`),r.radius.sm&&t.push(` --radius-sm: ${r.radius.sm};`),r.radius.md&&t.push(` --radius-md: ${r.radius.md};`),r.radius.lg&&t.push(` --radius-lg: ${r.radius.lg};`),r.radius.xl&&t.push(` --radius-xl: ${r.radius.xl};`),r.radius.full&&t.push(` --radius-full: ${r.radius.full};`)),r.transitions&&(r.transitions.fast&&t.push(` --transition-fast: ${r.transitions.fast};`),r.transitions.normal&&t.push(` --transition-normal: ${r.transitions.normal};`),r.transitions.slow&&t.push(` --transition-slow: ${r.transitions.slow};`))),t}generateTypographyVariables(){const r=[],t=Ut()?ig:sl;return r.push(" /* Semantic Typography Variables */"),r.push(" --ui-regular-font-weight: 400;"),r.push(" /* Markdown content - all markdown elements use same size */"),r.push(` --text-markdown: ${t.markdown};`),r.push(" /* Code content - all code elements use same size */"),r.push(` --text-code: ${t.code};`),r.push(" /* UI headers - dialog titles, panel headers */"),r.push(` --text-ui-header: ${t.uiHeader};`),r.push(" /* UI labels - buttons, menus, navigation */"),r.push(` --text-ui-label: ${t.uiLabel};`),r.push(" /* Metadata - timestamps, status, helper text */"),r.push(` --text-meta: ${t.meta};`),r.push(" /* Micro text - badges, shortcuts, indicators */"),r.push(` --text-micro: ${t.micro};`),r.push(" /* Heading line height and letter spacing */"),r.push(" --h1-line-height: 1.25rem;"),r.push(" --h2-line-height: 1.25rem;"),r.push(" --h3-line-height: 1.5rem;"),r.push(" --h4-line-height: 1.5rem;"),r.push(" --h5-line-height: 1.5rem;"),r.push(" --h6-line-height: 1.5rem;"),r.push(" --h1-letter-spacing: -0.025em;"),r.push(" --h2-letter-spacing: -0.02em;"),r.push(" --h3-letter-spacing: -0.015em;"),r.push(" --h4-letter-spacing: -0.01em;"),r.push(" --h5-letter-spacing: 0;"),r.push(" --h6-letter-spacing: 0.01em;"),r.push(" /* UI element line height and letter spacing */"),r.push(" --ui-button-line-height: 1.375rem;"),r.push(" --ui-button-letter-spacing: 0.02em;"),r.push(" --ui-button-font-weight: 500;"),r.push(" --ui-label-line-height: 1rem;"),r.push(" --ui-label-letter-spacing: 0.03em;"),r.push(" --ui-label-font-weight: 500;"),r.push(" --ui-caption-line-height: 1rem;"),r.push(" --ui-caption-letter-spacing: 0.025em;"),r.push(" --ui-caption-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Markdown line height and letter spacing */"),r.push(" --markdown-body-line-height: 1.5rem;"),r.push(" --markdown-body-letter-spacing: 0;"),r.push(" --markdown-body-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-h1-line-height: 1.25rem;"),r.push(" --markdown-h1-letter-spacing: -0.025em;"),r.push(" --markdown-h2-line-height: 1.25rem;"),r.push(" --markdown-h2-letter-spacing: -0.02em;"),r.push(" --markdown-h3-line-height: 1.5rem;"),r.push(" --markdown-h3-letter-spacing: -0.015em;"),r.push(" --markdown-h4-line-height: 1.5rem;"),r.push(" --markdown-h4-letter-spacing: -0.01em;"),r.push(" --markdown-h5-line-height: 1.5rem;"),r.push(" --markdown-h5-letter-spacing: 0;"),r.push(" --markdown-h6-line-height: 1.5rem;"),r.push(" --markdown-h6-letter-spacing: 0.01em;"),r.push(" --markdown-list-line-height: 1.375rem;"),r.push(" --markdown-code-block-line-height: 1rem;"),r.push(" --ui-button-small-line-height: 1.25rem;"),r.push(" --ui-button-small-letter-spacing: 0.02em;"),r.push(" --ui-button-small-font-weight: 500;"),r.push(" --markdown-body-small-line-height: 1.375rem;"),r.push(" --markdown-body-small-letter-spacing: 0;"),r.push(" --markdown-body-small-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-button-large-line-height: 1.5rem;"),r.push(" --ui-button-large-letter-spacing: 0.02em;"),r.push(" --ui-button-large-font-weight: 500;"),r.push(" --markdown-body-large-line-height: 1.625rem;"),r.push(" --markdown-body-large-letter-spacing: 0;"),r.push(" --markdown-body-large-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Code line height and letter spacing */"),r.push(" --code-inline-line-height: 1rem;"),r.push(" --code-inline-letter-spacing: 0;"),r.push(" --code-inline-font-weight: 400;"),r.push(" --code-block-line-height: 1.4rem;"),r.push(" --code-block-letter-spacing: 0;"),r.push(" --code-block-font-weight: 400;"),r.push(" --code-line-numbers-line-height: 1.25rem;"),r.push(" --code-line-numbers-letter-spacing: 0;"),r.push(" --code-line-numbers-font-weight: 400;"),r.push(" /* Additional UI element line height and letter spacing */"),r.push(" --ui-badge-line-height: 1rem;"),r.push(" --ui-badge-letter-spacing: 0.025em;"),r.push(" --ui-badge-font-weight: 500;"),r.push(" --ui-tooltip-line-height: 1rem;"),r.push(" --ui-tooltip-letter-spacing: 0.025em;"),r.push(" --ui-tooltip-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-input-line-height: 1.375rem;"),r.push(" --ui-input-letter-spacing: 0.02em;"),r.push(" --ui-input-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --ui-helper-text-line-height: 1rem;"),r.push(" --ui-helper-text-letter-spacing: 0.025em;"),r.push(" --ui-helper-text-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" /* Additional markdown line height and letter spacing */"),r.push(" --markdown-blockquote-line-height: 1.5rem;"),r.push(" --markdown-blockquote-letter-spacing: 0;"),r.push(" --markdown-blockquote-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-list-letter-spacing: 0;"),r.push(" --markdown-list-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-link-line-height: 1.5rem;"),r.push(" --markdown-link-letter-spacing: 0;"),r.push(" --markdown-link-font-weight: var(--ui-regular-font-weight, 400);"),r.push(" --markdown-code-line-height: 1.35;"),r.push(" --markdown-code-letter-spacing: 0;"),r.push(" --markdown-code-font-weight: 400;"),r.push(" --markdown-code-block-letter-spacing: 0;"),r.push(" --markdown-code-block-font-weight: 400;"),r}initializeInheritanceMap(){this.inheritanceMap.set("header.background","surface.background"),this.inheritanceMap.set("header.foreground","surface.foreground"),this.inheritanceMap.set("header.logoTint","primary.base"),this.inheritanceMap.set("header.divider","interactive.border"),this.inheritanceMap.set("sidebar.background","surface.muted"),this.inheritanceMap.set("sidebar.foreground","surface.mutedForeground"),this.inheritanceMap.set("sidebar.hover","interactive.hover"),this.inheritanceMap.set("sidebar.active","primary.base"),this.inheritanceMap.set("sidebar.activeForeground","primary.foreground")}opacity(r,t){return r.startsWith("#")?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}removeTransparency(r){return r.startsWith("#")?r.length===9?r.slice(0,7):r.length===5?r.slice(0,4):r:r.startsWith("rgba")?r.replace("rgba","rgb").replace(/,\s*[\d.]+\)$/,")"):r}addTransparency(r,t){if(r.startsWith("#")){const n=r.slice(1);if(n.length===3){const o=parseInt(n[0]+n[0],16),a=parseInt(n[1]+n[1],16),i=parseInt(n[2]+n[2],16);return`rgba(${o}, ${a}, ${i}, ${t})`}else if(n.length===6){const o=parseInt(n.slice(0,2),16),a=parseInt(n.slice(2,4),16),i=parseInt(n.slice(4,6),16);return`rgba(${o}, ${a}, ${i}, ${t})`}}return r.startsWith("rgb")?r.replace("rgb","rgba").replace(")",`, ${t})`):r}darken(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)-o,i=(n>>8&255)-o,l=(n&255)-o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}lighten(r,t){if(r.startsWith("#")){const n=parseInt(r.slice(1),16),o=Math.round(2.55*t),a=(n>>16)+o,i=(n>>8&255)+o,l=(n&255)+o;return"#"+(16777216+(a<255?a<0?0:a:255)*65536+(i<255?i<0?0:i:255)*256+(l<255?l<0?0:l:255)).toString(16).slice(1)}return r}adjustHue(r,t){return this.lighten(r,t/10)}emphasize(r){return this.lighten(r,15)}kebabCase(r){return r.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}const Fl={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"}}},Rl={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"}}},ro=[Fl,Rl];function la(s){return ro.find(r=>r.metadata.id===s)}const Nf=Fl.metadata.id,Cf=Rl.metadata.id,TS=()=>typeof window>"u"?!0:window.matchMedia("(prefers-color-scheme: dark)").matches,Mf=s=>s==="dark"?Rl:Fl,FS=s=>(ro.find(t=>t.metadata.variant===s)??Mf(s)).metadata.id,Eo=(s,r)=>{const t=la(s);return t&&t.metadata.variant===r?t:ro.find(o=>o.metadata.variant===r)??Mf(r)},RS=typeof window<"u"?c.useLayoutEffect:c.useEffect,ca=(s,r)=>{if(!s)return r==="light"?Nf:Cf;const t=la(s);return t&&t.metadata.variant===r?t.metadata.id:FS(r)},_S=s=>{let r=Nf,t=Cf,n="system";if(typeof window<"u"){const o=localStorage.getItem("themeMode"),a=localStorage.getItem("lightThemeId"),i=localStorage.getItem("darkThemeId"),l=localStorage.getItem("useSystemTheme"),d=localStorage.getItem("selectedThemeId"),u=localStorage.getItem("selectedThemeVariant");if(o==="light"||o==="dark"||o==="system")n=o;else if(l!==null){if(l==="true")n="system";else if(d){const f=la(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=ca(a,"light"),t=ca(i,"dark")}if(s){const o=la(s);o&&(o.metadata.variant==="light"?r=o.metadata.id:t=o.metadata.id)}return{themeMode:n,lightThemeId:r,darkThemeId:t}};function OS({children:s,defaultThemeId:r}){const t=De.useMemo(()=>new PS,[]),[n,o]=De.useState(()=>_S(r)),[a,i]=De.useState(()=>TS()),[l,d]=De.useState(()=>typeof window>"u"||!Ut()?null:window.__OPENCHAMBER_VSCODE_THEME__||null),u=De.useMemo(()=>Ut(),[]),m=De.useMemo(()=>u&&l?l:n.themeMode==="light"?Eo(n.lightThemeId,"light"):n.themeMode==="dark"||a?Eo(n.darkThemeId,"dark"):Eo(n.lightThemeId,"light"),[u,n,a,l]),f=De.useMemo(()=>u&&l?[l,...ro]:ro,[u,l]);De.useEffect(()=>{if(!u)return;const N=D=>{d(D);const C=D.metadata.variant==="dark"?"dark":"light",M=_e.getState();M.theme!==C&&M.setTheme(C)},v=D=>{const C=D.detail;C?.theme&&N(C.theme)},k=window.__OPENCHAMBER_VSCODE_THEME__;return k&&N(k),window.addEventListener("openchamber:vscode-theme",v),()=>window.removeEventListener("openchamber:vscode-theme",v)},[u]);const p=De.useCallback(N=>{if(typeof document>"u")return;const v=N.colors.surface.background;Zt()?document.body.style.backgroundColor="transparent":document.body.style.backgroundColor=v;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",v);const D=N.metadata.variant==="dark"?"(prefers-color-scheme: dark)":"(prefers-color-scheme: light)";let C=document.querySelector(`meta[name="theme-color"][media="${D}"]`);C||(C=document.createElement("meta"),C.setAttribute("name","theme-color"),C.setAttribute("media",D),document.head.appendChild(C)),C.setAttribute("content",v)},[]),g=De.useCallback(N=>{typeof document>"u"||document.documentElement.classList.toggle("vscode-runtime",N)},[]);RS(()=>{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]),De.useEffect(()=>{if(n.themeMode!=="system"||typeof window>"u")return;const N=window.matchMedia("(prefers-color-scheme: dark)"),v=k=>{i(k.matches)};return i(N.matches),N.addEventListener("change",v),()=>N.removeEventListener("change",v)},[n.themeMode]),De.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]),De.useEffect(()=>{rs({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]),De.useEffect(()=>{if(typeof window>"u")return;const N=v=>{const k=v.detail;k&&o(D=>{let C=D.themeMode;k.useSystemTheme===!0?C="system":k.useSystemTheme===!1&&(k.themeVariant==="dark"||k.themeVariant==="light")&&(C=k.themeVariant);let M=D.lightThemeId;typeof k.lightThemeId=="string"&&k.lightThemeId.length>0&&(M=ca(k.lightThemeId,"light"));let S=D.darkThemeId;return typeof k.darkThemeId=="string"&&k.darkThemeId.length>0&&(S=ca(k.darkThemeId,"dark")),C===D.themeMode&&M===D.lightThemeId&&S===D.darkThemeId?D:{themeMode:C,lightThemeId:M,darkThemeId:S}})};return window.addEventListener("openchamber:settings-synced",N),()=>window.removeEventListener("openchamber:settings-synced",N)},[]);const w=De.useCallback(N=>{const v=f.find(k=>k.metadata.id===N);v&&o(k=>v.metadata.variant==="dark"?k.darkThemeId===v.metadata.id&&k.themeMode==="dark"?k:{...k,darkThemeId:v.metadata.id,themeMode:"dark"}:k.lightThemeId===v.metadata.id&&k.themeMode==="light"?k:{...k,lightThemeId:v.metadata.id,themeMode:"light"})},[f]),h=De.useCallback(N=>{o(v=>v.themeMode===N?v:{...v,themeMode:N})},[]),j=De.useCallback(N=>{if(N){o(k=>k.themeMode==="system"?k:{...k,themeMode:"system"});return}const v=m.metadata.variant==="dark"?"dark":"light";o(k=>k.themeMode===v?k:{...k,themeMode:v})},[m.metadata.variant]),x=De.useCallback(N=>{const v=f.find(k=>k.metadata.id===N&&k.metadata.variant==="light");v&&o(k=>k.lightThemeId===v.metadata.id?k:{...k,lightThemeId:v.metadata.id})},[f]),y=De.useCallback(N=>{const v=f.find(k=>k.metadata.id===N&&k.metadata.variant==="dark");v&&o(k=>k.darkThemeId===v.metadata.id?k:{...k,darkThemeId:v.metadata.id})},[f]),b={currentTheme:m,availableThemes:f,setTheme:w,isSystemPreference:n.themeMode==="system",setSystemPreference:j,themeMode:n.themeMode,setThemeMode:h,lightThemeId:n.lightThemeId,darkThemeId:n.darkThemeId,setLightThemePreference:x,setDarkThemePreference:y};return e.jsx(gl.Provider,{value:b,children:s})}const $S=({children:s})=>{const{theme:r,applyTheme:t,fontSize:n,applyTypography:o,padding:a,applyPadding:i}=_e();return c.useLayoutEffect(()=>{t(),o(),i()},[r,t,n,o,a,i]),c.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{r==="system"&&t()};return l.addEventListener("change",d),()=>{l.removeEventListener("change",d)}},[r,t]),e.jsx(e.Fragment,{children:s})},LS={getLastAssistantMessage(){const s=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const t=s.messages.get(r);if(!t||t.length===0)return console.log("[ERROR] No messages in current session"),null;for(let n=t.length-1;n>=0;n--){const o=t[n];if(o.info.role==="assistant"){const a=o.parts.map(p=>{const g={id:p.id,type:p.type};return p.type==="text"?(g.text=p.text,g.textLength=p.text?.length||0):p.type==="tool"?(g.tool=p.tool,g.state=p.state?.status):(p.type==="step-start"||p.type==="step-finish")&&(g.isStepMarker=!0),g}),i=a.some(p=>p.type==="text"&&p.text&&p.text.trim().length>0),l=a.some(p=>p.type==="tool"),d=a.some(p=>p.type==="step-start"||p.type==="step-finish"),u=a.length===0,m=!i&&!l&&(!u||d),f={messageId:o.info.id,role:o.info.role,timestamp:o.info.time?.created||0,partsCount:a.length,parts:a,isEmpty:u,isEmptyResponse:m,raw:o};return console.log("[INSPECT] Last Assistant Message:",f),console.log("[SUMMARY] Summary:",{messageId:f.messageId,partsCount:f.partsCount,isEmpty:f.isEmpty,isEmptyResponse:f.isEmptyResponse,hasText:i,hasTools:l,hasStepMarkers:d,onlyStepMarkers:d&&!i&&!l}),f.isEmpty&&console.warn("[WARNING] Message has NO parts!"),f.isEmptyResponse&&(console.warn("[WARNING] Message has parts but NO meaningful content (empty text, no tools)!"),d&&!i&&!l&&(console.warn("[CRITICAL] CLAUDE EMPTY RESPONSE BUG: Only step-start/step-finish markers, no actual content!"),console.log("This is a known issue with Claude models (anthropic provider)"),console.log("Recommendation: Send a follow-up message or try a different model"))),f}}return console.log("[ERROR] No assistant messages found in current session"),null},truncateString(s,r=80){return!s||typeof s!="string"||s.length<=r?s:s.substring(0,r)+"…"},truncateMessages(s){return s.map(r=>({...r,parts:(r.parts||[]).map(t=>{const n={...t};return"text"in t&&(n.text=this.truncateString(t.text)),"textPreview"in t&&(n.textPreview=this.truncateString(t.textPreview)),t.state&&(n.state={...t.state},"output"in t.state&&(n.state.output=this.truncateString(t.state.output)),"error"in t.state&&(n.state.error=this.truncateString(t.state.error)),t.state.metadata&&"preview"in t.state.metadata&&(n.state.metadata={...t.state.metadata,preview:this.truncateString(t.state.metadata.preview)})),n})}))},getAllMessages(s=!1){const r=ue.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=mt.getState(),r=ue.getState(),t=s.currentDirectory||null,n=je.getDirectory()??null,o=r.sessions||[],a=new Set,i={};o.forEach(k=>{const D=k.directory;typeof D=="string"&&D.trim().length>0?(a.add(D),i[D]=(i[D]??0)+1):i["(none)"]=(i["(none)"]??0)+1});const l=(()=>{if(typeof window>"u")return{available:!1};try{return{available:!0,lastDirectory:window.localStorage.getItem("lastDirectory"),homeDirectory:window.localStorage.getItem("homeDirectory")}}catch(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 D=await fetch(k);return D.ok?await f(D):{status:D.status}}catch(D){return{error:D instanceof Error?D.message:String(D)}}};let w=null,h=null,j=null,x=null;const y=t?`/api/path?directory=${encodeURIComponent(t)}`:"/api/path";w=await g(y);const b=t?`/api/project/current?directory=${encodeURIComponent(t)}`:"/api/project/current";h=await g(b),j=await g("/api/config/settings");try{const k=await fetch("/api/health"),D=k.headers.get("content-type")||"",C=await p(k);x={status:k.status,ok:k.ok,contentType:D,type:D.includes("application/json")?"json":"html",preview:C?C.slice(0,120):null}}catch(k){x={error:k instanceof Error?k.message:String(k)}}let N={isGitRepo:null};if(t)try{N.isGitRepo=await rn(t)}catch(k){N={isGitRepo:null,error:k instanceof Error?k.message:String(k)}}const v={runtime:{isDesktop:m,hasRuntimeApis:!!d,desktopServerOrigin:u?.origin??null},location:typeof window<"u"?{href:window.location?.href??null,origin:window.location?.origin??null}:null,directories:{currentDirectory:t,opencodeDirectory:w?.directory||w?.worktree||n,homeDirectory:s.homeDirectory||null,isHomeReady:s.isHomeReady,hasPersistedDirectory:s.hasPersistedDirectory,isSwitchingDirectory:s.isSwitchingDirectory},sessions:{total:o.length,currentSessionId:r.currentSessionId,lastLoadedDirectory:r.lastLoadedDirectory,uniqueDirectories:a.size,directorySamples:Array.from(a).slice(0,5),directoryCounts:i},worktrees:{available:r.availableWorktrees.length,metadataEntries:r.worktreeMetadata.size},git:N,localStorage:l,opencode:{pathInfo:w,projectInfo:h,health:x},openchamber:{settingsInfo:j}};return console.log("[DEBUG] App status snapshot:",v),v},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=ue.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=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),[];const n=(s.messages.get(r)||[]).filter(o=>o.info.role==="assistant").filter(o=>{const a=o.parts||[],i=a.some(d=>d.type==="text"&&d.text&&d.text.trim().length>0),l=a.some(d=>d.type==="tool");return a.length===0||!i&&!l});return console.log(`[INSPECT] Found ${n.length} empty assistant messages`),n.forEach((o,a)=>{console.log(`[${a}] Empty message:`,{messageId:o.info.id,partsCount:o.parts.length,provider:o.info.providerID,model:o.info.modelID,timestamp:o.info.time?.created})}),n},showRetryHelp(){console.log(`[DEBUG] How to handle empty Claude responses:
121
- `),console.log("1. Check the last message:"),console.log(` __opencodeDebug.getLastAssistantMessage()
122
- `),console.log("2. Find all empty messages in session:"),console.log(` __opencodeDebug.findEmptyMessages()
123
- `),console.log("3. To retry, you can:"),console.log(" - Edit your last user message and resend"),console.log(' - Send a follow-up message like "Please provide the response"'),console.log(` - Try a different model (OpenAI models tend to be more reliable)
124
- `),console.log("[TIP] Empty responses are usually due to:"),console.log(" - Model rate limits"),console.log(" - Context length issues"),console.log(" - Model refusing to respond to certain prompts"),console.log(" - API errors from provider")},analyzeMessageCompletionConsistency(s={}){const{includeNonAssistant:r=!1,verbose:t=!0,maxTableRows:n=25}=s,o=ue.getState(),a=o.currentSessionId;if(!a)return console.log("[ERROR] No active session"),{summary:null,rows:[]};const i=o.messages.get(a)||[],l=r?i:i.filter(p=>p.info.role==="assistant"),d={totalMessages:i.length,analyzedMessages:l.length,completedMissing:0,completedBeforeTool:0,completedBeforeReasoning:0,runningToolsWhenCompleted:0,reasoningOpenWhenCompleted:0,withTools:0,withReasoning:0},u=p=>typeof p=="number"&&Number.isFinite(p)?p:null,m=p=>{const g=p.filter(w=>typeof w=="number");return g.length>0?Math.max(...g):null},f=l.map((p,g)=>{const w=p.info??{},h=Array.isArray(p.parts)?p.parts:[],j=w.time??{},x=u(j.completed),y=x!==null,b=h.filter(I=>I.type==="tool"),N=h.filter(I=>I.type==="reasoning"),v=m(b.map(I=>u(I.state?.time?.end??I.state?.time?.start))),k=m(N.map(I=>u(I.time?.end??I.time?.start))),D=m([v,k].filter(I=>I!==null)),C=b.some(I=>["pending","running","started"].includes(I.state?.status)),M=N.some(I=>typeof I.time?.end!="number");b.length>0&&(d.withTools+=1),N.length>0&&(d.withReasoning+=1),y||(d.completedMissing+=1);const S=!!(y&&typeof v=="number"&&x<v);S&&(d.completedBeforeTool+=1);const A=!!(y&&typeof k=="number"&&x<k);return A&&(d.completedBeforeReasoning+=1),y&&C&&(d.runningToolsWhenCompleted+=1),y&&M&&(d.reasoningOpenWhenCompleted+=1),{index:g,messageId:w.id,role:w.role,completedAt:x,latestToolTimestamp:v,latestReasoningTimestamp:k,latestPartTimestamp:D,completed_missing:!y,completed_before_tool:S,completed_before_reasoning:A,running_tools_when_completed:!!(y&&C),reasoning_open_when_completed:!!(y&&M),has_tools:b.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=ue.getState(),r=s.currentSessionId;if(!r)return console.log("[ERROR] No active session"),null;const n=(s.messages.get(r)||[]).filter(j=>j.info.role==="assistant");if(n.length===0)return console.log("[ERROR] No assistant messages"),null;const o=n[n.length-1],a=o.parts.filter(j=>j.type==="step-finish"),i=o.info.finish==="stop",d=o.info.time?.completed,u=o.info.status,m=typeof d=="number"&&d>0||u==="completed",f=!!(m&&i),p=s.messageStreamStates,g=o.info.sessionID?s.streamingMessageIds.get(o.info.sessionID)??null:null,w=p.get(o.info.id),h=o.info.id===g;return console.log("[SUMMARY] Completion Status:"),console.log("Message ID:",o.info.id),console.log("time.completed:",d,"(type:",typeof d,")"),console.log("status:",u),console.log("hasCompletedFlag:",m),console.log("hasStopReason:",i),console.log("messageIsComplete:",f),console.log("lifecycle phase:",w?.phase),console.log("isStreamingCandidate:",h),console.log("streamingMessageId:",g),console.log("Step-finish parts:",a),{messageId:o.info.id,completed:d,status:u,hasCompletedFlag:m,hasStopReason:i,messageIsComplete:f,stepFinishParts:a,raw:o}}};typeof window<"u"&&(window.__opencodeDebug=LS,Qt()&&(console.log("[DEBUG] OpenCode Debug Utils loaded! Use window.__opencodeDebug in console"),console.log("Available commands:"),console.log(" __opencodeDebug.getLastAssistantMessage() - Get last assistant message details"),console.log(" __opencodeDebug.getAllMessages(truncate?) - List all messages (truncate=true for short preview)"),console.log(" __opencodeDebug.truncateMessages(messages) - Truncate long fields in messages array"),console.log(" __opencodeDebug.getAppStatus() - Show app status snapshot"),console.log(" __opencodeDebug.checkLastMessage() - Check if last message is problematic"),console.log(" __opencodeDebug.findEmptyMessages() - Find all empty assistant messages"),console.log(" __opencodeDebug.showRetryHelp() - Show instructions for handling empty responses"),console.log(" __opencodeDebug.getStreamingState() - Get streaming state info"),console.log(" __opencodeDebug.analyzeMessageCompletionConsistency(opts?) - Compare time.completed vs part timings"),console.log(" __opencodeDebug.checkCompletionStatus() - Check completion status of last message")),window.addEventListener("error",s=>{try{const r=s.message||"",t=s.filename||"";typeof r=="string"&&r.includes("this._renderer.value.dimensions")&&/xterm/i.test(String(t))&&s.preventDefault()}catch{}}));let nu=!1;const BS=()=>{if(nu||typeof window>"u")return;nu=!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&&rs(a)},o=a=>{r={...r??{},...a},!t&&(t=setTimeout(n,150))};_e.subscribe(a=>{const i={showReasoningTraces:a.showReasoningTraces,autoDeleteEnabled:a.autoDeleteEnabled,autoDeleteAfterDays:a.autoDeleteAfterDays},l={};i.showReasoningTraces!==s.showReasoningTraces&&(l.showReasoningTraces=i.showReasoningTraces),i.autoDeleteEnabled!==s.autoDeleteEnabled&&(l.autoDeleteEnabled=i.autoDeleteEnabled),i.autoDeleteAfterDays!==s.autoDeleteAfterDays&&(l.autoDeleteAfterDays=i.autoDeleteAfterDays),s=i,Object.keys(l).length>0&&o(l)})};let ou=!1;const au="openchamber-typography-base",zS=()=>{if(typeof document>"u")return;const r=`:root {
125
- ${Object.entries(sl).map(([o,a])=>` --text-${o.replace(/([A-Z])/g,"-$1").toLowerCase()}: ${a};`).join(`
126
- `)}
127
- }
128
- `,t=document.getElementById(au);if(t){t.textContent=r;return}const n=document.createElement("style");n.id=au,n.textContent=r,document.head.appendChild(n)},WS=()=>{ou||typeof window>"u"||(ou=!0,zS())},HS=typeof window<"u"&&window.__OPENCHAMBER_RUNTIME_APIS__||(()=>{throw new Error("Runtime APIs not provided for legacy UI entrypoint.")})();await Pu();await Tu();BS();WS();await Sf();typeof window<"u"&&(window.debugContextTokens=()=>{const s=window.__zustand_session_store__;if(!s)return;const r=s.getState(),t=r.currentSessionId;if(!t)return;const o=(r.messages.get(t)||[]).filter(d=>d.info.role==="assistant");if(o.length===0)return;const i=o[o.length-1].info.tokens;i&&typeof i=="object"&&console.debug("Token breakdown:",{base:(i.input||0)+(i.output||0)+(i.reasoning||0),cache:i.cache?(i.cache.read||0)+(i.cache.write||0):0}),r.sessionContextUsage.get(t);const l=window.__zustand_config_store__;if(l){const d=l.getState().getCurrentModel(),u=d?.limit?.context||0,m=d&&d.limit&&typeof d.limit=="object"?Math.max(d.limit.output??0,0):0;u>0&&r.getContextUsage(u,m)}});const Df=document.getElementById("root");if(!Df)throw new Error("Root element not found");Fh.createRoot(Df).render(e.jsx(De.StrictMode,{children:e.jsx(OS,{children:e.jsx($S,{children:e.jsx(IS,{children:e.jsx(NS,{apis:HS})})})})}));if(typeof window<"u"){const s=()=>{try{window.opencodeDesktop?.markRendererReady?.()}catch(r){console.warn("Failed to notify desktop runtime that renderer is ready:",r)}};s(),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&s()})}const GS=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));export{ms as D,Kr as S,fs as a,Ay as b,R as c,Bw as d,zw as e,md as f,nn as g,Ww as h,Uw as i,GS as m,Qm as p,Hw as r,To as t};